Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_kvm.py @ 3e40b587

History | View | Annotate | Download (62.3 kB)

1
#
2
#
3

    
4
# Copyright (C) 2008, 2009, 2010, 2011 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 errno
27
import os
28
import os.path
29
import re
30
import tempfile
31
import time
32
import logging
33
import pwd
34
import struct
35
import fcntl
36
import shutil
37
import socket
38
import StringIO
39

    
40
from ganeti import utils
41
from ganeti import constants
42
from ganeti import errors
43
from ganeti import serializer
44
from ganeti import objects
45
from ganeti import uidpool
46
from ganeti import ssconf
47
from ganeti.hypervisor import hv_base
48
from ganeti import netutils
49
from ganeti.utils import wrapper as utils_wrapper
50

    
51

    
52
_KVM_NETWORK_SCRIPT = constants.SYSCONFDIR + "/ganeti/kvm-vif-bridge"
53

    
54
# TUN/TAP driver constants, taken from <linux/if_tun.h>
55
# They are architecture-independent and already hardcoded in qemu-kvm source,
56
# so we can safely include them here.
57
TUNSETIFF = 0x400454ca
58
TUNGETIFF = 0x800454d2
59
TUNGETFEATURES = 0x800454cf
60
IFF_TAP = 0x0002
61
IFF_NO_PI = 0x1000
62
IFF_VNET_HDR = 0x4000
63

    
64

    
65
def _ProbeTapVnetHdr(fd):
66
  """Check whether to enable the IFF_VNET_HDR flag.
67

68
  To do this, _all_ of the following conditions must be met:
69
   1. TUNGETFEATURES ioctl() *must* be implemented
70
   2. TUNGETFEATURES ioctl() result *must* contain the IFF_VNET_HDR flag
71
   3. TUNGETIFF ioctl() *must* be implemented; reading the kernel code in
72
      drivers/net/tun.c there is no way to test this until after the tap device
73
      has been created using TUNSETIFF, and there is no way to change the
74
      IFF_VNET_HDR flag after creating the interface, catch-22! However both
75
      TUNGETIFF and TUNGETFEATURES were introduced in kernel version 2.6.27,
76
      thus we can expect TUNGETIFF to be present if TUNGETFEATURES is.
77

78
   @type fd: int
79
   @param fd: the file descriptor of /dev/net/tun
80

81
  """
82
  req = struct.pack("I", 0)
83
  try:
84
    res = fcntl.ioctl(fd, TUNGETFEATURES, req)
85
  except EnvironmentError:
86
    logging.warning("TUNGETFEATURES ioctl() not implemented")
87
    return False
88

    
89
  tunflags = struct.unpack("I", res)[0]
90
  if tunflags & IFF_VNET_HDR:
91
    return True
92
  else:
93
    logging.warning("Host does not support IFF_VNET_HDR, not enabling")
94
    return False
95

    
96

    
97
def _OpenTap(vnet_hdr=True):
98
  """Open a new tap device and return its file descriptor.
99

100
  This is intended to be used by a qemu-type hypervisor together with the -net
101
  tap,fd=<fd> command line parameter.
102

103
  @type vnet_hdr: boolean
104
  @param vnet_hdr: Enable the VNET Header
105
  @return: (ifname, tapfd)
106
  @rtype: tuple
107

108
  """
109
  try:
110
    tapfd = os.open("/dev/net/tun", os.O_RDWR)
111
  except EnvironmentError:
112
    raise errors.HypervisorError("Failed to open /dev/net/tun")
113

    
114
  flags = IFF_TAP | IFF_NO_PI
115

    
116
  if vnet_hdr and _ProbeTapVnetHdr(tapfd):
117
    flags |= IFF_VNET_HDR
118

    
119
  # The struct ifreq ioctl request (see netdevice(7))
120
  ifr = struct.pack("16sh", "", flags)
121

    
122
  try:
123
    res = fcntl.ioctl(tapfd, TUNSETIFF, ifr)
124
  except EnvironmentError:
125
    raise errors.HypervisorError("Failed to allocate a new TAP device")
126

    
127
  # Get the interface name from the ioctl
128
  ifname = struct.unpack("16sh", res)[0].strip("\x00")
129
  return (ifname, tapfd)
130

    
131

    
132
class QmpMessage:
133
  """QEMU Messaging Protocol (QMP) message.
134

135
  """
136

    
137
  def __init__(self, data):
138
    """Creates a new QMP message based on the passed data.
139

140
    """
141
    if not isinstance(data, dict):
142
      raise TypeError("QmpMessage must be initialized with a dict")
143

    
144
    self.data = data
145

    
146
  def __getitem__(self, field_name):
147
    """Get the value of the required field if present, or None.
148

149
    Overrides the [] operator to provide access to the message data,
150
    returning None if the required item is not in the message
151
    @return: the value of the field_name field, or None if field_name
152
             is not contained in the message
153

154
    """
155

    
156
    if field_name in self.data:
157
      return self.data[field_name]
158

    
159
    return None
160

    
161
  def __setitem__(self, field_name, field_value):
162
    """Set the value of the required field_name to field_value.
163

164
    """
165
    self.data[field_name] = field_value
166

    
167
  @staticmethod
168
  def BuildFromJsonString(json_string):
169
    """Build a QmpMessage from a JSON encoded string.
170

171
    @type json_string: str
172
    @param json_string: JSON string representing the message
173
    @rtype: L{QmpMessage}
174
    @return: a L{QmpMessage} built from json_string
175

176
    """
177
    # Parse the string
178
    data = serializer.LoadJson(json_string)
179
    return QmpMessage(data)
180

    
181
  def __str__(self):
182
    # The protocol expects the JSON object to be sent as a single
183
    # line, hence the need for indent=False.
184
    return serializer.DumpJson(self.data, indent=False)
185

    
186
  def __eq__(self, other):
187
    # When comparing two QmpMessages, we are interested in comparing
188
    # their internal representation of the message data
189
    return self.data == other.data
190

    
191

    
192
class QmpConnection:
193
  """Connection to the QEMU Monitor using the QEMU Monitor Protocol (QMP).
194

195
  """
196
  _FIRST_MESSAGE_KEY = "QMP"
197
  _EVENT_KEY = "event"
198
  _ERROR_KEY = "error"
199
  _ERROR_CLASS_KEY = "class"
200
  _ERROR_DATA_KEY = "data"
201
  _ERROR_DESC_KEY = "desc"
202
  _EXECUTE_KEY = "execute"
203
  _ARGUMENTS_KEY = "arguments"
204
  _CAPABILITIES_COMMAND = "qmp_capabilities"
205
  _MESSAGE_END_TOKEN = "\r\n"
206
  _SOCKET_TIMEOUT = 5
207

    
208
  def __init__(self, monitor_filename):
209
    """Instantiates the QmpConnection object.
210

211
    @type monitor_filename: string
212
    @param monitor_filename: the filename of the UNIX raw socket on which the
213
                             QMP monitor is listening
214

215
    """
216
    self.monitor_filename = monitor_filename
217
    self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
218
    # We want to fail if the server doesn't send a complete message
219
    # in a reasonable amount of time
220
    self.sock.settimeout(self._SOCKET_TIMEOUT)
221
    self._connected = False
222
    self._buf = ""
223

    
224
  def _check_connection(self):
225
    """Make sure that the connection is established.
226

227
    """
228
    if not self._connected:
229
      raise errors.ProgrammerError("To use a QmpConnection you need to first"
230
                                   " invoke connect() on it")
231

    
232
  def connect(self):
233
    """Connects to the QMP monitor.
234

235
    Connects to the UNIX socket and makes sure that we can actually send and
236
    receive data to the kvm instance via QMP.
237

238
    @raise errors.HypervisorError: when there are communication errors
239
    @raise errors.ProgrammerError: when there are data serialization errors
240

241
    """
242
    self.sock.connect(self.monitor_filename)
243
    self._connected = True
244

    
245
    # Check if we receive a correct greeting message from the server
246
    # (As per the QEMU Protocol Specification 0.1 - section 2.2)
247
    greeting = self._Recv()
248
    if not greeting[self._FIRST_MESSAGE_KEY]:
249
      self._connected = False
250
      raise errors.HypervisorError("kvm: qmp communication error (wrong"
251
                                   " server greeting")
252

    
253
    # Let's put the monitor in command mode using the qmp_capabilities
254
    # command, or else no command will be executable.
255
    # (As per the QEMU Protocol Specification 0.1 - section 4)
256
    self.Execute(self._CAPABILITIES_COMMAND)
257

    
258
  def _ParseMessage(self, buf):
259
    """Extract and parse a QMP message from the given buffer.
260

261
    Seeks for a QMP message in the given buf. If found, it parses it and
262
    returns it together with the rest of the characters in the buf.
263
    If no message is found, returns None and the whole buffer.
264

265
    @raise errors.ProgrammerError: when there are data serialization errors
266

267
    """
268
    message = None
269
    # Check if we got the message end token (CRLF, as per the QEMU Protocol
270
    # Specification 0.1 - Section 2.1.1)
271
    pos = buf.find(self._MESSAGE_END_TOKEN)
272
    if pos >= 0:
273
      try:
274
        message = QmpMessage.BuildFromJsonString(buf[:pos + 1])
275
      except Exception, err:
276
        raise errors.ProgrammerError("QMP data serialization error: %s" % err)
277
      buf = buf[pos + 1:]
278

    
279
    return (message, buf)
280

    
281
  def _Recv(self):
282
    """Receives a message from QMP and decodes the received JSON object.
283

284
    @rtype: QmpMessage
285
    @return: the received message
286
    @raise errors.HypervisorError: when there are communication errors
287
    @raise errors.ProgrammerError: when there are data serialization errors
288

289
    """
