Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_kvm.py @ 47387b1e

History | View | Annotate | Download (12.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2008 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""KVM hypervisor
23

24
"""
25

    
26
import os
27
import os.path
28
import re
29
import tempfile
30
from cStringIO import StringIO
31

    
32
from ganeti import utils
33
from ganeti import constants
34
from ganeti import errors
35
from ganeti.hypervisor import hv_base
36

    
37

    
38
class KVMHypervisor(hv_base.BaseHypervisor):
39
  """Fake hypervisor interface.
40

41
  This can be used for testing the ganeti code without having to have
42
  a real virtualisation software installed.
43

44
  """
45
  _ROOT_DIR = constants.RUN_GANETI_DIR + "/kvm-hypervisor"
46
  _PIDS_DIR = _ROOT_DIR + "/pid"
47
  _CTRL_DIR = _ROOT_DIR + "/ctrl"
48
  _DIRS = [_ROOT_DIR, _PIDS_DIR, _CTRL_DIR]
49

    
50
  PARAMETERS = [
51
    constants.HV_KERNEL_PATH,
52
    constants.HV_INITRD_PATH,
53
    constants.HV_ACPI,
54
    ]
55

    
56
  def __init__(self):
57
    hv_base.BaseHypervisor.__init__(self)
58
    # Let's make sure the directories we need exist, even if the RUN_DIR lives
59
    # in a tmpfs filesystem or has been otherwise wiped out.
60
    for dir in self._DIRS:
61
      if not os.path.exists(dir):
62
        os.mkdir(dir)
63

    
64
  def _WriteNetScript(self, instance, seq, nic):
65
    """Write a script to connect a net interface to the proper bridge.
66

67
    This can be used by any qemu-type hypervisor.
68

69
    @param instance: instance we're acting on
70
    @type instance: instance object
71
    @param seq: nic sequence number
72
    @type seq: int
73
    @param nic: nic we're acting on
74
    @type nic: nic object
75
    @return: netscript file name
76
    @rtype: string
77

78
    """
79
    script = StringIO()
80
    script.write("#!/bin/sh\n")
81
    script.write("# this is autogenerated by Ganeti, please do not edit\n#\n")
82
    script.write("export INSTANCE=%s\n" % instance.name)
83
    script.write("export MAC=%s\n" % nic.mac)
84
    script.write("export IP=%s\n" % nic.ip)
85
    script.write("export BRIDGE=%s\n" % nic.bridge)
86
    script.write("export INTERFACE=$1\n")
87
    # TODO: make this configurable at ./configure time
88
    script.write("if [ -x /etc/ganeti/kvm-vif-bridge ]; then\n")
89
    script.write("  # Execute the user-specific vif file\n")
90
    script.write("  /etc/ganeti/kvm-vif-bridge\n")
91
    script.write("else\n")
92
    script.write("  # Connect the interface to the bridge\n")
93
    script.write("  /sbin/ifconfig $INTERFACE 0.0.0.0 up\n")
94
    script.write("  /usr/sbin/brctl addif $BRIDGE $INTERFACE\n")
95
    script.write("fi\n\n")
96
    # As much as we'd like to put this in our _ROOT_DIR, that will happen to be
97
    # mounted noexec sometimes, so we'll have to find another place.
98
    (tmpfd, tmpfile_name) = tempfile.mkstemp()
99
    tmpfile = os.fdopen(tmpfd, 'w')
100
    tmpfile.write(script.getvalue())
101
    tmpfile.close()
102
    os.chmod(tmpfile_name, 0755)
103
    return tmpfile_name
104

    
105
  def ListInstances(self):
106
    """Get the list of running instances.
107

108
    We can do this by listing our live instances directory and checking whether
109
    the associated kvm process is still alive.
110

111
    """
112
    result = []
113
    for name in os.listdir(self._PIDS_DIR):
114
      file = "%s/%s" % (self._PIDS_DIR, name)
115
      if utils.IsProcessAlive(utils.ReadPidFile(file)):
116
        result.append(name)
117
    return result
118

    
119
  def GetInstanceInfo(self, instance_name):
120
    """Get instance properties.
121

122
    Args:
123
      instance_name: the instance name
124

125
    Returns:
126
      (name, id, memory, vcpus, stat, times)
127
    """
128
    pidfile = "%s/%s" % (self._PIDS_DIR, instance_name)
129
    pid = utils.ReadPidFile(pidfile)
130
    if not utils.IsProcessAlive(pid):
131
      return None
132

    
133
    cmdline_file = "/proc/%s/cmdline" % pid
134
    try:
135
      fh = open(cmdline_file, 'r')
136
      try:
137
        cmdline = fh.read()
138
      finally:
139
        fh.close()
140
    except IOError, err:
141
      raise errors.HypervisorError("Failed to list instance %s: %s" %
142
                                   (instance_name, err))
143

    
144
    memory = 0
145
    vcpus = 0
146
    stat = "---b-"
147
    times = "0"
148

    
149
    arg_list = cmdline.split('\x00')
150
    while arg_list:
151
      arg =  arg_list.pop(0)
152
      if arg == '-m':
153
        memory = arg_list.pop(0)
154
      elif arg == '-smp':
155
        vcpus = arg_list.pop(0)
156

    
157
    return (instance_name, pid, memory, vcpus, stat, times)
158

    
159
  def GetAllInstancesInfo(self):
160
    """Get properties of all instances.
161

162
    Returns:
163
      [(name, id, memory, vcpus, stat, times),...]
164
    """
165
    data = []
166
    for name in os.listdir(self._PIDS_DIR):
167
      file = "%s/%s" % (self._PIDS_DIR, name)
168
      if utils.IsProcessAlive(utils.ReadPidFile(file)):
169
        data.append(self.GetInstanceInfo(name))
170

    
171
    return data
172

    
173
  def StartInstance(self, instance, block_devices, extra_args):
174
    """Start an instance.
175

176
    """
177
    temp_files = []
178
    pidfile = self._PIDS_DIR + "/%s" % instance.name
179
    if utils.IsProcessAlive(utils.ReadPidFile(pidfile)):
180
      raise errors.HypervisorError("Failed to start instance %s: %s" %
181
                                   (instance.name, "already running"))
182

    
183
    kvm = constants.KVM_PATH
184
    kvm_cmd = [kvm]
185
    kvm_cmd.extend(['-m', instance.beparams[constants.BE_MEMORY]])
186
    kvm_cmd.extend(['-smp', instance.beparams[constants.BE_VCPUS]])
187
    kvm_cmd.extend(['-pidfile', pidfile])
188
    # used just by the vnc server, if enabled
189
    kvm_cmd.extend(['-name', instance.name])
190
    kvm_cmd.extend(['-daemonize'])
191
    if not instance.hvparams[constants.HV_ACPI]:
192
      kvm_cmd.extend(['-no-acpi'])
193
    if not instance.nics:
194
      kvm_cmd.extend(['-net', 'none'])
195
    else:
196
      nic_seq = 0
197
      for nic in instance.nics:
198
        script = self._WriteNetScript(instance, nic_seq, nic)
199
        # FIXME: handle other models
200
        nic_val = "nic,macaddr=%s,model=virtio" % nic.mac
201
        kvm_cmd.extend(['-net', nic_val])
202
        kvm_cmd.extend(['-net', 'tap,script=%s' % script])
203
        temp_files.append(script)
204
        nic_seq += 1
205

    
206
    boot_drive = True
207
    for cfdev, rldev in block_devices:
208
      # TODO: handle FD_LOOP and FD_BLKTAP (?)
209
      if boot_drive:
210
        boot_val = ',boot=on'
211
        boot_drive = False
212
      else:
213
        boot_val = ''
214

    
215
      # TODO: handle different if= types
216
      if_val = ',if=virtio'
217

    
218
      drive_val = 'file=%s,format=raw%s%s' % (rldev.dev_path, if_val, boot_val)
219
      kvm_cmd.extend(['-drive', drive_val])
220

    
221
    kvm_cmd.extend(['-kernel', instance.hvparams[HV_KERNEL_PATH]])
222
    initrd_path = instance.hvparams[HV_INITRD_PATH]
223
    if initrd_path:
224
      kvm_cmd.extend(['-initrd', initrd_path])
225

    
226
    kvm_cmd.extend(['-append', 'console=ttyS0,38400 root=/dev/vda'])
227

    
228
    #"hvm_boot_order",
229
    #"hvm_cdrom_image_path",
230

    
231
    kvm_cmd.extend(['-nographic'])
232
    # FIXME: handle vnc, if needed
233
    # How do we decide whether to have it or not?? :(
234
    #"vnc_bind_address",
235
    #"network_port"
236
    base_control = '%s/%s' % (self._CTRL_DIR, instance.name)
237
    monitor_dev = 'unix:%s.monitor,server,nowait' % base_control
238
    kvm_cmd.extend(['-monitor', monitor_dev])
239
    serial_dev = 'unix:%s.serial,server,nowait' % base_control
240
    kvm_cmd.extend(['-serial', serial_dev])
241

    
242
    result = utils.RunCmd(kvm_cmd)
243
    if result.failed:
244
      raise errors.HypervisorError("Failed to start instance %s: %s (%s)" %
245
                                   (instance.name, result.fail_reason,
246
                                    result.output))
247

    
248
    if not utils.IsProcessAlive(utils.ReadPidFile(pidfile)):
249
      raise errors.HypervisorError("Failed to start instance %s: %s" %
250
                                   (instance.name))
251

    
252
    for file in temp_files:
253
      utils.RemoveFile(file)
254

    
255
  def StopInstance(self, instance, force=False):
256
    """Stop an instance.
257

258
    """
259
    pid_file = self._PIDS_DIR + "/%s" % instance.name
260
    pid = utils.ReadPidFile(pid_file)
261
    if pid > 0 and utils.IsProcessAlive(pid):
262
      if force or not instance.hvparams[constants.HV_ACPI]:
263
        utils.KillProcess(pid)
264
      else:
265
        # This only works if the instance os has acpi support
266
        monitor_socket = '%s/%s.monitor'  % (self._CTRL_DIR, instance.name)
267
        socat = 'socat -u STDIN UNIX-CONNECT:%s' % monitor_socket
268
        command = "echo 'system_powerdown' | %s" % socat
269
        result = utils.RunCmd(command)
270
        if result.failed:
271
          raise errors.HypervisorError("Failed to stop instance %s: %s" %
272
                                       (instance.name, result.fail_reason))
273

    
274
    if not utils.IsProcessAlive(pid):
275
      utils.RemoveFile(pid_file)
276

    
277
  def RebootInstance(self, instance):
278
    """Reboot an instance.
279

280
    """
281
    # For some reason if we do a 'send-key ctrl-alt-delete' to the control
282
    # socket the instance will stop, but now power up again. So we'll resort
283
    # to shutdown and restart.
284
    self.StopInstance(instance)
285
    self.StartInstance(instance)
286

    
287
  def GetNodeInfo(self):
288
    """Return information about the node.
289

290
    The return value is a dict, which has to have the following items:
291
      (all values in MiB)
292
      - memory_total: the total memory size on the node
293
      - memory_free: the available memory on the node for instances
294
      - memory_dom0: the memory used by the node itself, if available
295

296
    """
297
    # global ram usage from the xm info command
298
    # memory                 : 3583
299
    # free_memory            : 747
300
    # note: in xen 3, memory has changed to total_memory
301
    try:
302
      fh = file("/proc/meminfo")
303
      try:
304
        data = fh.readlines()
305
      finally:
306
        fh.close()
307
    except IOError, err:
308
      raise errors.HypervisorError("Failed to list node info: %s" % err)
309

    
310
    result = {}
311
    sum_free = 0
312
    for line in data:
313
      splitfields = line.split(":", 1)
314

    
315
      if len(splitfields) > 1:
316
        key = splitfields[0].strip()
317
        val = splitfields[1].strip()
318
        if key == 'MemTotal':
319
          result['memory_total'] = int(val.split()[0])/1024
320
        elif key in ('MemFree', 'Buffers', 'Cached'):
321
          sum_free += int(val.split()[0])/1024
322
        elif key == 'Active':
323
          result['memory_dom0'] = int(val.split()[0])/1024
324
    result['memory_free'] = sum_free
325

    
326
    cpu_total = 0
327
    try:
328
      fh = open("/proc/cpuinfo")
329
      try:
330
        cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
331
                                   fh.read()))
332
      finally:
333
        fh.close()
334
    except EnvironmentError, err:
335
      raise errors.HypervisorError("Failed to list node info: %s" % err)
336
    result['cpu_total'] = cpu_total
337

    
338
    return result
339

    
340
  @staticmethod
341
  def GetShellCommandForConsole(instance):
342
    """Return a command for connecting to the console of an instance.
343

344
    """
345
    # TODO: we can either try the serial socket or suggest vnc
346
    return "echo Console not available for the kvm hypervisor yet"
347

    
348
  def Verify(self):
349
    """Verify the hypervisor.
350

351
    Check that the binary exists.
352

353
    """
354
    if not os.path.exists(constants.KVM_PATH):
355
      return "The kvm binary ('%s') does not exist." % constants.KVM_PATH
356

    
357
  @classmethod
358
  def CheckParameterSyntax(cls, hvparams):
359
    """Check the given parameters for validity.
360

361
    For the KVM hypervisor, this only check the existence of the
362
    kernel.
363

364
    @type hvparams:  dict
365
    @param hvparams: dictionary with parameter names/value
366
    @raise errors.HypervisorError: when a parameter is not valid
367

368
    """
369
    super(KVMHypervisor, cls).CheckParameterSyntax(hvparams)
370

    
371
    if not hvparams[constants.HV_KERNEL_PATH]:
372
      raise errors.HypervisorError("Need a kernel for the instance")
373

    
374
    if not os.path.isabs(hvparams[constants.HV_KERNEL_PATH]):
375
      raise errors.HypervisorError("The kernel path must an absolute path")
376

    
377
    if hvparams[constants.HV_INITRD_PATH]:
378
      if not os.path.isabs(hvparams[constants.HV_INITRD_PATH]):
379
        raise errors.HypervisorError("The initrd path must an absolute path"
380
                                     ", if defined")
381

    
382
  def ValidateParameters(self, hvparams):
383
    """Check the given parameters for validity.
384

385
    For the KVM hypervisor, this checks the existence of the
386
    kernel.
387

388
    """
389
    super(KVMHypervisor, self).ValidateParameters(hvparams)
390

    
391
    kernel_path = hvparams[constants.HV_KERNEL_PATH]
392
    if not os.path.isfile(kernel_path):
393
      raise errors.HypervisorError("Instance kernel '%s' not found or"
394
                                   " not a file" % kernel_path)
395
    initrd_path = hvparams[constants.HV_INITRD_PATH]
396
    if initrd_path and not os.path.isfile(initrd_path):
397
      raise errors.HypervisorError("Instance initrd '%s' not found or"
398
                                   " not a file" % initrd_path)