Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_kvm.py @ 89473be8

History | View | Annotate | Download (99.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014 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 urllib2
38
import socket
39
import stat
40
import StringIO
41
from bitarray import bitarray
42
try:
43
  import affinity   # pylint: disable=F0401
44
except ImportError:
45
  affinity = None
46
try:
47
  import fdsend   # pylint: disable=F0401
48
except ImportError:
49
  fdsend = None
50

    
51
from ganeti import utils
52
from ganeti import constants
53
from ganeti import errors
54
from ganeti import serializer
55
from ganeti import objects
56
from ganeti import uidpool
57
from ganeti import ssconf
58
from ganeti import netutils
59
from ganeti import pathutils
60
from ganeti.hypervisor import hv_base
61
from ganeti.utils import wrapper as utils_wrapper
62

    
63

    
64
_KVM_NETWORK_SCRIPT = pathutils.CONF_DIR + "/kvm-vif-bridge"
65
_KVM_START_PAUSED_FLAG = "-S"
66

    
67
# TUN/TAP driver constants, taken from <linux/if_tun.h>
68
# They are architecture-independent and already hardcoded in qemu-kvm source,
69
# so we can safely include them here.
70
TUNSETIFF = 0x400454ca
71
TUNGETIFF = 0x800454d2
72
TUNGETFEATURES = 0x800454cf
73
IFF_TAP = 0x0002
74
IFF_NO_PI = 0x1000
75
IFF_VNET_HDR = 0x4000
76

    
77
#: SPICE parameters which depend on L{constants.HV_KVM_SPICE_BIND}
78
_SPICE_ADDITIONAL_PARAMS = frozenset([
79
  constants.HV_KVM_SPICE_IP_VERSION,
80
  constants.HV_KVM_SPICE_PASSWORD_FILE,
81
  constants.HV_KVM_SPICE_LOSSLESS_IMG_COMPR,
82
  constants.HV_KVM_SPICE_JPEG_IMG_COMPR,
83
  constants.HV_KVM_SPICE_ZLIB_GLZ_IMG_COMPR,
84
  constants.HV_KVM_SPICE_STREAMING_VIDEO_DETECTION,
85
  constants.HV_KVM_SPICE_USE_TLS,
86
  ])
87

    
88
# Constant bitarray that reflects to a free pci slot
89
# Use it with bitarray.search()
90
_AVAILABLE_PCI_SLOT = bitarray("0")
91

    
92
# below constants show the format of runtime file
93
# the nics are in second possition, while the disks in 4th (last)
94
# moreover disk entries are stored as a list of in tuples
95
# (L{objects.Disk}, link_name, uri)
96
_KVM_NICS_RUNTIME_INDEX = 1
97
_KVM_DISKS_RUNTIME_INDEX = 3
98
_DEVICE_RUNTIME_INDEX = {
99
  constants.HOTPLUG_TARGET_DISK: _KVM_DISKS_RUNTIME_INDEX,
100
  constants.HOTPLUG_TARGET_NIC: _KVM_NICS_RUNTIME_INDEX
101
  }
102
_FIND_RUNTIME_ENTRY = {
103
  constants.HOTPLUG_TARGET_NIC:
104
    lambda nic, kvm_nics: [n for n in kvm_nics if n.uuid == nic.uuid],
105
  constants.HOTPLUG_TARGET_DISK:
106
    lambda disk, kvm_disks: [(d, l, u) for (d, l, u) in kvm_disks
107
                             if d.uuid == disk.uuid]
108
  }
109
_RUNTIME_DEVICE = {
110
  constants.HOTPLUG_TARGET_NIC: lambda d: d,
111
  constants.HOTPLUG_TARGET_DISK: lambda (d, e, _): d
112
  }
113
_RUNTIME_ENTRY = {
114
  constants.HOTPLUG_TARGET_NIC: lambda d, e: d,
115
  constants.HOTPLUG_TARGET_DISK: lambda d, e: (d, e, None)
116
  }
117

    
118

    
119
def _GenerateDeviceKVMId(dev_type, dev):
120
  """Helper function to generate a unique device name used by KVM
121

122
  QEMU monitor commands use names to identify devices. Here we use their pci
123
  slot and a part of their UUID to name them. dev.pci might be None for old
124
  devices in the cluster.
125

126
  @type dev_type: sting
127
  @param dev_type: device type of param dev
128
  @type dev: L{objects.Disk} or L{objects.NIC}
129
  @param dev: the device object for which we generate a kvm name
130
  @raise errors.HotplugError: in case a device has no pci slot (old devices)
131

132
  """
133

    
134
  if not dev.pci:
135
    raise errors.HotplugError("Hotplug is not supported for %s with UUID %s" %
136
                              (dev_type, dev.uuid))
137

    
138
  return "%s-%s-pci-%d" % (dev_type.lower(), dev.uuid.split("-")[0], dev.pci)
139

    
140

    
141
def _UpdatePCISlots(dev, pci_reservations):
142
  """Update pci configuration for a stopped instance
143

144
  If dev has a pci slot then reserve it, else find first available
145
  in pci_reservations bitarray. It acts on the same objects passed
146
  as params so there is no need to return anything.
147

148
  @type dev: L{objects.Disk} or L{objects.NIC}
149
  @param dev: the device object for which we update its pci slot
150
  @type pci_reservations: bitarray
151
  @param pci_reservations: existing pci reservations for an instance
152
  @raise errors.HotplugError: in case an instance has all its slot occupied
153

154
  """
155
  if dev.pci:
156
    free = dev.pci
157
  else: # pylint: disable=E1103
158
    [free] = pci_reservations.search(_AVAILABLE_PCI_SLOT, 1)
159
    if not free:
160
      raise errors.HypervisorError("All PCI slots occupied")
161
    dev.pci = int(free)
162

    
163
  pci_reservations[free] = True
164

    
165

    
166
def _GetExistingDeviceInfo(dev_type, device, runtime):
167
  """Helper function to get an existing device inside the runtime file
168

169
  Used when an instance is running. Load kvm runtime file and search
170
  for a device based on its type and uuid.
171

172
  @type dev_type: sting
173
  @param dev_type: device type of param dev
174
  @type device: L{objects.Disk} or L{objects.NIC}
175
  @param device: the device object for which we generate a kvm name
176
  @type runtime: tuple (cmd, nics, hvparams, disks)
177
  @param runtime: the runtime data to search for the device
178
  @raise errors.HotplugError: in case the requested device does not
179
    exist (e.g. device has been added without --hotplug option) or
180
    device info has not pci slot (e.g. old devices in the cluster)
181

182
  """
183
  index = _DEVICE_RUNTIME_INDEX[dev_type]
184
  found = _FIND_RUNTIME_ENTRY[dev_type](device, runtime[index])
185
  if not found:
186
    raise errors.HotplugError("Cannot find runtime info for %s with UUID %s" %
187
                              (dev_type, device.uuid))
188

    
189
  return found[0]
190

    
191

    
192
def _UpgradeSerializedRuntime(serialized_runtime):
193
  """Upgrade runtime data
194

195
  Remove any deprecated fields or change the format of the data.
196
  The runtime files are not upgraded when Ganeti is upgraded, so the required
197
  modification have to be performed here.
198

199
  @type serialized_runtime: string
200
  @param serialized_runtime: raw text data read from actual runtime file
201
  @return: (cmd, nic dicts, hvparams, bdev dicts)
202
  @rtype: tuple
203

204
  """
205
  loaded_runtime = serializer.Load(serialized_runtime)
206
  kvm_cmd, serialized_nics, hvparams = loaded_runtime[:3]
207
  if len(loaded_runtime) >= 4:
208
    serialized_disks = loaded_runtime[3]
209
  else:
210
    serialized_disks = []
211

    
212
  for nic in serialized_nics:
213
    # Add a dummy uuid slot if an pre-2.8 NIC is found
214
    if "uuid" not in nic:
215
      nic["uuid"] = utils.NewUUID()
216

    
217
  return kvm_cmd, serialized_nics, hvparams, serialized_disks
218

    
219

    
220
def _AnalyzeSerializedRuntime(serialized_runtime):
221
  """Return runtime entries for a serialized runtime file
222

223
  @type serialized_runtime: string
224
  @param serialized_runtime: raw text data read from actual runtime file
225
  @return: (cmd, nics, hvparams, bdevs)
226
  @rtype: tuple
227

228
  """
229
  kvm_cmd, serialized_nics, hvparams, serialized_disks = \
230
    _UpgradeSerializedRuntime(serialized_runtime)
231
  kvm_nics = [objects.NIC.FromDict(snic) for snic in serialized_nics]
232
  kvm_disks = [(objects.Disk.FromDict(sdisk), link, uri)
233
               for sdisk, link, uri in serialized_disks]
234

    
235
  return (kvm_cmd, kvm_nics, hvparams, kvm_disks)
236

    
237

    
238
def _GetTunFeatures(fd, _ioctl=fcntl.ioctl):
239
  """Retrieves supported TUN features from file descriptor.
240

241
  @see: L{_ProbeTapVnetHdr}
242

243
  """
244
  req = struct.pack("I", 0)
245
  try:
246
    buf = _ioctl(fd, TUNGETFEATURES, req)
247
  except EnvironmentError, err:
248
    logging.warning("ioctl(TUNGETFEATURES) failed: %s", err)
249
    return None
250
  else:
251
    (flags, ) = struct.unpack("I", buf)
252
    return flags
253

    
254

    
255
def _ProbeTapVnetHdr(fd, _features_fn=_GetTunFeatures):
256
  """Check whether to enable the IFF_VNET_HDR flag.
257

258
  To do this, _all_ of the following conditions must be met:
259
   1. TUNGETFEATURES ioctl() *must* be implemented
260
   2. TUNGETFEATURES ioctl() result *must* contain the IFF_VNET_HDR flag
261
   3. TUNGETIFF ioctl() *must* be implemented; reading the kernel code in
262
      drivers/net/tun.c there is no way to test this until after the tap device
263
      has been created using TUNSETIFF, and there is no way to change the
264
      IFF_VNET_HDR flag after creating the interface, catch-22! However both
265
      TUNGETIFF and TUNGETFEATURES were introduced in kernel version 2.6.27,
266
      thus we can expect TUNGETIFF to be present if TUNGETFEATURES is.
267

268
   @type fd: int
269
   @param fd: the file descriptor of /dev/net/tun
270

271
  """
272
  flags = _features_fn(fd)
273

    
274
  if flags is None:
275
    # Not supported
276
    return False
277

    
278
  result = bool(flags & IFF_VNET_HDR)
279

    
280
  if not result:
281
    logging.warning("Kernel does not support IFF_VNET_HDR, not enabling")
282

    
283
  return result
284

    
285

    
286
def _OpenTap(vnet_hdr=True, name=""):
287
  """Open a new tap device and return its file descriptor.
288

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

292
  @type vnet_hdr: boolean
293
  @param vnet_hdr: Enable the VNET Header
294

295
  @type name: string
296
  @param name: name for the TAP interface being created; if an empty
297
               string is passed, the OS will generate a unique name
298

299
  @return: (ifname, tapfd)
300
  @rtype: tuple
301

302
  """
303
  try:
304
    tapfd = os.open("/dev/net/tun", os.O_RDWR)
305
  except EnvironmentError:
306
    raise errors.HypervisorError("Failed to open /dev/net/tun")
307

    
308
  flags = IFF_TAP | IFF_NO_PI
309

    
310
  if vnet_hdr and _ProbeTapVnetHdr(tapfd):
311
    flags |= IFF_VNET_HDR
312

    
313
  # The struct ifreq ioctl request (see netdevice(7))
314
  ifr = struct.pack("16sh", name, flags)
315

    
316
  try:
317
    res = fcntl.ioctl(tapfd, TUNSETIFF, ifr)
318
  except EnvironmentError, err:
319
    raise errors.HypervisorError("Failed to allocate a new TAP device: %s" %
320
                                 err)
321

    
322
  # Get the interface name from the ioctl
323
  ifname = struct.unpack("16sh", res)[0].strip("\x00")
324
  return (ifname, tapfd)
325

    
326

    
327
class HeadRequest(urllib2.Request):
328
  def get_method(self):
329
    return "HEAD"
330

    
331

    
332
def _CheckUrl(url):
333
  """Check if a given URL exists on the server
334

335
  """
336
  try:
337
    urllib2.urlopen(HeadRequest(url))
338
    return True
339
  except urllib2.URLError:
340
    return False
341

    
342

    
343
class QmpMessage:
344
  """QEMU Messaging Protocol (QMP) message.
345

346
  """
347
  def __init__(self, data):
348
    """Creates a new QMP message based on the passed data.
349

350
    """
351
    if not isinstance(data, dict):
352
      raise TypeError("QmpMessage must be initialized with a dict")
353

    
354
    self.data = data
355

    
356
  def __getitem__(self, field_name):
357
    """Get the value of the required field if present, or None.
358

359
    Overrides the [] operator to provide access to the message data,
360
    returning None if the required item is not in the message
361
    @return: the value of the field_name field, or None if field_name
362
             is not contained in the message
363

364
    """
365
    return self.data.get(field_name, None)
366

    
367
  def __setitem__(self, field_name, field_value):
368
    """Set the value of the required field_name to field_value.
369

370
    """
371
    self.data[field_name] = field_value
372

    
373
  def __len__(self):
374
    """Return the number of fields stored in this QmpMessage.
375

376
    """
377
    return len(self.data)
378

    
379
  def __delitem__(self, key):
380
    """Delete the specified element from the QmpMessage.
381

382
    """
383
    del(self.data[key])
384

    
385
  @staticmethod
386
  def BuildFromJsonString(json_string):
387
    """Build a QmpMessage from a JSON encoded string.
388

389
    @type json_string: str
390
    @param json_string: JSON string representing the message
391
    @rtype: L{QmpMessage}
392
    @return: a L{QmpMessage} built from json_string
393

394
    """
395
    # Parse the string
396
    data = serializer.LoadJson(json_string)
397
    return QmpMessage(data)
398

    
399
  def __str__(self):
400
    # The protocol expects the JSON object to be sent as a single line.
401
    return serializer.DumpJson(self.data)
402

    
403
  def __eq__(self, other):
404
    # When comparing two QmpMessages, we are interested in comparing
405
    # their internal representation of the message data
406
    return self.data == other.data
407

    
408

    
409
class MonitorSocket(object):
410
  _SOCKET_TIMEOUT = 5
411

    
412
  def __init__(self, monitor_filename):
413
    """Instantiates the MonitorSocket object.
414

415
    @type monitor_filename: string
416
    @param monitor_filename: the filename of the UNIX raw socket on which the
417
                             monitor (QMP or simple one) is listening
418

419
    """
420
    self.monitor_filename = monitor_filename
421
    self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
422
    # We want to fail if the server doesn't send a complete message
423
    # in a reasonable amount of time
424
    self.sock.settimeout(self._SOCKET_TIMEOUT)
425
    self._connected = False
426

    
427
  def _check_socket(self):
428
    sock_stat = None
429
    try:
430
      sock_stat = os.stat(self.monitor_filename)
431
    except EnvironmentError, err:
432
      if err.errno == errno.ENOENT:
433
        raise errors.HypervisorError("No monitor socket found")
434
      else:
435
        raise errors.HypervisorError("Error checking monitor socket: %s",
436
                                     utils.ErrnoOrStr(err))
437
    if not stat.S_ISSOCK(sock_stat.st_mode):
438
      raise errors.HypervisorError("Monitor socket is not a socket")
439

    
440
  def _check_connection(self):
441
    """Make sure that the connection is established.
442

443
    """
444
    if not self._connected:
445
      raise errors.ProgrammerError("To use a MonitorSocket you need to first"
446
                                   " invoke connect() on it")
447

    
448
  def connect(self):
449
    """Connects to the monitor.
450

451
    Connects to the UNIX socket
452

453
    @raise errors.HypervisorError: when there are communication errors
454

455
    """
456
    if self._connected:
457
      raise errors.ProgrammerError("Cannot connect twice")
458

    
459
    self._check_socket()
460

    
461
    # Check file existance/stuff
462
    try:
463
      self.sock.connect(self.monitor_filename)
464
    except EnvironmentError:
465
      raise errors.HypervisorError("Can't connect to qmp socket")
466
    self._connected = True
467

    
468
  def close(self):
469
    """Closes the socket
470

471
    It cannot be used after this call.
472

473
    """
474
    self.sock.close()
475

    
476

    
477
class QmpConnection(MonitorSocket):
478
  """Connection to the QEMU Monitor using the QEMU Monitor Protocol (QMP).
479

480
  """
481
  _FIRST_MESSAGE_KEY = "QMP"
482
  _EVENT_KEY = "event"
483
  _ERROR_KEY = "error"
484
  _RETURN_KEY = RETURN_KEY = "return"
485
  _ACTUAL_KEY = ACTUAL_KEY = "actual"
486
  _ERROR_CLASS_KEY = "class"
487
  _ERROR_DESC_KEY = "desc"
488
  _EXECUTE_KEY = "execute"
489
  _ARGUMENTS_KEY = "arguments"
490
  _CAPABILITIES_COMMAND = "qmp_capabilities"
491
  _MESSAGE_END_TOKEN = "\r\n"
492

    
493
  def __init__(self, monitor_filename):
494
    super(QmpConnection, self).__init__(monitor_filename)
495
    self._buf = ""
496

    
497
  def connect(self):
498
    """Connects to the QMP monitor.
499

500
    Connects to the UNIX socket and makes sure that we can actually send and
501
    receive data to the kvm instance via QMP.
502

503
    @raise errors.HypervisorError: when there are communication errors
504
    @raise errors.ProgrammerError: when there are data serialization errors
505

506
    """
507
    super(QmpConnection, self).connect()
508
    # Check if we receive a correct greeting message from the server
509
    # (As per the QEMU Protocol Specification 0.1 - section 2.2)
510
    greeting = self._Recv()
511
    if not greeting[self._FIRST_MESSAGE_KEY]:
512
      self._connected = False
513
      raise errors.HypervisorError("kvm: QMP communication error (wrong"
514
                                   " server greeting")
515

    
516
    # Let's put the monitor in command mode using the qmp_capabilities
517
    # command, or else no command will be executable.
518
    # (As per the QEMU Protocol Specification 0.1 - section 4)
519
    self.Execute(self._CAPABILITIES_COMMAND)
520

    
521
  def _ParseMessage(self, buf):
522
    """Extract and parse a QMP message from the given buffer.
523

524
    Seeks for a QMP message in the given buf. If found, it parses it and
525
    returns it together with the rest of the characters in the buf.
526
    If no message is found, returns None and the whole buffer.
527

528
    @raise errors.ProgrammerError: when there are data serialization errors
529

530
    """
531
    message = None
532
    # Check if we got the message end token (CRLF, as per the QEMU Protocol
533
    # Specification 0.1 - Section 2.1.1)
534
    pos = buf.find(self._MESSAGE_END_TOKEN)
535
    if pos >= 0:
536
      try:
537
        message = QmpMessage.BuildFromJsonString(buf[:pos + 1])
538
      except Exception, err:
539
        raise errors.ProgrammerError("QMP data serialization error: %s" % err)
540
      buf = buf[pos + 1:]
541

    
542
    return (message, buf)
543

    
544
  def _Recv(self):
545
    """Receives a message from QMP and decodes the received JSON object.
546

547
    @rtype: QmpMessage
548
    @return: the received message
549
    @raise errors.HypervisorError: when there are communication errors
550
    @raise errors.ProgrammerError: when there are data serialization errors
551

552
    """
553
    self._check_connection()
554

    
555
    # Check if there is already a message in the buffer
556
    (message, self._buf) = self._ParseMessage(self._buf)
557
    if message:
558
      return message
559

    
560
    recv_buffer = StringIO.StringIO(self._buf)
561
    recv_buffer.seek(len(self._buf))
562
    try:
563
      while True:
564
        data = self.sock.recv(4096)
565
        if not data:
566
          break
567
        recv_buffer.write(data)
568

    
569
        (message, self._buf) = self._ParseMessage(recv_buffer.getvalue())
570
        if message:
571
          return message
572

    
573
    except socket.timeout, err:
574
      raise errors.HypervisorError("Timeout while receiving a QMP message: "
575
                                   "%s" % (err))
576
    except socket.error, err:
577
      raise errors.HypervisorError("Unable to receive data from KVM using the"
578
                                   " QMP protocol: %s" % err)
579

    
580
  def _Send(self, message):
581
    """Encodes and sends a message to KVM using QMP.
582

583
    @type message: QmpMessage
584
    @param message: message to send to KVM
585
    @raise errors.HypervisorError: when there are communication errors
586
    @raise errors.ProgrammerError: when there are data serialization errors
587

588
    """
589
    self._check_connection()
590
    try:
591
      message_str = str(message)
592
    except Exception, err:
593
      raise errors.ProgrammerError("QMP data deserialization error: %s" % err)
594

    
595
    try:
596
      self.sock.sendall(message_str)
597
    except socket.timeout, err:
598
      raise errors.HypervisorError("Timeout while sending a QMP message: "
599
                                   "%s (%s)" % (err.string, err.errno))
600
    except socket.error, err:
601
      raise errors.HypervisorError("Unable to send data from KVM using the"
602
                                   " QMP protocol: %s" % err)
603

    
604
  def Execute(self, command, arguments=None):
605
    """Executes a QMP command and returns the response of the server.
606

607
    @type command: str
608
    @param command: the command to execute
609
    @type arguments: dict
610
    @param arguments: dictionary of arguments to be passed to the command
611
    @rtype: dict
612
    @return: dictionary representing the received JSON object
613
    @raise errors.HypervisorError: when there are communication errors
614
    @raise errors.ProgrammerError: when there are data serialization errors
615

616
    """
617
    self._check_connection()
618
    message = QmpMessage({self._EXECUTE_KEY: command})
619
    if arguments:
620
      message[self._ARGUMENTS_KEY] = arguments
621
    self._Send(message)
622

    
623
    # Events can occur between the sending of the command and the reception
624
    # of the response, so we need to filter out messages with the event key.
625
    while True:
626
      response = self._Recv()
627
      err = response[self._ERROR_KEY]
628
      if err:
629
        raise errors.HypervisorError("kvm: error executing the %s"
630
                                     " command: %s (%s):" %
631
                                     (command,
632
                                      err[self._ERROR_DESC_KEY],
633
                                      err[self._ERROR_CLASS_KEY]))
634

    
635
      elif not response[self._EVENT_KEY]:
636
        return response
637

    
638

    
639
class KVMHypervisor(hv_base.BaseHypervisor):
640
  """KVM hypervisor interface
641

642
  """
643
  CAN_MIGRATE = True
644

    
645
  _ROOT_DIR = pathutils.RUN_DIR + "/kvm-hypervisor"
646
  _PIDS_DIR = _ROOT_DIR + "/pid" # contains live instances pids
647
  _UIDS_DIR = _ROOT_DIR + "/uid" # contains instances reserved uids
648
  _CTRL_DIR = _ROOT_DIR + "/ctrl" # contains instances control sockets
649
  _CONF_DIR = _ROOT_DIR + "/conf" # contains instances startup data
650
  _NICS_DIR = _ROOT_DIR + "/nic" # contains instances nic <-> tap associations
651
  _KEYMAP_DIR = _ROOT_DIR + "/keymap" # contains instances keymaps
652
  # KVM instances with chroot enabled are started in empty chroot directories.
653
  _CHROOT_DIR = _ROOT_DIR + "/chroot" # for empty chroot directories
654
  # After an instance is stopped, its chroot directory is removed.
655
  # If the chroot directory is not empty, it can't be removed.
656
  # A non-empty chroot directory indicates a possible security incident.
657
  # To support forensics, the non-empty chroot directory is quarantined in
658
  # a separate directory, called 'chroot-quarantine'.
659
  _CHROOT_QUARANTINE_DIR = _ROOT_DIR + "/chroot-quarantine"
660
  _DIRS = [_ROOT_DIR, _PIDS_DIR, _UIDS_DIR, _CTRL_DIR, _CONF_DIR, _NICS_DIR,
661
           _CHROOT_DIR, _CHROOT_QUARANTINE_DIR, _KEYMAP_DIR]
662

    
663
  PARAMETERS = {
664
    constants.HV_KVM_PATH: hv_base.REQ_FILE_CHECK,
665
    constants.HV_KERNEL_PATH: hv_base.OPT_FILE_CHECK,
666
    constants.HV_INITRD_PATH: hv_base.OPT_FILE_CHECK,
667
    constants.HV_ROOT_PATH: hv_base.NO_CHECK,
668
    constants.HV_KERNEL_ARGS: hv_base.NO_CHECK,
669
    constants.HV_ACPI: hv_base.NO_CHECK,
670
    constants.HV_SERIAL_CONSOLE: hv_base.NO_CHECK,
671
    constants.HV_SERIAL_SPEED: hv_base.NO_CHECK,
672
    constants.HV_VNC_BIND_ADDRESS: hv_base.NO_CHECK, # will be checked later
673
    constants.HV_VNC_TLS: hv_base.NO_CHECK,
674
    constants.HV_VNC_X509: hv_base.OPT_DIR_CHECK,
675
    constants.HV_VNC_X509_VERIFY: hv_base.NO_CHECK,
676
    constants.HV_VNC_PASSWORD_FILE: hv_base.OPT_FILE_CHECK,
677
    constants.HV_KVM_SPICE_BIND: hv_base.NO_CHECK, # will be checked later
678
    constants.HV_KVM_SPICE_IP_VERSION:
679
      (False, lambda x: (x == constants.IFACE_NO_IP_VERSION_SPECIFIED or
680
                         x in constants.VALID_IP_VERSIONS),
681
       "The SPICE IP version should be 4 or 6",
682
       None, None),
683
    constants.HV_KVM_SPICE_PASSWORD_FILE: hv_base.OPT_FILE_CHECK,
684
    constants.HV_KVM_SPICE_LOSSLESS_IMG_COMPR:
685
      hv_base.ParamInSet(
686
        False, constants.HT_KVM_SPICE_VALID_LOSSLESS_IMG_COMPR_OPTIONS),
687
    constants.HV_KVM_SPICE_JPEG_IMG_COMPR:
688
      hv_base.ParamInSet(
689
        False, constants.HT_KVM_SPICE_VALID_LOSSY_IMG_COMPR_OPTIONS),
690
    constants.HV_KVM_SPICE_ZLIB_GLZ_IMG_COMPR:
691
      hv_base.ParamInSet(
692
        False, constants.HT_KVM_SPICE_VALID_LOSSY_IMG_COMPR_OPTIONS),
693
    constants.HV_KVM_SPICE_STREAMING_VIDEO_DETECTION:
694
      hv_base.ParamInSet(
695
        False, constants.HT_KVM_SPICE_VALID_VIDEO_STREAM_DETECTION_OPTIONS),
696
    constants.HV_KVM_SPICE_AUDIO_COMPR: hv_base.NO_CHECK,
697
    constants.HV_KVM_SPICE_USE_TLS: hv_base.NO_CHECK,
698
    constants.HV_KVM_SPICE_TLS_CIPHERS: hv_base.NO_CHECK,
699
    constants.HV_KVM_SPICE_USE_VDAGENT: hv_base.NO_CHECK,
700
    constants.HV_KVM_FLOPPY_IMAGE_PATH: hv_base.OPT_FILE_CHECK,
701
    constants.HV_CDROM_IMAGE_PATH: hv_base.OPT_FILE_OR_URL_CHECK,
702
    constants.HV_KVM_CDROM2_IMAGE_PATH: hv_base.OPT_FILE_OR_URL_CHECK,
703
    constants.HV_BOOT_ORDER:
704
      hv_base.ParamInSet(True, constants.HT_KVM_VALID_BO_TYPES),
705
    constants.HV_NIC_TYPE:
706
      hv_base.ParamInSet(True, constants.HT_KVM_VALID_NIC_TYPES),
707
    constants.HV_DISK_TYPE:
708
      hv_base.ParamInSet(True, constants.HT_KVM_VALID_DISK_TYPES),
709
    constants.HV_KVM_CDROM_DISK_TYPE:
710
      hv_base.ParamInSet(False, constants.HT_KVM_VALID_DISK_TYPES),
711
    constants.HV_USB_MOUSE:
712
      hv_base.ParamInSet(False, constants.HT_KVM_VALID_MOUSE_TYPES),
713
    constants.HV_KEYMAP: hv_base.NO_CHECK,
714
    constants.HV_MIGRATION_PORT: hv_base.REQ_NET_PORT_CHECK,
715
    constants.HV_MIGRATION_BANDWIDTH: hv_base.REQ_NONNEGATIVE_INT_CHECK,
716
    constants.HV_MIGRATION_DOWNTIME: hv_base.REQ_NONNEGATIVE_INT_CHECK,
717
    constants.HV_MIGRATION_MODE: hv_base.MIGRATION_MODE_CHECK,
718
    constants.HV_USE_LOCALTIME: hv_base.NO_CHECK,
719
    constants.HV_DISK_CACHE:
720
      hv_base.ParamInSet(True, constants.HT_VALID_CACHE_TYPES),
721
    constants.HV_SECURITY_MODEL:
722
      hv_base.ParamInSet(True, constants.HT_KVM_VALID_SM_TYPES),
723
    constants.HV_SECURITY_DOMAIN: hv_base.NO_CHECK,
724
    constants.HV_KVM_FLAG:
725
      hv_base.ParamInSet(False, constants.HT_KVM_FLAG_VALUES),
726
    constants.HV_VHOST_NET: hv_base.NO_CHECK,
727
    constants.HV_KVM_USE_CHROOT: hv_base.NO_CHECK,
728
    constants.HV_KVM_USER_SHUTDOWN: hv_base.NO_CHECK,
729
    constants.HV_MEM_PATH: hv_base.OPT_DIR_CHECK,
730
    constants.HV_REBOOT_BEHAVIOR:
731
      hv_base.ParamInSet(True, constants.REBOOT_BEHAVIORS),
732
    constants.HV_CPU_MASK: hv_base.OPT_MULTI_CPU_MASK_CHECK,
733
    constants.HV_CPU_TYPE: hv_base.NO_CHECK,
734
    constants.HV_CPU_CORES: hv_base.OPT_NONNEGATIVE_INT_CHECK,
735
    constants.HV_CPU_THREADS: hv_base.OPT_NONNEGATIVE_INT_CHECK,
736
    constants.HV_CPU_SOCKETS: hv_base.OPT_NONNEGATIVE_INT_CHECK,
737
    constants.HV_SOUNDHW: hv_base.NO_CHECK,
738
    constants.HV_USB_DEVICES: hv_base.NO_CHECK,
739
    constants.HV_VGA: hv_base.NO_CHECK,
740
    constants.HV_KVM_EXTRA: hv_base.NO_CHECK,
741
    constants.HV_KVM_MACHINE_VERSION: hv_base.NO_CHECK,
742
    constants.HV_VNET_HDR: hv_base.NO_CHECK,
743
    }
744

    
745
  _VIRTIO = "virtio"
746
  _VIRTIO_NET_PCI = "virtio-net-pci"
747
  _VIRTIO_BLK_PCI = "virtio-blk-pci"
748

    
749
  _MIGRATION_STATUS_RE = re.compile(r"Migration\s+status:\s+(\w+)",
750
                                    re.M | re.I)
751
  _MIGRATION_PROGRESS_RE = \
752
    re.compile(r"\s*transferred\s+ram:\s+(?P<transferred>\d+)\s+kbytes\s*\n"
753
               r"\s*remaining\s+ram:\s+(?P<remaining>\d+)\s+kbytes\s*\n"
754
               r"\s*total\s+ram:\s+(?P<total>\d+)\s+kbytes\s*\n", re.I)
755

    
756
  _MIGRATION_INFO_MAX_BAD_ANSWERS = 5
757
  _MIGRATION_INFO_RETRY_DELAY = 2
758

    
759
  _VERSION_RE = re.compile(r"\b(\d+)\.(\d+)(\.(\d+))?\b")
760

    
761
  _CPU_INFO_RE = re.compile(r"cpu\s+\#(\d+).*thread_id\s*=\s*(\d+)", re.I)
762
  _CPU_INFO_CMD = "info cpus"
763
  _CONT_CMD = "cont"
764

    
765
  _DEFAULT_MACHINE_VERSION_RE = re.compile(r"^(\S+).*\(default\)", re.M)
766
  _CHECK_MACHINE_VERSION_RE = \
767
    staticmethod(lambda x: re.compile(r"^(%s)[ ]+.*PC" % x, re.M))
768

    
769
  _QMP_RE = re.compile(r"^-qmp\s", re.M)
770
  _SPICE_RE = re.compile(r"^-spice\s", re.M)
771
  _VHOST_RE = re.compile(r"^-net\s.*,vhost=on|off", re.M)
772
  _ENABLE_KVM_RE = re.compile(r"^-enable-kvm\s", re.M)
773
  _DISABLE_KVM_RE = re.compile(r"^-disable-kvm\s", re.M)
774
  _NETDEV_RE = re.compile(r"^-netdev\s", re.M)
775
  _DISPLAY_RE = re.compile(r"^-display\s", re.M)
776
  _MACHINE_RE = re.compile(r"^-machine\s", re.M)
777
  _VIRTIO_NET_RE = re.compile(r"^name \"%s\"" % _VIRTIO_NET_PCI, re.M)
778
  _VIRTIO_BLK_RE = re.compile(r"^name \"%s\"" % _VIRTIO_BLK_PCI, re.M)
779
  # match  -drive.*boot=on|off on different lines, but in between accept only
780
  # dashes not preceeded by a new line (which would mean another option
781
  # different than -drive is starting)
782
  _BOOT_RE = re.compile(r"^-drive\s([^-]|(?<!^)-)*,boot=on\|off", re.M | re.S)
783
  _UUID_RE = re.compile(r"^-uuid\s", re.M)
784

    
785
  _INFO_PCI_RE = re.compile(r'Bus.*device[ ]*(\d+).*')
786
  _INFO_PCI_CMD = "info pci"
787
  _INFO_VERSION_RE = \
788
    re.compile(r'^QEMU (\d+)\.(\d+)(\.(\d+))?.*monitor.*', re.M)
789
  _INFO_VERSION_CMD = "info version"
790

    
791
  _DEFAULT_PCI_RESERVATIONS = "11110000000000000000000000000000"
792

    
793
  ANCILLARY_FILES = [
794
    _KVM_NETWORK_SCRIPT,
795
    ]
796
  ANCILLARY_FILES_OPT = [
797
    _KVM_NETWORK_SCRIPT,
798
    ]
799

    
800
  # Supported kvm options to get output from
801
  _KVMOPT_HELP = "help"
802
  _KVMOPT_MLIST = "mlist"
803
  _KVMOPT_DEVICELIST = "devicelist"
804

    
805
  # Command to execute to get the output from kvm, and whether to
806
  # accept the output even on failure.
807
  _KVMOPTS_CMDS = {
808
    _KVMOPT_HELP: (["--help"], False),
809
    _KVMOPT_MLIST: (["-M", "?"], False),
810
    _KVMOPT_DEVICELIST: (["-device", "?"], True),
811
  }
812

    
813
  def __init__(self):
814
    hv_base.BaseHypervisor.__init__(self)
815
    # Let's make sure the directories we need exist, even if the RUN_DIR lives
816
    # in a tmpfs filesystem or has been otherwise wiped out.
817
    dirs = [(dname, constants.RUN_DIRS_MODE) for dname in self._DIRS]
818
    utils.EnsureDirs(dirs)
819

    
820
  @classmethod
821
  def _InstancePidFile(cls, instance_name):
822
    """Returns the instance pidfile.
823

824
    """
825
    return utils.PathJoin(cls._PIDS_DIR, instance_name)
826

    
827
  @classmethod
828
  def _InstanceUidFile(cls, instance_name):
829
    """Returns the instance uidfile.
830

831
    """
832
    return utils.PathJoin(cls._UIDS_DIR, instance_name)
833

    
834
  @classmethod
835
  def _InstancePidInfo(cls, pid):
836
    """Check pid file for instance information.
837

838
    Check that a pid file is associated with an instance, and retrieve
839
    information from its command line.
840

841
    @type pid: string or int
842
    @param pid: process id of the instance to check
843
    @rtype: tuple
844
    @return: (instance_name, memory, vcpus)
845
    @raise errors.HypervisorError: when an instance cannot be found
846

847
    """
848
    alive = utils.IsProcessAlive(pid)
849
    if not alive:
850
      raise errors.HypervisorError("Cannot get info for pid %s" % pid)
851

    
852
    cmdline_file = utils.PathJoin("/proc", str(pid), "cmdline")
853
    try:
854
      cmdline = utils.ReadFile(cmdline_file)
855
    except EnvironmentError, err:
856
      raise errors.HypervisorError("Can't open cmdline file for pid %s: %s" %
857
                                   (pid, err))
858

    
859
    instance = None
860
    memory = 0
861
    vcpus = 0
862

    
863
    arg_list = cmdline.split("\x00")
864
    while arg_list:
865
      arg = arg_list.pop(0)
866
      if arg == "-name":
867
        instance = arg_list.pop(0)
868
      elif arg == "-m":
869
        memory = int(arg_list.pop(0))
870
      elif arg == "-smp":
871
        vcpus = int(arg_list.pop(0).split(",")[0])
872

    
873
    if instance is None:
874
      raise errors.HypervisorError("Pid %s doesn't contain a ganeti kvm"
875
                                   " instance" % pid)
876

    
877
    return (instance, memory, vcpus)
878

    
879
  @classmethod
880
  def _InstancePidAlive(cls, instance_name):
881
    """Returns the instance pidfile, pid, and liveness.
882

883
    @type instance_name: string
884
    @param instance_name: instance name
885
    @rtype: tuple
886
    @return: (pid file name, pid, liveness)
887

888
    """
889
    pidfile = cls._InstancePidFile(instance_name)
890
    pid = utils.ReadPidFile(pidfile)
891

    
892
    alive = False
893
    try:
894
      cmd_instance = cls._InstancePidInfo(pid)[0]
895
      alive = (cmd_instance == instance_name)
896
    except errors.HypervisorError:
897
      pass
898

    
899
    return (pidfile, pid, alive)
900

    
901
  @classmethod
902
  def _CheckDown(cls, instance_name):
903
    """Raises an error unless the given instance is down.
904

905
    """
906
    alive = cls._InstancePidAlive(instance_name)[2]
907
    if alive:
908
      raise errors.HypervisorError("Failed to start instance %s: %s" %
909
                                   (instance_name, "already running"))
910

    
911
  @classmethod
912
  def _InstanceMonitor(cls, instance_name):
913
    """Returns the instance monitor socket name
914

915
    """
916
    return utils.PathJoin(cls._CTRL_DIR, "%s.monitor" % instance_name)
917

    
918
  @classmethod
919
  def _InstanceSerial(cls, instance_name):
920
    """Returns the instance serial socket name
921

922
    """
923
    return utils.PathJoin(cls._CTRL_DIR, "%s.serial" % instance_name)
924

    
925
  @classmethod
926
  def _InstanceQmpMonitor(cls, instance_name):
927
    """Returns the instance serial QMP socket name
928

929
    """
930
    return utils.PathJoin(cls._CTRL_DIR, "%s.qmp" % instance_name)
931

    
932
  @classmethod
933
  def _InstanceShutdownMonitor(cls, instance_name):
934
    """Returns the instance QMP output filename
935

936
    """
937
    return utils.PathJoin(cls._CTRL_DIR, "%s.shutdown" % instance_name)
938

    
939
  @staticmethod
940
  def _SocatUnixConsoleParams():
941
    """Returns the correct parameters for socat
942

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

945
    """
946
    if constants.SOCAT_USE_ESCAPE:
947
      return "raw,echo=0,escape=%s" % constants.SOCAT_ESCAPE_CODE
948
    else:
949
      return "echo=0,icanon=0"
950

    
951
  @classmethod
952
  def _InstanceKVMRuntime(cls, instance_name):
953
    """Returns the instance KVM runtime filename
954

955
    """
956
    return utils.PathJoin(cls._CONF_DIR, "%s.runtime" % instance_name)
957

    
958
  @classmethod
959
  def _InstanceChrootDir(cls, instance_name):
960
    """Returns the name of the KVM chroot dir of the instance
961

962
    """
963
    return utils.PathJoin(cls._CHROOT_DIR, instance_name)
964

    
965
  @classmethod
966
  def _InstanceNICDir(cls, instance_name):
967
    """Returns the name of the directory holding the tap device files for a
968
    given instance.
969

970
    """
971
    return utils.PathJoin(cls._NICS_DIR, instance_name)
972

    
973
  @classmethod
974
  def _InstanceNICFile(cls, instance_name, seq):
975
    """Returns the name of the file containing the tap device for a given NIC
976

977
    """
978
    return utils.PathJoin(cls._InstanceNICDir(instance_name), str(seq))
979

    
980
  @classmethod
981
  def _InstanceKeymapFile(cls, instance_name):
982
    """Returns the name of the file containing the keymap for a given instance
983

984
    """
985
    return utils.PathJoin(cls._KEYMAP_DIR, instance_name)
986

    
987
  @classmethod
988
  def _TryReadUidFile(cls, uid_file):
989
    """Try to read a uid file
990

991
    """
992
    if os.path.exists(uid_file):
993
      try:
994
        uid = int(utils.ReadOneLineFile(uid_file))
995
        return uid
996
      except EnvironmentError:
997
        logging.warning("Can't read uid file", exc_info=True)
998
      except (TypeError, ValueError):
999
        logging.warning("Can't parse uid file contents", exc_info=True)
1000
    return None
1001

    
1002
  @classmethod
1003
  def _RemoveInstanceRuntimeFiles(cls, pidfile, instance_name):
1004
    """Removes an instance's rutime sockets/files/dirs.
1005

1006
    """
1007
    utils.RemoveFile(pidfile)
1008
    utils.RemoveFile(cls._InstanceMonitor(instance_name))
1009
    utils.RemoveFile(cls._InstanceSerial(instance_name))
1010
    utils.RemoveFile(cls._InstanceQmpMonitor(instance_name))
1011
    utils.RemoveFile(cls._InstanceKVMRuntime(instance_name))
1012
    utils.RemoveFile(cls._InstanceKeymapFile(instance_name))
1013
    uid_file = cls._InstanceUidFile(instance_name)
1014
    uid = cls._TryReadUidFile(uid_file)
1015
    utils.RemoveFile(uid_file)
1016
    if uid is not None:
1017
      uidpool.ReleaseUid(uid)
1018
    try:
1019
      shutil.rmtree(cls._InstanceNICDir(instance_name))
1020
    except OSError, err:
1021
      if err.errno != errno.ENOENT:
1022
        raise
1023
    try:
1024
      chroot_dir = cls._InstanceChrootDir(instance_name)
1025
      utils.RemoveDir(chroot_dir)
1026
    except OSError, err:
1027
      if err.errno == errno.ENOTEMPTY:
1028
        # The chroot directory is expected to be empty, but it isn't.
1029
        new_chroot_dir = tempfile.mkdtemp(dir=cls._CHROOT_QUARANTINE_DIR,
1030
                                          prefix="%s-%s-" %
1031
                                          (instance_name,
1032
                                           utils.TimestampForFilename()))
1033
        logging.warning("The chroot directory of instance %s can not be"
1034
                        " removed as it is not empty. Moving it to the"
1035
                        " quarantine instead. Please investigate the"
1036
                        " contents (%s) and clean up manually",
1037
                        instance_name, new_chroot_dir)
1038
        utils.RenameFile(chroot_dir, new_chroot_dir)
1039
      else:
1040
        raise
1041

    
1042
  @staticmethod
1043
  def _ConfigureNIC(instance, seq, nic, tap):
1044
    """Run the network configuration script for a specified NIC
1045

1046
    @param instance: instance we're acting on
1047
    @type instance: instance object
1048
    @param seq: nic sequence number
1049
    @type seq: int
1050
    @param nic: nic we're acting on
1051
    @type nic: nic object
1052
    @param tap: the host's tap interface this NIC corresponds to
1053
    @type tap: str
1054

1055
    """
1056
    env = {
1057
      "PATH": "%s:/sbin:/usr/sbin" % os.environ["PATH"],
1058
      "INSTANCE": instance.name,
1059
      "MAC": nic.mac,
1060
      "MODE": nic.nicparams[constants.NIC_MODE],
1061
      "INTERFACE": tap,
1062
      "INTERFACE_INDEX": str(seq),
1063
      "INTERFACE_UUID": nic.uuid,
1064
      "TAGS": " ".join(instance.GetTags()),
1065
    }
1066

    
1067
    if nic.ip:
1068
      env["IP"] = nic.ip
1069

    
1070
    if nic.name:
1071
      env["INTERFACE_NAME"] = nic.name
1072

    
1073
    if nic.nicparams[constants.NIC_LINK]:
1074
      env["LINK"] = nic.nicparams[constants.NIC_LINK]
1075

    
1076
    if nic.network:
1077
      n = objects.Network.FromDict(nic.netinfo)
1078
      env.update(n.HooksDict())
1079

    
1080
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1081
      env["BRIDGE"] = nic.nicparams[constants.NIC_LINK]
1082

    
1083
    result = utils.RunCmd([pathutils.KVM_IFUP, tap], env=env)
1084
    if result.failed:
1085
      raise errors.HypervisorError("Failed to configure interface %s: %s;"
1086
                                   " network configuration script output: %s" %
1087
                                   (tap, result.fail_reason, result.output))
1088

    
1089
  @staticmethod
1090
  def _VerifyAffinityPackage():
1091
    if affinity is None:
1092
      raise errors.HypervisorError("affinity Python package not"
1093
                                   " found; cannot use CPU pinning under KVM")
1094

    
1095
  @staticmethod
1096
  def _BuildAffinityCpuMask(cpu_list):
1097
    """Create a CPU mask suitable for sched_setaffinity from a list of
1098
    CPUs.
1099

1100
    See man taskset for more info on sched_setaffinity masks.
1101
    For example: [ 0, 2, 5, 6 ] will return 101 (0x65, 0..01100101).
1102

1103
    @type cpu_list: list of int
1104
    @param cpu_list: list of physical CPU numbers to map to vCPUs in order
1105
    @rtype: int
1106
    @return: a bit mask of CPU affinities
1107

1108
    """
1109
    if cpu_list == constants.CPU_PINNING_OFF:
1110
      return constants.CPU_PINNING_ALL_KVM
1111
    else:
1112
      return sum(2 ** cpu for cpu in cpu_list)
1113

    
1114
  @classmethod
1115
  def _AssignCpuAffinity(cls, cpu_mask, process_id, thread_dict):
1116
    """Change CPU affinity for running VM according to given CPU mask.
1117

1118
    @param cpu_mask: CPU mask as given by the user. e.g. "0-2,4:all:1,3"
1119
    @type cpu_mask: string
1120
    @param process_id: process ID of KVM process. Used to pin entire VM
1121
                       to physical CPUs.
1122
    @type process_id: int
1123
    @param thread_dict: map of virtual CPUs to KVM thread IDs
1124
    @type thread_dict: dict int:int
1125

1126
    """
1127
    # Convert the string CPU mask to a list of list of int's
1128
    cpu_list = utils.ParseMultiCpuMask(cpu_mask)
1129

    
1130
    if len(cpu_list) == 1:
1131
      all_cpu_mapping = cpu_list[0]
1132
      if all_cpu_mapping == constants.CPU_PINNING_OFF:
1133
        # If CPU pinning has 1 entry that's "all", then do nothing
1134
        pass
1135
      else:
1136
        # If CPU pinning has one non-all entry, map the entire VM to
1137
        # one set of physical CPUs
1138
        cls._VerifyAffinityPackage()
1139
        affinity.set_process_affinity_mask(
1140
          process_id, cls._BuildAffinityCpuMask(all_cpu_mapping))
1141
    else:
1142
      # The number of vCPUs mapped should match the number of vCPUs
1143
      # reported by KVM. This was already verified earlier, so
1144
      # here only as a sanity check.
1145
      assert len(thread_dict) == len(cpu_list)
1146
      cls._VerifyAffinityPackage()
1147

    
1148
      # For each vCPU, map it to the proper list of physical CPUs
1149
      for vcpu, i in zip(cpu_list, range(len(cpu_list))):
1150
        affinity.set_process_affinity_mask(thread_dict[i],
1151
                                           cls._BuildAffinityCpuMask(vcpu))
1152

    
1153
  def _GetVcpuThreadIds(self, instance_name):
1154
    """Get a mapping of vCPU no. to thread IDs for the instance
1155

1156
    @type instance_name: string
1157
    @param instance_name: instance in question
1158
    @rtype: dictionary of int:int
1159
    @return: a dictionary mapping vCPU numbers to thread IDs
1160

1161
    """
1162
    result = {}
1163
    output = self._CallMonitorCommand(instance_name, self._CPU_INFO_CMD)
1164
    for line in output.stdout.splitlines():
1165
      match = self._CPU_INFO_RE.search(line)
1166
      if not match:
1167
        continue
1168
      grp = map(int, match.groups())
1169
      result[grp[0]] = grp[1]
1170

    
1171
    return result
1172

    
1173
  def _ExecuteCpuAffinity(self, instance_name, cpu_mask):
1174
    """Complete CPU pinning.
1175

1176
    @type instance_name: string
1177
    @param instance_name: name of instance
1178
    @type cpu_mask: string
1179
    @param cpu_mask: CPU pinning mask as entered by user
1180

1181
    """
1182
    # Get KVM process ID, to be used if need to pin entire VM
1183
    _, pid, _ = self._InstancePidAlive(instance_name)
1184
    # Get vCPU thread IDs, to be used if need to pin vCPUs separately
1185
    thread_dict = self._GetVcpuThreadIds(instance_name)
1186
    # Run CPU pinning, based on configured mask
1187
    self._AssignCpuAffinity(cpu_mask, pid, thread_dict)
1188

    
1189
  def ListInstances(self, hvparams=None):
1190
    """Get the list of running instances.
1191

1192
    We can do this by listing our live instances directory and
1193
    checking whether the associated kvm process is still alive.
1194

1195
    """
1196
    result = []
1197
    for name in os.listdir(self._PIDS_DIR):
1198
      if self._InstancePidAlive(name)[2] or self._IsUserShutdown(name):
1199
        result.append(name)
1200
    return result
1201

    
1202
  @classmethod
1203
  def _IsUserShutdown(cls, instance_name):
1204
    return os.path.exists(cls._InstanceShutdownMonitor(instance_name))
1205

    
1206
  @classmethod
1207
  def _ClearUserShutdown(cls, instance_name):
1208
    utils.RemoveFile(cls._InstanceShutdownMonitor(instance_name))
1209

    
1210
  def GetInstanceInfo(self, instance_name, hvparams=None):
1211
    """Get instance properties.
1212

1213
    @type instance_name: string
1214
    @param instance_name: the instance name
1215
    @type hvparams: dict of strings
1216
    @param hvparams: hvparams to be used with this instance
1217
    @rtype: tuple of strings
1218
    @return: (name, id, memory, vcpus, stat, times)
1219

1220
    """
1221
    _, pid, alive = self._InstancePidAlive(instance_name)
1222
    if not alive:
1223
      if self._IsUserShutdown(instance_name):
1224
        return (instance_name, -1, 0, 0, hv_base.HvInstanceState.SHUTDOWN, 0)
1225
      else:
1226
        return None
1227

    
1228
    _, memory, vcpus = self._InstancePidInfo(pid)
1229
    istat = hv_base.HvInstanceState.RUNNING
1230
    times = 0
1231

    
1232
    try:
1233
      qmp = QmpConnection(self._InstanceQmpMonitor(instance_name))
1234
      qmp.connect()
1235
      vcpus = len(qmp.Execute("query-cpus")[qmp.RETURN_KEY])
1236
      # Will fail if ballooning is not enabled, but we can then just resort to
1237
      # the value above.
1238
      mem_bytes = qmp.Execute("query-balloon")[qmp.RETURN_KEY][qmp.ACTUAL_KEY]
1239
      memory = mem_bytes / 1048576
1240
    except errors.HypervisorError:
1241
      pass
1242

    
1243
    return (instance_name, pid, memory, vcpus, istat, times)
1244

    
1245
  def GetAllInstancesInfo(self, hvparams=None):
1246
    """Get properties of all instances.
1247

1248
    @type hvparams: dict of strings
1249
    @param hvparams: hypervisor parameter
1250
    @return: list of tuples (name, id, memory, vcpus, stat, times)
1251

1252
    """
1253
    data = []
1254
    for name in os.listdir(self._PIDS_DIR):
1255
      try:
1256
        info = self.GetInstanceInfo(name)
1257
      except errors.HypervisorError:
1258
        # Ignore exceptions due to instances being shut down
1259
        continue
1260
      if info:
1261
        data.append(info)
1262
    return data
1263

    
1264
  def _GenerateKVMBlockDevicesOptions(self, instance, kvm_disks,
1265
                                      kvmhelp, devlist):
1266
    """Generate KVM options regarding instance's block devices.
1267

1268
    @type instance: L{objects.Instance}
1269
    @param instance: the instance object
1270
    @type kvm_disks: list of tuples
1271
    @param kvm_disks: list of tuples [(disk, link_name, uri)..]
1272
    @type kvmhelp: string
1273
    @param kvmhelp: output of kvm --help
1274
    @type devlist: string
1275
    @param devlist: output of kvm -device ?
1276
    @rtype: list
1277
    @return: list of command line options eventually used by kvm executable
1278

1279
    """
1280
    hvp = instance.hvparams
1281
    kernel_path = hvp[constants.HV_KERNEL_PATH]
1282
    if kernel_path:
1283
      boot_disk = False
1284
    else:
1285
      boot_disk = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_DISK
1286

    
1287
    # whether this is an older KVM version that uses the boot=on flag
1288
    # on devices
1289
    needs_boot_flag = self._BOOT_RE.search(kvmhelp)
1290

    
1291
    dev_opts = []
1292
    device_driver = None
1293
    disk_type = hvp[constants.HV_DISK_TYPE]
1294
    if disk_type == constants.HT_DISK_PARAVIRTUAL:
1295
      if_val = ",if=%s" % self._VIRTIO
1296
      try:
1297
        if self._VIRTIO_BLK_RE.search(devlist):
1298
          if_val = ",if=none"
1299
          # will be passed in -device option as driver
1300
          device_driver = self._VIRTIO_BLK_PCI
1301
      except errors.HypervisorError, _:
1302
        pass
1303
    else:
1304
      if_val = ",if=%s" % disk_type
1305
    # Cache mode
1306
    disk_cache = hvp[constants.HV_DISK_CACHE]
1307
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1308
      if disk_cache != "none":
1309
        # TODO: make this a hard error, instead of a silent overwrite
1310
        logging.warning("KVM: overriding disk_cache setting '%s' with 'none'"
1311
                        " to prevent shared storage corruption on migration",
1312
                        disk_cache)
1313
      cache_val = ",cache=none"
1314
    elif disk_cache != constants.HT_CACHE_DEFAULT:
1315
      cache_val = ",cache=%s" % disk_cache
1316
    else:
1317
      cache_val = ""
1318
    for cfdev, link_name, uri in kvm_disks:
1319
      if cfdev.mode != constants.DISK_RDWR:
1320
        raise errors.HypervisorError("Instance has read-only disks which"
1321
                                     " are not supported by KVM")
1322
      # TODO: handle FD_LOOP and FD_BLKTAP (?)
1323
      boot_val = ""
1324
      if boot_disk:
1325
        dev_opts.extend(["-boot", "c"])
1326
        boot_disk = False
1327
        if needs_boot_flag and disk_type != constants.HT_DISK_IDE:
1328
          boot_val = ",boot=on"
1329

    
1330
      access_mode = cfdev.params.get(constants.LDP_ACCESS,
1331
                                     constants.DISK_KERNELSPACE)
1332
      if (uri and access_mode == constants.DISK_USERSPACE):
1333
        drive_uri = uri
1334
      else:
1335
        drive_uri = link_name
1336

    
1337
      drive_val = "file=%s,format=raw%s%s%s" % \
1338
                  (drive_uri, if_val, boot_val, cache_val)
1339

    
1340
      if device_driver:
1341
        # kvm_disks are the 4th entry of runtime file that did not exist in
1342
        # the past. That means that cfdev should always have pci slot and
1343
        # _GenerateDeviceKVMId() will not raise a exception.
1344
        kvm_devid = _GenerateDeviceKVMId(constants.HOTPLUG_TARGET_DISK, cfdev)
1345
        drive_val += (",id=%s" % kvm_devid)
1346
        drive_val += (",bus=0,unit=%d" % cfdev.pci)
1347
        dev_val = ("%s,drive=%s,id=%s" %
1348
                   (device_driver, kvm_devid, kvm_devid))
1349
        dev_val += ",bus=pci.0,addr=%s" % hex(cfdev.pci)
1350
        dev_opts.extend(["-device", dev_val])
1351

    
1352
      dev_opts.extend(["-drive", drive_val])
1353

    
1354
    return dev_opts
1355

    
1356
  @staticmethod
1357
  def _CdromOption(kvm_cmd, cdrom_disk_type, cdrom_image, cdrom_boot,
1358
                   needs_boot_flag):
1359
    """Extends L{kvm_cmd} with the '-drive' option for a cdrom, and
1360
    optionally the '-boot' option.
1361

1362
    Example: -drive file=cdrom.iso,media=cdrom,format=raw,if=ide -boot d
1363

1364
    Example: -drive file=cdrom.iso,media=cdrom,format=raw,if=ide,boot=on
1365

1366
    Example: -drive file=http://hostname.com/cdrom.iso,media=cdrom
1367

1368
    @type kvm_cmd: string
1369
    @param kvm_cmd: KVM command line
1370

1371
    @type cdrom_disk_type:
1372
    @param cdrom_disk_type:
1373

1374
    @type cdrom_image:
1375
    @param cdrom_image:
1376

1377
    @type cdrom_boot:
1378
    @param cdrom_boot:
1379

1380
    @type needs_boot_flag:
1381
    @param needs_boot_flag:
1382

1383
    """
1384
    # Check that the ISO image is accessible
1385
    # See https://bugs.launchpad.net/qemu/+bug/597575
1386
    if utils.IsUrl(cdrom_image) and not _CheckUrl(cdrom_image):
1387
      raise errors.HypervisorError("Cdrom ISO image '%s' is not accessible" %
1388
                                   cdrom_image)
1389

    
1390
    # set cdrom 'media' and 'format', if needed
1391
    if utils.IsUrl(cdrom_image):
1392
      options = ",media=cdrom"
1393
    else:
1394
      options = ",media=cdrom,format=raw"
1395

    
1396
    # set cdrom 'if' type
1397
    if cdrom_boot:
1398
      if_val = ",if=" + constants.HT_DISK_IDE
1399
    elif cdrom_disk_type == constants.HT_DISK_PARAVIRTUAL:
1400
      if_val = ",if=virtio"
1401
    else:
1402
      if_val = ",if=" + cdrom_disk_type
1403

    
1404
    # set boot flag, if needed
1405
    boot_val = ""
1406
    if cdrom_boot:
1407
      kvm_cmd.extend(["-boot", "d"])
1408

    
1409
      # whether this is an older KVM version that requires the 'boot=on' flag
1410
      # on devices
1411
      if needs_boot_flag:
1412
        boot_val = ",boot=on"
1413

    
1414
    # build '-drive' option
1415
    drive_val = "file=%s%s%s%s" % (cdrom_image, options, if_val, boot_val)
1416
    kvm_cmd.extend(["-drive", drive_val])
1417

    
1418
  def _GenerateKVMRuntime(self, instance, block_devices, startup_paused,
1419
                          kvmhelp):
1420
    """Generate KVM information to start an instance.
1421

1422
    @type kvmhelp: string
1423
    @param kvmhelp: output of kvm --help
1424
    @attention: this function must not have any side-effects; for
1425
        example, it must not write to the filesystem, or read values
1426
        from the current system the are expected to differ between
1427
        nodes, since it is only run once at instance startup;
1428
        actions/kvm arguments that can vary between systems should be
1429
        done in L{_ExecuteKVMRuntime}
1430

1431
    """
1432
    # pylint: disable=R0912,R0914,R0915
1433
    hvp = instance.hvparams
1434
    self.ValidateParameters(hvp)
1435

    
1436
    pidfile = self._InstancePidFile(instance.name)
1437
    kvm = hvp[constants.HV_KVM_PATH]
1438
    kvm_cmd = [kvm]
1439
    # used just by the vnc server, if enabled
1440
    kvm_cmd.extend(["-name", instance.name])
1441
    kvm_cmd.extend(["-m", instance.beparams[constants.BE_MAXMEM]])
1442

    
1443
    smp_list = ["%s" % instance.beparams[constants.BE_VCPUS]]
1444
    if hvp[constants.HV_CPU_CORES]:
1445
      smp_list.append("cores=%s" % hvp[constants.HV_CPU_CORES])
1446
    if hvp[constants.HV_CPU_THREADS]:
1447
      smp_list.append("threads=%s" % hvp[constants.HV_CPU_THREADS])
1448
    if hvp[constants.HV_CPU_SOCKETS]:
1449
      smp_list.append("sockets=%s" % hvp[constants.HV_CPU_SOCKETS])
1450

    
1451
    kvm_cmd.extend(["-smp", ",".join(smp_list)])
1452

    
1453
    kvm_cmd.extend(["-pidfile", pidfile])
1454
    kvm_cmd.extend(["-balloon", "virtio"])
1455
    kvm_cmd.extend(["-daemonize"])
1456
    if not instance.hvparams[constants.HV_ACPI]:
1457
      kvm_cmd.extend(["-no-acpi"])
1458
    if instance.hvparams[constants.HV_REBOOT_BEHAVIOR] == \
1459
        constants.INSTANCE_REBOOT_EXIT:
1460
      kvm_cmd.extend(["-no-reboot"])
1461

    
1462
    mversion = hvp[constants.HV_KVM_MACHINE_VERSION]
1463
    if not mversion:
1464
      mversion = self._GetDefaultMachineVersion(kvm)
1465
    if self._MACHINE_RE.search(kvmhelp):
1466
      # TODO (2.8): kernel_irqchip and kvm_shadow_mem machine properties, as
1467
      # extra hypervisor parameters. We should also investigate whether and how
1468
      # shadow_mem should be considered for the resource model.
1469
      if (hvp[constants.HV_KVM_FLAG] == constants.HT_KVM_ENABLED):
1470
        specprop = ",accel=kvm"
1471
      else:
1472
        specprop = ""
1473
      machinespec = "%s%s" % (mversion, specprop)
1474
      kvm_cmd.extend(["-machine", machinespec])
1475
    else:
1476
      kvm_cmd.extend(["-M", mversion])
1477
      if (hvp[constants.HV_KVM_FLAG] == constants.HT_KVM_ENABLED and
1478
          self._ENABLE_KVM_RE.search(kvmhelp)):
1479
        kvm_cmd.extend(["-enable-kvm"])
1480
      elif (hvp[constants.HV_KVM_FLAG] == constants.HT_KVM_DISABLED and
1481
            self._DISABLE_KVM_RE.search(kvmhelp)):
1482
        kvm_cmd.extend(["-disable-kvm"])
1483

    
1484
    kernel_path = hvp[constants.HV_KERNEL_PATH]
1485
    if kernel_path:
1486
      boot_cdrom = boot_floppy = boot_network = False
1487
    else:
1488
      boot_cdrom = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_CDROM
1489
      boot_floppy = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_FLOPPY
1490
      boot_network = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_NETWORK
1491

    
1492
    if startup_paused:
1493
      kvm_cmd.extend([_KVM_START_PAUSED_FLAG])
1494

    
1495
    if boot_network:
1496
      kvm_cmd.extend(["-boot", "n"])
1497

    
1498
    disk_type = hvp[constants.HV_DISK_TYPE]
1499

    
1500
    # Now we can specify a different device type for CDROM devices.
1501
    cdrom_disk_type = hvp[constants.HV_KVM_CDROM_DISK_TYPE]
1502
    if not cdrom_disk_type:
1503
      cdrom_disk_type = disk_type
1504

    
1505
    cdrom_image1 = hvp[constants.HV_CDROM_IMAGE_PATH]
1506
    if cdrom_image1:
1507
      needs_boot_flag = self._BOOT_RE.search(kvmhelp)
1508
      self._CdromOption(kvm_cmd, cdrom_disk_type, cdrom_image1, boot_cdrom,
1509
                        needs_boot_flag)
1510

    
1511
    cdrom_image2 = hvp[constants.HV_KVM_CDROM2_IMAGE_PATH]
1512
    if cdrom_image2:
1513
      self._CdromOption(kvm_cmd, cdrom_disk_type, cdrom_image2, False, False)
1514

    
1515
    floppy_image = hvp[constants.HV_KVM_FLOPPY_IMAGE_PATH]
1516
    if floppy_image:
1517
      options = ",format=raw,media=disk"
1518
      if boot_floppy:
1519
        kvm_cmd.extend(["-boot", "a"])
1520
        options = "%s,boot=on" % options
1521
      if_val = ",if=floppy"
1522
      options = "%s%s" % (options, if_val)
1523
      drive_val = "file=%s%s" % (floppy_image, options)
1524
      kvm_cmd.extend(["-drive", drive_val])
1525

    
1526
    if kernel_path:
1527
      kvm_cmd.extend(["-kernel", kernel_path])
1528
      initrd_path = hvp[constants.HV_INITRD_PATH]
1529
      if initrd_path:
1530
        kvm_cmd.extend(["-initrd", initrd_path])
1531
      root_append = ["root=%s" % hvp[constants.HV_ROOT_PATH],
1532
                     hvp[constants.HV_KERNEL_ARGS]]
1533
      if hvp[constants.HV_SERIAL_CONSOLE]:
1534
        serial_speed = hvp[constants.HV_SERIAL_SPEED]
1535
        root_append.append("console=ttyS0,%s" % serial_speed)
1536
      kvm_cmd.extend(["-append", " ".join(root_append)])
1537

    
1538
    mem_path = hvp[constants.HV_MEM_PATH]
1539
    if mem_path:
1540
      kvm_cmd.extend(["-mem-path", mem_path, "-mem-prealloc"])
1541

    
1542
    monitor_dev = ("unix:%s,server,nowait" %
1543
                   self._InstanceMonitor(instance.name))
1544
    kvm_cmd.extend(["-monitor", monitor_dev])
1545
    if hvp[constants.HV_SERIAL_CONSOLE]:
1546
      serial_dev = ("unix:%s,server,nowait" %
1547
                    self._InstanceSerial(instance.name))
1548
      kvm_cmd.extend(["-serial", serial_dev])
1549
    else:
1550
      kvm_cmd.extend(["-serial", "none"])
1551

    
1552
    mouse_type = hvp[constants.HV_USB_MOUSE]
1553
    vnc_bind_address = hvp[constants.HV_VNC_BIND_ADDRESS]
1554
    spice_bind = hvp[constants.HV_KVM_SPICE_BIND]
1555
    spice_ip_version = None
1556

    
1557
    kvm_cmd.extend(["-usb"])
1558

    
1559
    if mouse_type:
1560
      kvm_cmd.extend(["-usbdevice", mouse_type])
1561
    elif vnc_bind_address:
1562
      kvm_cmd.extend(["-usbdevice", constants.HT_MOUSE_TABLET])
1563

    
1564
    if vnc_bind_address:
1565
      if netutils.IsValidInterface(vnc_bind_address):
1566
        if_addresses = netutils.GetInterfaceIpAddresses(vnc_bind_address)
1567
        if_ip4_addresses = if_addresses[constants.IP4_VERSION]
1568
        if len(if_ip4_addresses) < 1:
1569
          logging.error("Could not determine IPv4 address of interface %s",
1570
                        vnc_bind_address)
1571
        else:
1572
          vnc_bind_address = if_ip4_addresses[0]
1573
      if netutils.IP4Address.IsValid(vnc_bind_address):
1574
        if instance.network_port > constants.VNC_BASE_PORT:
1575
          display = instance.network_port - constants.VNC_BASE_PORT
1576
          if vnc_bind_address == constants.IP4_ADDRESS_ANY:
1577
            vnc_arg = ":%d" % (display)
1578
          else:
1579
            vnc_arg = "%s:%d" % (vnc_bind_address, display)
1580
        else:
1581
          logging.error("Network port is not a valid VNC display (%d < %d),"
1582
                        " not starting VNC",
1583
                        instance.network_port, constants.VNC_BASE_PORT)
1584
          vnc_arg = "none"
1585

    
1586
        # Only allow tls and other option when not binding to a file, for now.
1587
        # kvm/qemu gets confused otherwise about the filename to use.
1588
        vnc_append = ""
1589
        if hvp[constants.HV_VNC_TLS]:
1590
          vnc_append = "%s,tls" % vnc_append
1591
          if hvp[constants.HV_VNC_X509_VERIFY]:
1592
            vnc_append = "%s,x509verify=%s" % (vnc_append,
1593
                                               hvp[constants.HV_VNC_X509])
1594
          elif hvp[constants.HV_VNC_X509]:
1595
            vnc_append = "%s,x509=%s" % (vnc_append,
1596
                                         hvp[constants.HV_VNC_X509])
1597
        if hvp[constants.HV_VNC_PASSWORD_FILE]:
1598
          vnc_append = "%s,password" % vnc_append
1599

    
1600
        vnc_arg = "%s%s" % (vnc_arg, vnc_append)
1601

    
1602
      else:
1603
        vnc_arg = "unix:%s/%s.vnc" % (vnc_bind_address, instance.name)
1604

    
1605
      kvm_cmd.extend(["-vnc", vnc_arg])
1606
    elif spice_bind:
1607
      # FIXME: this is wrong here; the iface ip address differs
1608
      # between systems, so it should be done in _ExecuteKVMRuntime
1609
      if netutils.IsValidInterface(spice_bind):
1610
        # The user specified a network interface, we have to figure out the IP
1611
        # address.
1612
        addresses = netutils.GetInterfaceIpAddresses(spice_bind)
1613
        spice_ip_version = hvp[constants.HV_KVM_SPICE_IP_VERSION]
1614

    
1615
        # if the user specified an IP version and the interface does not
1616
        # have that kind of IP addresses, throw an exception
1617
        if spice_ip_version != constants.IFACE_NO_IP_VERSION_SPECIFIED:
1618
          if not addresses[spice_ip_version]:
1619
            raise errors.HypervisorError("SPICE: Unable to get an IPv%s address"
1620
                                         " for %s" % (spice_ip_version,
1621
                                                      spice_bind))
1622

    
1623
        # the user did not specify an IP version, we have to figure it out
1624
        elif (addresses[constants.IP4_VERSION] and
1625
              addresses[constants.IP6_VERSION]):
1626
          # we have both ipv4 and ipv6, let's use the cluster default IP
1627
          # version
1628
          cluster_family = ssconf.SimpleStore().GetPrimaryIPFamily()
1629
          spice_ip_version = \
1630
            netutils.IPAddress.GetVersionFromAddressFamily(cluster_family)
1631
        elif addresses[constants.IP4_VERSION]:
1632
          spice_ip_version = constants.IP4_VERSION
1633
        elif addresses[constants.IP6_VERSION]:
1634
          spice_ip_version = constants.IP6_VERSION
1635
        else:
1636
          raise errors.HypervisorError("SPICE: Unable to get an IP address"
1637
                                       " for %s" % (spice_bind))
1638

    
1639
        spice_address = addresses[spice_ip_version][0]
1640

    
1641
      else:
1642
        # spice_bind is known to be a valid IP address, because
1643
        # ValidateParameters checked it.
1644
        spice_address = spice_bind
1645

    
1646
      spice_arg = "addr=%s" % spice_address
1647
      if hvp[constants.HV_KVM_SPICE_USE_TLS]:
1648
        spice_arg = ("%s,tls-port=%s,x509-cacert-file=%s" %
1649
                     (spice_arg, instance.network_port,
1650
                      pathutils.SPICE_CACERT_FILE))
1651
        spice_arg = ("%s,x509-key-file=%s,x509-cert-file=%s" %
1652
                     (spice_arg, pathutils.SPICE_CERT_FILE,
1653
                      pathutils.SPICE_CERT_FILE))
1654
        tls_ciphers = hvp[constants.HV_KVM_SPICE_TLS_CIPHERS]
1655
        if tls_ciphers:
1656
          spice_arg = "%s,tls-ciphers=%s" % (spice_arg, tls_ciphers)
1657
      else:
1658
        spice_arg = "%s,port=%s" % (spice_arg, instance.network_port)
1659

    
1660
      if not hvp[constants.HV_KVM_SPICE_PASSWORD_FILE]:
1661
        spice_arg = "%s,disable-ticketing" % spice_arg
1662

    
1663
      if spice_ip_version:
1664
        spice_arg = "%s,ipv%s" % (spice_arg, spice_ip_version)
1665

    
1666
      # Image compression options
1667
      img_lossless = hvp[constants.HV_KVM_SPICE_LOSSLESS_IMG_COMPR]
1668
      img_jpeg = hvp[constants.HV_KVM_SPICE_JPEG_IMG_COMPR]
1669
      img_zlib_glz = hvp[constants.HV_KVM_SPICE_ZLIB_GLZ_IMG_COMPR]
1670
      if img_lossless:
1671
        spice_arg = "%s,image-compression=%s" % (spice_arg, img_lossless)
1672
      if img_jpeg:
1673
        spice_arg = "%s,jpeg-wan-compression=%s" % (spice_arg, img_jpeg)
1674
      if img_zlib_glz:
1675
        spice_arg = "%s,zlib-glz-wan-compression=%s" % (spice_arg, img_zlib_glz)
1676

    
1677
      # Video stream detection
1678
      video_streaming = hvp[constants.HV_KVM_SPICE_STREAMING_VIDEO_DETECTION]
1679
      if video_streaming:
1680
        spice_arg = "%s,streaming-video=%s" % (spice_arg, video_streaming)
1681

    
1682
      # Audio compression, by default in qemu-kvm it is on
1683
      if not hvp[constants.HV_KVM_SPICE_AUDIO_COMPR]:
1684
        spice_arg = "%s,playback-compression=off" % spice_arg
1685
      if not hvp[constants.HV_KVM_SPICE_USE_VDAGENT]:
1686
        spice_arg = "%s,agent-mouse=off" % spice_arg
1687
      else:
1688
        # Enable the spice agent communication channel between the host and the
1689
        # agent.
1690
        kvm_cmd.extend(["-device", "virtio-serial-pci"])
1691
        kvm_cmd.extend([
1692
          "-device",
1693
          "virtserialport,chardev=spicechannel0,name=com.redhat.spice.0",
1694
          ])
1695
        kvm_cmd.extend(["-chardev", "spicevmc,id=spicechannel0,name=vdagent"])
1696

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

    
1700
    else:
1701
      # From qemu 1.4 -nographic is incompatible with -daemonize. The new way
1702
      # also works in earlier versions though (tested with 1.1 and 1.3)
1703
      if self._DISPLAY_RE.search(kvmhelp):
1704
        kvm_cmd.extend(["-display", "none"])
1705
      else:
1706
        kvm_cmd.extend(["-nographic"])
1707

    
1708
    if hvp[constants.HV_USE_LOCALTIME]:
1709
      kvm_cmd.extend(["-localtime"])
1710

    
1711
    if hvp[constants.HV_KVM_USE_CHROOT]:
1712
      kvm_cmd.extend(["-chroot", self._InstanceChrootDir(instance.name)])
1713

    
1714
    # Add qemu-KVM -cpu param
1715
    if hvp[constants.HV_CPU_TYPE]:
1716
      kvm_cmd.extend(["-cpu", hvp[constants.HV_CPU_TYPE]])
1717

    
1718
    # As requested by music lovers
1719
    if hvp[constants.HV_SOUNDHW]:
1720
      kvm_cmd.extend(["-soundhw", hvp[constants.HV_SOUNDHW]])
1721

    
1722
    # Pass a -vga option if requested, or if spice is used, for backwards
1723
    # compatibility.
1724
    if hvp[constants.HV_VGA]:
1725
      kvm_cmd.extend(["-vga", hvp[constants.HV_VGA]])
1726
    elif spice_bind:
1727
      kvm_cmd.extend(["-vga", "qxl"])
1728

    
1729
    # Various types of usb devices, comma separated
1730
    if hvp[constants.HV_USB_DEVICES]:
1731
      for dev in hvp[constants.HV_USB_DEVICES].split(","):
1732
        kvm_cmd.extend(["-usbdevice", dev])
1733

    
1734
    # Set system UUID to instance UUID
1735
    if self._UUID_RE.search(kvmhelp):
1736
      kvm_cmd.extend(["-uuid", instance.uuid])
1737

    
1738
    if hvp[constants.HV_KVM_EXTRA]:
1739
      kvm_cmd.extend(hvp[constants.HV_KVM_EXTRA].split(" "))
1740

    
1741
    pci_reservations = bitarray(self._DEFAULT_PCI_RESERVATIONS)
1742
    kvm_disks = []
1743
    for disk, link_name, uri in block_devices:
1744
      _UpdatePCISlots(disk, pci_reservations)
1745
      kvm_disks.append((disk, link_name, uri))
1746

    
1747
    kvm_nics = []
1748
    for nic in instance.nics:
1749
      _UpdatePCISlots(nic, pci_reservations)
1750
      kvm_nics.append(nic)
1751

    
1752
    hvparams = hvp
1753

    
1754
    return (kvm_cmd, kvm_nics, hvparams, kvm_disks)
1755

    
1756
  def _WriteKVMRuntime(self, instance_name, data):
1757
    """Write an instance's KVM runtime
1758

1759
    """
1760
    try:
1761
      utils.WriteFile(self._InstanceKVMRuntime(instance_name),
1762
                      data=data)
1763
    except EnvironmentError, err:
1764
      raise errors.HypervisorError("Failed to save KVM runtime file: %s" % err)
1765

    
1766
  def _ReadKVMRuntime(self, instance_name):
1767
    """Read an instance's KVM runtime
1768

1769
    """
1770
    try:
1771
      file_content = utils.ReadFile(self._InstanceKVMRuntime(instance_name))
1772
    except EnvironmentError, err:
1773
      raise errors.HypervisorError("Failed to load KVM runtime file: %s" % err)
1774
    return file_content
1775

    
1776
  def _SaveKVMRuntime(self, instance, kvm_runtime):
1777
    """Save an instance's KVM runtime
1778

1779
    """
1780
    kvm_cmd, kvm_nics, hvparams, kvm_disks = kvm_runtime
1781

    
1782
    serialized_nics = [nic.ToDict() for nic in kvm_nics]
1783
    serialized_disks = [(blk.ToDict(), link, uri)
1784
                        for blk, link, uri in kvm_disks]
1785
    serialized_form = serializer.Dump((kvm_cmd, serialized_nics, hvparams,
1786
                                      serialized_disks))
1787

    
1788
    self._WriteKVMRuntime(instance.name, serialized_form)
1789

    
1790
  def _LoadKVMRuntime(self, instance, serialized_runtime=None):
1791
    """Load an instance's KVM runtime
1792

1793
    """
1794
    if not serialized_runtime:
1795
      serialized_runtime = self._ReadKVMRuntime(instance.name)
1796

    
1797
    return _AnalyzeSerializedRuntime(serialized_runtime)
1798

    
1799
  def _RunKVMCmd(self, name, kvm_cmd, tap_fds=None):
1800
    """Run the KVM cmd and check for errors
1801

1802
    @type name: string
1803
    @param name: instance name
1804
    @type kvm_cmd: list of strings
1805
    @param kvm_cmd: runcmd input for kvm
1806
    @type tap_fds: list of int
1807
    @param tap_fds: fds of tap devices opened by Ganeti
1808

1809
    """
1810
    try:
1811
      result = utils.RunCmd(kvm_cmd, noclose_fds=tap_fds)
1812
    finally:
1813
      for fd in tap_fds:
1814
        utils_wrapper.CloseFdNoError(fd)
1815

    
1816
    if result.failed:
1817
      raise errors.HypervisorError("Failed to start instance %s: %s (%s)" %
1818
                                   (name, result.fail_reason, result.output))
1819
    if not self._InstancePidAlive(name)[2]:
1820
      raise errors.HypervisorError("Failed to start instance %s" % name)
1821

    
1822
  # too many local variables
1823
  # pylint: disable=R0914
1824
  def _ExecuteKVMRuntime(self, instance, kvm_runtime, kvmhelp, incoming=None):
1825
    """Execute a KVM cmd, after completing it with some last minute data.
1826

1827
    @type incoming: tuple of strings
1828
    @param incoming: (target_host_ip, port)
1829
    @type kvmhelp: string
1830
    @param kvmhelp: output of kvm --help
1831

1832
    """
1833
    # Small _ExecuteKVMRuntime hv parameters programming howto:
1834
    #  - conf_hvp contains the parameters as configured on ganeti. they might
1835
    #    have changed since the instance started; only use them if the change
1836
    #    won't affect the inside of the instance (which hasn't been rebooted).
1837
    #  - up_hvp contains the parameters as they were when the instance was
1838
    #    started, plus any new parameter which has been added between ganeti
1839
    #    versions: it is paramount that those default to a value which won't
1840
    #    affect the inside of the instance as well.
1841
    conf_hvp = instance.hvparams
1842
    name = instance.name
1843
    self._CheckDown(name)
1844

    
1845
    self._ClearUserShutdown(instance.name)
1846
    self._StartKvmd(instance.hvparams)
1847

    
1848
    temp_files = []
1849

    
1850
    kvm_cmd, kvm_nics, up_hvp, kvm_disks = kvm_runtime
1851
    # the first element of kvm_cmd is always the path to the kvm binary
1852
    kvm_path = kvm_cmd[0]
1853
    up_hvp = objects.FillDict(conf_hvp, up_hvp)
1854

    
1855
    # We know it's safe to run as a different user upon migration, so we'll use
1856
    # the latest conf, from conf_hvp.
1857
    security_model = conf_hvp[constants.HV_SECURITY_MODEL]
1858
    if security_model == constants.HT_SM_USER:
1859
      kvm_cmd.extend(["-runas", conf_hvp[constants.HV_SECURITY_DOMAIN]])
1860

    
1861
    keymap = conf_hvp[constants.HV_KEYMAP]
1862
    if keymap:
1863
      keymap_path = self._InstanceKeymapFile(name)
1864
      # If a keymap file is specified, KVM won't use its internal defaults. By
1865
      # first including the "en-us" layout, an error on loading the actual
1866
      # layout (e.g. because it can't be found) won't lead to a non-functional
1867
      # keyboard. A keyboard with incorrect keys is still better than none.
1868
      utils.WriteFile(keymap_path, data="include en-us\ninclude %s\n" % keymap)
1869
      kvm_cmd.extend(["-k", keymap_path])
1870

    
1871
    # We have reasons to believe changing something like the nic driver/type
1872
    # upon migration won't exactly fly with the instance kernel, so for nic
1873
    # related parameters we'll use up_hvp
1874
    tapfds = []
1875
    taps = []
1876
    devlist = self._GetKVMOutput(kvm_path, self._KVMOPT_DEVICELIST)
1877
    if not kvm_nics:
1878
      kvm_cmd.extend(["-net", "none"])
1879
    else:
1880
      vnet_hdr = False
1881
      tap_extra = ""
1882
      nic_type = up_hvp[constants.HV_NIC_TYPE]
1883
      if nic_type == constants.HT_NIC_PARAVIRTUAL:
1884
        nic_model = self._VIRTIO
1885
        try:
1886
          if self._VIRTIO_NET_RE.search(devlist):
1887
            nic_model = self._VIRTIO_NET_PCI
1888
            vnet_hdr = up_hvp[constants.HV_VNET_HDR]
1889
        except errors.HypervisorError, _:
1890
          # Older versions of kvm don't support DEVICE_LIST, but they don't
1891
          # have new virtio syntax either.
1892
          pass
1893

    
1894
        if up_hvp[constants.HV_VHOST_NET]:
1895
          # check for vhost_net support
1896
          if self._VHOST_RE.search(kvmhelp):
1897
            tap_extra = ",vhost=on"
1898
          else:
1899
            raise errors.HypervisorError("vhost_net is configured"
1900
                                         " but it is not available")
1901
      else:
1902
        nic_model = nic_type
1903

    
1904
      kvm_supports_netdev = self._NETDEV_RE.search(kvmhelp)
1905

    
1906
      for nic_seq, nic in enumerate(kvm_nics):
1907
        tapname, tapfd = _OpenTap(vnet_hdr=vnet_hdr)
1908
        tapfds.append(tapfd)
1909
        taps.append(tapname)
1910
        if kvm_supports_netdev:
1911
          nic_val = "%s,mac=%s" % (nic_model, nic.mac)
1912
          try:
1913
            # kvm_nics already exist in old runtime files and thus there might
1914
            # be some entries without pci slot (therefore try: except:)
1915
            kvm_devid = _GenerateDeviceKVMId(constants.HOTPLUG_TARGET_NIC, nic)
1916
            netdev = kvm_devid
1917
            nic_val += (",id=%s,bus=pci.0,addr=%s" % (kvm_devid, hex(nic.pci)))
1918
          except errors.HotplugError:
1919
            netdev = "netdev%d" % nic_seq
1920
          nic_val += (",netdev=%s" % netdev)
1921
          tap_val = ("type=tap,id=%s,fd=%d%s" %
1922
                     (netdev, tapfd, tap_extra))
1923
          kvm_cmd.extend(["-netdev", tap_val, "-device", nic_val])
1924
        else:
1925
          nic_val = "nic,vlan=%s,macaddr=%s,model=%s" % (nic_seq,
1926
                                                         nic.mac, nic_model)
1927
          tap_val = "tap,vlan=%s,fd=%d" % (nic_seq, tapfd)
1928
          kvm_cmd.extend(["-net", tap_val, "-net", nic_val])
1929

    
1930
    if incoming:
1931
      target, port = incoming
1932
      kvm_cmd.extend(["-incoming", "tcp:%s:%s" % (target, port)])
1933

    
1934
    # Changing the vnc password doesn't bother the guest that much. At most it
1935
    # will surprise people who connect to it. Whether positively or negatively
1936
    # it's debatable.
1937
    vnc_pwd_file = conf_hvp[constants.HV_VNC_PASSWORD_FILE]
1938
    vnc_pwd = None
1939
    if vnc_pwd_file:
1940
      try:
1941
        vnc_pwd = utils.ReadOneLineFile(vnc_pwd_file, strict=True)
1942
      except EnvironmentError, err:
1943
        raise errors.HypervisorError("Failed to open VNC password file %s: %s"
1944
                                     % (vnc_pwd_file, err))
1945

    
1946
    if conf_hvp[constants.HV_KVM_USE_CHROOT]:
1947
      utils.EnsureDirs([(self._InstanceChrootDir(name),
1948
                         constants.SECURE_DIR_MODE)])
1949

    
1950
    # Automatically enable QMP if version is >= 0.14
1951
    if self._QMP_RE.search(kvmhelp):
1952
      logging.debug("Enabling QMP")
1953
      kvm_cmd.extend(["-qmp", "unix:%s,server,nowait" %
1954
                      self._InstanceQmpMonitor(instance.name)])
1955

    
1956
    # Configure the network now for starting instances and bridged interfaces,
1957
    # during FinalizeMigration for incoming instances' routed interfaces
1958
    for nic_seq, nic in enumerate(kvm_nics):
1959
      if (incoming and
1960
          nic.nicparams[constants.NIC_MODE] != constants.NIC_MODE_BRIDGED):
1961
        continue
1962
      self._ConfigureNIC(instance, nic_seq, nic, taps[nic_seq])
1963

    
1964
    bdev_opts = self._GenerateKVMBlockDevicesOptions(instance,
1965
                                                     kvm_disks,
1966
                                                     kvmhelp,
1967
                                                     devlist)
1968
    kvm_cmd.extend(bdev_opts)
1969
    # CPU affinity requires kvm to start paused, so we set this flag if the
1970
    # instance is not already paused and if we are not going to accept a
1971
    # migrating instance. In the latter case, pausing is not needed.
1972
    start_kvm_paused = not (_KVM_START_PAUSED_FLAG in kvm_cmd) and not incoming
1973
    if start_kvm_paused:
1974
      kvm_cmd.extend([_KVM_START_PAUSED_FLAG])
1975

    
1976
    # Note: CPU pinning is using up_hvp since changes take effect
1977
    # during instance startup anyway, and to avoid problems when soft
1978
    # rebooting the instance.
1979
    cpu_pinning = False
1980
    if up_hvp.get(constants.HV_CPU_MASK, None):
1981
      cpu_pinning = True
1982

    
1983
    if security_model == constants.HT_SM_POOL:
1984
      ss = ssconf.SimpleStore()
1985
      uid_pool = uidpool.ParseUidPool(ss.GetUidPool(), separator="\n")
1986
      all_uids = set(uidpool.ExpandUidPool(uid_pool))
1987
      uid = uidpool.RequestUnusedUid(all_uids)
1988
      try:
1989
        username = pwd.getpwuid(uid.GetUid()).pw_name
1990
        kvm_cmd.extend(["-runas", username])
1991
        self._RunKVMCmd(name, kvm_cmd, tapfds)
1992
      except:
1993
        uidpool.ReleaseUid(uid)
1994
        raise
1995
      else:
1996
        uid.Unlock()
1997
        utils.WriteFile(self._InstanceUidFile(name), data=uid.AsStr())
1998
    else:
1999
      self._RunKVMCmd(name, kvm_cmd, tapfds)
2000

    
2001
    utils.EnsureDirs([(self._InstanceNICDir(instance.name),
2002
                     constants.RUN_DIRS_MODE)])
2003
    for nic_seq, tap in enumerate(taps):
2004
      utils.WriteFile(self._InstanceNICFile(instance.name, nic_seq),
2005
                      data=tap)
2006

    
2007
    if vnc_pwd:
2008
      change_cmd = "change vnc password %s" % vnc_pwd
2009
      self._CallMonitorCommand(instance.name, change_cmd)
2010

    
2011
    # Setting SPICE password. We are not vulnerable to malicious passwordless
2012
    # connection attempts because SPICE by default does not allow connections
2013
    # if neither a password nor the "disable_ticketing" options are specified.
2014
    # As soon as we send the password via QMP, that password is a valid ticket
2015
    # for connection.
2016
    spice_password_file = conf_hvp[constants.HV_KVM_SPICE_PASSWORD_FILE]
2017
    if spice_password_file:
2018
      spice_pwd = ""
2019
      try:
2020
        spice_pwd = utils.ReadOneLineFile(spice_password_file, strict=True)
2021
      except EnvironmentError, err:
2022
        raise errors.HypervisorError("Failed to open SPICE password file %s: %s"
2023
                                     % (spice_password_file, err))
2024

    
2025
      qmp = QmpConnection(self._InstanceQmpMonitor(instance.name))
2026
      qmp.connect()
2027
      arguments = {
2028
          "protocol": "spice",
2029
          "password": spice_pwd,
2030
      }
2031
      qmp.Execute("set_password", arguments)
2032

    
2033
    for filename in temp_files:
2034
      utils.RemoveFile(filename)
2035

    
2036
    # If requested, set CPU affinity and resume instance execution
2037
    if cpu_pinning:
2038
      self._ExecuteCpuAffinity(instance.name, up_hvp[constants.HV_CPU_MASK])
2039

    
2040
    start_memory = self._InstanceStartupMemory(instance)
2041
    if start_memory < instance.beparams[constants.BE_MAXMEM]:
2042
      self.BalloonInstanceMemory(instance, start_memory)
2043

    
2044
    if start_kvm_paused:
2045
      # To control CPU pinning, ballooning, and vnc/spice passwords
2046
      # the VM was started in a frozen state. If freezing was not
2047
      # explicitly requested resume the vm status.
2048
      self._CallMonitorCommand(instance.name, self._CONT_CMD)
2049

    
2050
  @staticmethod
2051
  def _StartKvmd(hvparams):
2052
    """Ensure that the Kvm daemon is running.
2053

2054
    """
2055
    if hvparams is None \
2056
          or not hvparams[constants.HV_KVM_USER_SHUTDOWN] \
2057
          or utils.IsDaemonAlive(constants.KVMD):
2058
      return
2059

    
2060
    result = utils.RunCmd(constants.KVMD)
2061

    
2062
    if result.failed:
2063
      raise errors.HypervisorError("Failed to start KVM daemon")
2064

    
2065
  def StartInstance(self, instance, block_devices, startup_paused):
2066
    """Start an instance.
2067

2068
    """
2069
    self._CheckDown(instance.name)
2070
    kvmpath = instance.hvparams[constants.HV_KVM_PATH]
2071
    kvmhelp = self._GetKVMOutput(kvmpath, self._KVMOPT_HELP)
2072
    kvm_runtime = self._GenerateKVMRuntime(instance, block_devices,
2073
                                           startup_paused, kvmhelp)
2074
    self._SaveKVMRuntime(instance, kvm_runtime)
2075
    self._ExecuteKVMRuntime(instance, kvm_runtime, kvmhelp)
2076

    
2077
  @classmethod
2078
  def _CallMonitorCommand(cls, instance_name, command):
2079
    """Invoke a command on the instance monitor.
2080

2081
    """
2082
    # TODO: Replace monitor calls with QMP once KVM >= 0.14 is the minimum
2083
    # version. The monitor protocol is designed for human consumption, whereas
2084
    # QMP is made for programmatic usage. In the worst case QMP can also
2085
    # execute monitor commands. As it is, all calls to socat take at least
2086
    # 500ms and likely more: socat can't detect the end of the reply and waits
2087
    # for 500ms of no data received before exiting (500 ms is the default for
2088
    # the "-t" parameter).
2089
    socat = ("echo %s | %s STDIO UNIX-CONNECT:%s" %
2090
             (utils.ShellQuote(command),
2091
              constants.SOCAT_PATH,
2092
              utils.ShellQuote(cls._InstanceMonitor(instance_name))))
2093
    result = utils.RunCmd(socat)
2094
    if result.failed:
2095
      msg = ("Failed to send command '%s' to instance '%s', reason '%s',"
2096
             " output: %s" %
2097
             (command, instance_name, result.fail_reason, result.output))
2098
      raise errors.HypervisorError(msg)
2099

    
2100
    return result
2101

    
2102
  def _GetFreePCISlot(self, instance, dev):
2103
    """Get the first available pci slot of a runnung instance.
2104

2105
    """
2106
    slots = bitarray(32)
2107
    slots.setall(False) # pylint: disable=E1101
2108
    output = self._CallMonitorCommand(instance.name, self._INFO_PCI_CMD)
2109
    for line in output.stdout.splitlines():
2110
      match = self._INFO_PCI_RE.search(line)
2111
      if match:
2112
        slot = int(match.group(1))
2113
        slots[slot] = True
2114

    
2115
    [free] = slots.search(_AVAILABLE_PCI_SLOT, 1) # pylint: disable=E1101
2116
    if not free:
2117
      raise errors.HypervisorError("All PCI slots occupied")
2118

    
2119
    dev.pci = int(free)
2120

    
2121
  def VerifyHotplugSupport(self, instance, action, dev_type):
2122
    """Verifies that hotplug is supported.
2123

2124
    Hotplug is *not* supported in case of:
2125
     - security models and chroot (disk hotplug)
2126
     - fdsend module is missing (nic hot-add)
2127

2128
    @raise errors.HypervisorError: in one of the previous cases
2129

2130
    """
2131
    if dev_type == constants.HOTPLUG_TARGET_DISK:
2132
      hvp = instance.hvparams
2133
      security_model = hvp[constants.HV_SECURITY_MODEL]
2134
      use_chroot = hvp[constants.HV_KVM_USE_CHROOT]
2135
      if use_chroot:
2136
        raise errors.HotplugError("Disk hotplug is not supported"
2137
                                  " in case of chroot.")
2138
      if security_model != constants.HT_SM_NONE:
2139
        raise errors.HotplugError("Disk Hotplug is not supported in case"
2140
                                  " security models are used.")
2141

    
2142
    if (dev_type == constants.HOTPLUG_TARGET_NIC and
2143
        action == constants.HOTPLUG_ACTION_ADD and not fdsend):
2144
      raise errors.HotplugError("Cannot hot-add NIC."
2145
                                " fdsend python module is missing.")
2146

    
2147
  def HotplugSupported(self, instance):
2148
    """Checks if hotplug is generally supported.
2149

2150
    Hotplug is *not* supported in case of:
2151
     - qemu versions < 1.0
2152
     - for stopped instances
2153

2154
    @raise errors.HypervisorError: in one of the previous cases
2155

2156
    """
2157
    try:
2158
      output = self._CallMonitorCommand(instance.name, self._INFO_VERSION_CMD)
2159
    except errors.HypervisorError:
2160
      raise errors.HotplugError("Instance is probably down")
2161

    
2162
    # TODO: search for netdev_add, drive_add, device_add.....
2163
    match = self._INFO_VERSION_RE.search(output.stdout)
2164
    if not match:
2165
      raise errors.HotplugError("Cannot parse qemu version via monitor")
2166

    
2167
    v_major, v_min, _, _ = match.groups()
2168
    if (int(v_major), int(v_min)) < (1, 0):
2169
      raise errors.HotplugError("Hotplug not supported for qemu versions < 1.0")
2170

    
2171
  def _CallHotplugCommand(self, name, cmd):
2172
    output = self._CallMonitorCommand(name, cmd)
2173
    # TODO: parse output and check if succeeded
2174
    for line in output.stdout.splitlines():
2175
      logging.info("%s", line)
2176

    
2177
  def HotAddDevice(self, instance, dev_type, device, extra, seq):
2178
    """ Helper method to hot-add a new device
2179

2180
    It gets free pci slot generates the device name and invokes the
2181
    device specific method.
2182

2183
    """
2184
    # in case of hot-mod this is given
2185
    if device.pci is None:
2186
      self._GetFreePCISlot(instance, device)
2187
    kvm_devid = _GenerateDeviceKVMId(dev_type, device)
2188
    runtime = self._LoadKVMRuntime(instance)
2189
    if dev_type == constants.HOTPLUG_TARGET_DISK:
2190
      command = "drive_add dummy file=%s,if=none,id=%s,format=raw\n" % \
2191
                 (extra, kvm_devid)
2192
      command += ("device_add virtio-blk-pci,bus=pci.0,addr=%s,drive=%s,id=%s" %
2193
                  (hex(device.pci), kvm_devid, kvm_devid))
2194
    elif dev_type == constants.HOTPLUG_TARGET_NIC:
2195
      (tap, fd) = _OpenTap()
2196
      self._ConfigureNIC(instance, seq, device, tap)
2197
      self._PassTapFd(instance, fd, device)
2198
      command = "netdev_add tap,id=%s,fd=%s\n" % (kvm_devid, kvm_devid)
2199
      args = "virtio-net-pci,bus=pci.0,addr=%s,mac=%s,netdev=%s,id=%s" % \
2200
               (hex(device.pci), device.mac, kvm_devid, kvm_devid)
2201
      command += "device_add %s" % args
2202
      utils.WriteFile(self._InstanceNICFile(instance.name, seq), data=tap)
2203

    
2204
    self._CallHotplugCommand(instance.name, command)
2205
    # update relevant entries in runtime file
2206
    index = _DEVICE_RUNTIME_INDEX[dev_type]
2207
    entry = _RUNTIME_ENTRY[dev_type](device, extra)
2208
    runtime[index].append(entry)
2209
    self._SaveKVMRuntime(instance, runtime)
2210

    
2211
  def HotDelDevice(self, instance, dev_type, device, _, seq):
2212
    """ Helper method for hot-del device
2213

2214
    It gets device info from runtime file, generates the device name and
2215
    invokes the device specific method.
2216

2217
    """
2218
    runtime = self._LoadKVMRuntime(instance)
2219
    entry = _GetExistingDeviceInfo(dev_type, device, runtime)
2220
    kvm_device = _RUNTIME_DEVICE[dev_type](entry)
2221
    kvm_devid = _GenerateDeviceKVMId(dev_type, kvm_device)
2222
    if dev_type == constants.HOTPLUG_TARGET_DISK:
2223
      command = "device_del %s\n" % kvm_devid
2224
      command += "drive_del %s" % kvm_devid
2225
    elif dev_type == constants.HOTPLUG_TARGET_NIC:
2226
      command = "device_del %s\n" % kvm_devid
2227
      command += "netdev_del %s" % kvm_devid
2228
      utils.RemoveFile(self._InstanceNICFile(instance.name, seq))
2229
    self._CallHotplugCommand(instance.name, command)
2230
    index = _DEVICE_RUNTIME_INDEX[dev_type]
2231
    runtime[index].remove(entry)
2232
    self._SaveKVMRuntime(instance, runtime)
2233

    
2234
    return kvm_device.pci
2235

    
2236
  def HotModDevice(self, instance, dev_type, device, _, seq):
2237
    """ Helper method for hot-mod device
2238

2239
    It gets device info from runtime file, generates the device name and
2240
    invokes the device specific method. Currently only NICs support hot-mod
2241

2242
    """
2243
    if dev_type == constants.HOTPLUG_TARGET_NIC:
2244
      # putting it back in the same pci slot
2245
      device.pci = self.HotDelDevice(instance, dev_type, device, _, seq)
2246
      # TODO: remove sleep when socat gets removed
2247
      time.sleep(2)
2248
      self.HotAddDevice(instance, dev_type, device, _, seq)
2249

    
2250
  def _PassTapFd(self, instance, fd, nic):
2251
    """Pass file descriptor to kvm process via monitor socket using SCM_RIGHTS
2252

2253
    """
2254
    # TODO: factor out code related to unix sockets.
2255
    #       squash common parts between monitor and qmp
2256
    kvm_devid = _GenerateDeviceKVMId(constants.HOTPLUG_TARGET_NIC, nic)
2257
    command = "getfd %s\n" % kvm_devid
2258
    fds = [fd]
2259
    logging.info("%s", fds)
2260
    try:
2261
      monsock = MonitorSocket(self._InstanceMonitor(instance.name))
2262
      monsock.connect()
2263
      fdsend.sendfds(monsock.sock, command, fds=fds)
2264
    finally:
2265
      monsock.close()
2266

    
2267
  @classmethod
2268
  def _ParseKVMVersion(cls, text):
2269
    """Parse the KVM version from the --help output.
2270

2271
    @type text: string
2272
    @param text: output of kvm --help
2273
    @return: (version, v_maj, v_min, v_rev)
2274
    @raise errors.HypervisorError: when the KVM version cannot be retrieved
2275

2276
    """
2277
    match = cls._VERSION_RE.search(text.splitlines()[0])
2278
    if not match:
2279
      raise errors.HypervisorError("Unable to get KVM version")
2280

    
2281
    v_all = match.group(0)
2282
    v_maj = int(match.group(1))
2283
    v_min = int(match.group(2))
2284
    if match.group(4):
2285
      v_rev = int(match.group(4))
2286
    else:
2287
      v_rev = 0
2288
    return (v_all, v_maj, v_min, v_rev)
2289

    
2290
  @classmethod
2291
  def _GetKVMOutput(cls, kvm_path, option):
2292
    """Return the output of a kvm invocation
2293

2294
    @type kvm_path: string
2295
    @param kvm_path: path to the kvm executable
2296
    @type option: a key of _KVMOPTS_CMDS
2297
    @param option: kvm option to fetch the output from
2298
    @return: output a supported kvm invocation
2299
    @raise errors.HypervisorError: when the KVM help output cannot be retrieved
2300

2301
    """
2302
    assert option in cls._KVMOPTS_CMDS, "Invalid output option"
2303

    
2304
    optlist, can_fail = cls._KVMOPTS_CMDS[option]
2305

    
2306
    result = utils.RunCmd([kvm_path] + optlist)
2307
    if result.failed and not can_fail:
2308
      raise errors.HypervisorError("Unable to get KVM %s output" %
2309
                                    " ".join(optlist))
2310
    return result.output
2311

    
2312
  @classmethod
2313
  def _GetKVMVersion(cls, kvm_path):
2314
    """Return the installed KVM version.
2315

2316
    @return: (version, v_maj, v_min, v_rev)
2317
    @raise errors.HypervisorError: when the KVM version cannot be retrieved
2318

2319
    """
2320
    return cls._ParseKVMVersion(cls._GetKVMOutput(kvm_path, cls._KVMOPT_HELP))
2321

    
2322
  @classmethod
2323
  def _GetDefaultMachineVersion(cls, kvm_path):
2324
    """Return the default hardware revision (e.g. pc-1.1)
2325

2326
    """
2327
    output = cls._GetKVMOutput(kvm_path, cls._KVMOPT_MLIST)
2328
    match = cls._DEFAULT_MACHINE_VERSION_RE.search(output)
2329
    if match:
2330
      return match.group(1)
2331
    else:
2332
      return "pc"
2333

    
2334
  @classmethod
2335
  def _StopInstance(cls, instance, force=False, name=None):
2336
    """Stop an instance.
2337

2338
    """
2339
    if name is not None and not force:
2340
      raise errors.HypervisorError("Cannot shutdown cleanly by name only")
2341
    if name is None:
2342
      name = instance.name
2343
      acpi = instance.hvparams[constants.HV_ACPI]
2344
    else:
2345
      acpi = False
2346
    _, pid, alive = cls._InstancePidAlive(name)
2347
    if pid > 0 and alive:
2348
      if force or not acpi:
2349
        utils.KillProcess(pid)
2350
      else:
2351
        cls._CallMonitorCommand(name, "system_powerdown")
2352
    cls._ClearUserShutdown(instance.name)
2353

    
2354
  def StopInstance(self, instance, force=False, retry=False, name=None):
2355
    """Stop an instance.
2356

2357
    """
2358
    self._StopInstance(instance, force, name)
2359

    
2360
  def CleanupInstance(self, instance_name):
2361
    """Cleanup after a stopped instance
2362

2363
    """
2364
    pidfile, pid, alive = self._InstancePidAlive(instance_name)
2365
    if pid > 0 and alive:
2366
      raise errors.HypervisorError("Cannot cleanup a live instance")
2367
    self._RemoveInstanceRuntimeFiles(pidfile, instance_name)
2368
    self._ClearUserShutdown(instance_name)
2369

    
2370
  def RebootInstance(self, instance):
2371
    """Reboot an instance.
2372

2373
    """
2374
    # For some reason if we do a 'send-key ctrl-alt-delete' to the control
2375
    # socket the instance will stop, but now power up again. So we'll resort
2376
    # to shutdown and restart.
2377
    _, _, alive = self._InstancePidAlive(instance.name)
2378
    if not alive:
2379
      raise errors.HypervisorError("Failed to reboot instance %s:"
2380
                                   " not running" % instance.name)
2381
    # StopInstance will delete the saved KVM runtime so:
2382
    # ...first load it...
2383
    kvm_runtime = self._LoadKVMRuntime(instance)
2384
    # ...now we can safely call StopInstance...
2385
    if not self.StopInstance(instance):
2386
      self.StopInstance(instance, force=True)
2387
    # ...and finally we can save it again, and execute it...
2388
    self._SaveKVMRuntime(instance, kvm_runtime)
2389
    kvmpath = instance.hvparams[constants.HV_KVM_PATH]
2390
    kvmhelp = self._GetKVMOutput(kvmpath, self._KVMOPT_HELP)
2391
    self._ExecuteKVMRuntime(instance, kvm_runtime, kvmhelp)
2392

    
2393
  def MigrationInfo(self, instance):
2394
    """Get instance information to perform a migration.
2395

2396
    @type instance: L{objects.Instance}
2397
    @param instance: instance to be migrated
2398
    @rtype: string
2399
    @return: content of the KVM runtime file
2400

2401
    """
2402
    return self._ReadKVMRuntime(instance.name)
2403

    
2404
  def AcceptInstance(self, instance, info, target):
2405
    """Prepare to accept an instance.
2406

2407
    @type instance: L{objects.Instance}
2408
    @param instance: instance to be accepted
2409
    @type info: string
2410
    @param info: content of the KVM runtime file on the source node
2411
    @type target: string
2412
    @param target: target host (usually ip), on this node
2413

2414
    """
2415
    kvm_runtime = self._LoadKVMRuntime(instance, serialized_runtime=info)
2416
    incoming_address = (target, instance.hvparams[constants.HV_MIGRATION_PORT])
2417
    kvmpath = instance.hvparams[constants.HV_KVM_PATH]
2418
    kvmhelp = self._GetKVMOutput(kvmpath, self._KVMOPT_HELP)
2419
    self._ExecuteKVMRuntime(instance, kvm_runtime, kvmhelp,
2420
                            incoming=incoming_address)
2421

    
2422
  def FinalizeMigrationDst(self, instance, info, success):
2423
    """Finalize the instance migration on the target node.
2424

2425
    Stop the incoming mode KVM.
2426

2427
    @type instance: L{objects.Instance}
2428
    @param instance: instance whose migration is being finalized
2429

2430
    """
2431
    if success:
2432
      kvm_runtime = self._LoadKVMRuntime(instance, serialized_runtime=info)
2433
      kvm_nics = kvm_runtime[1]
2434

    
2435
      for nic_seq, nic in enumerate(kvm_nics):
2436
        if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2437
          # Bridged interfaces have already been configured
2438
          continue
2439
        try:
2440
          tap = utils.ReadFile(self._InstanceNICFile(instance.name, nic_seq))
2441
        except EnvironmentError, err:
2442
          logging.warning("Failed to find host interface for %s NIC #%d: %s",
2443
                          instance.name, nic_seq, str(err))
2444
          continue
2445
        try:
2446
          self._ConfigureNIC(instance, nic_seq, nic, tap)
2447
        except errors.HypervisorError, err:
2448
          logging.warning(str(err))
2449

    
2450
      self._WriteKVMRuntime(instance.name, info)
2451
    else:
2452
      self.StopInstance(instance, force=True)
2453

    
2454
  def MigrateInstance(self, cluster_name, instance, target, live):
2455
    """Migrate an instance to a target node.
2456

2457
    The migration will not be attempted if the instance is not
2458
    currently running.
2459

2460
    @type cluster_name: string
2461
    @param cluster_name: name of the cluster
2462
    @type instance: L{objects.Instance}
2463
    @param instance: the instance to be migrated
2464
    @type target: string
2465
    @param target: ip address of the target node
2466
    @type live: boolean
2467
    @param live: perform a live migration
2468

2469
    """
2470
    instance_name = instance.name
2471
    port = instance.hvparams[constants.HV_MIGRATION_PORT]
2472
    _, _, alive = self._InstancePidAlive(instance_name)
2473
    if not alive:
2474
      raise errors.HypervisorError("Instance not running, cannot migrate")
2475

    
2476
    if not live:
2477
      self._CallMonitorCommand(instance_name, "stop")
2478

    
2479
    migrate_command = ("migrate_set_speed %dm" %
2480
                       instance.hvparams[constants.HV_MIGRATION_BANDWIDTH])
2481
    self._CallMonitorCommand(instance_name, migrate_command)
2482

    
2483
    migrate_command = ("migrate_set_downtime %dms" %
2484
                       instance.hvparams[constants.HV_MIGRATION_DOWNTIME])
2485
    self._CallMonitorCommand(instance_name, migrate_command)
2486

    
2487
    migrate_command = "migrate -d tcp:%s:%s" % (target, port)
2488
    self._CallMonitorCommand(instance_name, migrate_command)
2489

    
2490
  def FinalizeMigrationSource(self, instance, success, live):
2491
    """Finalize the instance migration on the source node.
2492

2493
    @type instance: L{objects.Instance}
2494
    @param instance: the instance that was migrated
2495
    @type success: bool
2496
    @param success: whether the migration succeeded or not
2497
    @type live: bool
2498
    @param live: whether the user requested a live migration or not
2499

2500
    """
2501
    if success:
2502
      pidfile, pid, _ = self._InstancePidAlive(instance.name)
2503
      utils.KillProcess(pid)
2504
      self._RemoveInstanceRuntimeFiles(pidfile, instance.name)
2505
    elif live:
2506
      self._CallMonitorCommand(instance.name, self._CONT_CMD)
2507
    self._ClearUserShutdown(instance.name)
2508

    
2509
  def GetMigrationStatus(self, instance):
2510
    """Get the migration status
2511

2512
    @type instance: L{objects.Instance}
2513
    @param instance: the instance that is being migrated
2514
    @rtype: L{objects.MigrationStatus}
2515
    @return: the status of the current migration (one of
2516
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
2517
             progress info that can be retrieved from the hypervisor
2518

2519
    """
2520
    info_command = "info migrate"
2521
    for _ in range(self._MIGRATION_INFO_MAX_BAD_ANSWERS):
2522
      result = self._CallMonitorCommand(instance.name, info_command)
2523
      match = self._MIGRATION_STATUS_RE.search(result.stdout)
2524
      if not match:
2525
        if not result.stdout:
2526
          logging.info("KVM: empty 'info migrate' result")
2527
        else:
2528
          logging.warning("KVM: unknown 'info migrate' result: %s",
2529
                          result.stdout)
2530
      else:
2531
        status = match.group(1)
2532
        if status in constants.HV_KVM_MIGRATION_VALID_STATUSES:
2533
          migration_status = objects.MigrationStatus(status=status)
2534
          match = self._MIGRATION_PROGRESS_RE.search(result.stdout)
2535
          if match:
2536
            migration_status.transferred_ram = match.group("transferred")
2537
            migration_status.total_ram = match.group("total")
2538

    
2539
          return migration_status
2540

    
2541
        logging.warning("KVM: unknown migration status '%s'", status)
2542

    
2543
      time.sleep(self._MIGRATION_INFO_RETRY_DELAY)
2544

    
2545
    return objects.MigrationStatus(status=constants.HV_MIGRATION_FAILED)
2546

    
2547
  def BalloonInstanceMemory(self, instance, mem):
2548
    """Balloon an instance memory to a certain value.
2549

2550
    @type instance: L{objects.Instance}
2551
    @param instance: instance to be accepted
2552
    @type mem: int
2553
    @param mem: actual memory size to use for instance runtime
2554

2555
    """
2556
    self._CallMonitorCommand(instance.name, "balloon %d" % mem)
2557

    
2558
  def GetNodeInfo(self, hvparams=None):
2559
    """Return information about the node.
2560

2561
    @type hvparams: dict of strings
2562
    @param hvparams: hypervisor parameters, not used in this class
2563

2564
    @return: a dict as returned by L{BaseHypervisor.GetLinuxNodeInfo} plus
2565
        the following keys:
2566
          - hv_version: the hypervisor version in the form (major, minor,
2567
                        revision)
2568

2569
    """
2570
    result = self.GetLinuxNodeInfo()
2571
    kvmpath = constants.KVM_PATH
2572
    if hvparams is not None:
2573
      kvmpath = hvparams.get(constants.HV_KVM_PATH, constants.KVM_PATH)
2574
    _, v_major, v_min, v_rev = self._GetKVMVersion(kvmpath)
2575
    result[constants.HV_NODEINFO_KEY_VERSION] = (v_major, v_min, v_rev)
2576
    return result
2577

    
2578
  @classmethod
2579
  def GetInstanceConsole(cls, instance, primary_node, node_group,
2580
                         hvparams, beparams):
2581
    """Return a command for connecting to the console of an instance.
2582

2583
    """
2584
    if hvparams[constants.HV_SERIAL_CONSOLE]:
2585
      cmd = [pathutils.KVM_CONSOLE_WRAPPER,
2586
             constants.SOCAT_PATH, utils.ShellQuote(instance.name),
2587
             utils.ShellQuote(cls._InstanceMonitor(instance.name)),
2588
             "STDIO,%s" % cls._SocatUnixConsoleParams(),
2589
             "UNIX-CONNECT:%s" % cls._InstanceSerial(instance.name)]
2590
      ndparams = node_group.FillND(primary_node)
2591
      return objects.InstanceConsole(instance=instance.name,
2592
                                     kind=constants.CONS_SSH,
2593
                                     host=primary_node.name,
2594
                                     port=ndparams.get(constants.ND_SSH_PORT),
2595
                                     user=constants.SSH_CONSOLE_USER,
2596
                                     command=cmd)
2597

    
2598
    vnc_bind_address = hvparams[constants.HV_VNC_BIND_ADDRESS]
2599
    if vnc_bind_address and instance.network_port > constants.VNC_BASE_PORT:
2600
      display = instance.network_port - constants.VNC_BASE_PORT
2601
      return objects.InstanceConsole(instance=instance.name,
2602
                                     kind=constants.CONS_VNC,
2603
                                     host=vnc_bind_address,
2604
                                     port=instance.network_port,
2605
                                     display=display)
2606

    
2607
    spice_bind = hvparams[constants.HV_KVM_SPICE_BIND]
2608
    if spice_bind:
2609
      return objects.InstanceConsole(instance=instance.name,
2610
                                     kind=constants.CONS_SPICE,
2611
                                     host=spice_bind,
2612
                                     port=instance.network_port)
2613

    
2614
    return objects.InstanceConsole(instance=instance.name,
2615
                                   kind=constants.CONS_MESSAGE,
2616
                                   message=("No serial shell for instance %s" %
2617
                                            instance.name))
2618

    
2619
  def Verify(self, hvparams=None):
2620
    """Verify the hypervisor.
2621

2622
    Check that the required binaries exist.
2623

2624
    @type hvparams: dict of strings
2625
    @param hvparams: hypervisor parameters to be verified against, not used here
2626

2627
    @return: Problem description if something is wrong, C{None} otherwise
2628

2629
    """
2630
    msgs = []
2631
    kvmpath = constants.KVM_PATH
2632
    if hvparams is not None:
2633
      kvmpath = hvparams.get(constants.HV_KVM_PATH, constants.KVM_PATH)
2634
    if not os.path.exists(kvmpath):
2635
      msgs.append("The KVM binary ('%s') does not exist" % kvmpath)
2636
    if not os.path.exists(constants.SOCAT_PATH):
2637
      msgs.append("The socat binary ('%s') does not exist" %
2638
                  constants.SOCAT_PATH)
2639

    
2640
    return self._FormatVerifyResults(msgs)
2641

    
2642
  @classmethod
2643
  def CheckParameterSyntax(cls, hvparams):
2644
    """Check the given parameters for validity.
2645

2646
    @type hvparams:  dict
2647
    @param hvparams: dictionary with parameter names/value
2648
    @raise errors.HypervisorError: when a parameter is not valid
2649

2650
    """
2651
    super(KVMHypervisor, cls).CheckParameterSyntax(hvparams)
2652

    
2653
    kernel_path = hvparams[constants.HV_KERNEL_PATH]
2654
    if kernel_path:
2655
      if not hvparams[constants.HV_ROOT_PATH]:
2656
        raise errors.HypervisorError("Need a root partition for the instance,"
2657
                                     " if a kernel is defined")
2658

    
2659
    if (hvparams[constants.HV_VNC_X509_VERIFY] and
2660
        not hvparams[constants.HV_VNC_X509]):
2661
      raise errors.HypervisorError("%s must be defined, if %s is" %
2662
                                   (constants.HV_VNC_X509,
2663
                                    constants.HV_VNC_X509_VERIFY))
2664

    
2665
    if hvparams[constants.HV_SERIAL_CONSOLE]:
2666
      serial_speed = hvparams[constants.HV_SERIAL_SPEED]
2667
      valid_speeds = constants.VALID_SERIAL_SPEEDS
2668
      if not serial_speed or serial_speed not in valid_speeds:
2669
        raise errors.HypervisorError("Invalid serial console speed, must be"
2670
                                     " one of: %s" %
2671
                                     utils.CommaJoin(valid_speeds))
2672

    
2673
    boot_order = hvparams[constants.HV_BOOT_ORDER]
2674
    if (boot_order == constants.HT_BO_CDROM and
2675
        not hvparams[constants.HV_CDROM_IMAGE_PATH]):
2676
      raise errors.HypervisorError("Cannot boot from cdrom without an"
2677
                                   " ISO path")
2678

    
2679
    security_model = hvparams[constants.HV_SECURITY_MODEL]
2680
    if security_model == constants.HT_SM_USER:
2681
      if not hvparams[constants.HV_SECURITY_DOMAIN]:
2682
        raise errors.HypervisorError("A security domain (user to run kvm as)"
2683
                                     " must be specified")
2684
    elif (security_model == constants.HT_SM_NONE or
2685
          security_model == constants.HT_SM_POOL):
2686
      if hvparams[constants.HV_SECURITY_DOMAIN]:
2687
        raise errors.HypervisorError("Cannot have a security domain when the"
2688
                                     " security model is 'none' or 'pool'")
2689

    
2690
    spice_bind = hvparams[constants.HV_KVM_SPICE_BIND]
2691
    spice_ip_version = hvparams[constants.HV_KVM_SPICE_IP_VERSION]
2692
    if spice_bind:
2693
      if spice_ip_version != constants.IFACE_NO_IP_VERSION_SPECIFIED:
2694
        # if an IP version is specified, the spice_bind parameter must be an
2695
        # IP of that family
2696
        if (netutils.IP4Address.IsValid(spice_bind) and
2697
            spice_ip_version != constants.IP4_VERSION):
2698
          raise errors.HypervisorError("SPICE: Got an IPv4 address (%s), but"
2699
                                       " the specified IP version is %s" %
2700
                                       (spice_bind, spice_ip_version))
2701

    
2702
        if (netutils.IP6Address.IsValid(spice_bind) and
2703
            spice_ip_version != constants.IP6_VERSION):
2704
          raise errors.HypervisorError("SPICE: Got an IPv6 address (%s), but"
2705
                                       " the specified IP version is %s" %
2706
                                       (spice_bind, spice_ip_version))
2707
    else:
2708
      # All the other SPICE parameters depend on spice_bind being set. Raise an
2709
      # error if any of them is set without it.
2710
      for param in _SPICE_ADDITIONAL_PARAMS:
2711
        if hvparams[param]:
2712
          raise errors.HypervisorError("SPICE: %s requires %s to be set" %
2713
                                       (param, constants.HV_KVM_SPICE_BIND))
2714

    
2715
  @classmethod
2716
  def ValidateParameters(cls, hvparams):
2717
    """Check the given parameters for validity.
2718

2719
    @type hvparams:  dict
2720
    @param hvparams: dictionary with parameter names/value
2721
    @raise errors.HypervisorError: when a parameter is not valid
2722

2723
    """
2724
    super(KVMHypervisor, cls).ValidateParameters(hvparams)
2725

    
2726
    kvm_path = hvparams[constants.HV_KVM_PATH]
2727

    
2728
    security_model = hvparams[constants.HV_SECURITY_MODEL]
2729
    if security_model == constants.HT_SM_USER:
2730
      username = hvparams[constants.HV_SECURITY_DOMAIN]
2731
      try:
2732
        pwd.getpwnam(username)
2733
      except KeyError:
2734
        raise errors.HypervisorError("Unknown security domain user %s"
2735
                                     % username)
2736
    vnc_bind_address = hvparams[constants.HV_VNC_BIND_ADDRESS]
2737
    if vnc_bind_address:
2738
      bound_to_addr = netutils.IP4Address.IsValid(vnc_bind_address)
2739
      is_interface = netutils.IsValidInterface(vnc_bind_address)
2740
      is_path = utils.IsNormAbsPath(vnc_bind_address)
2741
      if not bound_to_addr and not is_interface and not is_path:
2742
        raise errors.HypervisorError("VNC: The %s parameter must be either"
2743
                                     " a valid IP address, an interface name,"
2744
                                     " or an absolute path" %
2745
                                     constants.HV_KVM_SPICE_BIND)
2746

    
2747
    spice_bind = hvparams[constants.HV_KVM_SPICE_BIND]
2748
    if spice_bind:
2749
      # only one of VNC and SPICE can be used currently.
2750
      if hvparams[constants.HV_VNC_BIND_ADDRESS]:
2751
        raise errors.HypervisorError("Both SPICE and VNC are configured, but"
2752
                                     " only one of them can be used at a"
2753
                                     " given time")
2754

    
2755
      # check that KVM supports SPICE
2756
      kvmhelp = cls._GetKVMOutput(kvm_path, cls._KVMOPT_HELP)
2757
      if not cls._SPICE_RE.search(kvmhelp):
2758
        raise errors.HypervisorError("SPICE is configured, but it is not"
2759
                                     " supported according to 'kvm --help'")
2760

    
2761
      # if spice_bind is not an IP address, it must be a valid interface
2762
      bound_to_addr = (netutils.IP4Address.IsValid(spice_bind) or
2763
                       netutils.IP6Address.IsValid(spice_bind))
2764
      if not bound_to_addr and not netutils.IsValidInterface(spice_bind):
2765
        raise errors.HypervisorError("SPICE: The %s parameter must be either"
2766
                                     " a valid IP address or interface name" %
2767
                                     constants.HV_KVM_SPICE_BIND)
2768

    
2769
    machine_version = hvparams[constants.HV_KVM_MACHINE_VERSION]
2770
    if machine_version:
2771
      output = cls._GetKVMOutput(kvm_path, cls._KVMOPT_MLIST)
2772
      if not cls._CHECK_MACHINE_VERSION_RE(machine_version).search(output):
2773
        raise errors.HypervisorError("Unsupported machine version: %s" %
2774
                                     machine_version)
2775

    
2776
  @classmethod
2777
  def PowercycleNode(cls, hvparams=None):
2778
    """KVM powercycle, just a wrapper over Linux powercycle.
2779

2780
    @type hvparams: dict of strings
2781
    @param hvparams: hypervisor params to be used on this node
2782

2783
    """
2784
    cls.LinuxPowercycle()