290
    self._check_connection()
291

    
292
    # Check if there is already a message in the buffer
293
    (message, self._buf) = self._ParseMessage(self._buf)
294
    if message:
295
      return message
296

    
297
    recv_buffer = StringIO.StringIO(self._buf)
298
    recv_buffer.seek(len(self._buf))
299
    try:
300
      while True:
301
        data = self.sock.recv(4096)
302
        if not data:
303
          break
304
        recv_buffer.write(data)
305

    
306
        (message, self._buf) = self._ParseMessage(recv_buffer.getvalue())
307
        if message:
308
          return message
309

    
310
    except socket.timeout, err:
311
      raise errors.HypervisorError("Timeout while receiving a QMP message: "
312
                                   "%s" % (err))
313
    except socket.error, err:
314
      raise errors.HypervisorError("Unable to receive data from KVM using the"
315
                                   " QMP protocol: %s" % err)
316

    
317
  def _Send(self, message):
318
    """Encodes and sends a message to KVM using QMP.
319

320
    @type message: QmpMessage
321
    @param message: message to send to KVM
322
    @raise errors.HypervisorError: when there are communication errors
323
    @raise errors.ProgrammerError: when there are data serialization errors
324

325
    """
326
    self._check_connection()
327
    try:
328
      message_str = str(message)
329
    except Exception, err:
330
      raise errors.ProgrammerError("QMP data deserialization error: %s" % err)
331

    
332
    try:
333
      self.sock.sendall(message_str)
334
    except socket.timeout, err:
335
      raise errors.HypervisorError("Timeout while sending a QMP message: "
336
                                   "%s (%s)" % (err.string, err.errno))
337
    except socket.error, err:
338
      raise errors.HypervisorError("Unable to send data from KVM using the"
339
                                   " QMP protocol: %s" % err)
340

    
341
  def Execute(self, command, arguments=None):
342
    """Executes a QMP command and returns the response of the server.
343

344
    @type command: str
345
    @param command: the command to execute
346
    @type arguments: dict
347
    @param arguments: dictionary of arguments to be passed to the command
348
    @rtype: dict
349
    @return: dictionary representing the received JSON object
350
    @raise errors.HypervisorError: when there are communication errors
351
    @raise errors.ProgrammerError: when there are data serialization errors
352

353
    """
354
    self._check_connection()
355
    message = QmpMessage({self._EXECUTE_KEY: command})
356
    if arguments:
357
      message[self._ARGUMENTS_KEY] = arguments
358
    self._Send(message)
359

    
360
    # Events can occur between the sending of the command and the reception
361
    # of the response, so we need to filter out messages with the event key.
362
    while True:
363
      response = self._Recv()
364
      err = response[self._ERROR_KEY]
365
      if err:
366
        raise errors.HypervisorError("kvm: error executing the %s"
367
                                     " command: %s (%s, %s):" %
368
                                     (command,
369
                                      err[self._ERROR_DESC_KEY],
370
                                      err[self._ERROR_CLASS_KEY],
371
                                      err[self._ERROR_DATA_KEY]))
372

    
373
      elif not response[self._EVENT_KEY]:
374
        return response
375

    
376

    
377
class KVMHypervisor(hv_base.BaseHypervisor):
378
  """KVM hypervisor interface"""
379
  CAN_MIGRATE = True
380

    
381
  _ROOT_DIR = constants.RUN_GANETI_DIR + "/kvm-hypervisor"
382
  _PIDS_DIR = _ROOT_DIR + "/pid" # contains live instances pids
383
  _UIDS_DIR = _ROOT_DIR + "/uid" # contains instances reserved uids
384
  _CTRL_DIR = _ROOT_DIR + "/ctrl" # contains instances control sockets
385
  _CONF_DIR = _ROOT_DIR + "/conf" # contains instances startup data
386
  _NICS_DIR = _ROOT_DIR + "/nic" # contains instances nic <-> tap associations
387
  _KEYMAP_DIR = _ROOT_DIR + "/keymap" # contains instances keymaps
388
  # KVM instances with chroot enabled are started in empty chroot directories.
389
  _CHROOT_DIR = _ROOT_DIR + "/chroot" # for empty chroot directories
390
  # After an instance is stopped, its chroot directory is removed.
391
  # If the chroot directory is not empty, it can't be removed.
392
  # A non-empty chroot directory indicates a possible security incident.
393
  # To support forensics, the non-empty chroot directory is quarantined in
394
  # a separate directory, called 'chroot-quarantine'.
395
  _CHROOT_QUARANTINE_DIR = _ROOT_DIR + "/chroot-quarantine"
396
  _DIRS = [_ROOT_DIR, _PIDS_DIR, _UIDS_DIR, _CTRL_DIR, _CONF_DIR, _NICS_DIR,
397
           _CHROOT_DIR, _CHROOT_QUARANTINE_DIR]
398

    
399
  PARAMETERS = {
400
    constants.HV_KERNEL_PATH: hv_base.OPT_FILE_CHECK,
401
    constants.HV_INITRD_PATH: hv_base.OPT_FILE_CHECK,
402
    constants.HV_ROOT_PATH: hv_base.NO_CHECK,
403
    constants.HV_KERNEL_ARGS: hv_base.NO_CHECK,
404
    constants.HV_ACPI: hv_base.NO_CHECK,
405
    constants.HV_SERIAL_CONSOLE: hv_base.NO_CHECK,
406
    constants.HV_VNC_BIND_ADDRESS:
407
      (False, lambda x: (netutils.IP4Address.IsValid(x) or
408
                         utils.IsNormAbsPath(x)),
409
       "the VNC bind address must be either a valid IP address or an absolute"
410
       " pathname", None, None),
411
    constants.HV_VNC_TLS: hv_base.NO_CHECK,
412
    constants.HV_VNC_X509: hv_base.OPT_DIR_CHECK,
413
    constants.HV_VNC_X509_VERIFY: hv_base.NO_CHECK,
414
    constants.HV_VNC_PASSWORD_FILE: hv_base.OPT_FILE_CHECK,
415
    constants.HV_KVM_SPICE_BIND: hv_base.NO_CHECK, # will be checked later
416
    constants.HV_KVM_SPICE_IP_VERSION:
417
      (False, lambda x: (x == constants.IFACE_NO_IP_VERSION_SPECIFIED or
418
                         x in constants.VALID_IP_VERSIONS),
419
       "the SPICE IP version should be 4 or 6",
420
       None, None),
421
    constants.HV_KVM_SPICE_PASSWORD_FILE: hv_base.OPT_FILE_CHECK,
422
    constants.HV_KVM_SPICE_LOSSLESS_IMG_COMPR:
423
      hv_base.ParamInSet(False,
424
        constants.HT_KVM_SPICE_VALID_LOSSLESS_IMG_COMPR_OPTIONS),
425
    constants.HV_KVM_SPICE_JPEG_IMG_COMPR:
426
      hv_base.ParamInSet(False,
427
        constants.HT_KVM_SPICE_VALID_LOSSY_IMG_COMPR_OPTIONS),
428
    constants.HV_KVM_SPICE_ZLIB_GLZ_IMG_COMPR:
429
      hv_base.ParamInSet(False,
430
        constants.HT_KVM_SPICE_VALID_LOSSY_IMG_COMPR_OPTIONS),
431
    constants.HV_KVM_SPICE_STREAMING_VIDEO_DETECTION:
432
      hv_base.ParamInSet(False,
433
        constants.HT_KVM_SPICE_VALID_VIDEO_STREAM_DETECTION_OPTIONS),
434
    constants.HV_KVM_SPICE_AUDIO_COMPR: hv_base.NO_CHECK,
435
    constants.HV_KVM_SPICE_USE_TLS: hv_base.NO_CHECK,
436
    constants.HV_KVM_SPICE_TLS_CIPHERS: hv_base.NO_CHECK,
437
    constants.HV_KVM_SPICE_USE_VDAGENT: hv_base.NO_CHECK,
438
    constants.HV_KVM_FLOPPY_IMAGE_PATH: hv_base.OPT_FILE_CHECK,
439
    constants.HV_CDROM_IMAGE_PATH: hv_base.OPT_FILE_CHECK,
440
    constants.HV_KVM_CDROM2_IMAGE_PATH: hv_base.OPT_FILE_CHECK,
441
    constants.HV_BOOT_ORDER:
442
      hv_base.ParamInSet(True, constants.HT_KVM_VALID_BO_TYPES),
443
    constants.HV_NIC_TYPE:
444
      hv_base.ParamInSet(True, constants.HT_KVM_VALID_NIC_TYPES),
445
    constants.HV_DISK_TYPE:
446
      hv_base.ParamInSet(True, constants.HT_KVM_VALID_DISK_TYPES),
447
    constants.HV_KVM_CDROM_DISK_TYPE:
448
      hv_base.ParamInSet(False, constants.HT_KVM_VALID_DISK_TYPES),
449
    constants.HV_USB_MOUSE:
450
      hv_base.ParamInSet(False, constants.HT_KVM_VALID_MOUSE_TYPES),
451
    constants.HV_KEYMAP: hv_base.NO_CHECK,
452
    constants.HV_MIGRATION_PORT: hv_base.REQ_NET_PORT_CHECK,
453
    constants.HV_MIGRATION_BANDWIDTH: hv_base.NO_CHECK,
454
    constants.HV_MIGRATION_DOWNTIME: hv_base.NO_CHECK,
455
    constants.HV_MIGRATION_MODE: hv_base.MIGRATION_MODE_CHECK,
456
    constants.HV_USE_LOCALTIME: hv_base.NO_CHECK,
457
    constants.HV_DISK_CACHE:
458
      hv_base.ParamInSet(True, constants.HT_VALID_CACHE_TYPES),
459
    constants.HV_SECURITY_MODEL:
460
      hv_base.ParamInSet(True, constants.HT_KVM_VALID_SM_TYPES),
461
    constants.HV_SECURITY_DOMAIN: hv_base.NO_CHECK,
462
    constants.HV_KVM_FLAG:
463
      hv_base.ParamInSet(False, constants.HT_KVM_FLAG_VALUES),
464
    constants.HV_VHOST_NET: hv_base.NO_CHECK,
465
    constants.HV_KVM_USE_CHROOT: hv_base.NO_CHECK,
466
    constants.HV_MEM_PATH: hv_base.OPT_DIR_CHECK,
467
    constants.HV_REBOOT_BEHAVIOR:
468
      hv_base.ParamInSet(True, constants.REBOOT_BEHAVIORS)
469
    }
470

    
471
  _MIGRATION_STATUS_RE = re.compile("Migration\s+status:\s+(\w+)",
472
                                    re.M | re.I)
473
  _MIGRATION_INFO_MAX_BAD_ANSWERS = 5
474
  _MIGRATION_INFO_RETRY_DELAY = 2
475

    
476
  _VERSION_RE = re.compile(r"\b(\d+)\.(\d+)\.(\d+)\b")
477

    
478
  ANCILLARY_FILES = [
479
    _KVM_NETWORK_SCRIPT,
480
    ]
481

    
482
  def __init__(self):
483
    hv_base.BaseHypervisor.__init__(self)
484
    # Let's make sure the directories we need exist, even if the RUN_DIR lives
485
    # in a tmpfs filesystem or has been otherwise wiped out.
486
    dirs = [(dname, constants.RUN_DIRS_MODE) for dname in self._DIRS]
487
    utils.EnsureDirs(dirs)
488

    
489
  @classmethod
490
  def _InstancePidFile(cls, instance_name):
491
    """Returns the instance pidfile.
492

493
    """
494
    return utils.PathJoin(cls._PIDS_DIR, instance_name)
495

    
496
  @classmethod
497
  def _InstanceUidFile(cls, instance_name):
498
    """Returns the instance uidfile.
499

500
    """
501
    return utils.PathJoin(cls._UIDS_DIR, instance_name)
502

    
503
  @classmethod
504
  def _InstancePidInfo(cls, pid):
505
    """Check pid file for instance information.
506

507
    Check that a pid file is associated with an instance, and retrieve
508
    information from its command line.
509

510
    @type pid: string or int
511
    @param pid: process id of the instance to check
512
    @rtype: tuple
513
    @return: (instance_name, memory, vcpus)
514
    @raise errors.HypervisorError: when an instance cannot be found
515

516
    """
517
    alive = utils.IsProcessAlive(pid)
518
    if not alive:
519
      raise errors.HypervisorError("Cannot get info for pid %s" % pid)
520

    
521
    cmdline_file = utils.PathJoin("/proc", str(pid), "cmdline")
522
    try:
523
      cmdline = utils.ReadFile(cmdline_file)
524
    except EnvironmentError, err:
525
      raise errors.HypervisorError("Can't open cmdline file for pid %s: %s" %
526
                                   (pid, err))
527

    
528
    instance = None
529
    memory = 0
530
    vcpus = 0
531

    
532
    arg_list = cmdline.split("\x00")
533
    while arg_list:
534
      arg = arg_list.pop(0)
535
      if arg == "-name":
536
        instance = arg_list.pop(0)
537
      elif arg == "-m":
538
        memory = int(arg_list.pop(0))
539
      elif arg == "-smp":
540
        vcpus = int(arg_list.pop(0))
541

    
542
    if instance is None:
543
      raise errors.HypervisorError("Pid %s doesn't contain a ganeti kvm"
544
                                   " instance" % pid)
545

    
546
    return (instance, memory, vcpus)
547

    
548
  def _InstancePidAlive(self, instance_name):
549
    """Returns the instance pidfile, pid, and liveness.
550

551
    @type instance_name: string
552
    @param instance_name: instance name
553
    @rtype: tuple
554
    @return: (pid file name, pid, liveness)
555

556
    """
557
    pidfile = self._InstancePidFile(instance_name)
558
    pid = utils.ReadPidFile(pidfile)
559

    
560
    alive = False
561
    try:
562
      cmd_instance = self._InstancePidInfo(pid)[0]
563
      alive = (cmd_instance == instance_name)
564
    except errors.HypervisorError:
565
      pass
566

    
567
    return (pidfile, pid, alive)
568

    
569
  def _CheckDown(self, instance_name):
570
    """Raises an error unless the given instance is down.
571

572
    """
573
    alive = self._InstancePidAlive(instance_name)[2]
574
    if alive:
575
      raise errors.HypervisorError("Failed to start instance %s: %s" %
576
                                   (instance_name, "already running"))
577

    
578
  @classmethod
579
  def _InstanceMonitor(cls, instance_name):
580
    """Returns the instance monitor socket name
581

582
    """
583
    return utils.PathJoin(cls._CTRL_DIR, "%s.monitor" % instance_name)
584

    
585
  @classmethod
586
  def _InstanceSerial(cls, instance_name):
587
    """Returns the instance serial socket name
588

589
    """
590
    return utils.PathJoin(cls._CTRL_DIR, "%s.serial" % instance_name)
591

    
592
  @classmethod
593
  def _InstanceQmpMonitor(cls, instance_name):
594
    """Returns the instance serial QMP socket name
595

596
    """
597
    return utils.PathJoin(cls._CTRL_DIR, "%s.qmp" % instance_name)
598

    
599
  @staticmethod
600
  def _SocatUnixConsoleParams():
601
    """Returns the correct parameters for socat
602

603
    If we have a new-enough socat we can use raw mode with an escape character.
604

605
    """
606
    if constants.SOCAT_USE_ESCAPE:
607
      return "raw,echo=0,escape=%s" % constants.SOCAT_ESCAPE_CODE
608
    else:
609
      return "echo=0,icanon=0"
610

    
611
  @classmethod
612
  def _InstanceKVMRuntime(cls, instance_name):
613
    """Returns the instance KVM runtime filename
614

615
    """
616
    return utils.PathJoin(cls._CONF_DIR, "%s.runtime" % instance_name)
617

    
618
  @classmethod
619
  def _InstanceChrootDir(cls, instance_name):
620
    """Returns the name of the KVM chroot dir of the instance
621

622
    """
623
    return utils.PathJoin(cls._CHROOT_DIR, instance_name)
624

    
625
  @classmethod
626
  def _InstanceNICDir(cls, instance_name):
627
    """Returns the name of the directory holding the tap device files for a
628
    given instance.
629

630
    """
631
    return utils.PathJoin(cls._NICS_DIR, instance_name)
632

    
633
  @classmethod
634
  def _InstanceNICFile(cls, instance_name, seq):
635
    """Returns the name of the file containing the tap device for a given NIC
636

637
    """
638
    return utils.PathJoin(cls._InstanceNICDir(instance_name), str(seq))
639

    
640
  @classmethod
641
  def _InstanceKeymapFile(cls, instance_name):
642
    """Returns the name of the file containing the keymap for a given instance
643

644
    """
645
    return utils.PathJoin(cls._KEYMAP_DIR, instance_name)
646

    
647
  @classmethod
648
  def _TryReadUidFile(cls, uid_file):
649
    """Try to read a uid file
650

651
    """
652
    if os.path.exists(uid_file):
653
      try:
654
        uid = int(utils.ReadOneLineFile(uid_file))
655
        return uid
656
      except EnvironmentError:
657
        logging.warning("Can't read uid file", exc_info=True)
658
      except (TypeError, ValueError):
659
        logging.warning("Can't parse uid file contents", exc_info=True)
660
    return None
661

    
662
  @classmethod
663
  def _RemoveInstanceRuntimeFiles(cls, pidfile, instance_name):
664
    """Removes an instance's rutime sockets/files/dirs.
665

666
    """
667
    utils.RemoveFile(pidfile)
668
    utils.RemoveFile(cls._InstanceMonitor(instance_name))
669
    utils.RemoveFile(cls._InstanceSerial(instance_name))
670
    utils.RemoveFile(cls._InstanceQmpMonitor(instance_name))
671
    utils.RemoveFile(cls._InstanceKVMRuntime(instance_name))
672
    utils.RemoveFile(cls._InstanceKeymapFile(instance_name))
673
    uid_file = cls._InstanceUidFile(instance_name)
674
    uid = cls._TryReadUidFile(uid_file)
675
    utils.RemoveFile(uid_file)
676
    if uid is not None:
677
      uidpool.ReleaseUid(uid)
678
    try:
679
      shutil.rmtree(cls._InstanceNICDir(instance_name))
680
    except OSError, err:
681
      if err.errno != errno.ENOENT:
682
        raise
683
    try:
684
      chroot_dir = cls._InstanceChrootDir(instance_name)
685
      utils.RemoveDir(chroot_dir)
686
    except OSError, err:
687
      if err.errno == errno.ENOTEMPTY:
688
        # The chroot directory is expected to be empty, but it isn't.
689
        new_chroot_dir = tempfile.mkdtemp(dir=cls._CHROOT_QUARANTINE_DIR,
690
                                          prefix="%s-%s-" %
691
                                          (instance_name,
692
                                           utils.TimestampForFilename()))
693
        logging.warning("The chroot directory of instance %s can not be"
694
                        " removed as it is not empty. Moving it to the"
695
                        " quarantine instead. Please investigate the"
696
                        " contents (%s) and clean up manually",
697
                        instance_name, new_chroot_dir)
698
        utils.RenameFile(chroot_dir, new_chroot_dir)
699
      else:
700
        raise
701

    
702
  @staticmethod
703
  def _ConfigureNIC(instance, seq, nic, tap):
704
    """Run the network configuration script for a specified NIC
705

706
    @param instance: instance we're acting on
707
    @type instance: instance object
708
    @param seq: nic sequence number
709
    @type seq: int
710
    @param nic: nic we're acting on
711
    @type nic: nic object
712
    @param tap: the host's tap interface this NIC corresponds to
713
    @type tap: str
714

715
    """
716

    
717
    if instance.tags:
718
      tags = " ".join(instance.tags)
719
    else:
720
      tags = ""
721

    
722
    env = {
723
      "PATH": "%s:/sbin:/usr/sbin" % os.environ["PATH"],
724
      "INSTANCE": instance.name,
725
      "MAC": nic.mac,
726
      "MODE": nic.nicparams[constants.NIC_MODE],
727
      "INTERFACE": tap,
728
      "INTERFACE_INDEX": str(seq),
729
      "TAGS": tags,
730
    }
731

    
732
    if nic.ip:
733
      env["IP"] = nic.ip
734

    
735
    if nic.nicparams[constants.NIC_LINK]:
736
      env["LINK"] = nic.nicparams[constants.NIC_LINK]
737

    
738
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
739
      env["BRIDGE"] = nic.nicparams[constants.NIC_LINK]
740

    
741
    result = utils.RunCmd([constants.KVM_IFUP, tap], env=env)
742
    if result.failed:
743
      raise errors.HypervisorError("Failed to configure interface %s: %s."
744
                                   " Network configuration script output: %s" %
745
                                   (tap, result.fail_reason, result.output))
746

    
747
  def ListInstances(self):
748
    """Get the list of running instances.
749

750
    We can do this by listing our live instances directory and
751
    checking whether the associated kvm process is still alive.
752

753
    """
754
    result = []
755
    for name in os.listdir(self._PIDS_DIR):
756
      if self._InstancePidAlive(name)[2]:
757
        result.append(name)
758
    return result
759

    
760
  def GetInstanceInfo(self, instance_name):
761
    """Get instance properties.
762

763
    @type instance_name: string
764
    @param instance_name: the instance name
765
    @rtype: tuple of strings
766
    @return: (name, id, memory, vcpus, stat, times)
767

768
    """
769
    _, pid, alive = self._InstancePidAlive(instance_name)
770
    if not alive:
771
      return None
772

    
773
    _, memory, vcpus = self._InstancePidInfo(pid)
774
    stat = "---b-"
775
    times = "0"
776

    
777
    return (instance_name, pid, memory, vcpus, stat, times)
778

    
779
  def GetAllInstancesInfo(self):
780
    """Get properties of all instances.
781

782
    @return: list of tuples (name, id, memory, vcpus, stat, times)
783

784
    """
785
    data = []
786
    for name in os.listdir(self._PIDS_DIR):
787
      try:
788
        info = self.GetInstanceInfo(name)
789
      except errors.HypervisorError:
790
        continue
791
      if info:
792
        data.append(info)
793
    return data
794

    
795
  def _GenerateKVMRuntime(self, instance, block_devices, startup_paused):
796
    """Generate KVM information to start an instance.
797

798
    """
799
    # pylint: disable=R0914,R0915
800
    _, v_major, v_min, _ = self._GetKVMVersion()
801

    
802
    pidfile = self._InstancePidFile(instance.name)
803
    kvm = constants.KVM_PATH
804
    kvm_cmd = [kvm]
805
    # used just by the vnc server, if enabled
806
    kvm_cmd.extend(["-name", instance.name])
807
    kvm_cmd.extend(["-m", instance.beparams[constants.BE_MEMORY]])
808
    kvm_cmd.extend(["-smp", instance.beparams[constants.BE_VCPUS]])
809
    kvm_cmd.extend(["-pidfile", pidfile])
810
    kvm_cmd.extend(["-daemonize"])
811
    if not instance.hvparams[constants.HV_ACPI]:
812
      kvm_cmd.extend(["-no-acpi"])
813
    if startup_paused:
814
      kvm_cmd.extend(["-S"])
815
    if instance.hvparams[constants.HV_REBOOT_BEHAVIOR] == \
816
        constants.INSTANCE_REBOOT_EXIT:
817
      kvm_cmd.extend(["-no-reboot"])
818

    
819
    hvp = instance.hvparams
820
    boot_disk = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_DISK
821
    boot_cdrom = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_CDROM
822
    boot_floppy = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_FLOPPY
823
    boot_network = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_NETWORK
824

    
825
    self.ValidateParameters(hvp)
826

    
827
    if hvp[constants.HV_KVM_FLAG] == constants.HT_KVM_ENABLED:
828
      kvm_cmd.extend(["-enable-kvm"])
829
    elif hvp[constants.HV_KVM_FLAG] == constants.HT_KVM_DISABLED:
830
      kvm_cmd.extend(["-disable-kvm"])
831

    
832
    if boot_network:
833
      kvm_cmd.extend(["-boot", "n"])
834

    
835
    disk_type = hvp[constants.HV_DISK_TYPE]
836
    if disk_type == constants.HT_DISK_PARAVIRTUAL:
837
      if_val = ",if=virtio"
838
    else:
839
      if_val = ",if=%s" % disk_type
840
    # Cache mode
841
    disk_cache = hvp[constants.HV_DISK_CACHE]
842
    if instance.disk_template in constants.DTS_EXT_MIRROR:
843
      if disk_cache != "none":
844
        # TODO: make this a hard error, instead of a silent overwrite
845
        logging.warning("KVM: overriding disk_cache setting '%s' with 'none'"
846
                        " to prevent shared storage corruption on migration",
847
                        disk_cache)
848
      cache_val = ",cache=none"
849
    elif disk_cache != constants.HT_CACHE_DEFAULT:
850
      cache_val = ",cache=%s" % disk_cache
851
    else:
852
      cache_val = ""
853
    for cfdev, dev_path in block_devices:
854
      if cfdev.mode != constants.DISK_RDWR:
855
        raise errors.HypervisorError("Instance has read-only disks which"
856
                                     " are not supported by KVM")
857
      # TODO: handle FD_LOOP and FD_BLKTAP (?)
858
      boot_val = ""
859
      if boot_disk:
860
        kvm_cmd.extend(["-boot", "c"])
861
        boot_disk = False
862
        if (v_major, v_min) < (0, 14) and disk_type != constants.HT_DISK_IDE:
863
          boot_val = ",boot=on"
864

    
865
      drive_val = "file=%s,format=raw%s%s%s" % (dev_path, if_val, boot_val,
866
                                                cache_val)
867
      kvm_cmd.extend(["-drive", drive_val])
868

    
869
    #Now we can specify a different device type for CDROM devices.
870
    cdrom_disk_type = hvp[constants.HV_KVM_CDROM_DISK_TYPE]
871
    if not cdrom_disk_type:
872
      cdrom_disk_type = disk_type
873

    
874
    iso_image = hvp[constants.HV_CDROM_IMAGE_PATH]
875
    if iso_image:
876
      options = ",format=raw,media=cdrom"
877
      if boot_cdrom:
878
        kvm_cmd.extend(["-boot", "d"])
879
        if cdrom_disk_type != constants.HT_DISK_IDE:
880
          options = "%s,boot=on,if=%s" % (options, constants.HT_DISK_IDE)
881
        else:
882
          options = "%s,boot=on" % options
883
      else:
884
        if cdrom_disk_type == constants.HT_DISK_PARAVIRTUAL:
885
          if_val = ",if=virtio"
886
        else:
887
          if_val = ",if=%s" % cdrom_disk_type
888
        options = "%s%s" % (options, if_val)
889
      drive_val = "file=%s%s" % (iso_image, options)
890
      kvm_cmd.extend(["-drive", drive_val])
891

    
892
    iso_image2 = hvp[constants.HV_KVM_CDROM2_IMAGE_PATH]
893
    if iso_image2:
894
      options = ",format=raw,media=cdrom"
895
      if cdrom_disk_type == constants.HT_DISK_PARAVIRTUAL:
896
        if_val = ",if=virtio"
897
      else:
898
        if_val = ",if=%s" % cdrom_disk_type
899
      options = "%s%s" % (options, if_val)
900
      drive_val = "file=%s%s" % (iso_image2, options)
901
      kvm_cmd.extend(["-drive", drive_val])
902

    
903
    floppy_image = hvp[constants.HV_KVM_FLOPPY_IMAGE_PATH]
904
    if floppy_image:
905
      options = ",format=raw,media=disk"
906
      if boot_floppy:
907
        kvm_cmd.extend(["-boot", "a"])
908
        options = "%s,boot=on" % options
909
      if_val = ",if=floppy"
910
      options = "%s%s" % (options, if_val)
911
      drive_val = "file=%s%s" % (floppy_image, options)
912
      kvm_cmd.extend(["-drive", drive_val])
913

    
914
    kernel_path = hvp[constants.HV_KERNEL_PATH]
915
    if kernel_path:
916
      kvm_cmd.extend(["-kernel", kernel_path])
917
      initrd_path = hvp[constants.HV_INITRD_PATH]
918
      if initrd_path:
919
        kvm_cmd.extend(["-initrd", initrd_path])
920
      root_append = ["root=%s" % hvp[constants.HV_ROOT_PATH],
921
                     hvp[constants.HV_KERNEL_ARGS]]
922
      if hvp[constants.HV_SERIAL_CONSOLE]:
923
        root_append.append("console=ttyS0,38400")
924
      kvm_cmd.extend(["-append", " ".join(root_append)])
925

    
926
    mem_path = hvp[constants.HV_MEM_PATH]
927
    if mem_path:
928
      kvm_cmd.extend(["-mem-path", mem_path, "-mem-prealloc"])
929

    
930
    mouse_type = hvp[constants.HV_USB_MOUSE]
931
    vnc_bind_address = hvp[constants.HV_VNC_BIND_ADDRESS]
932

    
933
    if mouse_type:
934
      kvm_cmd.extend(["-usb"])
935
      kvm_cmd.extend(["-usbdevice", mouse_type])
936
    elif vnc_bind_address:
937
      kvm_cmd.extend(["-usbdevice", constants.HT_MOUSE_TABLET])
938

    
939
    keymap = hvp[constants.HV_KEYMAP]
940
    if keymap:
941
      keymap_path = self._InstanceKeymapFile(instance.name)
942
      # If a keymap file is specified, KVM won't use its internal defaults. By
943
      # first including the "en-us" layout, an error on loading the actual
944
      # layout (e.g. because it can't be found) won't lead to a non-functional
945
      # keyboard. A keyboard with incorrect keys is still better than none.
946
      utils.WriteFile(keymap_path, data="include en-us\ninclude %s\n" % keymap)
947
      kvm_cmd.extend(["-k", keymap_path])
948

    
949
    if vnc_bind_address:
950
      if netutils.IP4Address.IsValid(vnc_bind_address):
951
        if instance.network_port > constants.VNC_BASE_PORT:
952
          display = instance.network_port - constants.VNC_BASE_PORT
953
          if vnc_bind_address == constants.IP4_ADDRESS_ANY:
954
            vnc_arg = ":%d" % (display)
955
          else:
956
            vnc_arg = "%s:%d" % (vnc_bind_address, display)
957
        else:
958
          logging.error("Network port is not a valid VNC display (%d < %d)."
959
                        " Not starting VNC", instance.network_port,
960
                        constants.VNC_BASE_PORT)
961
          vnc_arg = "none"
962

    
963
        # Only allow tls and other option when not binding to a file, for now.
964
        # kvm/qemu gets confused otherwise about the filename to use.
965
        vnc_append = ""
966
        if hvp[constants.HV_VNC_TLS]:
967
          vnc_append = "%s,tls" % vnc_append
968
          if hvp[constants.HV_VNC_X509_VERIFY]:
969
            vnc_append = "%s,x509verify=%s" % (vnc_append,
970
                                               hvp[constants.HV_VNC_X509])
971
          elif hvp[constants.HV_VNC_X509]:
972
            vnc_append = "%s,x509=%s" % (vnc_append,
973
                                         hvp[constants.HV_VNC_X509])
974
        if hvp[constants.HV_VNC_PASSWORD_FILE]:
975
          vnc_append = "%s,password" % vnc_append
976

    
977
        vnc_arg = "%s%s" % (vnc_arg, vnc_append)
978

    
979
      else:
980
        vnc_arg = "unix:%s/%s.vnc" % (vnc_bind_address, instance.name)
981

    
982
      kvm_cmd.extend(["-vnc", vnc_arg])
983
    else:
984
      kvm_cmd.extend(["-nographic"])
985

    
986
    monitor_dev = ("unix:%s,server,nowait" %
987
                   self._InstanceMonitor(instance.name))
988
    kvm_cmd.extend(["-monitor", monitor_dev])
989
    if hvp[constants.HV_SERIAL_CONSOLE]:
990
      serial_dev = ("unix:%s,server,nowait" %
991
                    self._InstanceSerial(instance.name))
992
      kvm_cmd.extend(["-serial", serial_dev])
993
    else:
994
      kvm_cmd.extend(["-serial", "none"])
995

    
996
    spice_bind = hvp[constants.HV_KVM_SPICE_BIND]
997
    spice_ip_version = None
998
    if spice_bind:
999
      if netutils.IsValidInterface(spice_bind):
1000
        # The user specified a network interface, we have to figure out the IP
1001
        # address.
1002
        addresses = netutils.GetInterfaceIpAddresses(spice_bind)
1003
        spice_ip_version = hvp[constants.HV_KVM_SPICE_IP_VERSION]
1004

    
1005
        # if the user specified an IP version and the interface does not
1006
        # have that kind of IP addresses, throw an exception
1007
        if spice_ip_version != constants.IFACE_NO_IP_VERSION_SPECIFIED:
1008
          if not addresses[spice_ip_version]:
1009
            raise errors.HypervisorError("spice: unable to get an IPv%s address"
1010
                                         " for %s" % (spice_ip_version,
1011
                                                      spice_bind))
1012

    
1013
        # the user did not specify an IP version, we have to figure it out
1014
        elif (addresses[constants.IP4_VERSION] and
1015
              addresses[constants.IP6_VERSION]):
1016
          # we have both ipv4 and ipv6, let's use the cluster default IP
1017
          # version
1018
          cluster_family = ssconf.SimpleStore().GetPrimaryIPFamily()
1019
          spice_ip_version = netutils.IPAddress.GetVersionFromAddressFamily(
1020
              cluster_family)
1021
        elif addresses[constants.IP4_VERSION]:
1022
          spice_ip_version = constants.IP4_VERSION
1023
        elif addresses[constants.IP6_VERSION]:
1024
          spice_ip_version = constants.IP6_VERSION
1025
        else:
1026
          raise errors.HypervisorError("spice: unable to get an IP address"
1027
                                       " for %s" % (spice_bind))
1028

    
1029
        spice_address = addresses[spice_ip_version][0]
1030

    
1031
      else:
1032
        # spice_bind is known to be a valid IP address, because
1033
        # ValidateParameters checked it.
1034
        spice_address = spice_bind
1035

    
1036
      spice_arg = "addr=%s" % spice_address
1037
      if hvp[constants.HV_KVM_SPICE_USE_TLS]:
1038
        spice_arg = "%s,tls-port=%s,x509-cacert-file=%s" % (spice_arg,
1039
            instance.network_port, constants.SPICE_CACERT_FILE)
1040
        spice_arg = "%s,x509-key-file=%s,x509-cert-file=%s" % (spice_arg,
1041
            constants.SPICE_CERT_FILE, constants.SPICE_CERT_FILE)
1042
        tls_ciphers = hvp[constants.HV_KVM_SPICE_TLS_CIPHERS]
1043
        if tls_ciphers:
1044
          spice_arg = "%s,tls-ciphers=%s" % (spice_arg, tls_ciphers)
1045
      else:
1046
        spice_arg = "%s,port=%s" % (spice_arg, instance.network_port)
1047

    
1048
      if not hvp[constants.HV_KVM_SPICE_PASSWORD_FILE]:
1049
        spice_arg = "%s,disable-ticketing" % spice_arg
1050

    
1051
      if spice_ip_version:
1052
        spice_arg = "%s,ipv%s" % (spice_arg, spice_ip_version)
1053

    
1054
      # Image compression options
1055
      img_lossless = hvp[constants.HV_KVM_SPICE_LOSSLESS_IMG_COMPR]
1056
      img_jpeg = hvp[constants.HV_KVM_SPICE_JPEG_IMG_COMPR]
1057
      img_zlib_glz = hvp[constants.HV_KVM_SPICE_ZLIB_GLZ_IMG_COMPR]
1058
      if img_lossless:
1059
        spice_arg = "%s,image-compression=%s" % (spice_arg, img_lossless)
1060
      if img_jpeg:
1061
        spice_arg = "%s,jpeg-wan-compression=%s" % (spice_arg, img_jpeg)
1062
      if img_zlib_glz:
1063
        spice_arg = "%s,zlib-glz-wan-compression=%s" % (spice_arg, img_zlib_glz)
1064

    
1065
      # Video stream detection
1066
      video_streaming = hvp[constants.HV_KVM_SPICE_STREAMING_VIDEO_DETECTION]
1067
      if video_streaming:
1068
        spice_arg = "%s,streaming-video=%s" % (spice_arg, video_streaming)
1069

    
1070
      # Audio compression, by default in qemu-kvm it is on
1071
      if not hvp[constants.HV_KVM_SPICE_AUDIO_COMPR]:
1072
        spice_arg = "%s,playback-compression=off" % spice_arg
1073
      if not hvp[constants.HV_KVM_SPICE_USE_VDAGENT]:
1074
        spice_arg = "%s,agent-mouse=off" % spice_arg
1075

    
1076
      logging.info("KVM: SPICE will listen on port %s", instance.network_port)
1077
      kvm_cmd.extend(["-spice", spice_arg])
1078

    
1079
      # Tell kvm to use the paravirtualized graphic card, optimized for SPICE
1080
      kvm_cmd.extend(["-vga", "qxl"])
1081

    
1082
    if hvp[constants.HV_USE_LOCALTIME]:
1083
      kvm_cmd.extend(["-localtime"])
1084

    
1085
    if hvp[constants.HV_KVM_USE_CHROOT]:
1086
      kvm_cmd.extend(["-chroot", self._InstanceChrootDir(instance.name)])
1087

    
1088
    # Save the current instance nics, but defer their expansion as parameters,
1089
    # as we'll need to generate executable temp files for them.
1090
    kvm_nics = instance.nics
1091
    hvparams = hvp
1092

    
1093
    return (kvm_cmd, kvm_nics, hvparams)
1094

    
1095
  def _WriteKVMRuntime(self, instance_name, data):
1096
    """Write an instance's KVM runtime
1097

1098
    """
1099
    try:
1100
      utils.WriteFile(self._InstanceKVMRuntime(instance_name),
1101
                      data=data)
1102
    except EnvironmentError, err:
1103
      raise errors.HypervisorError("Failed to save KVM runtime file: %s" % err)
1104

    
1105
  def _ReadKVMRuntime(self, instance_name):
1106
    """Read an instance's KVM runtime
1107

1108
    """
1109
    try:
1110
      file_content = utils.ReadFile(self._InstanceKVMRuntime(instance_name))
1111
    except EnvironmentError, err:
1112
      raise errors.HypervisorError("Failed to load KVM runtime file: %s" % err)
1113
    return file_content
1114

    
1115
  def _SaveKVMRuntime(self, instance, kvm_runtime):
1116
    """Save an instance's KVM runtime
1117

1118
    """
1119
    kvm_cmd, kvm_nics, hvparams = kvm_runtime
1120
    serialized_nics = [nic.ToDict() for nic in kvm_nics]
1121
    serialized_form = serializer.Dump((kvm_cmd, serialized_nics, hvparams))
1122
    self._WriteKVMRuntime(instance.name, serialized_form)
1123

    
1124
  def _LoadKVMRuntime(self, instance, serialized_runtime=None):
1125
    """Load an instance's KVM runtime
1126

1127
    """
1128
    if not serialized_runtime:
1129
      serialized_runtime = self._ReadKVMRuntime(instance.name)
1130
    loaded_runtime = serializer.Load(serialized_runtime)
1131
    kvm_cmd, serialized_nics, hvparams = loaded_runtime
1132
    kvm_nics = [objects.NIC.FromDict(snic) for snic in serialized_nics]
1133
    return (kvm_cmd, kvm_nics, hvparams)
1134

    
1135
  def _RunKVMCmd(self, name, kvm_cmd, tap_fds=None):
1136
    """Run the KVM cmd and check for errors
1137

1138
    @type name: string
1139
    @param name: instance name
1140
    @type kvm_cmd: list of strings
1141
    @param kvm_cmd: runcmd input for kvm
1142
    @type tap_fds: list of int
1143
    @param tap_fds: fds of tap devices opened by Ganeti
1144

1145
    """
1146
    try:
1147
      result = utils.RunCmd(kvm_cmd, noclose_fds=tap_fds)
1148
    finally:
1149
      for fd in tap_fds:
1150
        utils_wrapper.CloseFdNoError(fd)
1151

    
1152
    if result.failed:
1153
      raise errors.HypervisorError("Failed to start instance %s: %s (%s)" %
1154
                                   (name, result.fail_reason, result.output))
1155
    if not self._InstancePidAlive(name)[2]:
1156
      raise errors.HypervisorError("Failed to start instance %s" % name)
1157

    
1158
  def _ExecuteKVMRuntime(self, instance, kvm_runtime, incoming=None):
1159
    """Execute a KVM cmd, after completing it with some last minute data
1160

1161
    @type incoming: tuple of strings
1162
    @param incoming: (target_host_ip, port)
1163

1164
    """
1165
    # Small _ExecuteKVMRuntime hv parameters programming howto:
1166
    #  - conf_hvp contains the parameters as configured on ganeti. they might
1167
    #    have changed since the instance started; only use them if the change
1168
    #    won't affect the inside of the instance (which hasn't been rebooted).
1169
    #  - up_hvp contains the parameters as they were when the instance was
1170
    #    started, plus any new parameter which has been added between ganeti
1171
    #    versions: it is paramount that those default to a value which won't
1172
    #    affect the inside of the instance as well.
1173
    conf_hvp = instance.hvparams
1174
    name = instance.name
1175
    self._CheckDown(name)
1176

    
1177
    temp_files = []
1178

    
1179
    kvm_cmd, kvm_nics, up_hvp = kvm_runtime
1180
    up_hvp = objects.FillDict(conf_hvp, up_hvp)
1181

    
1182
    _, v_major, v_min, _ = self._GetKVMVersion()
1183

    
1184
    # We know it's safe to run as a different user upon migration, so we'll use
1185
    # the latest conf, from conf_hvp.
1186
    security_model = conf_hvp[constants.HV_SECURITY_MODEL]
1187
    if security_model == constants.HT_SM_USER:
1188
      kvm_cmd.extend(["-runas", conf_hvp[constants.HV_SECURITY_DOMAIN]])
1189

    
1190
    # We have reasons to believe changing something like the nic driver/type
1191
    # upon migration won't exactly fly with the instance kernel, so for nic
1192
    # related parameters we'll use up_hvp
1193
    tapfds = []
1194
    taps = []
1195
    if not kvm_nics:
1196
      kvm_cmd.extend(["-net", "none"])
1197
    else:
1198
      vnet_hdr = False
1199
      tap_extra = ""
1200
      nic_type = up_hvp[constants.HV_NIC_TYPE]
1201
      if nic_type == constants.HT_NIC_PARAVIRTUAL:
1202
        # From version 0.12.0, kvm uses a new sintax for network configuration.
1203
        if (v_major, v_min) >= (0, 12):
1204
          nic_model = "virtio-net-pci"
1205
          vnet_hdr = True
1206
        else:
1207
          nic_model = "virtio"
1208

    
1209
        if up_hvp[constants.HV_VHOST_NET]:
1210
          # vhost_net is only available from version 0.13.0 or newer
1211
          if (v_major, v_min) >= (0, 13):
1212
            tap_extra = ",vhost=on"
1213
          else:
1214
            raise errors.HypervisorError("vhost_net is configured"
1215
                                        " but it is not available")
1216
      else:
1217
        nic_model = nic_type
1218

    
1219
      for nic_seq, nic in enumerate(kvm_nics):
1220
        tapname, tapfd = _OpenTap(vnet_hdr)
1221
        tapfds.append(tapfd)
1222
        taps.append(tapname)
1223
        if (v_major, v_min) >= (0, 12):
1224
          nic_val = "%s,mac=%s,netdev=netdev%s" % (nic_model, nic.mac, nic_seq)
1225
          tap_val = "type=tap,id=netdev%s,fd=%d%s" % (nic_seq, tapfd, tap_extra)
1226
          kvm_cmd.extend(["-netdev", tap_val, "-device", nic_val])
1227
        else:
1228
          nic_val = "nic,vlan=%s,macaddr=%s,model=%s" % (nic_seq,
1229
                                                         nic.mac, nic_model)
1230
          tap_val = "tap,vlan=%s,fd=%d" % (nic_seq, tapfd)
1231
          kvm_cmd.extend(["-net", tap_val, "-net", nic_val])
1232

    
1233
    if incoming:
1234
      target, port = incoming
1235
      kvm_cmd.extend(["-incoming", "tcp:%s:%s" % (target, port)])
1236

    
1237
    # Changing the vnc password doesn't bother the guest that much. At most it
1238
    # will surprise people who connect to it. Whether positively or negatively
1239
    # it's debatable.
1240
    vnc_pwd_file = conf_hvp[constants.HV_VNC_PASSWORD_FILE]
1241
    vnc_pwd = None
1242
    if vnc_pwd_file:
1243
      try:
1244
        vnc_pwd = utils.ReadOneLineFile(vnc_pwd_file, strict=True)
1245
      except EnvironmentError, err:
1246
        raise errors.HypervisorError("Failed to open VNC password file %s: %s"
1247
                                     % (vnc_pwd_file, err))
1248

    
1249
    if conf_hvp[constants.HV_KVM_USE_CHROOT]:
1250
      utils.EnsureDirs([(self._InstanceChrootDir(name),
1251
                         constants.SECURE_DIR_MODE)])
1252

    
1253
    # Automatically enable QMP if version is >= 0.14
1254
    if (v_major, v_min) >= (0, 14):
1255
      logging.debug("Enabling QMP")
1256
      kvm_cmd.extend(["-qmp", "unix:%s,server,nowait" %
1257
                    self._InstanceQmpMonitor(instance.name)])
1258

    
1259
    # Configure the network now for starting instances and bridged interfaces,
1260
    # during FinalizeMigration for incoming instances' routed interfaces
1261
    for nic_seq, nic in enumerate(kvm_nics):
1262
      if (incoming and
1263
          nic.nicparams[constants.NIC_MODE] != constants.NIC_MODE_BRIDGED):
1264
        continue
1265
      self._ConfigureNIC(instance, nic_seq, nic, taps[nic_seq])
1266

    
1267
    if security_model == constants.HT_SM_POOL:
1268
      ss = ssconf.SimpleStore()
1269
      uid_pool = uidpool.ParseUidPool(ss.GetUidPool(), separator="\n")
1270
      all_uids = set(uidpool.ExpandUidPool(uid_pool))
1271
      uid = uidpool.RequestUnusedUid(all_uids)
1272
      try:
1273
        username = pwd.getpwuid(uid.GetUid()).pw_name
1274
        kvm_cmd.extend(["-runas", username])
1275
        self._RunKVMCmd(name, kvm_cmd, tapfds)
1276
      except:
1277
        uidpool.ReleaseUid(uid)
1278
        raise
1279
      else:
1280
        uid.Unlock()
1281
        utils.WriteFile(self._InstanceUidFile(name), data=uid.AsStr())
1282
    else:
1283
      self._RunKVMCmd(name, kvm_cmd, tapfds)
1284

    
1285
    utils.EnsureDirs([(self._InstanceNICDir(instance.name),
1286
                     constants.RUN_DIRS_MODE)])
1287
    for nic_seq, tap in enumerate(taps):
1288
      utils.WriteFile(self._InstanceNICFile(instance.name, nic_seq),
1289
                      data=tap)
1290

    
1291
    if vnc_pwd:
1292
      change_cmd = "change vnc password %s" % vnc_pwd
1293
      self._CallMonitorCommand(instance.name, change_cmd)
1294

    
1295
    # Setting SPICE password. We are not vulnerable to malicious passwordless
1296
    # connection attempts because SPICE by default does not allow connections
1297
    # if neither a password nor the "disable_ticketing" options are specified.
1298
    # As soon as we send the password via QMP, that password is a valid ticket
1299
    # for connection.
1300
    spice_password_file = conf_hvp[constants.HV_KVM_SPICE_PASSWORD_FILE]
1301
    if spice_password_file:
1302
      try:
1303
        spice_pwd = utils.ReadOneLineFile(spice_password_file, strict=True)
1304
        qmp = QmpConnection(self._InstanceQmpMonitor(instance.name))
1305
        qmp.connect()
1306
        arguments = {
1307
            "protocol": "spice",
1308
            "password": spice_pwd,
1309
        }
1310
        qmp.Execute("set_password", arguments)
1311
      except EnvironmentError, err:
1312
        raise errors.HypervisorError("Failed to open SPICE password file %s: %s"
1313
                                     % (spice_password_file, err))
1314

    
1315
    for filename in temp_files:
1316
      utils.RemoveFile(filename)
1317

    
1318
  def StartInstance(self, instance, block_devices, startup_paused):
1319
    """Start an instance.
1320

1321
    """
1322
    self._CheckDown(instance.name)
1323
    kvm_runtime = self._GenerateKVMRuntime(instance, block_devices,
1324
                                           startup_paused)
1325
    self._SaveKVMRuntime(instance, kvm_runtime)
1326
    self._ExecuteKVMRuntime(instance, kvm_runtime)
1327

    
1328
  def _CallMonitorCommand(self, instance_name, command):
1329
    """Invoke a command on the instance monitor.
1330

1331
    """
1332
    socat = ("echo %s | %s STDIO UNIX-CONNECT:%s" %
1333
             (utils.ShellQuote(command),
1334
              constants.SOCAT_PATH,
1335
              utils.ShellQuote(self._InstanceMonitor(instance_name))))
1336
    result = utils.RunCmd(socat)
1337
    if result.failed:
1338
      msg = ("Failed to send command '%s' to instance %s."
1339
             " output: %s, error: %s, fail_reason: %s" %
1340
             (command, instance_name,
1341
              result.stdout, result.stderr, result.fail_reason))
1342
      raise errors.HypervisorError(msg)
1343

    
1344
    return result
1345

    
1346
  @classmethod
1347
  def _GetKVMVersion(cls):
1348
    """Return the installed KVM version.
1349

1350
    @return: (version, v_maj, v_min, v_rev)
1351
    @raise L{errors.HypervisorError}: when the KVM version cannot be retrieved
1352

1353
    """
1354
    result = utils.RunCmd([constants.KVM_PATH, "--help"])
1355
    if result.failed:
1356
      raise errors.HypervisorError("Unable to get KVM version")
1357
    match = cls._VERSION_RE.search(result.output.splitlines()[0])
1358
    if not match:
1359
      raise errors.HypervisorError("Unable to get KVM version")
1360

    
1361
    return (match.group(0), int(match.group(1)), int(match.group(2)),
1362
            int(match.group(3)))
1363

    
1364
  def StopInstance(self, instance, force=False, retry=False, name=None):
1365
    """Stop an instance.
1366

1367
    """
1368
    if name is not None and not force:
1369
      raise errors.HypervisorError("Cannot shutdown cleanly by name only")
1370
    if name is None:
1371
      name = instance.name
1372
      acpi = instance.hvparams[constants.HV_ACPI]
1373
    else:
1374
      acpi = False
1375
    _, pid, alive = self._InstancePidAlive(name)
1376
    if pid > 0 and alive:
1377
      if force or not acpi:
1378
        utils.KillProcess(pid)
1379
      else:
1380
        self._CallMonitorCommand(name, "system_powerdown")
1381

    
1382
  def CleanupInstance(self, instance_name):
1383
    """Cleanup after a stopped instance
1384

1385
    """
1386
    pidfile, pid, alive = self._InstancePidAlive(instance_name)
1387
    if pid > 0 and alive:
1388
      raise errors.HypervisorError("Cannot cleanup a live instance")
1389
    self._RemoveInstanceRuntimeFiles(pidfile, instance_name)
1390

    
1391
  def RebootInstance(self, instance):
1392
    """Reboot an instance.
1393

1394
    """
1395
    # For some reason if we do a 'send-key ctrl-alt-delete' to the control
1396
    # socket the instance will stop, but now power up again. So we'll resort
1397
    # to shutdown and restart.
1398
    _, _, alive = self._InstancePidAlive(instance.name)
1399
    if not alive:
1400
      raise errors.HypervisorError("Failed to reboot instance %s:"
1401
                                   " not running" % instance.name)
1402
    # StopInstance will delete the saved KVM runtime so:
1403
    # ...first load it...
1404
    kvm_runtime = self._LoadKVMRuntime(instance)
1405
    # ...now we can safely call StopInstance...
1406
    if not self.StopInstance(instance):
1407
      self.StopInstance(instance, force=True)
1408
    # ...and finally we can save it again, and execute it...
1409
    self._SaveKVMRuntime(instance, kvm_runtime)
1410
    self._ExecuteKVMRuntime(instance, kvm_runtime)
1411

    
1412
  def MigrationInfo(self, instance):
1413
    """Get instance information to perform a migration.
1414

1415
    @type instance: L{objects.Instance}
1416
    @param instance: instance to be migrated
1417
    @rtype: string
1418
    @return: content of the KVM runtime file
1419

1420
    """
1421
    return self._ReadKVMRuntime(instance.name)
1422

    
1423
  def AcceptInstance(self, instance, info, target):
1424
    """Prepare to accept an instance.
1425

1426
    @type instance: L{objects.Instance}
1427
    @param instance: instance to be accepted
1428
    @type info: string
1429
    @param info: content of the KVM runtime file on the source node
1430
    @type target: string
1431
    @param target: target host (usually ip), on this node
1432

1433
    """
1434
    kvm_runtime = self._LoadKVMRuntime(instance, serialized_runtime=info)
1435
    incoming_address = (target, instance.hvparams[constants.HV_MIGRATION_PORT])
1436
    self._ExecuteKVMRuntime(instance, kvm_runtime, incoming=incoming_address)
1437

    
1438
  def FinalizeMigration(self, instance, info, success):
1439
    """Finalize an instance migration.
1440

1441
    Stop the incoming mode KVM.
1442

1443
    @type instance: L{objects.Instance}
1444
    @param instance: instance whose migration is being finalized
1445

1446
    """
1447
    if success:
1448
      kvm_runtime = self._LoadKVMRuntime(instance, serialized_runtime=info)
1449
      kvm_nics = kvm_runtime[1]
1450

    
1451
      for nic_seq, nic in enumerate(kvm_nics):
1452
        if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1453
          # Bridged interfaces have already been configured
1454
          continue
1455
        try:
1456
          tap = utils.ReadFile(self._InstanceNICFile(instance.name, nic_seq))
1457
        except EnvironmentError, err:
1458
          logging.warning("Failed to find host interface for %s NIC #%d: %s",
1459
                          instance.name, nic_seq, str(err))
1460
          continue
1461
        try:
1462
          self._ConfigureNIC(instance, nic_seq, nic, tap)
1463
        except errors.HypervisorError, err:
1464
          logging.warning(str(err))
1465

    
1466
      self._WriteKVMRuntime(instance.name, info)
1467
    else:
1468
      self.StopInstance(instance, force=True)
1469

    
1470
  def MigrateInstance(self, instance, target, live):
1471
    """Migrate an instance to a target node.
1472

1473
    The migration will not be attempted if the instance is not
1474
    currently running.
1475

1476
    @type instance: L{objects.Instance}
1477
    @param instance: the instance to be migrated
1478
    @type target: string
1479
    @param target: ip address of the target node
1480
    @type live: boolean
1481
    @param live: perform a live migration
1482

1483
    """
1484
    instance_name = instance.name
1485
    port = instance.hvparams[constants.HV_MIGRATION_PORT]
1486
    pidfile, pid, alive = self._InstancePidAlive(instance_name)
1487
    if not alive:
1488
      raise errors.HypervisorError("Instance not running, cannot migrate")
1489

    
1490
    if not live:
1491
      self._CallMonitorCommand(instance_name, "stop")
1492

    
1493
    migrate_command = ("migrate_set_speed %dm" %
1494
        instance.hvparams[constants.HV_MIGRATION_BANDWIDTH])
1495
    self._CallMonitorCommand(instance_name, migrate_command)
1496

    
1497
    migrate_command = ("migrate_set_downtime %dms" %
1498
        instance.hvparams[constants.HV_MIGRATION_DOWNTIME])
1499
    self._CallMonitorCommand(instance_name, migrate_command)
1500

    
1501
    migrate_command = "migrate -d tcp:%s:%s" % (target, port)
1502
    self._CallMonitorCommand(instance_name, migrate_command)
1503

    
1504
    info_command = "info migrate"
1505
    done = False
1506
    broken_answers = 0
1507
    while not done:
1508
      result = self._CallMonitorCommand(instance_name, info_command)
1509
      match = self._MIGRATION_STATUS_RE.search(result.stdout)
1510
      if not match:
1511
        broken_answers += 1
1512
        if not result.stdout:
1513
          logging.info("KVM: empty 'info migrate' result")
1514
        else:
1515
          logging.warning("KVM: unknown 'info migrate' result: %s",
1516
                          result.stdout)
1517
        time.sleep(self._MIGRATION_INFO_RETRY_DELAY)
1518
      else:
1519
        status = match.group(1)
1520
        if status == "completed":
1521
          done = True
1522
        elif status == "active":
1523
          # reset the broken answers count
1524
          broken_answers = 0
1525
          time.sleep(self._MIGRATION_INFO_RETRY_DELAY)
1526
        elif status == "failed" or status == "cancelled":
1527
          if not live:
1528
            self._CallMonitorCommand(instance_name, 'cont')
1529
          raise errors.HypervisorError("Migration %s at the kvm level" %
1530
                                       status)
1531
        else:
1532
          logging.warning("KVM: unknown migration status '%s'", status)
1533
          broken_answers += 1
1534
          time.sleep(self._MIGRATION_INFO_RETRY_DELAY)
1535
      if broken_answers >= self._MIGRATION_INFO_MAX_BAD_ANSWERS:
1536
        raise errors.HypervisorError("Too many 'info migrate' broken answers")
1537

    
1538
    utils.KillProcess(pid)
1539
    self._RemoveInstanceRuntimeFiles(pidfile, instance_name)
1540

    
1541
  def GetNodeInfo(self):
1542
    """Return information about the node.
1543

1544
    This is just a wrapper over the base GetLinuxNodeInfo method.
1545

1546
    @return: a dict with the following keys (values in MiB):
1547
          - memory_total: the total memory size on the node
1548
          - memory_free: the available memory on the node for instances
1549
          - memory_dom0: the memory used by the node itself, if available
1550

1551
    """
1552
    return self.GetLinuxNodeInfo()
1553

    
1554
  @classmethod
1555
  def GetInstanceConsole(cls, instance, hvparams, beparams):
1556
    """Return a command for connecting to the console of an instance.
1557

1558
    """
1559
    if hvparams[constants.HV_SERIAL_CONSOLE]:
1560
      cmd = [constants.KVM_CONSOLE_WRAPPER,
1561
             constants.SOCAT_PATH, utils.ShellQuote(instance.name),
1562
             utils.ShellQuote(cls._InstanceMonitor(instance.name)),
1563
             "STDIO,%s" % cls._SocatUnixConsoleParams(),
1564
             "UNIX-CONNECT:%s" % cls._InstanceSerial(instance.name)]
1565
      return objects.InstanceConsole(instance=instance.name,
1566
                                     kind=constants.CONS_SSH,
1567
                                     host=instance.primary_node,
1568
                                     user=constants.GANETI_RUNAS,
1569
                                     command=cmd)
1570

    
1571
    vnc_bind_address = hvparams[constants.HV_VNC_BIND_ADDRESS]
1572
    if vnc_bind_address and instance.network_port > constants.VNC_BASE_PORT:
1573
      display = instance.network_port - constants.VNC_BASE_PORT
1574
      return objects.InstanceConsole(instance=instance.name,
1575
                                     kind=constants.CONS_VNC,
1576
                                     host=vnc_bind_address,
1577
                                     port=instance.network_port,
1578
                                     display=display)
1579

    
1580
    spice_bind = hvparams[constants.HV_KVM_SPICE_BIND]
1581
    if spice_bind:
1582
      return objects.InstanceConsole(instance=instance.name,
1583
                                     kind=constants.CONS_SPICE,
1584
                                     host=spice_bind,
1585
                                     port=instance.network_port)
1586

    
1587
    return objects.InstanceConsole(instance=instance.name,
1588
                                   kind=constants.CONS_MESSAGE,
1589
                                   message=("No serial shell for instance %s" %
1590
                                            instance.name))
1591

    
1592
  def Verify(self):
1593
    """Verify the hypervisor.
1594

1595
    Check that the binary exists.
1596

1597
    """
1598
    if not os.path.exists(constants.KVM_PATH):
1599
      return "The kvm binary ('%s') does not exist." % constants.KVM_PATH
1600
    if not os.path.exists(constants.SOCAT_PATH):
1601
      return "The socat binary ('%s') does not exist." % constants.SOCAT_PATH
1602

    
1603
  @classmethod
1604
  def CheckParameterSyntax(cls, hvparams):
1605
    """Check the given parameters for validity.
1606

1607
    @type hvparams:  dict
1608
    @param hvparams: dictionary with parameter names/value
1609
    @raise errors.HypervisorError: when a parameter is not valid
1610

1611
    """
1612
    super(KVMHypervisor, cls).CheckParameterSyntax(hvparams)
1613

    
1614
    kernel_path = hvparams[constants.HV_KERNEL_PATH]
1615
    if kernel_path:
1616
      if not hvparams[constants.HV_ROOT_PATH]:
1617
        raise errors.HypervisorError("Need a root partition for the instance,"
1618
                                     " if a kernel is defined")
1619

    
1620
    if (hvparams[constants.HV_VNC_X509_VERIFY] and
1621
        not hvparams[constants.HV_VNC_X509]):
1622
      raise errors.HypervisorError("%s must be defined, if %s is" %
1623
                                   (constants.HV_VNC_X509,
1624
                                    constants.HV_VNC_X509_VERIFY))
1625

    
1626
    boot_order = hvparams[constants.HV_BOOT_ORDER]
1627
    if (boot_order == constants.HT_BO_CDROM and
1628
        not hvparams[constants.HV_CDROM_IMAGE_PATH]):
1629
      raise errors.HypervisorError("Cannot boot from cdrom without an"
1630
                                   " ISO path")
1631

    
1632
    security_model = hvparams[constants.HV_SECURITY_MODEL]
1633
    if security_model == constants.HT_SM_USER:
1634
      if not hvparams[constants.HV_SECURITY_DOMAIN]:
1635
        raise errors.HypervisorError("A security domain (user to run kvm as)"
1636
                                     " must be specified")
1637
    elif (security_model == constants.HT_SM_NONE or
1638
          security_model == constants.HT_SM_POOL):
1639
      if hvparams[constants.HV_SECURITY_DOMAIN]:
1640
        raise errors.HypervisorError("Cannot have a security domain when the"
1641
                                     " security model is 'none' or 'pool'")
1642

    
1643
    spice_bind = hvparams[constants.HV_KVM_SPICE_BIND]
1644
    spice_ip_version = hvparams[constants.HV_KVM_SPICE_IP_VERSION]
1645
    if spice_bind:
1646
      if spice_ip_version != constants.IFACE_NO_IP_VERSION_SPECIFIED:
1647
        # if an IP version is specified, the spice_bind parameter must be an
1648
        # IP of that family
1649
        if (netutils.IP4Address.IsValid(spice_bind) and
1650
            spice_ip_version != constants.IP4_VERSION):
1651
          raise errors.HypervisorError("spice: got an IPv4 address (%s), but"
1652
                                       " the specified IP version is %s" %
1653
                                       (spice_bind, spice_ip_version))
1654

    
1655
        if (netutils.IP6Address.IsValid(spice_bind) and
1656
            spice_ip_version != constants.IP6_VERSION):
1657
          raise errors.HypervisorError("spice: got an IPv6 address (%s), but"
1658
                                       " the specified IP version is %s" %
1659
                                       (spice_bind, spice_ip_version))
1660
    else:
1661
      # All the other SPICE parameters depend on spice_bind being set. Raise an
1662
      # error if any of them is set without it.
1663
      spice_additional_params = frozenset([
1664
        constants.HV_KVM_SPICE_IP_VERSION,
1665
        constants.HV_KVM_SPICE_PASSWORD_FILE,
1666
        constants.HV_KVM_SPICE_LOSSLESS_IMG_COMPR,
1667
        constants.HV_KVM_SPICE_JPEG_IMG_COMPR,
1668
        constants.HV_KVM_SPICE_ZLIB_GLZ_IMG_COMPR,
1669
        constants.HV_KVM_SPICE_STREAMING_VIDEO_DETECTION,
1670
        constants.HV_KVM_SPICE_USE_TLS,
1671
        ])
1672
      for param in spice_additional_params:
1673
        if hvparams[param]:
1674
          raise errors.HypervisorError("spice: %s requires %s to be set" %
1675
                                       (param, constants.HV_KVM_SPICE_BIND))
1676

    
1677
  @classmethod
1678
  def ValidateParameters(cls, hvparams):
1679
    """Check the given parameters for validity.
1680

1681
    @type hvparams:  dict
1682
    @param hvparams: dictionary with parameter names/value
1683
    @raise errors.HypervisorError: when a parameter is not valid
1684

1685
    """
1686
    super(KVMHypervisor, cls).ValidateParameters(hvparams)
1687

    
1688
    security_model = hvparams[constants.HV_SECURITY_MODEL]
1689
    if security_model == constants.HT_SM_USER:
1690
      username = hvparams[constants.HV_SECURITY_DOMAIN]
1691
      try:
1692
        pwd.getpwnam(username)
1693
      except KeyError:
1694
        raise errors.HypervisorError("Unknown security domain user %s"
1695
                                     % username)
1696

    
1697
    spice_bind = hvparams[constants.HV_KVM_SPICE_BIND]
1698
    if spice_bind:
1699
      # only one of VNC and SPICE can be used currently.
1700
      if hvparams[constants.HV_VNC_BIND_ADDRESS]:
1701
        raise errors.HypervisorError("both SPICE and VNC are configured, but"
1702
                                     " only one of them can be used at a"
1703
                                     " given time.")
1704

    
1705
      # KVM version should be >= 0.14.0
1706
      _, v_major, v_min, _ = cls._GetKVMVersion()
1707
      if (v_major, v_min) < (0, 14):
1708
        raise errors.HypervisorError("spice is configured, but it is not"
1709
                                     " available in versions of KVM < 0.14")
1710

    
1711
      # if spice_bind is not an IP address, it must be a valid interface
1712
      bound_to_addr = (netutils.IP4Address.IsValid(spice_bind)
1713
                       or netutils.IP6Address.IsValid(spice_bind))
1714
      if not bound_to_addr and not netutils.IsValidInterface(spice_bind):
1715
        raise errors.HypervisorError("spice: the %s parameter must be either"
1716
                                     " a valid IP address or interface name" %
1717
                                     constants.HV_KVM_SPICE_BIND)
1718

    
1719
  @classmethod
1720
  def PowercycleNode(cls):
1721
    """KVM powercycle, just a wrapper over Linux powercycle.
1722

1723
    """
1724
    cls.LinuxPowercycle()