root / lib / hypervisor / hv_kvm.py @ 27b6654e
History | View | Annotate | Download (99.1 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 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): |
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 |
@return: (ifname, tapfd)
|
295 |
@rtype: tuple
|
296 |
|
297 |
"""
|
298 |
try:
|
299 |
tapfd = os.open("/dev/net/tun", os.O_RDWR)
|
300 |
except EnvironmentError: |
301 |
raise errors.HypervisorError("Failed to open /dev/net/tun") |
302 |
|
303 |
flags = IFF_TAP | IFF_NO_PI |
304 |
|
305 |
if vnet_hdr and _ProbeTapVnetHdr(tapfd): |
306 |
flags |= IFF_VNET_HDR |
307 |
|
308 |
# The struct ifreq ioctl request (see netdevice(7))
|
309 |
ifr = struct.pack("16sh", "", flags) |
310 |
|
311 |
try:
|
312 |
res = fcntl.ioctl(tapfd, TUNSETIFF, ifr) |
313 |
except EnvironmentError, err: |
314 |
raise errors.HypervisorError("Failed to allocate a new TAP device: %s" % |
315 |
err) |
316 |
|
317 |
# Get the interface name from the ioctl
|
318 |
ifname = struct.unpack("16sh", res)[0].strip("\x00") |
319 |
return (ifname, tapfd)
|
320 |
|
321 |
|
322 |
def _CheckUrl(url): |
323 |
"""Check if a given URL exists on the server
|
324 |
|
325 |
"""
|
326 |
req = urllib2.Request(url) |
327 |
|
328 |
# XXX: ugly but true
|
329 |
req.get_method = lambda: "HEAD" |
330 |
|
331 |
try:
|
332 |
resp = urllib2.urlopen(req) |
333 |
except urllib2.URLError:
|
334 |
return False |
335 |
|
336 |
del resp
|
337 |
return True |
338 |
|
339 |
|
340 |
class QmpMessage: |
341 |
"""QEMU Messaging Protocol (QMP) message.
|
342 |
|
343 |
"""
|
344 |
def __init__(self, data): |
345 |
"""Creates a new QMP message based on the passed data.
|
346 |
|
347 |
"""
|
348 |
if not isinstance(data, dict): |
349 |
raise TypeError("QmpMessage must be initialized with a dict") |
350 |
|
351 |
self.data = data
|
352 |
|
353 |
def __getitem__(self, field_name): |
354 |
"""Get the value of the required field if present, or None.
|
355 |
|
356 |
Overrides the [] operator to provide access to the message data,
|
357 |
returning None if the required item is not in the message
|
358 |
@return: the value of the field_name field, or None if field_name
|
359 |
is not contained in the message
|
360 |
|
361 |
"""
|
362 |
return self.data.get(field_name, None) |
363 |
|
364 |
def __setitem__(self, field_name, field_value): |
365 |
"""Set the value of the required field_name to field_value.
|
366 |
|
367 |
"""
|
368 |
self.data[field_name] = field_value
|
369 |
|
370 |
def __len__(self): |
371 |
"""Return the number of fields stored in this QmpMessage.
|
372 |
|
373 |
"""
|
374 |
return len(self.data) |
375 |
|
376 |
def __delitem__(self, key): |
377 |
"""Delete the specified element from the QmpMessage.
|
378 |
|
379 |
"""
|
380 |
del(self.data[key]) |
381 |
|
382 |
@staticmethod
|
383 |
def BuildFromJsonString(json_string): |
384 |
"""Build a QmpMessage from a JSON encoded string.
|
385 |
|
386 |
@type json_string: str
|
387 |
@param json_string: JSON string representing the message
|
388 |
@rtype: L{QmpMessage}
|
389 |
@return: a L{QmpMessage} built from json_string
|
390 |
|
391 |
"""
|
392 |
# Parse the string
|
393 |
data = serializer.LoadJson(json_string) |
394 |
return QmpMessage(data)
|
395 |
|
396 |
def __str__(self): |
397 |
# The protocol expects the JSON object to be sent as a single line.
|
398 |
return serializer.DumpJson(self.data) |
399 |
|
400 |
def __eq__(self, other): |
401 |
# When comparing two QmpMessages, we are interested in comparing
|
402 |
# their internal representation of the message data
|
403 |
return self.data == other.data |
404 |
|
405 |
|
406 |
class MonitorSocket(object): |
407 |
_SOCKET_TIMEOUT = 5
|
408 |
|
409 |
def __init__(self, monitor_filename): |
410 |
"""Instantiates the MonitorSocket object.
|
411 |
|
412 |
@type monitor_filename: string
|
413 |
@param monitor_filename: the filename of the UNIX raw socket on which the
|
414 |
monitor (QMP or simple one) is listening
|
415 |
|
416 |
"""
|
417 |
self.monitor_filename = monitor_filename
|
418 |
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
419 |
# We want to fail if the server doesn't send a complete message
|
420 |
# in a reasonable amount of time
|
421 |
self.sock.settimeout(self._SOCKET_TIMEOUT) |
422 |
self._connected = False |
423 |
|
424 |
def _check_socket(self): |
425 |
sock_stat = None
|
426 |
try:
|
427 |
sock_stat = os.stat(self.monitor_filename)
|
428 |
except EnvironmentError, err: |
429 |
if err.errno == errno.ENOENT:
|
430 |
raise errors.HypervisorError("No monitor socket found") |
431 |
else:
|
432 |
raise errors.HypervisorError("Error checking monitor socket: %s", |
433 |
utils.ErrnoOrStr(err)) |
434 |
if not stat.S_ISSOCK(sock_stat.st_mode): |
435 |
raise errors.HypervisorError("Monitor socket is not a socket") |
436 |
|
437 |
def _check_connection(self): |
438 |
"""Make sure that the connection is established.
|
439 |
|
440 |
"""
|
441 |
if not self._connected: |
442 |
raise errors.ProgrammerError("To use a MonitorSocket you need to first" |
443 |
" invoke connect() on it")
|
444 |
|
445 |
def connect(self): |
446 |
"""Connects to the monitor.
|
447 |
|
448 |
Connects to the UNIX socket
|
449 |
|
450 |
@raise errors.HypervisorError: when there are communication errors
|
451 |
|
452 |
"""
|
453 |
if self._connected: |
454 |
raise errors.ProgrammerError("Cannot connect twice") |
455 |
|
456 |
self._check_socket()
|
457 |
|
458 |
# Check file existance/stuff
|
459 |
try:
|
460 |
self.sock.connect(self.monitor_filename) |
461 |
except EnvironmentError: |
462 |
raise errors.HypervisorError("Can't connect to qmp socket") |
463 |
self._connected = True |
464 |
|
465 |
def close(self): |
466 |
"""Closes the socket
|
467 |
|
468 |
It cannot be used after this call.
|
469 |
|
470 |
"""
|
471 |
self.sock.close()
|
472 |
|
473 |
|
474 |
class QmpConnection(MonitorSocket): |
475 |
"""Connection to the QEMU Monitor using the QEMU Monitor Protocol (QMP).
|
476 |
|
477 |
"""
|
478 |
_FIRST_MESSAGE_KEY = "QMP"
|
479 |
_EVENT_KEY = "event"
|
480 |
_ERROR_KEY = "error"
|
481 |
_RETURN_KEY = RETURN_KEY = "return"
|
482 |
_ACTUAL_KEY = ACTUAL_KEY = "actual"
|
483 |
_ERROR_CLASS_KEY = "class"
|
484 |
_ERROR_DATA_KEY = "data"
|
485 |
_ERROR_DESC_KEY = "desc"
|
486 |
_EXECUTE_KEY = "execute"
|
487 |
_ARGUMENTS_KEY = "arguments"
|
488 |
_CAPABILITIES_COMMAND = "qmp_capabilities"
|
489 |
_MESSAGE_END_TOKEN = "\r\n"
|
490 |
|
491 |
def __init__(self, monitor_filename): |
492 |
super(QmpConnection, self).__init__(monitor_filename) |
493 |
self._buf = "" |
494 |
|
495 |
def connect(self): |
496 |
"""Connects to the QMP monitor.
|
497 |
|
498 |
Connects to the UNIX socket and makes sure that we can actually send and
|
499 |
receive data to the kvm instance via QMP.
|
500 |
|
501 |
@raise errors.HypervisorError: when there are communication errors
|
502 |
@raise errors.ProgrammerError: when there are data serialization errors
|
503 |
|
504 |
"""
|
505 |
super(QmpConnection, self).connect() |
506 |
# Check if we receive a correct greeting message from the server
|
507 |
# (As per the QEMU Protocol Specification 0.1 - section 2.2)
|
508 |
greeting = self._Recv()
|
509 |
if not greeting[self._FIRST_MESSAGE_KEY]: |
510 |
self._connected = False |
511 |
raise errors.HypervisorError("kvm: QMP communication error (wrong" |
512 |
" server greeting")
|
513 |
|
514 |
# Let's put the monitor in command mode using the qmp_capabilities
|
515 |
# command, or else no command will be executable.
|
516 |
# (As per the QEMU Protocol Specification 0.1 - section 4)
|
517 |
self.Execute(self._CAPABILITIES_COMMAND) |
518 |
|
519 |
def _ParseMessage(self, buf): |
520 |
"""Extract and parse a QMP message from the given buffer.
|
521 |
|
522 |
Seeks for a QMP message in the given buf. If found, it parses it and
|
523 |
returns it together with the rest of the characters in the buf.
|
524 |
If no message is found, returns None and the whole buffer.
|
525 |
|
526 |
@raise errors.ProgrammerError: when there are data serialization errors
|
527 |
|
528 |
"""
|
529 |
message = None
|
530 |
# Check if we got the message end token (CRLF, as per the QEMU Protocol
|
531 |
# Specification 0.1 - Section 2.1.1)
|
532 |
pos = buf.find(self._MESSAGE_END_TOKEN)
|
533 |
if pos >= 0: |
534 |
try:
|
535 |
message = QmpMessage.BuildFromJsonString(buf[:pos + 1])
|
536 |
except Exception, err: |
537 |
raise errors.ProgrammerError("QMP data serialization error: %s" % err) |
538 |
buf = buf[pos + 1:]
|
539 |
|
540 |
return (message, buf)
|
541 |
|
542 |
def _Recv(self): |
543 |
"""Receives a message from QMP and decodes the received JSON object.
|
544 |
|
545 |
@rtype: QmpMessage
|
546 |
@return: the received message
|
547 |
@raise errors.HypervisorError: when there are communication errors
|
548 |
@raise errors.ProgrammerError: when there are data serialization errors
|
549 |
|
550 |
"""
|
551 |
self._check_connection()
|
552 |
|
553 |
# Check if there is already a message in the buffer
|
554 |
(message, self._buf) = self._ParseMessage(self._buf) |
555 |
if message:
|
556 |
return message
|
557 |
|
558 |
recv_buffer = StringIO.StringIO(self._buf)
|
559 |
recv_buffer.seek(len(self._buf)) |
560 |
try:
|
561 |
while True: |
562 |
data = self.sock.recv(4096) |
563 |
if not data: |
564 |
break
|
565 |
recv_buffer.write(data) |
566 |
|
567 |
(message, self._buf) = self._ParseMessage(recv_buffer.getvalue()) |
568 |
if message:
|
569 |
return message
|
570 |
|
571 |
except socket.timeout, err:
|
572 |
raise errors.HypervisorError("Timeout while receiving a QMP message: " |
573 |
"%s" % (err))
|
574 |
except socket.error, err:
|
575 |
raise errors.HypervisorError("Unable to receive data from KVM using the" |
576 |
" QMP protocol: %s" % err)
|
577 |
|
578 |
def _Send(self, message): |
579 |
"""Encodes and sends a message to KVM using QMP.
|
580 |
|
581 |
@type message: QmpMessage
|
582 |
@param message: message to send to KVM
|
583 |
@raise errors.HypervisorError: when there are communication errors
|
584 |
@raise errors.ProgrammerError: when there are data serialization errors
|
585 |
|
586 |
"""
|
587 |
self._check_connection()
|
588 |
try:
|
589 |
message_str = str(message)
|
590 |
except Exception, err: |
591 |
raise errors.ProgrammerError("QMP data deserialization error: %s" % err) |
592 |
|
593 |
try:
|
594 |
self.sock.sendall(message_str)
|
595 |
except socket.timeout, err:
|
596 |
raise errors.HypervisorError("Timeout while sending a QMP message: " |
597 |
"%s (%s)" % (err.string, err.errno))
|
598 |
except socket.error, err:
|
599 |
raise errors.HypervisorError("Unable to send data from KVM using the" |
600 |
" QMP protocol: %s" % err)
|
601 |
|
602 |
def Execute(self, command, arguments=None): |
603 |
"""Executes a QMP command and returns the response of the server.
|
604 |
|
605 |
@type command: str
|
606 |
@param command: the command to execute
|
607 |
@type arguments: dict
|
608 |
@param arguments: dictionary of arguments to be passed to the command
|
609 |
@rtype: dict
|
610 |
@return: dictionary representing the received JSON object
|
611 |
@raise errors.HypervisorError: when there are communication errors
|
612 |
@raise errors.ProgrammerError: when there are data serialization errors
|
613 |
|
614 |
"""
|
615 |
self._check_connection()
|
616 |
message = QmpMessage({self._EXECUTE_KEY: command})
|
617 |
if arguments:
|
618 |
message[self._ARGUMENTS_KEY] = arguments
|
619 |
self._Send(message)
|
620 |
|
621 |
# Events can occur between the sending of the command and the reception
|
622 |
# of the response, so we need to filter out messages with the event key.
|
623 |
while True: |
624 |
response = self._Recv()
|
625 |
err = response[self._ERROR_KEY]
|
626 |
if err:
|
627 |
raise errors.HypervisorError("kvm: error executing the %s" |
628 |
" command: %s (%s, %s):" %
|
629 |
(command, |
630 |
err[self._ERROR_DESC_KEY],
|
631 |
err[self._ERROR_CLASS_KEY],
|
632 |
err[self._ERROR_DATA_KEY]))
|
633 |
|
634 |
elif not response[self._EVENT_KEY]: |
635 |
return response
|
636 |
|
637 |
|
638 |
class KVMHypervisor(hv_base.BaseHypervisor): |
639 |
"""KVM hypervisor interface
|
640 |
|
641 |
"""
|
642 |
CAN_MIGRATE = True
|
643 |
|
644 |
_ROOT_DIR = pathutils.RUN_DIR + "/kvm-hypervisor"
|
645 |
_PIDS_DIR = _ROOT_DIR + "/pid" # contains live instances pids |
646 |
_UIDS_DIR = _ROOT_DIR + "/uid" # contains instances reserved uids |
647 |
_CTRL_DIR = _ROOT_DIR + "/ctrl" # contains instances control sockets |
648 |
_CONF_DIR = _ROOT_DIR + "/conf" # contains instances startup data |
649 |
_NICS_DIR = _ROOT_DIR + "/nic" # contains instances nic <-> tap associations |
650 |
_KEYMAP_DIR = _ROOT_DIR + "/keymap" # contains instances keymaps |
651 |
# KVM instances with chroot enabled are started in empty chroot directories.
|
652 |
_CHROOT_DIR = _ROOT_DIR + "/chroot" # for empty chroot directories |
653 |
# After an instance is stopped, its chroot directory is removed.
|
654 |
# If the chroot directory is not empty, it can't be removed.
|
655 |
# A non-empty chroot directory indicates a possible security incident.
|
656 |
# To support forensics, the non-empty chroot directory is quarantined in
|
657 |
# a separate directory, called 'chroot-quarantine'.
|
658 |
_CHROOT_QUARANTINE_DIR = _ROOT_DIR + "/chroot-quarantine"
|
659 |
_DIRS = [_ROOT_DIR, _PIDS_DIR, _UIDS_DIR, _CTRL_DIR, _CONF_DIR, _NICS_DIR, |
660 |
_CHROOT_DIR, _CHROOT_QUARANTINE_DIR, _KEYMAP_DIR] |
661 |
|
662 |
PARAMETERS = { |
663 |
constants.HV_KVM_PATH: hv_base.REQ_FILE_CHECK, |
664 |
constants.HV_KERNEL_PATH: hv_base.OPT_FILE_CHECK, |
665 |
constants.HV_INITRD_PATH: hv_base.OPT_FILE_CHECK, |
666 |
constants.HV_ROOT_PATH: hv_base.NO_CHECK, |
667 |
constants.HV_KERNEL_ARGS: hv_base.NO_CHECK, |
668 |
constants.HV_ACPI: hv_base.NO_CHECK, |
669 |
constants.HV_SERIAL_CONSOLE: hv_base.NO_CHECK, |
670 |
constants.HV_SERIAL_SPEED: hv_base.NO_CHECK, |
671 |
constants.HV_VNC_BIND_ADDRESS: hv_base.NO_CHECK, # will be checked later
|
672 |
constants.HV_VNC_TLS: hv_base.NO_CHECK, |
673 |
constants.HV_VNC_X509: hv_base.OPT_DIR_CHECK, |
674 |
constants.HV_VNC_X509_VERIFY: hv_base.NO_CHECK, |
675 |
constants.HV_VNC_PASSWORD_FILE: hv_base.OPT_FILE_CHECK, |
676 |
constants.HV_KVM_SPICE_BIND: hv_base.NO_CHECK, # will be checked later
|
677 |
constants.HV_KVM_SPICE_IP_VERSION: |
678 |
(False, lambda x: (x == constants.IFACE_NO_IP_VERSION_SPECIFIED or |
679 |
x in constants.VALID_IP_VERSIONS),
|
680 |
"The SPICE IP version should be 4 or 6",
|
681 |
None, None), |
682 |
constants.HV_KVM_SPICE_PASSWORD_FILE: hv_base.OPT_FILE_CHECK, |
683 |
constants.HV_KVM_SPICE_LOSSLESS_IMG_COMPR: |
684 |
hv_base.ParamInSet( |
685 |
False, constants.HT_KVM_SPICE_VALID_LOSSLESS_IMG_COMPR_OPTIONS),
|
686 |
constants.HV_KVM_SPICE_JPEG_IMG_COMPR: |
687 |
hv_base.ParamInSet( |
688 |
False, constants.HT_KVM_SPICE_VALID_LOSSY_IMG_COMPR_OPTIONS),
|
689 |
constants.HV_KVM_SPICE_ZLIB_GLZ_IMG_COMPR: |
690 |
hv_base.ParamInSet( |
691 |
False, constants.HT_KVM_SPICE_VALID_LOSSY_IMG_COMPR_OPTIONS),
|
692 |
constants.HV_KVM_SPICE_STREAMING_VIDEO_DETECTION: |
693 |
hv_base.ParamInSet( |
694 |
False, constants.HT_KVM_SPICE_VALID_VIDEO_STREAM_DETECTION_OPTIONS),
|
695 |
constants.HV_KVM_SPICE_AUDIO_COMPR: hv_base.NO_CHECK, |
696 |
constants.HV_KVM_SPICE_USE_TLS: hv_base.NO_CHECK, |
697 |
constants.HV_KVM_SPICE_TLS_CIPHERS: hv_base.NO_CHECK, |
698 |
constants.HV_KVM_SPICE_USE_VDAGENT: hv_base.NO_CHECK, |
699 |
constants.HV_KVM_FLOPPY_IMAGE_PATH: hv_base.OPT_FILE_CHECK, |
700 |
constants.HV_CDROM_IMAGE_PATH: hv_base.OPT_FILE_OR_URL_CHECK, |
701 |
constants.HV_KVM_CDROM2_IMAGE_PATH: hv_base.OPT_FILE_CHECK, |
702 |
constants.HV_BOOT_ORDER: |
703 |
hv_base.ParamInSet(True, constants.HT_KVM_VALID_BO_TYPES),
|
704 |
constants.HV_NIC_TYPE: |
705 |
hv_base.ParamInSet(True, constants.HT_KVM_VALID_NIC_TYPES),
|
706 |
constants.HV_DISK_TYPE: |
707 |
hv_base.ParamInSet(True, constants.HT_KVM_VALID_DISK_TYPES),
|
708 |
constants.HV_KVM_CDROM_DISK_TYPE: |
709 |
hv_base.ParamInSet(False, constants.HT_KVM_VALID_DISK_TYPES),
|
710 |
constants.HV_USB_MOUSE: |
711 |
hv_base.ParamInSet(False, constants.HT_KVM_VALID_MOUSE_TYPES),
|
712 |
constants.HV_KEYMAP: hv_base.NO_CHECK, |
713 |
constants.HV_MIGRATION_PORT: hv_base.REQ_NET_PORT_CHECK, |
714 |
constants.HV_MIGRATION_BANDWIDTH: hv_base.REQ_NONNEGATIVE_INT_CHECK, |
715 |
constants.HV_MIGRATION_DOWNTIME: hv_base.REQ_NONNEGATIVE_INT_CHECK, |
716 |
constants.HV_MIGRATION_MODE: hv_base.MIGRATION_MODE_CHECK, |
717 |
constants.HV_USE_LOCALTIME: hv_base.NO_CHECK, |
718 |
constants.HV_DISK_CACHE: |
719 |
hv_base.ParamInSet(True, constants.HT_VALID_CACHE_TYPES),
|
720 |
constants.HV_SECURITY_MODEL: |
721 |
hv_base.ParamInSet(True, constants.HT_KVM_VALID_SM_TYPES),
|
722 |
constants.HV_SECURITY_DOMAIN: hv_base.NO_CHECK, |
723 |
constants.HV_KVM_FLAG: |
724 |
hv_base.ParamInSet(False, constants.HT_KVM_FLAG_VALUES),
|
725 |
constants.HV_VHOST_NET: hv_base.NO_CHECK, |
726 |
constants.HV_KVM_USE_CHROOT: hv_base.NO_CHECK, |
727 |
constants.HV_KVM_USER_SHUTDOWN: hv_base.NO_CHECK, |
728 |
constants.HV_MEM_PATH: hv_base.OPT_DIR_CHECK, |
729 |
constants.HV_REBOOT_BEHAVIOR: |
730 |
hv_base.ParamInSet(True, constants.REBOOT_BEHAVIORS),
|
731 |
constants.HV_CPU_MASK: hv_base.OPT_MULTI_CPU_MASK_CHECK, |
732 |
constants.HV_CPU_TYPE: hv_base.NO_CHECK, |
733 |
constants.HV_CPU_CORES: hv_base.OPT_NONNEGATIVE_INT_CHECK, |
734 |
constants.HV_CPU_THREADS: hv_base.OPT_NONNEGATIVE_INT_CHECK, |
735 |
constants.HV_CPU_SOCKETS: hv_base.OPT_NONNEGATIVE_INT_CHECK, |
736 |
constants.HV_SOUNDHW: hv_base.NO_CHECK, |
737 |
constants.HV_USB_DEVICES: hv_base.NO_CHECK, |
738 |
constants.HV_VGA: hv_base.NO_CHECK, |
739 |
constants.HV_KVM_EXTRA: hv_base.NO_CHECK, |
740 |
constants.HV_KVM_MACHINE_VERSION: hv_base.NO_CHECK, |
741 |
constants.HV_VNET_HDR: hv_base.NO_CHECK, |
742 |
} |
743 |
|
744 |
_VIRTIO = "virtio"
|
745 |
_VIRTIO_NET_PCI = "virtio-net-pci"
|
746 |
_VIRTIO_BLK_PCI = "virtio-blk-pci"
|
747 |
|
748 |
_MIGRATION_STATUS_RE = re.compile(r"Migration\s+status:\s+(\w+)",
|
749 |
re.M | re.I) |
750 |
_MIGRATION_PROGRESS_RE = \ |
751 |
re.compile(r"\s*transferred\s+ram:\s+(?P<transferred>\d+)\s+kbytes\s*\n"
|
752 |
r"\s*remaining\s+ram:\s+(?P<remaining>\d+)\s+kbytes\s*\n"
|
753 |
r"\s*total\s+ram:\s+(?P<total>\d+)\s+kbytes\s*\n", re.I)
|
754 |
|
755 |
_MIGRATION_INFO_MAX_BAD_ANSWERS = 5
|
756 |
_MIGRATION_INFO_RETRY_DELAY = 2
|
757 |
|
758 |
_VERSION_RE = re.compile(r"\b(\d+)\.(\d+)(\.(\d+))?\b")
|
759 |
|
760 |
_CPU_INFO_RE = re.compile(r"cpu\s+\#(\d+).*thread_id\s*=\s*(\d+)", re.I)
|
761 |
_CPU_INFO_CMD = "info cpus"
|
762 |
_CONT_CMD = "cont"
|
763 |
|
764 |
_DEFAULT_MACHINE_VERSION_RE = re.compile(r"^(\S+).*\(default\)", re.M)
|
765 |
_CHECK_MACHINE_VERSION_RE = \ |
766 |
staticmethod(lambda x: re.compile(r"^(%s)[ ]+.*PC" % x, re.M)) |
767 |
|
768 |
_QMP_RE = re.compile(r"^-qmp\s", re.M)
|
769 |
_SPICE_RE = re.compile(r"^-spice\s", re.M)
|
770 |
_VHOST_RE = re.compile(r"^-net\s.*,vhost=on|off", re.M)
|
771 |
_ENABLE_KVM_RE = re.compile(r"^-enable-kvm\s", re.M)
|
772 |
_DISABLE_KVM_RE = re.compile(r"^-disable-kvm\s", re.M)
|
773 |
_NETDEV_RE = re.compile(r"^-netdev\s", re.M)
|
774 |
_DISPLAY_RE = re.compile(r"^-display\s", re.M)
|
775 |
_MACHINE_RE = re.compile(r"^-machine\s", re.M)
|
776 |
_VIRTIO_NET_RE = re.compile(r"^name \"%s\"" % _VIRTIO_NET_PCI, re.M)
|
777 |
_VIRTIO_BLK_RE = re.compile(r"^name \"%s\"" % _VIRTIO_BLK_PCI, re.M)
|
778 |
# match -drive.*boot=on|off on different lines, but in between accept only
|
779 |
# dashes not preceeded by a new line (which would mean another option
|
780 |
# different than -drive is starting)
|
781 |
_BOOT_RE = re.compile(r"^-drive\s([^-]|(?<!^)-)*,boot=on\|off", re.M | re.S)
|
782 |
_UUID_RE = re.compile(r"^-uuid\s", re.M)
|
783 |
|
784 |
_INFO_PCI_RE = re.compile(r'Bus.*device[ ]*(\d+).*')
|
785 |
_INFO_PCI_CMD = "info pci"
|
786 |
_INFO_VERSION_RE = \ |
787 |
re.compile(r'^QEMU (\d+)\.(\d+)(\.(\d+))?.*monitor.*', re.M)
|
788 |
_INFO_VERSION_CMD = "info version"
|
789 |
|
790 |
_DEFAULT_PCI_RESERVATIONS = "11110000000000000000000000000000"
|
791 |
|
792 |
ANCILLARY_FILES = [ |
793 |
_KVM_NETWORK_SCRIPT, |
794 |
] |
795 |
ANCILLARY_FILES_OPT = [ |
796 |
_KVM_NETWORK_SCRIPT, |
797 |
] |
798 |
|
799 |
# Supported kvm options to get output from
|
800 |
_KVMOPT_HELP = "help"
|
801 |
_KVMOPT_MLIST = "mlist"
|
802 |
_KVMOPT_DEVICELIST = "devicelist"
|
803 |
|
804 |
# Command to execute to get the output from kvm, and whether to
|
805 |
# accept the output even on failure.
|
806 |
_KVMOPTS_CMDS = { |
807 |
_KVMOPT_HELP: (["--help"], False), |
808 |
_KVMOPT_MLIST: (["-M", "?"], False), |
809 |
_KVMOPT_DEVICELIST: (["-device", "?"], True), |
810 |
} |
811 |
|
812 |
def __init__(self): |
813 |
hv_base.BaseHypervisor.__init__(self)
|
814 |
# Let's make sure the directories we need exist, even if the RUN_DIR lives
|
815 |
# in a tmpfs filesystem or has been otherwise wiped out.
|
816 |
dirs = [(dname, constants.RUN_DIRS_MODE) for dname in self._DIRS] |
817 |
utils.EnsureDirs(dirs) |
818 |
|
819 |
@classmethod
|
820 |
def _InstancePidFile(cls, instance_name): |
821 |
"""Returns the instance pidfile.
|
822 |
|
823 |
"""
|
824 |
return utils.PathJoin(cls._PIDS_DIR, instance_name)
|
825 |
|
826 |
@classmethod
|
827 |
def _InstanceUidFile(cls, instance_name): |
828 |
"""Returns the instance uidfile.
|
829 |
|
830 |
"""
|
831 |
return utils.PathJoin(cls._UIDS_DIR, instance_name)
|
832 |
|
833 |
@classmethod
|
834 |
def _InstancePidInfo(cls, pid): |
835 |
"""Check pid file for instance information.
|
836 |
|
837 |
Check that a pid file is associated with an instance, and retrieve
|
838 |
information from its command line.
|
839 |
|
840 |
@type pid: string or int
|
841 |
@param pid: process id of the instance to check
|
842 |
@rtype: tuple
|
843 |
@return: (instance_name, memory, vcpus)
|
844 |
@raise errors.HypervisorError: when an instance cannot be found
|
845 |
|
846 |
"""
|
847 |
alive = utils.IsProcessAlive(pid) |
848 |
if not alive: |
849 |
raise errors.HypervisorError("Cannot get info for pid %s" % pid) |
850 |
|
851 |
cmdline_file = utils.PathJoin("/proc", str(pid), "cmdline") |
852 |
try:
|
853 |
cmdline = utils.ReadFile(cmdline_file) |
854 |
except EnvironmentError, err: |
855 |
raise errors.HypervisorError("Can't open cmdline file for pid %s: %s" % |
856 |
(pid, err)) |
857 |
|
858 |
instance = None
|
859 |
memory = 0
|
860 |
vcpus = 0
|
861 |
|
862 |
arg_list = cmdline.split("\x00")
|
863 |
while arg_list:
|
864 |
arg = arg_list.pop(0)
|
865 |
if arg == "-name": |
866 |
instance = arg_list.pop(0)
|
867 |
elif arg == "-m": |
868 |
memory = int(arg_list.pop(0)) |
869 |
elif arg == "-smp": |
870 |
vcpus = int(arg_list.pop(0).split(",")[0]) |
871 |
|
872 |
if instance is None: |
873 |
raise errors.HypervisorError("Pid %s doesn't contain a ganeti kvm" |
874 |
" instance" % pid)
|
875 |
|
876 |
return (instance, memory, vcpus)
|
877 |
|
878 |
@classmethod
|
879 |
def _InstancePidAlive(cls, instance_name): |
880 |
"""Returns the instance pidfile, pid, and liveness.
|
881 |
|
882 |
@type instance_name: string
|
883 |
@param instance_name: instance name
|
884 |
@rtype: tuple
|
885 |
@return: (pid file name, pid, liveness)
|
886 |
|
887 |
"""
|
888 |
pidfile = cls._InstancePidFile(instance_name) |
889 |
pid = utils.ReadPidFile(pidfile) |
890 |
|
891 |
alive = False
|
892 |
try:
|
893 |
cmd_instance = cls._InstancePidInfo(pid)[0]
|
894 |
alive = (cmd_instance == instance_name) |
895 |
except errors.HypervisorError:
|
896 |
pass
|
897 |
|
898 |
return (pidfile, pid, alive)
|
899 |
|
900 |
@classmethod
|
901 |
def _CheckDown(cls, instance_name): |
902 |
"""Raises an error unless the given instance is down.
|
903 |
|
904 |
"""
|
905 |
alive = cls._InstancePidAlive(instance_name)[2]
|
906 |
if alive:
|
907 |
raise errors.HypervisorError("Failed to start instance %s: %s" % |
908 |
(instance_name, "already running"))
|
909 |
|
910 |
@classmethod
|
911 |
def _InstanceMonitor(cls, instance_name): |
912 |
"""Returns the instance monitor socket name
|
913 |
|
914 |
"""
|
915 |
return utils.PathJoin(cls._CTRL_DIR, "%s.monitor" % instance_name) |
916 |
|
917 |
@classmethod
|
918 |
def _InstanceSerial(cls, instance_name): |
919 |
"""Returns the instance serial socket name
|
920 |
|
921 |
"""
|
922 |
return utils.PathJoin(cls._CTRL_DIR, "%s.serial" % instance_name) |
923 |
|
924 |
@classmethod
|
925 |
def _InstanceQmpMonitor(cls, instance_name): |
926 |
"""Returns the instance serial QMP socket name
|
927 |
|
928 |
"""
|
929 |
return utils.PathJoin(cls._CTRL_DIR, "%s.qmp" % instance_name) |
930 |
|
931 |
@classmethod
|
932 |
def _InstanceShutdownMonitor(cls, instance_name): |
933 |
"""Returns the instance QMP output filename
|
934 |
|
935 |
"""
|
936 |
return utils.PathJoin(cls._CTRL_DIR, "%s.shutdown" % instance_name) |
937 |
|
938 |
@staticmethod
|
939 |
def _SocatUnixConsoleParams(): |
940 |
"""Returns the correct parameters for socat
|
941 |
|
942 |
If we have a new-enough socat we can use raw mode with an escape character.
|
943 |
|
944 |
"""
|
945 |
if constants.SOCAT_USE_ESCAPE:
|
946 |
return "raw,echo=0,escape=%s" % constants.SOCAT_ESCAPE_CODE |
947 |
else:
|
948 |
return "echo=0,icanon=0" |
949 |
|
950 |
@classmethod
|
951 |
def _InstanceKVMRuntime(cls, instance_name): |
952 |
"""Returns the instance KVM runtime filename
|
953 |
|
954 |
"""
|
955 |
return utils.PathJoin(cls._CONF_DIR, "%s.runtime" % instance_name) |
956 |
|
957 |
@classmethod
|
958 |
def _InstanceChrootDir(cls, instance_name): |
959 |
"""Returns the name of the KVM chroot dir of the instance
|
960 |
|
961 |
"""
|
962 |
return utils.PathJoin(cls._CHROOT_DIR, instance_name)
|
963 |
|
964 |
@classmethod
|
965 |
def _InstanceNICDir(cls, instance_name): |
966 |
"""Returns the name of the directory holding the tap device files for a
|
967 |
given instance.
|
968 |
|
969 |
"""
|
970 |
return utils.PathJoin(cls._NICS_DIR, instance_name)
|
971 |
|
972 |
@classmethod
|
973 |
def _InstanceNICFile(cls, instance_name, seq): |
974 |
"""Returns the name of the file containing the tap device for a given NIC
|
975 |
|
976 |
"""
|
977 |
return utils.PathJoin(cls._InstanceNICDir(instance_name), str(seq)) |
978 |
|
979 |
@classmethod
|
980 |
def _InstanceKeymapFile(cls, instance_name): |
981 |
"""Returns the name of the file containing the keymap for a given instance
|
982 |
|
983 |
"""
|
984 |
return utils.PathJoin(cls._KEYMAP_DIR, instance_name)
|
985 |
|
986 |
@classmethod
|
987 |
def _TryReadUidFile(cls, uid_file): |
988 |
"""Try to read a uid file
|
989 |
|
990 |
"""
|
991 |
if os.path.exists(uid_file):
|
992 |
try:
|
993 |
uid = int(utils.ReadOneLineFile(uid_file))
|
994 |
return uid
|
995 |
except EnvironmentError: |
996 |
logging.warning("Can't read uid file", exc_info=True) |
997 |
except (TypeError, ValueError): |
998 |
logging.warning("Can't parse uid file contents", exc_info=True) |
999 |
return None |
1000 |
|
1001 |
@classmethod
|
1002 |
def _RemoveInstanceRuntimeFiles(cls, pidfile, instance_name): |
1003 |
"""Removes an instance's rutime sockets/files/dirs.
|
1004 |
|
1005 |
"""
|
1006 |
utils.RemoveFile(pidfile) |
1007 |
utils.RemoveFile(cls._InstanceMonitor(instance_name)) |
1008 |
utils.RemoveFile(cls._InstanceSerial(instance_name)) |
1009 |
utils.RemoveFile(cls._InstanceQmpMonitor(instance_name)) |
1010 |
utils.RemoveFile(cls._InstanceKVMRuntime(instance_name)) |
1011 |
utils.RemoveFile(cls._InstanceKeymapFile(instance_name)) |
1012 |
uid_file = cls._InstanceUidFile(instance_name) |
1013 |
uid = cls._TryReadUidFile(uid_file) |
1014 |
utils.RemoveFile(uid_file) |
1015 |
if uid is not None: |
1016 |
uidpool.ReleaseUid(uid) |
1017 |
try:
|
1018 |
shutil.rmtree(cls._InstanceNICDir(instance_name)) |
1019 |
except OSError, err: |
1020 |
if err.errno != errno.ENOENT:
|
1021 |
raise
|
1022 |
try:
|
1023 |
chroot_dir = cls._InstanceChrootDir(instance_name) |
1024 |
utils.RemoveDir(chroot_dir) |
1025 |
except OSError, err: |
1026 |
if err.errno == errno.ENOTEMPTY:
|
1027 |
# The chroot directory is expected to be empty, but it isn't.
|
1028 |
new_chroot_dir = tempfile.mkdtemp(dir=cls._CHROOT_QUARANTINE_DIR, |
1029 |
prefix="%s-%s-" %
|
1030 |
(instance_name, |
1031 |
utils.TimestampForFilename())) |
1032 |
logging.warning("The chroot directory of instance %s can not be"
|
1033 |
" removed as it is not empty. Moving it to the"
|
1034 |
" quarantine instead. Please investigate the"
|
1035 |
" contents (%s) and clean up manually",
|
1036 |
instance_name, new_chroot_dir) |
1037 |
utils.RenameFile(chroot_dir, new_chroot_dir) |
1038 |
else:
|
1039 |
raise
|
1040 |
|
1041 |
@staticmethod
|
1042 |
def _ConfigureNIC(instance, seq, nic, tap): |
1043 |
"""Run the network configuration script for a specified NIC
|
1044 |
|
1045 |
@param instance: instance we're acting on
|
1046 |
@type instance: instance object
|
1047 |
@param seq: nic sequence number
|
1048 |
@type seq: int
|
1049 |
@param nic: nic we're acting on
|
1050 |
@type nic: nic object
|
1051 |
@param tap: the host's tap interface this NIC corresponds to
|
1052 |
@type tap: str
|
1053 |
|
1054 |
"""
|
1055 |
env = { |
1056 |
"PATH": "%s:/sbin:/usr/sbin" % os.environ["PATH"], |
1057 |
"INSTANCE": instance.name,
|
1058 |
"MAC": nic.mac,
|
1059 |
"MODE": nic.nicparams[constants.NIC_MODE],
|
1060 |
"INTERFACE": tap,
|
1061 |
"INTERFACE_INDEX": str(seq), |
1062 |
"INTERFACE_UUID": nic.uuid,
|
1063 |
"TAGS": " ".join(instance.GetTags()), |
1064 |
} |
1065 |
|
1066 |
if nic.ip:
|
1067 |
env["IP"] = nic.ip
|
1068 |
|
1069 |
if nic.name:
|
1070 |
env["INTERFACE_NAME"] = nic.name
|
1071 |
|
1072 |
if nic.nicparams[constants.NIC_LINK]:
|
1073 |
env["LINK"] = nic.nicparams[constants.NIC_LINK]
|
1074 |
|
1075 |
if nic.network:
|
1076 |
n = objects.Network.FromDict(nic.netinfo) |
1077 |
env.update(n.HooksDict()) |
1078 |
|
1079 |
if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
|
1080 |
env["BRIDGE"] = nic.nicparams[constants.NIC_LINK]
|
1081 |
|
1082 |
result = utils.RunCmd([pathutils.KVM_IFUP, tap], env=env) |
1083 |
if result.failed:
|
1084 |
raise errors.HypervisorError("Failed to configure interface %s: %s;" |
1085 |
" network configuration script output: %s" %
|
1086 |
(tap, result.fail_reason, result.output)) |
1087 |
|
1088 |
@staticmethod
|
1089 |
def _VerifyAffinityPackage(): |
1090 |
if affinity is None: |
1091 |
raise errors.HypervisorError("affinity Python package not" |
1092 |
" found; cannot use CPU pinning under KVM")
|
1093 |
|
1094 |
@staticmethod
|
1095 |
def _BuildAffinityCpuMask(cpu_list): |
1096 |
"""Create a CPU mask suitable for sched_setaffinity from a list of
|
1097 |
CPUs.
|
1098 |
|
1099 |
See man taskset for more info on sched_setaffinity masks.
|
1100 |
For example: [ 0, 2, 5, 6 ] will return 101 (0x65, 0..01100101).
|
1101 |
|
1102 |
@type cpu_list: list of int
|
1103 |
@param cpu_list: list of physical CPU numbers to map to vCPUs in order
|
1104 |
@rtype: int
|
1105 |
@return: a bit mask of CPU affinities
|
1106 |
|
1107 |
"""
|
1108 |
if cpu_list == constants.CPU_PINNING_OFF:
|
1109 |
return constants.CPU_PINNING_ALL_KVM
|
1110 |
else:
|
1111 |
return sum(2 ** cpu for cpu in cpu_list) |
1112 |
|
1113 |
@classmethod
|
1114 |
def _AssignCpuAffinity(cls, cpu_mask, process_id, thread_dict): |
1115 |
"""Change CPU affinity for running VM according to given CPU mask.
|
1116 |
|
1117 |
@param cpu_mask: CPU mask as given by the user. e.g. "0-2,4:all:1,3"
|
1118 |
@type cpu_mask: string
|
1119 |
@param process_id: process ID of KVM process. Used to pin entire VM
|
1120 |
to physical CPUs.
|
1121 |
@type process_id: int
|
1122 |
@param thread_dict: map of virtual CPUs to KVM thread IDs
|
1123 |
@type thread_dict: dict int:int
|
1124 |
|
1125 |
"""
|
1126 |
# Convert the string CPU mask to a list of list of int's
|
1127 |
cpu_list = utils.ParseMultiCpuMask(cpu_mask) |
1128 |
|
1129 |
if len(cpu_list) == 1: |
1130 |
all_cpu_mapping = cpu_list[0]
|
1131 |
if all_cpu_mapping == constants.CPU_PINNING_OFF:
|
1132 |
# If CPU pinning has 1 entry that's "all", then do nothing
|
1133 |
pass
|
1134 |
else:
|
1135 |
# If CPU pinning has one non-all entry, map the entire VM to
|
1136 |
# one set of physical CPUs
|
1137 |
cls._VerifyAffinityPackage() |
1138 |
affinity.set_process_affinity_mask( |
1139 |
process_id, cls._BuildAffinityCpuMask(all_cpu_mapping)) |
1140 |
else:
|
1141 |
# The number of vCPUs mapped should match the number of vCPUs
|
1142 |
# reported by KVM. This was already verified earlier, so
|
1143 |
# here only as a sanity check.
|
1144 |
assert len(thread_dict) == len(cpu_list) |
1145 |
cls._VerifyAffinityPackage() |
1146 |
|
1147 |
# For each vCPU, map it to the proper list of physical CPUs
|
1148 |
for vcpu, i in zip(cpu_list, range(len(cpu_list))): |
1149 |
affinity.set_process_affinity_mask(thread_dict[i], |
1150 |
cls._BuildAffinityCpuMask(vcpu)) |
1151 |
|
1152 |
def _GetVcpuThreadIds(self, instance_name): |
1153 |
"""Get a mapping of vCPU no. to thread IDs for the instance
|
1154 |
|
1155 |
@type instance_name: string
|
1156 |
@param instance_name: instance in question
|
1157 |
@rtype: dictionary of int:int
|
1158 |
@return: a dictionary mapping vCPU numbers to thread IDs
|
1159 |
|
1160 |
"""
|
1161 |
result = {} |
1162 |
output = self._CallMonitorCommand(instance_name, self._CPU_INFO_CMD) |
1163 |
for line in output.stdout.splitlines(): |
1164 |
match = self._CPU_INFO_RE.search(line)
|
1165 |
if not match: |
1166 |
continue
|
1167 |
grp = map(int, match.groups()) |
1168 |
result[grp[0]] = grp[1] |
1169 |
|
1170 |
return result
|
1171 |
|
1172 |
def _ExecuteCpuAffinity(self, instance_name, cpu_mask): |
1173 |
"""Complete CPU pinning.
|
1174 |
|
1175 |
@type instance_name: string
|
1176 |
@param instance_name: name of instance
|
1177 |
@type cpu_mask: string
|
1178 |
@param cpu_mask: CPU pinning mask as entered by user
|
1179 |
|
1180 |
"""
|
1181 |
# Get KVM process ID, to be used if need to pin entire VM
|
1182 |
_, pid, _ = self._InstancePidAlive(instance_name)
|
1183 |
# Get vCPU thread IDs, to be used if need to pin vCPUs separately
|
1184 |
thread_dict = self._GetVcpuThreadIds(instance_name)
|
1185 |
# Run CPU pinning, based on configured mask
|
1186 |
self._AssignCpuAffinity(cpu_mask, pid, thread_dict)
|
1187 |
|
1188 |
def ListInstances(self, hvparams=None): |
1189 |
"""Get the list of running instances.
|
1190 |
|
1191 |
We can do this by listing our live instances directory and
|
1192 |
checking whether the associated kvm process is still alive.
|
1193 |
|
1194 |
"""
|
1195 |
result = [] |
1196 |
for name in os.listdir(self._PIDS_DIR): |
1197 |
if self._InstancePidAlive(name)[2] or self._IsUserShutdown(name): |
1198 |
result.append(name) |
1199 |
return result
|
1200 |
|
1201 |
@classmethod
|
1202 |
def _IsUserShutdown(cls, instance_name): |
1203 |
return os.path.exists(cls._InstanceShutdownMonitor(instance_name))
|
1204 |
|
1205 |
@classmethod
|
1206 |
def _ClearUserShutdown(cls, instance_name): |
1207 |
utils.RemoveFile(cls._InstanceShutdownMonitor(instance_name)) |
1208 |
|
1209 |
def GetInstanceInfo(self, instance_name, hvparams=None): |
1210 |
"""Get instance properties.
|
1211 |
|
1212 |
@type instance_name: string
|
1213 |
@param instance_name: the instance name
|
1214 |
@type hvparams: dict of strings
|
1215 |
@param hvparams: hvparams to be used with this instance
|
1216 |
@rtype: tuple of strings
|
1217 |
@return: (name, id, memory, vcpus, stat, times)
|
1218 |
|
1219 |
"""
|
1220 |
_, pid, alive = self._InstancePidAlive(instance_name)
|
1221 |
if not alive: |
1222 |
if self._IsUserShutdown(instance_name): |
1223 |
return (instance_name, -1, 0, 0, hv_base.HvInstanceState.SHUTDOWN, 0) |
1224 |
else:
|
1225 |
return None |
1226 |
|
1227 |
_, memory, vcpus = self._InstancePidInfo(pid)
|
1228 |
istat = hv_base.HvInstanceState.RUNNING |
1229 |
times = 0
|
1230 |
|
1231 |
try:
|
1232 |
qmp = QmpConnection(self._InstanceQmpMonitor(instance_name))
|
1233 |
qmp.connect() |
1234 |
vcpus = len(qmp.Execute("query-cpus")[qmp.RETURN_KEY]) |
1235 |
# Will fail if ballooning is not enabled, but we can then just resort to
|
1236 |
# the value above.
|
1237 |
mem_bytes = qmp.Execute("query-balloon")[qmp.RETURN_KEY][qmp.ACTUAL_KEY]
|
1238 |
memory = mem_bytes / 1048576
|
1239 |
except errors.HypervisorError:
|
1240 |
pass
|
1241 |
|
1242 |
return (instance_name, pid, memory, vcpus, istat, times)
|
1243 |
|
1244 |
def GetAllInstancesInfo(self, hvparams=None): |
1245 |
"""Get properties of all instances.
|
1246 |
|
1247 |
@type hvparams: dict of strings
|
1248 |
@param hvparams: hypervisor parameter
|
1249 |
@return: list of tuples (name, id, memory, vcpus, stat, times)
|
1250 |
|
1251 |
"""
|
1252 |
data = [] |
1253 |
for name in os.listdir(self._PIDS_DIR): |
1254 |
try:
|
1255 |
info = self.GetInstanceInfo(name)
|
1256 |
except errors.HypervisorError:
|
1257 |
# Ignore exceptions due to instances being shut down
|
1258 |
continue
|
1259 |
if info:
|
1260 |
data.append(info) |
1261 |
return data
|
1262 |
|
1263 |
def _GenerateKVMBlockDevicesOptions(self, instance, kvm_disks, |
1264 |
kvmhelp, devlist): |
1265 |
"""Generate KVM options regarding instance's block devices.
|
1266 |
|
1267 |
@type instance: L{objects.Instance}
|
1268 |
@param instance: the instance object
|
1269 |
@type kvm_disks: list of tuples
|
1270 |
@param kvm_disks: list of tuples [(disk, link_name, uri)..]
|
1271 |
@type kvmhelp: string
|
1272 |
@param kvmhelp: output of kvm --help
|
1273 |
@type devlist: string
|
1274 |
@param devlist: output of kvm -device ?
|
1275 |
@rtype: list
|
1276 |
@return: list of command line options eventually used by kvm executable
|
1277 |
|
1278 |
"""
|
1279 |
hvp = instance.hvparams |
1280 |
kernel_path = hvp[constants.HV_KERNEL_PATH] |
1281 |
if kernel_path:
|
1282 |
boot_disk = False
|
1283 |
else:
|
1284 |
boot_disk = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_DISK |
1285 |
|
1286 |
# whether this is an older KVM version that uses the boot=on flag
|
1287 |
# on devices
|
1288 |
needs_boot_flag = self._BOOT_RE.search(kvmhelp)
|
1289 |
|
1290 |
dev_opts = [] |
1291 |
device_driver = None
|
1292 |
disk_type = hvp[constants.HV_DISK_TYPE] |
1293 |
if disk_type == constants.HT_DISK_PARAVIRTUAL:
|
1294 |
if_val = ",if=%s" % self._VIRTIO |
1295 |
try:
|
1296 |
if self._VIRTIO_BLK_RE.search(devlist): |
1297 |
if_val = ",if=none"
|
1298 |
# will be passed in -device option as driver
|
1299 |
device_driver = self._VIRTIO_BLK_PCI
|
1300 |
except errors.HypervisorError, _:
|
1301 |
pass
|
1302 |
else:
|
1303 |
if_val = ",if=%s" % disk_type
|
1304 |
# Cache mode
|
1305 |
disk_cache = hvp[constants.HV_DISK_CACHE] |
1306 |
if instance.disk_template in constants.DTS_EXT_MIRROR: |
1307 |
if disk_cache != "none": |
1308 |
# TODO: make this a hard error, instead of a silent overwrite
|
1309 |
logging.warning("KVM: overriding disk_cache setting '%s' with 'none'"
|
1310 |
" to prevent shared storage corruption on migration",
|
1311 |
disk_cache) |
1312 |
cache_val = ",cache=none"
|
1313 |
elif disk_cache != constants.HT_CACHE_DEFAULT:
|
1314 |
cache_val = ",cache=%s" % disk_cache
|
1315 |
else:
|
1316 |
cache_val = ""
|
1317 |
for cfdev, link_name, uri in kvm_disks: |
1318 |
if cfdev.mode != constants.DISK_RDWR:
|
1319 |
raise errors.HypervisorError("Instance has read-only disks which" |
1320 |
" are not supported by KVM")
|
1321 |
# TODO: handle FD_LOOP and FD_BLKTAP (?)
|
1322 |
boot_val = ""
|
1323 |
if boot_disk:
|
1324 |
dev_opts.extend(["-boot", "c"]) |
1325 |
boot_disk = False
|
1326 |
if needs_boot_flag and disk_type != constants.HT_DISK_IDE: |
1327 |
boot_val = ",boot=on"
|
1328 |
|
1329 |
access_mode = cfdev.params.get(constants.LDP_ACCESS, |
1330 |
constants.DISK_KERNELSPACE) |
1331 |
if (uri and access_mode == constants.DISK_USERSPACE): |
1332 |
drive_uri = uri |
1333 |
else:
|
1334 |
drive_uri = link_name |
1335 |
|
1336 |
drive_val = "file=%s,format=raw%s%s%s" % \
|
1337 |
(drive_uri, if_val, boot_val, cache_val) |
1338 |
|
1339 |
if device_driver:
|
1340 |
# kvm_disks are the 4th entry of runtime file that did not exist in
|
1341 |
# the past. That means that cfdev should always have pci slot and
|
1342 |
# _GenerateDeviceKVMId() will not raise a exception.
|
1343 |
kvm_devid = _GenerateDeviceKVMId(constants.HOTPLUG_TARGET_DISK, cfdev) |
1344 |
drive_val += (",id=%s" % kvm_devid)
|
1345 |
drive_val += (",bus=0,unit=%d" % cfdev.pci)
|
1346 |
dev_val = ("%s,drive=%s,id=%s" %
|
1347 |
(device_driver, kvm_devid, kvm_devid)) |
1348 |
dev_val += ",bus=pci.0,addr=%s" % hex(cfdev.pci) |
1349 |
dev_opts.extend(["-device", dev_val])
|
1350 |
|
1351 |
dev_opts.extend(["-drive", drive_val])
|
1352 |
|
1353 |
return dev_opts
|
1354 |
|
1355 |
def _GenerateKVMRuntime(self, instance, block_devices, startup_paused, |
1356 |
kvmhelp): |
1357 |
"""Generate KVM information to start an instance.
|
1358 |
|
1359 |
@type kvmhelp: string
|
1360 |
@param kvmhelp: output of kvm --help
|
1361 |
@attention: this function must not have any side-effects; for
|
1362 |
example, it must not write to the filesystem, or read values
|
1363 |
from the current system the are expected to differ between
|
1364 |
nodes, since it is only run once at instance startup;
|
1365 |
actions/kvm arguments that can vary between systems should be
|
1366 |
done in L{_ExecuteKVMRuntime}
|
1367 |
|
1368 |
"""
|
1369 |
# pylint: disable=R0912,R0914,R0915
|
1370 |
hvp = instance.hvparams |
1371 |
self.ValidateParameters(hvp)
|
1372 |
|
1373 |
pidfile = self._InstancePidFile(instance.name)
|
1374 |
kvm = hvp[constants.HV_KVM_PATH] |
1375 |
kvm_cmd = [kvm] |
1376 |
# used just by the vnc server, if enabled
|
1377 |
kvm_cmd.extend(["-name", instance.name])
|
1378 |
kvm_cmd.extend(["-m", instance.beparams[constants.BE_MAXMEM]])
|
1379 |
|
1380 |
smp_list = ["%s" % instance.beparams[constants.BE_VCPUS]]
|
1381 |
if hvp[constants.HV_CPU_CORES]:
|
1382 |
smp_list.append("cores=%s" % hvp[constants.HV_CPU_CORES])
|
1383 |
if hvp[constants.HV_CPU_THREADS]:
|
1384 |
smp_list.append("threads=%s" % hvp[constants.HV_CPU_THREADS])
|
1385 |
if hvp[constants.HV_CPU_SOCKETS]:
|
1386 |
smp_list.append("sockets=%s" % hvp[constants.HV_CPU_SOCKETS])
|
1387 |
|
1388 |
kvm_cmd.extend(["-smp", ",".join(smp_list)]) |
1389 |
|
1390 |
kvm_cmd.extend(["-pidfile", pidfile])
|
1391 |
kvm_cmd.extend(["-balloon", "virtio"]) |
1392 |
kvm_cmd.extend(["-daemonize"])
|
1393 |
if not instance.hvparams[constants.HV_ACPI]: |
1394 |
kvm_cmd.extend(["-no-acpi"])
|
1395 |
if instance.hvparams[constants.HV_REBOOT_BEHAVIOR] == \
|
1396 |
constants.INSTANCE_REBOOT_EXIT: |
1397 |
kvm_cmd.extend(["-no-reboot"])
|
1398 |
|
1399 |
mversion = hvp[constants.HV_KVM_MACHINE_VERSION] |
1400 |
if not mversion: |
1401 |
mversion = self._GetDefaultMachineVersion(kvm)
|
1402 |
if self._MACHINE_RE.search(kvmhelp): |
1403 |
# TODO (2.8): kernel_irqchip and kvm_shadow_mem machine properties, as
|
1404 |
# extra hypervisor parameters. We should also investigate whether and how
|
1405 |
# shadow_mem should be considered for the resource model.
|
1406 |
if (hvp[constants.HV_KVM_FLAG] == constants.HT_KVM_ENABLED):
|
1407 |
specprop = ",accel=kvm"
|
1408 |
else:
|
1409 |
specprop = ""
|
1410 |
machinespec = "%s%s" % (mversion, specprop)
|
1411 |
kvm_cmd.extend(["-machine", machinespec])
|
1412 |
else:
|
1413 |
kvm_cmd.extend(["-M", mversion])
|
1414 |
if (hvp[constants.HV_KVM_FLAG] == constants.HT_KVM_ENABLED and |
1415 |
self._ENABLE_KVM_RE.search(kvmhelp)):
|
1416 |
kvm_cmd.extend(["-enable-kvm"])
|
1417 |
elif (hvp[constants.HV_KVM_FLAG] == constants.HT_KVM_DISABLED and |
1418 |
self._DISABLE_KVM_RE.search(kvmhelp)):
|
1419 |
kvm_cmd.extend(["-disable-kvm"])
|
1420 |
|
1421 |
kernel_path = hvp[constants.HV_KERNEL_PATH] |
1422 |
if kernel_path:
|
1423 |
boot_cdrom = boot_floppy = boot_network = False
|
1424 |
else:
|
1425 |
boot_cdrom = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_CDROM |
1426 |
boot_floppy = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_FLOPPY |
1427 |
boot_network = hvp[constants.HV_BOOT_ORDER] == constants.HT_BO_NETWORK |
1428 |
|
1429 |
if startup_paused:
|
1430 |
kvm_cmd.extend([_KVM_START_PAUSED_FLAG]) |
1431 |
|
1432 |
if boot_network:
|
1433 |
kvm_cmd.extend(["-boot", "n"]) |
1434 |
|
1435 |
# whether this is an older KVM version that uses the boot=on flag
|
1436 |
# on devices
|
1437 |
needs_boot_flag = self._BOOT_RE.search(kvmhelp)
|
1438 |
|
1439 |
disk_type = hvp[constants.HV_DISK_TYPE] |
1440 |
|
1441 |
#Now we can specify a different device type for CDROM devices.
|
1442 |
cdrom_disk_type = hvp[constants.HV_KVM_CDROM_DISK_TYPE] |
1443 |
if not cdrom_disk_type: |
1444 |
cdrom_disk_type = disk_type |
1445 |
|
1446 |
iso_image = hvp[constants.HV_CDROM_IMAGE_PATH] |
1447 |
if iso_image:
|
1448 |
options = ",media=cdrom"
|
1449 |
if re.match(r'(https?|ftps?)://', iso_image): |
1450 |
# Check that the iso image is really there
|
1451 |
# See https://bugs.launchpad.net/qemu/+bug/597575
|
1452 |
if not _CheckUrl(iso_image): |
1453 |
raise errors.HypervisorError("ISO image %s is not accessible" % |
1454 |
iso_image) |
1455 |
else:
|
1456 |
options = "%s,format=raw" % options
|
1457 |
# set cdrom 'if' type
|
1458 |
if boot_cdrom:
|
1459 |
actual_cdrom_type = constants.HT_DISK_IDE |
1460 |
elif cdrom_disk_type == constants.HT_DISK_PARAVIRTUAL:
|
1461 |
actual_cdrom_type = "virtio"
|
1462 |
else:
|
1463 |
actual_cdrom_type = cdrom_disk_type |
1464 |
if_val = ",if=%s" % actual_cdrom_type
|
1465 |
# set boot flag, if needed
|
1466 |
boot_val = ""
|
1467 |
if boot_cdrom:
|
1468 |
kvm_cmd.extend(["-boot", "d"]) |
1469 |
if needs_boot_flag:
|
1470 |
boot_val = ",boot=on"
|
1471 |
# and finally build the entire '-drive' value
|
1472 |
drive_val = "file=%s%s%s%s" % (iso_image, options, if_val, boot_val)
|
1473 |
kvm_cmd.extend(["-drive", drive_val])
|
1474 |
|
1475 |
iso_image2 = hvp[constants.HV_KVM_CDROM2_IMAGE_PATH] |
1476 |
if iso_image2:
|
1477 |
options = ",format=raw,media=cdrom"
|
1478 |
if cdrom_disk_type == constants.HT_DISK_PARAVIRTUAL:
|
1479 |
if_val = ",if=virtio"
|
1480 |
else:
|
1481 |
if_val = ",if=%s" % cdrom_disk_type
|
1482 |
drive_val = "file=%s%s%s" % (iso_image2, options, if_val)
|
1483 |
kvm_cmd.extend(["-drive", drive_val])
|
1484 |
|
1485 |
floppy_image = hvp[constants.HV_KVM_FLOPPY_IMAGE_PATH] |
1486 |
if floppy_image:
|
1487 |
options = ",format=raw,media=disk"
|
1488 |
if boot_floppy:
|
1489 |
kvm_cmd.extend(["-boot", "a"]) |
1490 |
options = "%s,boot=on" % options
|
1491 |
if_val = ",if=floppy"
|
1492 |
options = "%s%s" % (options, if_val)
|
1493 |
drive_val = "file=%s%s" % (floppy_image, options)
|
1494 |
kvm_cmd.extend(["-drive", drive_val])
|
1495 |
|
1496 |
if kernel_path:
|
1497 |
kvm_cmd.extend(["-kernel", kernel_path])
|
1498 |
initrd_path = hvp[constants.HV_INITRD_PATH] |
1499 |
if initrd_path:
|
1500 |
kvm_cmd.extend(["-initrd", initrd_path])
|
1501 |
root_append = ["root=%s" % hvp[constants.HV_ROOT_PATH],
|
1502 |
hvp[constants.HV_KERNEL_ARGS]] |
1503 |
if hvp[constants.HV_SERIAL_CONSOLE]:
|
1504 |
serial_speed = hvp[constants.HV_SERIAL_SPEED] |
1505 |
root_append.append("console=ttyS0,%s" % serial_speed)
|
1506 |
kvm_cmd.extend(["-append", " ".join(root_append)]) |
1507 |
|
1508 |
mem_path = hvp[constants.HV_MEM_PATH] |
1509 |
if mem_path:
|
1510 |
kvm_cmd.extend(["-mem-path", mem_path, "-mem-prealloc"]) |
1511 |
|
1512 |
monitor_dev = ("unix:%s,server,nowait" %
|
1513 |
self._InstanceMonitor(instance.name))
|
1514 |
kvm_cmd.extend(["-monitor", monitor_dev])
|
1515 |
if hvp[constants.HV_SERIAL_CONSOLE]:
|
1516 |
serial_dev = ("unix:%s,server,nowait" %
|
1517 |
self._InstanceSerial(instance.name))
|
1518 |
kvm_cmd.extend(["-serial", serial_dev])
|
1519 |
else:
|
1520 |
kvm_cmd.extend(["-serial", "none"]) |
1521 |
|
1522 |
mouse_type = hvp[constants.HV_USB_MOUSE] |
1523 |
vnc_bind_address = hvp[constants.HV_VNC_BIND_ADDRESS] |
1524 |
spice_bind = hvp[constants.HV_KVM_SPICE_BIND] |
1525 |
spice_ip_version = None
|
1526 |
|
1527 |
kvm_cmd.extend(["-usb"])
|
1528 |
|
1529 |
if mouse_type:
|
1530 |
kvm_cmd.extend(["-usbdevice", mouse_type])
|
1531 |
elif vnc_bind_address:
|
1532 |
kvm_cmd.extend(["-usbdevice", constants.HT_MOUSE_TABLET])
|
1533 |
|
1534 |
if vnc_bind_address:
|
1535 |
if netutils.IsValidInterface(vnc_bind_address):
|
1536 |
if_addresses = netutils.GetInterfaceIpAddresses(vnc_bind_address) |
1537 |
if_ip4_addresses = if_addresses[constants.IP4_VERSION] |
1538 |
if len(if_ip4_addresses) < 1: |
1539 |
logging.error("Could not determine IPv4 address of interface %s",
|
1540 |
vnc_bind_address) |
1541 |
else:
|
1542 |
vnc_bind_address = if_ip4_addresses[0]
|
1543 |
if netutils.IP4Address.IsValid(vnc_bind_address):
|
1544 |
if instance.network_port > constants.VNC_BASE_PORT:
|
1545 |
display = instance.network_port - constants.VNC_BASE_PORT |
1546 |
if vnc_bind_address == constants.IP4_ADDRESS_ANY:
|
1547 |
vnc_arg = ":%d" % (display)
|
1548 |
else:
|
1549 |
vnc_arg = "%s:%d" % (vnc_bind_address, display)
|
1550 |
else:
|
1551 |
logging.error("Network port is not a valid VNC display (%d < %d),"
|
1552 |
" not starting VNC",
|
1553 |
instance.network_port, constants.VNC_BASE_PORT) |
1554 |
vnc_arg = "none"
|
1555 |
|
1556 |
# Only allow tls and other option when not binding to a file, for now.
|
1557 |
# kvm/qemu gets confused otherwise about the filename to use.
|
1558 |
vnc_append = ""
|
1559 |
if hvp[constants.HV_VNC_TLS]:
|
1560 |
vnc_append = "%s,tls" % vnc_append
|
1561 |
if hvp[constants.HV_VNC_X509_VERIFY]:
|
1562 |
vnc_append = "%s,x509verify=%s" % (vnc_append,
|
1563 |
hvp[constants.HV_VNC_X509]) |
1564 |
elif hvp[constants.HV_VNC_X509]:
|
1565 |
vnc_append = "%s,x509=%s" % (vnc_append,
|
1566 |
hvp[constants.HV_VNC_X509]) |
1567 |
if hvp[constants.HV_VNC_PASSWORD_FILE]:
|
1568 |
vnc_append = "%s,password" % vnc_append
|
1569 |
|
1570 |
vnc_arg = "%s%s" % (vnc_arg, vnc_append)
|
1571 |
|
1572 |
else:
|
1573 |
vnc_arg = "unix:%s/%s.vnc" % (vnc_bind_address, instance.name)
|
1574 |
|
1575 |
kvm_cmd.extend(["-vnc", vnc_arg])
|
1576 |
elif spice_bind:
|
1577 |
# FIXME: this is wrong here; the iface ip address differs
|
1578 |
# between systems, so it should be done in _ExecuteKVMRuntime
|
1579 |
if netutils.IsValidInterface(spice_bind):
|
1580 |
# The user specified a network interface, we have to figure out the IP
|
1581 |
# address.
|
1582 |
addresses = netutils.GetInterfaceIpAddresses(spice_bind) |
1583 |
spice_ip_version = hvp[constants.HV_KVM_SPICE_IP_VERSION] |
1584 |
|
1585 |
# if the user specified an IP version and the interface does not
|
1586 |
# have that kind of IP addresses, throw an exception
|
1587 |
if spice_ip_version != constants.IFACE_NO_IP_VERSION_SPECIFIED:
|
1588 |
if not addresses[spice_ip_version]: |
1589 |
raise errors.HypervisorError("SPICE: Unable to get an IPv%s address" |
1590 |
" for %s" % (spice_ip_version,
|
1591 |
spice_bind)) |
1592 |
|
1593 |
# the user did not specify an IP version, we have to figure it out
|
1594 |
elif (addresses[constants.IP4_VERSION] and |
1595 |
addresses[constants.IP6_VERSION]): |
1596 |
# we have both ipv4 and ipv6, let's use the cluster default IP
|
1597 |
# version
|
1598 |
cluster_family = ssconf.SimpleStore().GetPrimaryIPFamily() |
1599 |
spice_ip_version = \ |
1600 |
netutils.IPAddress.GetVersionFromAddressFamily(cluster_family) |
1601 |
elif addresses[constants.IP4_VERSION]:
|
1602 |
spice_ip_version = constants.IP4_VERSION |
1603 |
elif addresses[constants.IP6_VERSION]:
|
1604 |
spice_ip_version = constants.IP6_VERSION |
1605 |
else:
|
1606 |
raise errors.HypervisorError("SPICE: Unable to get an IP address" |
1607 |
" for %s" % (spice_bind))
|
1608 |
|
1609 |
spice_address = addresses[spice_ip_version][0]
|
1610 |
|
1611 |
else:
|
1612 |
# spice_bind is known to be a valid IP address, because
|
1613 |
# ValidateParameters checked it.
|
1614 |
spice_address = spice_bind |
1615 |
|
1616 |
spice_arg = "addr=%s" % spice_address
|
1617 |
if hvp[constants.HV_KVM_SPICE_USE_TLS]:
|
1618 |
spice_arg = ("%s,tls-port=%s,x509-cacert-file=%s" %
|
1619 |
(spice_arg, instance.network_port, |
1620 |
pathutils.SPICE_CACERT_FILE)) |
1621 |
spice_arg = ("%s,x509-key-file=%s,x509-cert-file=%s" %
|
1622 |
(spice_arg, pathutils.SPICE_CERT_FILE, |
1623 |
pathutils.SPICE_CERT_FILE)) |
1624 |
tls_ciphers = hvp[constants.HV_KVM_SPICE_TLS_CIPHERS] |
1625 |
if tls_ciphers:
|
1626 |
spice_arg = "%s,tls-ciphers=%s" % (spice_arg, tls_ciphers)
|
1627 |
else:
|
1628 |
spice_arg = "%s,port=%s" % (spice_arg, instance.network_port)
|
1629 |
|
1630 |
if not hvp[constants.HV_KVM_SPICE_PASSWORD_FILE]: |
1631 |
spice_arg = "%s,disable-ticketing" % spice_arg
|
1632 |
|
1633 |
if spice_ip_version:
|
1634 |
spice_arg = "%s,ipv%s" % (spice_arg, spice_ip_version)
|
1635 |
|
1636 |
# Image compression options
|
1637 |
img_lossless = hvp[constants.HV_KVM_SPICE_LOSSLESS_IMG_COMPR] |
1638 |
img_jpeg = hvp[constants.HV_KVM_SPICE_JPEG_IMG_COMPR] |
1639 |
img_zlib_glz = hvp[constants.HV_KVM_SPICE_ZLIB_GLZ_IMG_COMPR] |
1640 |
if img_lossless:
|
1641 |
spice_arg = "%s,image-compression=%s" % (spice_arg, img_lossless)
|
1642 |
if img_jpeg:
|
1643 |
spice_arg = "%s,jpeg-wan-compression=%s" % (spice_arg, img_jpeg)
|
1644 |
if img_zlib_glz:
|
1645 |
spice_arg = "%s,zlib-glz-wan-compression=%s" % (spice_arg, img_zlib_glz)
|
1646 |
|
1647 |
# Video stream detection
|
1648 |
video_streaming = hvp[constants.HV_KVM_SPICE_STREAMING_VIDEO_DETECTION] |
1649 |
if video_streaming:
|
1650 |
spice_arg = "%s,streaming-video=%s" % (spice_arg, video_streaming)
|
1651 |
|
1652 |
# Audio compression, by default in qemu-kvm it is on
|
1653 |
if not hvp[constants.HV_KVM_SPICE_AUDIO_COMPR]: |
1654 |
spice_arg = "%s,playback-compression=off" % spice_arg
|
1655 |
if not hvp[constants.HV_KVM_SPICE_USE_VDAGENT]: |
1656 |
spice_arg = "%s,agent-mouse=off" % spice_arg
|
1657 |
else:
|
1658 |
# Enable the spice agent communication channel between the host and the
|
1659 |
# agent.
|
1660 |
kvm_cmd.extend(["-device", "virtio-serial-pci"]) |
1661 |
kvm_cmd.extend([ |
1662 |
"-device",
|
1663 |
"virtserialport,chardev=spicechannel0,name=com.redhat.spice.0",
|
1664 |
]) |
1665 |
kvm_cmd.extend(["-chardev", "spicevmc,id=spicechannel0,name=vdagent"]) |
1666 |
|
1667 |
logging.info("KVM: SPICE will listen on port %s", instance.network_port)
|
1668 |
kvm_cmd.extend(["-spice", spice_arg])
|
1669 |
|
1670 |
else:
|
1671 |
# From qemu 1.4 -nographic is incompatible with -daemonize. The new way
|
1672 |
# also works in earlier versions though (tested with 1.1 and 1.3)
|
1673 |
if self._DISPLAY_RE.search(kvmhelp): |
1674 |
kvm_cmd.extend(["-display", "none"]) |
1675 |
else:
|
1676 |
kvm_cmd.extend(["-nographic"])
|
1677 |
|
1678 |
if hvp[constants.HV_USE_LOCALTIME]:
|
1679 |
kvm_cmd.extend(["-localtime"])
|
1680 |
|
1681 |
if hvp[constants.HV_KVM_USE_CHROOT]:
|
1682 |
kvm_cmd.extend(["-chroot", self._InstanceChrootDir(instance.name)]) |
1683 |
|
1684 |
# Add qemu-KVM -cpu param
|
1685 |
if hvp[constants.HV_CPU_TYPE]:
|
1686 |
kvm_cmd.extend(["-cpu", hvp[constants.HV_CPU_TYPE]])
|
1687 |
|
1688 |
# As requested by music lovers
|
1689 |
if hvp[constants.HV_SOUNDHW]:
|
1690 |
kvm_cmd.extend(["-soundhw", hvp[constants.HV_SOUNDHW]])
|
1691 |
|
1692 |
# Pass a -vga option if requested, or if spice is used, for backwards
|
1693 |
# compatibility.
|
1694 |
if hvp[constants.HV_VGA]:
|
1695 |
kvm_cmd.extend(["-vga", hvp[constants.HV_VGA]])
|
1696 |
elif spice_bind:
|
1697 |
kvm_cmd.extend(["-vga", "qxl"]) |
1698 |
|
1699 |
# Various types of usb devices, comma separated
|
1700 |
if hvp[constants.HV_USB_DEVICES]:
|
1701 |
for dev in hvp[constants.HV_USB_DEVICES].split(","): |
1702 |
kvm_cmd.extend(["-usbdevice", dev])
|
1703 |
|
1704 |
# Set system UUID to instance UUID
|
1705 |
if self._UUID_RE.search(kvmhelp): |
1706 |
kvm_cmd.extend(["-uuid", instance.uuid])
|
1707 |
|
1708 |
if hvp[constants.HV_KVM_EXTRA]:
|
1709 |
kvm_cmd.extend(hvp[constants.HV_KVM_EXTRA].split(" "))
|
1710 |
|
1711 |
pci_reservations = bitarray(self._DEFAULT_PCI_RESERVATIONS)
|
1712 |
kvm_disks = [] |
1713 |
for disk, link_name, uri in block_devices: |
1714 |
_UpdatePCISlots(disk, pci_reservations) |
1715 |
kvm_disks.append((disk, link_name, uri)) |
1716 |
|
1717 |
kvm_nics = [] |
1718 |
for nic in instance.nics: |
1719 |
_UpdatePCISlots(nic, pci_reservations) |
1720 |
kvm_nics.append(nic) |
1721 |
|
1722 |
hvparams = hvp |
1723 |
|
1724 |
return (kvm_cmd, kvm_nics, hvparams, kvm_disks)
|
1725 |
|
1726 |
def _WriteKVMRuntime(self, instance_name, data): |
1727 |
"""Write an instance's KVM runtime
|
1728 |
|
1729 |
"""
|
1730 |
try:
|
1731 |
utils.WriteFile(self._InstanceKVMRuntime(instance_name),
|
1732 |
data=data) |
1733 |
except EnvironmentError, err: |
1734 |
raise errors.HypervisorError("Failed to save KVM runtime file: %s" % err) |
1735 |
|
1736 |
def _ReadKVMRuntime(self, instance_name): |
1737 |
"""Read an instance's KVM runtime
|
1738 |
|
1739 |
"""
|
1740 |
try:
|
1741 |
file_content = utils.ReadFile(self._InstanceKVMRuntime(instance_name))
|
1742 |
except EnvironmentError, err: |
1743 |
raise errors.HypervisorError("Failed to load KVM runtime file: %s" % err) |
1744 |
return file_content
|
1745 |
|
1746 |
def _SaveKVMRuntime(self, instance, kvm_runtime): |
1747 |
"""Save an instance's KVM runtime
|
1748 |
|
1749 |
"""
|
1750 |
kvm_cmd, kvm_nics, hvparams, kvm_disks = kvm_runtime |
1751 |
|
1752 |
serialized_nics = [nic.ToDict() for nic in kvm_nics] |
1753 |
serialized_disks = [(blk.ToDict(), link, uri) |
1754 |
for blk, link, uri in kvm_disks] |
1755 |
serialized_form = serializer.Dump((kvm_cmd, serialized_nics, hvparams, |
1756 |
serialized_disks)) |
1757 |
|
1758 |
self._WriteKVMRuntime(instance.name, serialized_form)
|
1759 |
|
1760 |
def _LoadKVMRuntime(self, instance, serialized_runtime=None): |
1761 |
"""Load an instance's KVM runtime
|
1762 |
|
1763 |
"""
|
1764 |
if not serialized_runtime: |
1765 |
serialized_runtime = self._ReadKVMRuntime(instance.name)
|
1766 |
|
1767 |
return _AnalyzeSerializedRuntime(serialized_runtime)
|
1768 |
|
1769 |
def _RunKVMCmd(self, name, kvm_cmd, tap_fds=None): |
1770 |
"""Run the KVM cmd and check for errors
|
1771 |
|
1772 |
@type name: string
|
1773 |
@param name: instance name
|
1774 |
@type kvm_cmd: list of strings
|
1775 |
@param kvm_cmd: runcmd input for kvm
|
1776 |
@type tap_fds: list of int
|
1777 |
@param tap_fds: fds of tap devices opened by Ganeti
|
1778 |
|
1779 |
"""
|
1780 |
try:
|
1781 |
result = utils.RunCmd(kvm_cmd, noclose_fds=tap_fds) |
1782 |
finally:
|
1783 |
for fd in tap_fds: |
1784 |
utils_wrapper.CloseFdNoError(fd) |
1785 |
|
1786 |
if result.failed:
|
1787 |
raise errors.HypervisorError("Failed to start instance %s: %s (%s)" % |
1788 |
(name, result.fail_reason, result.output)) |
1789 |
if not self._InstancePidAlive(name)[2]: |
1790 |
raise errors.HypervisorError("Failed to start instance %s" % name) |
1791 |
|
1792 |
# too many local variables
|
1793 |
# pylint: disable=R0914
|
1794 |
def _ExecuteKVMRuntime(self, instance, kvm_runtime, kvmhelp, incoming=None): |
1795 |
"""Execute a KVM cmd, after completing it with some last minute data.
|
1796 |
|
1797 |
@type incoming: tuple of strings
|
1798 |
@param incoming: (target_host_ip, port)
|
1799 |
@type kvmhelp: string
|
1800 |
@param kvmhelp: output of kvm --help
|
1801 |
|
1802 |
"""
|
1803 |
# Small _ExecuteKVMRuntime hv parameters programming howto:
|
1804 |
# - conf_hvp contains the parameters as configured on ganeti. they might
|
1805 |
# have changed since the instance started; only use them if the change
|
1806 |
# won't affect the inside of the instance (which hasn't been rebooted).
|
1807 |
# - up_hvp contains the parameters as they were when the instance was
|
1808 |
# started, plus any new parameter which has been added between ganeti
|
1809 |
# versions: it is paramount that those default to a value which won't
|
1810 |
# affect the inside of the instance as well.
|
1811 |
conf_hvp = instance.hvparams |
1812 |
name = instance.name |
1813 |
self._CheckDown(name)
|
1814 |
|
1815 |
self._ClearUserShutdown(instance.name)
|
1816 |
self._StartKvmd(instance.hvparams)
|
1817 |
|
1818 |
temp_files = [] |
1819 |
|
1820 |
kvm_cmd, kvm_nics, up_hvp, kvm_disks = kvm_runtime |
1821 |
# the first element of kvm_cmd is always the path to the kvm binary
|
1822 |
kvm_path = kvm_cmd[0]
|
1823 |
up_hvp = objects.FillDict(conf_hvp, up_hvp) |
1824 |
|
1825 |
# We know it's safe to run as a different user upon migration, so we'll use
|
1826 |
# the latest conf, from conf_hvp.
|
1827 |
security_model = conf_hvp[constants.HV_SECURITY_MODEL] |
1828 |
if security_model == constants.HT_SM_USER:
|
1829 |
kvm_cmd.extend(["-runas", conf_hvp[constants.HV_SECURITY_DOMAIN]])
|
1830 |
|
1831 |
keymap = conf_hvp[constants.HV_KEYMAP] |
1832 |
if keymap:
|
1833 |
keymap_path = self._InstanceKeymapFile(name)
|
1834 |
# If a keymap file is specified, KVM won't use its internal defaults. By
|
1835 |
# first including the "en-us" layout, an error on loading the actual
|
1836 |
# layout (e.g. because it can't be found) won't lead to a non-functional
|
1837 |
# keyboard. A keyboard with incorrect keys is still better than none.
|
1838 |
utils.WriteFile(keymap_path, data="include en-us\ninclude %s\n" % keymap)
|
1839 |
kvm_cmd.extend(["-k", keymap_path])
|
1840 |
|
1841 |
# We have reasons to believe changing something like the nic driver/type
|
1842 |
# upon migration won't exactly fly with the instance kernel, so for nic
|
1843 |
# related parameters we'll use up_hvp
|
1844 |
tapfds = [] |
1845 |
taps = [] |
1846 |
devlist = self._GetKVMOutput(kvm_path, self._KVMOPT_DEVICELIST) |
1847 |
if not kvm_nics: |
1848 |
kvm_cmd.extend(["-net", "none"]) |
1849 |
else:
|
1850 |
vnet_hdr = False
|
1851 |
tap_extra = ""
|
1852 |
nic_type = up_hvp[constants.HV_NIC_TYPE] |
1853 |
if nic_type == constants.HT_NIC_PARAVIRTUAL:
|
1854 |
nic_model = self._VIRTIO
|
1855 |
try:
|
1856 |
if self._VIRTIO_NET_RE.search(devlist): |
1857 |
nic_model = self._VIRTIO_NET_PCI
|
1858 |
vnet_hdr = up_hvp[constants.HV_VNET_HDR] |
1859 |
except errors.HypervisorError, _:
|
1860 |
# Older versions of kvm don't support DEVICE_LIST, but they don't
|
1861 |
# have new virtio syntax either.
|
1862 |
pass
|
1863 |
|
1864 |
if up_hvp[constants.HV_VHOST_NET]:
|
1865 |
# check for vhost_net support
|
1866 |
if self._VHOST_RE.search(kvmhelp): |
1867 |
tap_extra = ",vhost=on"
|
1868 |
else:
|
1869 |
raise errors.HypervisorError("vhost_net is configured" |
1870 |
" but it is not available")
|
1871 |
else:
|
1872 |
nic_model = nic_type |
1873 |
|
1874 |
kvm_supports_netdev = self._NETDEV_RE.search(kvmhelp)
|
1875 |
|
1876 |
for nic_seq, nic in enumerate(kvm_nics): |
1877 |
tapname, tapfd = _OpenTap(vnet_hdr=vnet_hdr) |
1878 |
tapfds.append(tapfd) |
1879 |
taps.append(tapname) |
1880 |
if kvm_supports_netdev:
|
1881 |
nic_val = "%s,mac=%s" % (nic_model, nic.mac)
|
1882 |
try:
|
1883 |
# kvm_nics already exist in old runtime files and thus there might
|
1884 |
# be some entries without pci slot (therefore try: except:)
|
1885 |
kvm_devid = _GenerateDeviceKVMId(constants.HOTPLUG_TARGET_NIC, nic) |
1886 |
netdev = kvm_devid |
1887 |
nic_val += (",id=%s,bus=pci.0,addr=%s" % (kvm_devid, hex(nic.pci))) |
1888 |
except errors.HotplugError:
|
1889 |
netdev = "netdev%d" % nic_seq
|
1890 |
nic_val += (",netdev=%s" % netdev)
|
1891 |
tap_val = ("type=tap,id=%s,fd=%d%s" %
|
1892 |
(netdev, tapfd, tap_extra)) |
1893 |
kvm_cmd.extend(["-netdev", tap_val, "-device", nic_val]) |
1894 |
else:
|
1895 |
nic_val = "nic,vlan=%s,macaddr=%s,model=%s" % (nic_seq,
|
1896 |
nic.mac, nic_model) |
1897 |
tap_val = "tap,vlan=%s,fd=%d" % (nic_seq, tapfd)
|
1898 |
kvm_cmd.extend(["-net", tap_val, "-net", nic_val]) |
1899 |
|
1900 |
if incoming:
|
1901 |
target, port = incoming |
1902 |
kvm_cmd.extend(["-incoming", "tcp:%s:%s" % (target, port)]) |
1903 |
|
1904 |
# Changing the vnc password doesn't bother the guest that much. At most it
|
1905 |
# will surprise people who connect to it. Whether positively or negatively
|
1906 |
# it's debatable.
|
1907 |
vnc_pwd_file = conf_hvp[constants.HV_VNC_PASSWORD_FILE] |
1908 |
vnc_pwd = None
|
1909 |
if vnc_pwd_file:
|
1910 |
try:
|
1911 |
vnc_pwd = utils.ReadOneLineFile(vnc_pwd_file, strict=True)
|
1912 |
except EnvironmentError, err: |
1913 |
raise errors.HypervisorError("Failed to open VNC password file %s: %s" |
1914 |
% (vnc_pwd_file, err)) |
1915 |
|
1916 |
if conf_hvp[constants.HV_KVM_USE_CHROOT]:
|
1917 |
utils.EnsureDirs([(self._InstanceChrootDir(name),
|
1918 |
constants.SECURE_DIR_MODE)]) |
1919 |
|
1920 |
# Automatically enable QMP if version is >= 0.14
|
1921 |
if self._QMP_RE.search(kvmhelp): |
1922 |
logging.debug("Enabling QMP")
|
1923 |
kvm_cmd.extend(["-qmp", "unix:%s,server,nowait" % |
1924 |
self._InstanceQmpMonitor(instance.name)])
|
1925 |
|
1926 |
# Configure the network now for starting instances and bridged interfaces,
|
1927 |
# during FinalizeMigration for incoming instances' routed interfaces
|
1928 |
for nic_seq, nic in enumerate(kvm_nics): |
1929 |
if (incoming and |
1930 |
nic.nicparams[constants.NIC_MODE] != constants.NIC_MODE_BRIDGED): |
1931 |
continue
|
1932 |
self._ConfigureNIC(instance, nic_seq, nic, taps[nic_seq])
|
1933 |
|
1934 |
bdev_opts = self._GenerateKVMBlockDevicesOptions(instance,
|
1935 |
kvm_disks, |
1936 |
kvmhelp, |
1937 |
devlist) |
1938 |
kvm_cmd.extend(bdev_opts) |
1939 |
# CPU affinity requires kvm to start paused, so we set this flag if the
|
1940 |
# instance is not already paused and if we are not going to accept a
|
1941 |
# migrating instance. In the latter case, pausing is not needed.
|
1942 |
start_kvm_paused = not (_KVM_START_PAUSED_FLAG in kvm_cmd) and not incoming |
1943 |
if start_kvm_paused:
|
1944 |
kvm_cmd.extend([_KVM_START_PAUSED_FLAG]) |
1945 |
|
1946 |
# Note: CPU pinning is using up_hvp since changes take effect
|
1947 |
# during instance startup anyway, and to avoid problems when soft
|
1948 |
# rebooting the instance.
|
1949 |
cpu_pinning = False
|
1950 |
if up_hvp.get(constants.HV_CPU_MASK, None): |
1951 |
cpu_pinning = True
|
1952 |
|
1953 |
if security_model == constants.HT_SM_POOL:
|
1954 |
ss = ssconf.SimpleStore() |
1955 |
uid_pool = uidpool.ParseUidPool(ss.GetUidPool(), separator="\n")
|
1956 |
all_uids = set(uidpool.ExpandUidPool(uid_pool))
|
1957 |
uid = uidpool.RequestUnusedUid(all_uids) |
1958 |
try:
|
1959 |
username = pwd.getpwuid(uid.GetUid()).pw_name |
1960 |
kvm_cmd.extend(["-runas", username])
|
1961 |
self._RunKVMCmd(name, kvm_cmd, tapfds)
|
1962 |
except:
|
1963 |
uidpool.ReleaseUid(uid) |
1964 |
raise
|
1965 |
else:
|
1966 |
uid.Unlock() |
1967 |
utils.WriteFile(self._InstanceUidFile(name), data=uid.AsStr())
|
1968 |
else:
|
1969 |
self._RunKVMCmd(name, kvm_cmd, tapfds)
|
1970 |
|
1971 |
utils.EnsureDirs([(self._InstanceNICDir(instance.name),
|
1972 |
constants.RUN_DIRS_MODE)]) |
1973 |
for nic_seq, tap in enumerate(taps): |
1974 |
utils.WriteFile(self._InstanceNICFile(instance.name, nic_seq),
|
1975 |
data=tap) |
1976 |
|
1977 |
if vnc_pwd:
|
1978 |
change_cmd = "change vnc password %s" % vnc_pwd
|
1979 |
self._CallMonitorCommand(instance.name, change_cmd)
|
1980 |
|
1981 |
# Setting SPICE password. We are not vulnerable to malicious passwordless
|
1982 |
# connection attempts because SPICE by default does not allow connections
|
1983 |
# if neither a password nor the "disable_ticketing" options are specified.
|
1984 |
# As soon as we send the password via QMP, that password is a valid ticket
|
1985 |
# for connection.
|
1986 |
spice_password_file = conf_hvp[constants.HV_KVM_SPICE_PASSWORD_FILE] |
1987 |
if spice_password_file:
|
1988 |
spice_pwd = ""
|
1989 |
try:
|
1990 |
spice_pwd = utils.ReadOneLineFile(spice_password_file, strict=True)
|
1991 |
except EnvironmentError, err: |
1992 |
raise errors.HypervisorError("Failed to open SPICE password file %s: %s" |
1993 |
% (spice_password_file, err)) |
1994 |
|
1995 |
qmp = QmpConnection(self._InstanceQmpMonitor(instance.name))
|
1996 |
qmp.connect() |
1997 |
arguments = { |
1998 |
"protocol": "spice", |
1999 |
"password": spice_pwd,
|
2000 |
} |
2001 |
qmp.Execute("set_password", arguments)
|
2002 |
|
2003 |
for filename in temp_files: |
2004 |
utils.RemoveFile(filename) |
2005 |
|
2006 |
# If requested, set CPU affinity and resume instance execution
|
2007 |
if cpu_pinning:
|
2008 |
self._ExecuteCpuAffinity(instance.name, up_hvp[constants.HV_CPU_MASK])
|
2009 |
|
2010 |
start_memory = self._InstanceStartupMemory(instance)
|
2011 |
if start_memory < instance.beparams[constants.BE_MAXMEM]:
|
2012 |
self.BalloonInstanceMemory(instance, start_memory)
|
2013 |
|
2014 |
if start_kvm_paused:
|
2015 |
# To control CPU pinning, ballooning, and vnc/spice passwords
|
2016 |
# the VM was started in a frozen state. If freezing was not
|
2017 |
# explicitly requested resume the vm status.
|
2018 |
self._CallMonitorCommand(instance.name, self._CONT_CMD) |
2019 |
|
2020 |
@staticmethod
|
2021 |
def _StartKvmd(hvparams): |
2022 |
"""Ensure that the Kvm daemon is running.
|
2023 |
|
2024 |
"""
|
2025 |
if hvparams is None \ |
2026 |
or not hvparams[constants.HV_KVM_USER_SHUTDOWN] \ |
2027 |
or utils.IsDaemonAlive(constants.KVMD):
|
2028 |
return
|
2029 |
|
2030 |
result = utils.RunCmd(constants.KVMD) |
2031 |
|
2032 |
if result.failed:
|
2033 |
raise errors.HypervisorError("Failed to start KVM daemon") |
2034 |
|
2035 |
def StartInstance(self, instance, block_devices, startup_paused): |
2036 |
"""Start an instance.
|
2037 |
|
2038 |
"""
|
2039 |
self._CheckDown(instance.name)
|
2040 |
kvmpath = instance.hvparams[constants.HV_KVM_PATH] |
2041 |
kvmhelp = self._GetKVMOutput(kvmpath, self._KVMOPT_HELP) |
2042 |
kvm_runtime = self._GenerateKVMRuntime(instance, block_devices,
|
2043 |
startup_paused, kvmhelp) |
2044 |
self._SaveKVMRuntime(instance, kvm_runtime)
|
2045 |
self._ExecuteKVMRuntime(instance, kvm_runtime, kvmhelp)
|
2046 |
|
2047 |
@classmethod
|
2048 |
def _CallMonitorCommand(cls, instance_name, command): |
2049 |
"""Invoke a command on the instance monitor.
|
2050 |
|
2051 |
"""
|
2052 |
# TODO: Replace monitor calls with QMP once KVM >= 0.14 is the minimum
|
2053 |
# version. The monitor protocol is designed for human consumption, whereas
|
2054 |
# QMP is made for programmatic usage. In the worst case QMP can also
|
2055 |
# execute monitor commands. As it is, all calls to socat take at least
|
2056 |
# 500ms and likely more: socat can't detect the end of the reply and waits
|
2057 |
# for 500ms of no data received before exiting (500 ms is the default for
|
2058 |
# the "-t" parameter).
|
2059 |
socat = ("echo %s | %s STDIO UNIX-CONNECT:%s" %
|
2060 |
(utils.ShellQuote(command), |
2061 |
constants.SOCAT_PATH, |
2062 |
utils.ShellQuote(cls._InstanceMonitor(instance_name)))) |
2063 |
result = utils.RunCmd(socat) |
2064 |
if result.failed:
|
2065 |
msg = ("Failed to send command '%s' to instance '%s', reason '%s',"
|
2066 |
" output: %s" %
|
2067 |
(command, instance_name, result.fail_reason, result.output)) |
2068 |
raise errors.HypervisorError(msg)
|
2069 |
|
2070 |
return result
|
2071 |
|
2072 |
def _GetFreePCISlot(self, instance, dev): |
2073 |
"""Get the first available pci slot of a runnung instance.
|
2074 |
|
2075 |
"""
|
2076 |
slots = bitarray(32)
|
2077 |
slots.setall(False) # pylint: disable=E1101 |
2078 |
output = self._CallMonitorCommand(instance.name, self._INFO_PCI_CMD) |
2079 |
for line in output.stdout.splitlines(): |
2080 |
match = self._INFO_PCI_RE.search(line)
|
2081 |
if match:
|
2082 |
slot = int(match.group(1)) |
2083 |
slots[slot] = True
|
2084 |
|
2085 |
[free] = slots.search(_AVAILABLE_PCI_SLOT, 1) # pylint: disable=E1101 |
2086 |
if not free: |
2087 |
raise errors.HypervisorError("All PCI slots occupied") |
2088 |
|
2089 |
dev.pci = int(free)
|
2090 |
|
2091 |
def VerifyHotplugSupport(self, instance, action, dev_type): |
2092 |
"""Verifies that hotplug is supported.
|
2093 |
|
2094 |
Hotplug is *not* supported in case of:
|
2095 |
- security models and chroot (disk hotplug)
|
2096 |
- fdsend module is missing (nic hot-add)
|
2097 |
|
2098 |
@raise errors.HypervisorError: in one of the previous cases
|
2099 |
|
2100 |
"""
|
2101 |
if dev_type == constants.HOTPLUG_TARGET_DISK:
|
2102 |
hvp = instance.hvparams |
2103 |
security_model = hvp[constants.HV_SECURITY_MODEL] |
2104 |
use_chroot = hvp[constants.HV_KVM_USE_CHROOT] |
2105 |
if use_chroot:
|
2106 |
raise errors.HotplugError("Disk hotplug is not supported" |
2107 |
" in case of chroot.")
|
2108 |
if security_model != constants.HT_SM_NONE:
|
2109 |
raise errors.HotplugError("Disk Hotplug is not supported in case" |
2110 |
" security models are used.")
|
2111 |
|
2112 |
if (dev_type == constants.HOTPLUG_TARGET_NIC and |
2113 |
action == constants.HOTPLUG_ACTION_ADD and not fdsend): |
2114 |
raise errors.HotplugError("Cannot hot-add NIC." |
2115 |
" fdsend python module is missing.")
|
2116 |
|
2117 |
def HotplugSupported(self, instance): |
2118 |
"""Checks if hotplug is generally supported.
|
2119 |
|
2120 |
Hotplug is *not* supported in case of:
|
2121 |
- qemu versions < 1.0
|
2122 |
- for stopped instances
|
2123 |
|
2124 |
@raise errors.HypervisorError: in one of the previous cases
|
2125 |
|
2126 |
"""
|
2127 |
try:
|
2128 |
output = self._CallMonitorCommand(instance.name, self._INFO_VERSION_CMD) |
2129 |
except errors.HypervisorError:
|
2130 |
raise errors.HotplugError("Instance is probably down") |
2131 |
|
2132 |
# TODO: search for netdev_add, drive_add, device_add.....
|
2133 |
match = self._INFO_VERSION_RE.search(output.stdout)
|
2134 |
if not match: |
2135 |
raise errors.HotplugError("Cannot parse qemu version via monitor") |
2136 |
|
2137 |
v_major, v_min, _, _ = match.groups() |
2138 |
if (int(v_major), int(v_min)) < (1, 0): |
2139 |
raise errors.HotplugError("Hotplug not supported for qemu versions < 1.0") |
2140 |
|
2141 |
def _CallHotplugCommand(self, name, cmd): |
2142 |
output = self._CallMonitorCommand(name, cmd)
|
2143 |
# TODO: parse output and check if succeeded
|
2144 |
for line in output.stdout.splitlines(): |
2145 |
logging.info("%s", line)
|
2146 |
|
2147 |
def HotAddDevice(self, instance, dev_type, device, extra, seq): |
2148 |
""" Helper method to hot-add a new device
|
2149 |
|
2150 |
It gets free pci slot generates the device name and invokes the
|
2151 |
device specific method.
|
2152 |
|
2153 |
"""
|
2154 |
# in case of hot-mod this is given
|
2155 |
if device.pci is None: |
2156 |
self._GetFreePCISlot(instance, device)
|
2157 |
kvm_devid = _GenerateDeviceKVMId(dev_type, device) |
2158 |
runtime = self._LoadKVMRuntime(instance)
|
2159 |
if dev_type == constants.HOTPLUG_TARGET_DISK:
|
2160 |
command = "drive_add dummy file=%s,if=none,id=%s,format=raw\n" % \
|
2161 |
(extra, kvm_devid) |
2162 |
command += ("device_add virtio-blk-pci,bus=pci.0,addr=%s,drive=%s,id=%s" %
|
2163 |
(hex(device.pci), kvm_devid, kvm_devid))
|
2164 |
elif dev_type == constants.HOTPLUG_TARGET_NIC:
|
2165 |
(tap, fd) = _OpenTap() |
2166 |
self._ConfigureNIC(instance, seq, device, tap)
|
2167 |
self._PassTapFd(instance, fd, device)
|
2168 |
command = "netdev_add tap,id=%s,fd=%s\n" % (kvm_devid, kvm_devid)
|
2169 |
args = "virtio-net-pci,bus=pci.0,addr=%s,mac=%s,netdev=%s,id=%s" % \
|
2170 |
(hex(device.pci), device.mac, kvm_devid, kvm_devid)
|
2171 |
command += "device_add %s" % args
|
2172 |
utils.WriteFile(self._InstanceNICFile(instance.name, seq), data=tap)
|
2173 |
|
2174 |
self._CallHotplugCommand(instance.name, command)
|
2175 |
# update relevant entries in runtime file
|
2176 |
index = _DEVICE_RUNTIME_INDEX[dev_type] |
2177 |
entry = _RUNTIME_ENTRY[dev_type](device, extra) |
2178 |
runtime[index].append(entry) |
2179 |
self._SaveKVMRuntime(instance, runtime)
|
2180 |
|
2181 |
def HotDelDevice(self, instance, dev_type, device, _, seq): |
2182 |
""" Helper method for hot-del device
|
2183 |
|
2184 |
It gets device info from runtime file, generates the device name and
|
2185 |
invokes the device specific method.
|
2186 |
|
2187 |
"""
|
2188 |
runtime = self._LoadKVMRuntime(instance)
|
2189 |
entry = _GetExistingDeviceInfo(dev_type, device, runtime) |
2190 |
kvm_device = _RUNTIME_DEVICE[dev_type](entry) |
2191 |
kvm_devid = _GenerateDeviceKVMId(dev_type, kvm_device) |
2192 |
if dev_type == constants.HOTPLUG_TARGET_DISK:
|
2193 |
command = "device_del %s\n" % kvm_devid
|
2194 |
command += "drive_del %s" % kvm_devid
|
2195 |
elif dev_type == constants.HOTPLUG_TARGET_NIC:
|
2196 |
command = "device_del %s\n" % kvm_devid
|
2197 |
command += "netdev_del %s" % kvm_devid
|
2198 |
utils.RemoveFile(self._InstanceNICFile(instance.name, seq))
|
2199 |
self._CallHotplugCommand(instance.name, command)
|
2200 |
index = _DEVICE_RUNTIME_INDEX[dev_type] |
2201 |
runtime[index].remove(entry) |
2202 |
self._SaveKVMRuntime(instance, runtime)
|
2203 |
|
2204 |
return kvm_device.pci
|
2205 |
|
2206 |
def HotModDevice(self, instance, dev_type, device, _, seq): |
2207 |
""" Helper method for hot-mod device
|
2208 |
|
2209 |
It gets device info from runtime file, generates the device name and
|
2210 |
invokes the device specific method. Currently only NICs support hot-mod
|
2211 |
|
2212 |
"""
|
2213 |
if dev_type == constants.HOTPLUG_TARGET_NIC:
|
2214 |
# putting it back in the same pci slot
|
2215 |
device.pci = self.HotDelDevice(instance, dev_type, device, _, seq)
|
2216 |
# TODO: remove sleep when socat gets removed
|
2217 |
time.sleep(2)
|
2218 |
self.HotAddDevice(instance, dev_type, device, _, seq)
|
2219 |
|
2220 |
def _PassTapFd(self, instance, fd, nic): |
2221 |
"""Pass file descriptor to kvm process via monitor socket using SCM_RIGHTS
|
2222 |
|
2223 |
"""
|
2224 |
# TODO: factor out code related to unix sockets.
|
2225 |
# squash common parts between monitor and qmp
|
2226 |
kvm_devid = _GenerateDeviceKVMId(constants.HOTPLUG_TARGET_NIC, nic) |
2227 |
command = "getfd %s\n" % kvm_devid
|
2228 |
fds = [fd] |
2229 |
logging.info("%s", fds)
|
2230 |
try:
|
2231 |
monsock = MonitorSocket(self._InstanceMonitor(instance.name))
|
2232 |
monsock.connect() |
2233 |
fdsend.sendfds(monsock.sock, command, fds=fds) |
2234 |
finally:
|
2235 |
monsock.close() |
2236 |
|
2237 |
@classmethod
|
2238 |
def _ParseKVMVersion(cls, text): |
2239 |
"""Parse the KVM version from the --help output.
|
2240 |
|
2241 |
@type text: string
|
2242 |
@param text: output of kvm --help
|
2243 |
@return: (version, v_maj, v_min, v_rev)
|
2244 |
@raise errors.HypervisorError: when the KVM version cannot be retrieved
|
2245 |
|
2246 |
"""
|
2247 |
match = cls._VERSION_RE.search(text.splitlines()[0])
|
2248 |
if not match: |
2249 |
raise errors.HypervisorError("Unable to get KVM version") |
2250 |
|
2251 |
v_all = match.group(0)
|
2252 |
v_maj = int(match.group(1)) |
2253 |
v_min = int(match.group(2)) |
2254 |
if match.group(4): |
2255 |
v_rev = int(match.group(4)) |
2256 |
else:
|
2257 |
v_rev = 0
|
2258 |
return (v_all, v_maj, v_min, v_rev)
|
2259 |
|
2260 |
@classmethod
|
2261 |
def _GetKVMOutput(cls, kvm_path, option): |
2262 |
"""Return the output of a kvm invocation
|
2263 |
|
2264 |
@type kvm_path: string
|
2265 |
@param kvm_path: path to the kvm executable
|
2266 |
@type option: a key of _KVMOPTS_CMDS
|
2267 |
@param option: kvm option to fetch the output from
|
2268 |
@return: output a supported kvm invocation
|
2269 |
@raise errors.HypervisorError: when the KVM help output cannot be retrieved
|
2270 |
|
2271 |
"""
|
2272 |
assert option in cls._KVMOPTS_CMDS, "Invalid output option" |
2273 |
|
2274 |
optlist, can_fail = cls._KVMOPTS_CMDS[option] |
2275 |
|
2276 |
result = utils.RunCmd([kvm_path] + optlist) |
2277 |
if result.failed and not can_fail: |
2278 |
raise errors.HypervisorError("Unable to get KVM %s output" % |
2279 |
" ".join(optlist))
|
2280 |
return result.output
|
2281 |
|
2282 |
@classmethod
|
2283 |
def _GetKVMVersion(cls, kvm_path): |
2284 |
"""Return the installed KVM version.
|
2285 |
|
2286 |
@return: (version, v_maj, v_min, v_rev)
|
2287 |
@raise errors.HypervisorError: when the KVM version cannot be retrieved
|
2288 |
|
2289 |
"""
|
2290 |
return cls._ParseKVMVersion(cls._GetKVMOutput(kvm_path, cls._KVMOPT_HELP))
|
2291 |
|
2292 |
@classmethod
|
2293 |
def _GetDefaultMachineVersion(cls, kvm_path): |
2294 |
"""Return the default hardware revision (e.g. pc-1.1)
|
2295 |
|
2296 |
"""
|
2297 |
output = cls._GetKVMOutput(kvm_path, cls._KVMOPT_MLIST) |
2298 |
match = cls._DEFAULT_MACHINE_VERSION_RE.search(output) |
2299 |
if match:
|
2300 |
return match.group(1) |
2301 |
else:
|
2302 |
return "pc" |
2303 |
|
2304 |
@classmethod
|
2305 |
def _StopInstance(cls, instance, force=False, name=None): |
2306 |
"""Stop an instance.
|
2307 |
|
2308 |
"""
|
2309 |
if name is not None and not force: |
2310 |
raise errors.HypervisorError("Cannot shutdown cleanly by name only") |
2311 |
if name is None: |
2312 |
name = instance.name |
2313 |
acpi = instance.hvparams[constants.HV_ACPI] |
2314 |
else:
|
2315 |
acpi = False
|
2316 |
_, pid, alive = cls._InstancePidAlive(name) |
2317 |
if pid > 0 and alive: |
2318 |
if force or not acpi: |
2319 |
utils.KillProcess(pid) |
2320 |
else:
|
2321 |
cls._CallMonitorCommand(name, "system_powerdown")
|
2322 |
cls._ClearUserShutdown(instance.name) |
2323 |
|
2324 |
def StopInstance(self, instance, force=False, retry=False, name=None): |
2325 |
"""Stop an instance.
|
2326 |
|
2327 |
"""
|
2328 |
self._StopInstance(instance, force, name)
|
2329 |
|
2330 |
def CleanupInstance(self, instance_name): |
2331 |
"""Cleanup after a stopped instance
|
2332 |
|
2333 |
"""
|
2334 |
pidfile, pid, alive = self._InstancePidAlive(instance_name)
|
2335 |
if pid > 0 and alive: |
2336 |
raise errors.HypervisorError("Cannot cleanup a live instance") |
2337 |
self._RemoveInstanceRuntimeFiles(pidfile, instance_name)
|
2338 |
self._ClearUserShutdown(instance_name)
|
2339 |
|
2340 |
def RebootInstance(self, instance): |
2341 |
"""Reboot an instance.
|
2342 |
|
2343 |
"""
|
2344 |
# For some reason if we do a 'send-key ctrl-alt-delete' to the control
|
2345 |
# socket the instance will stop, but now power up again. So we'll resort
|
2346 |
# to shutdown and restart.
|
2347 |
_, _, alive = self._InstancePidAlive(instance.name)
|
2348 |
if not alive: |
2349 |
raise errors.HypervisorError("Failed to reboot instance %s:" |
2350 |
" not running" % instance.name)
|
2351 |
# StopInstance will delete the saved KVM runtime so:
|
2352 |
# ...first load it...
|
2353 |
kvm_runtime = self._LoadKVMRuntime(instance)
|
2354 |
# ...now we can safely call StopInstance...
|
2355 |
if not self.StopInstance(instance): |
2356 |
self.StopInstance(instance, force=True) |
2357 |
# ...and finally we can save it again, and execute it...
|
2358 |
self._SaveKVMRuntime(instance, kvm_runtime)
|
2359 |
kvmpath = instance.hvparams[constants.HV_KVM_PATH] |
2360 |
kvmhelp = self._GetKVMOutput(kvmpath, self._KVMOPT_HELP) |
2361 |
self._ExecuteKVMRuntime(instance, kvm_runtime, kvmhelp)
|
2362 |
|
2363 |
def MigrationInfo(self, instance): |
2364 |
"""Get instance information to perform a migration.
|
2365 |
|
2366 |
@type instance: L{objects.Instance}
|
2367 |
@param instance: instance to be migrated
|
2368 |
@rtype: string
|
2369 |
@return: content of the KVM runtime file
|
2370 |
|
2371 |
"""
|
2372 |
return self._ReadKVMRuntime(instance.name) |
2373 |
|
2374 |
def AcceptInstance(self, instance, info, target): |
2375 |
"""Prepare to accept an instance.
|
2376 |
|
2377 |
@type instance: L{objects.Instance}
|
2378 |
@param instance: instance to be accepted
|
2379 |
@type info: string
|
2380 |
@param info: content of the KVM runtime file on the source node
|
2381 |
@type target: string
|
2382 |
@param target: target host (usually ip), on this node
|
2383 |
|
2384 |
"""
|
2385 |
kvm_runtime = self._LoadKVMRuntime(instance, serialized_runtime=info)
|
2386 |
incoming_address = (target, instance.hvparams[constants.HV_MIGRATION_PORT]) |
2387 |
kvmpath = instance.hvparams[constants.HV_KVM_PATH] |
2388 |
kvmhelp = self._GetKVMOutput(kvmpath, self._KVMOPT_HELP) |
2389 |
self._ExecuteKVMRuntime(instance, kvm_runtime, kvmhelp,
|
2390 |
incoming=incoming_address) |
2391 |
|
2392 |
def FinalizeMigrationDst(self, instance, info, success): |
2393 |
"""Finalize the instance migration on the target node.
|
2394 |
|
2395 |
Stop the incoming mode KVM.
|
2396 |
|
2397 |
@type instance: L{objects.Instance}
|
2398 |
@param instance: instance whose migration is being finalized
|
2399 |
|
2400 |
"""
|
2401 |
if success:
|
2402 |
kvm_runtime = self._LoadKVMRuntime(instance, serialized_runtime=info)
|
2403 |
kvm_nics = kvm_runtime[1]
|
2404 |
|
2405 |
for nic_seq, nic in enumerate(kvm_nics): |
2406 |
if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
|
2407 |
# Bridged interfaces have already been configured
|
2408 |
continue
|
2409 |
try:
|
2410 |
tap = utils.ReadFile(self._InstanceNICFile(instance.name, nic_seq))
|
2411 |
except EnvironmentError, err: |
2412 |
logging.warning("Failed to find host interface for %s NIC #%d: %s",
|
2413 |
instance.name, nic_seq, str(err))
|
2414 |
continue
|
2415 |
try:
|
2416 |
self._ConfigureNIC(instance, nic_seq, nic, tap)
|
2417 |
except errors.HypervisorError, err:
|
2418 |
logging.warning(str(err))
|
2419 |
|
2420 |
self._WriteKVMRuntime(instance.name, info)
|
2421 |
else:
|
2422 |
self.StopInstance(instance, force=True) |
2423 |
|
2424 |
def MigrateInstance(self, cluster_name, instance, target, live): |
2425 |
"""Migrate an instance to a target node.
|
2426 |
|
2427 |
The migration will not be attempted if the instance is not
|
2428 |
currently running.
|
2429 |
|
2430 |
@type cluster_name: string
|
2431 |
@param cluster_name: name of the cluster
|
2432 |
@type instance: L{objects.Instance}
|
2433 |
@param instance: the instance to be migrated
|
2434 |
@type target: string
|
2435 |
@param target: ip address of the target node
|
2436 |
@type live: boolean
|
2437 |
@param live: perform a live migration
|
2438 |
|
2439 |
"""
|
2440 |
instance_name = instance.name |
2441 |
port = instance.hvparams[constants.HV_MIGRATION_PORT] |
2442 |
_, _, alive = self._InstancePidAlive(instance_name)
|
2443 |
if not alive: |
2444 |
raise errors.HypervisorError("Instance not running, cannot migrate") |
2445 |
|
2446 |
if not live: |
2447 |
self._CallMonitorCommand(instance_name, "stop") |
2448 |
|
2449 |
migrate_command = ("migrate_set_speed %dm" %
|
2450 |
instance.hvparams[constants.HV_MIGRATION_BANDWIDTH]) |
2451 |
self._CallMonitorCommand(instance_name, migrate_command)
|
2452 |
|
2453 |
migrate_command = ("migrate_set_downtime %dms" %
|
2454 |
instance.hvparams[constants.HV_MIGRATION_DOWNTIME]) |
2455 |
self._CallMonitorCommand(instance_name, migrate_command)
|
2456 |
|
2457 |
migrate_command = "migrate -d tcp:%s:%s" % (target, port)
|
2458 |
self._CallMonitorCommand(instance_name, migrate_command)
|
2459 |
|
2460 |
def FinalizeMigrationSource(self, instance, success, live): |
2461 |
"""Finalize the instance migration on the source node.
|
2462 |
|
2463 |
@type instance: L{objects.Instance}
|
2464 |
@param instance: the instance that was migrated
|
2465 |
@type success: bool
|
2466 |
@param success: whether the migration succeeded or not
|
2467 |
@type live: bool
|
2468 |
@param live: whether the user requested a live migration or not
|
2469 |
|
2470 |
"""
|
2471 |
if success:
|
2472 |
pidfile, pid, _ = self._InstancePidAlive(instance.name)
|
2473 |
utils.KillProcess(pid) |
2474 |
self._RemoveInstanceRuntimeFiles(pidfile, instance.name)
|
2475 |
elif live:
|
2476 |
self._CallMonitorCommand(instance.name, self._CONT_CMD) |
2477 |
self._ClearUserShutdown(instance.name)
|
2478 |
|
2479 |
def GetMigrationStatus(self, instance): |
2480 |
"""Get the migration status
|
2481 |
|
2482 |
@type instance: L{objects.Instance}
|
2483 |
@param instance: the instance that is being migrated
|
2484 |
@rtype: L{objects.MigrationStatus}
|
2485 |
@return: the status of the current migration (one of
|
2486 |
L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
|
2487 |
progress info that can be retrieved from the hypervisor
|
2488 |
|
2489 |
"""
|
2490 |
info_command = "info migrate"
|
2491 |
for _ in range(self._MIGRATION_INFO_MAX_BAD_ANSWERS): |
2492 |
result = self._CallMonitorCommand(instance.name, info_command)
|
2493 |
match = self._MIGRATION_STATUS_RE.search(result.stdout)
|
2494 |
if not match: |
2495 |
if not result.stdout: |
2496 |
logging.info("KVM: empty 'info migrate' result")
|
2497 |
else:
|
2498 |
logging.warning("KVM: unknown 'info migrate' result: %s",
|
2499 |
result.stdout) |
2500 |
else:
|
2501 |
status = match.group(1)
|
2502 |
if status in constants.HV_KVM_MIGRATION_VALID_STATUSES: |
2503 |
migration_status = objects.MigrationStatus(status=status) |
2504 |
match = self._MIGRATION_PROGRESS_RE.search(result.stdout)
|
2505 |
if match:
|
2506 |
migration_status.transferred_ram = match.group("transferred")
|
2507 |
migration_status.total_ram = match.group("total")
|
2508 |
|
2509 |
return migration_status
|
2510 |
|
2511 |
logging.warning("KVM: unknown migration status '%s'", status)
|
2512 |
|
2513 |
time.sleep(self._MIGRATION_INFO_RETRY_DELAY)
|
2514 |
|
2515 |
return objects.MigrationStatus(status=constants.HV_MIGRATION_FAILED)
|
2516 |
|
2517 |
def BalloonInstanceMemory(self, instance, mem): |
2518 |
"""Balloon an instance memory to a certain value.
|
2519 |
|
2520 |
@type instance: L{objects.Instance}
|
2521 |
@param instance: instance to be accepted
|
2522 |
@type mem: int
|
2523 |
@param mem: actual memory size to use for instance runtime
|
2524 |
|
2525 |
"""
|
2526 |
self._CallMonitorCommand(instance.name, "balloon %d" % mem) |
2527 |
|
2528 |
def GetNodeInfo(self, hvparams=None): |
2529 |
"""Return information about the node.
|
2530 |
|
2531 |
@type hvparams: dict of strings
|
2532 |
@param hvparams: hypervisor parameters, not used in this class
|
2533 |
|
2534 |
@return: a dict as returned by L{BaseHypervisor.GetLinuxNodeInfo} plus
|
2535 |
the following keys:
|
2536 |
- hv_version: the hypervisor version in the form (major, minor,
|
2537 |
revision)
|
2538 |
|
2539 |
"""
|
2540 |
result = self.GetLinuxNodeInfo()
|
2541 |
kvmpath = constants.KVM_PATH |
2542 |
if hvparams is not None: |
2543 |
kvmpath = hvparams.get(constants.HV_KVM_PATH, constants.KVM_PATH) |
2544 |
_, v_major, v_min, v_rev = self._GetKVMVersion(kvmpath)
|
2545 |
result[constants.HV_NODEINFO_KEY_VERSION] = (v_major, v_min, v_rev) |
2546 |
return result
|
2547 |
|
2548 |
@classmethod
|
2549 |
def GetInstanceConsole(cls, instance, primary_node, node_group, |
2550 |
hvparams, beparams): |
2551 |
"""Return a command for connecting to the console of an instance.
|
2552 |
|
2553 |
"""
|
2554 |
if hvparams[constants.HV_SERIAL_CONSOLE]:
|
2555 |
cmd = [pathutils.KVM_CONSOLE_WRAPPER, |
2556 |
constants.SOCAT_PATH, utils.ShellQuote(instance.name), |
2557 |
utils.ShellQuote(cls._InstanceMonitor(instance.name)), |
2558 |
"STDIO,%s" % cls._SocatUnixConsoleParams(),
|
2559 |
"UNIX-CONNECT:%s" % cls._InstanceSerial(instance.name)]
|
2560 |
ndparams = node_group.FillND(primary_node) |
2561 |
return objects.InstanceConsole(instance=instance.name,
|
2562 |
kind=constants.CONS_SSH, |
2563 |
host=primary_node.name, |
2564 |
port=ndparams.get(constants.ND_SSH_PORT), |
2565 |
user=constants.SSH_CONSOLE_USER, |
2566 |
command=cmd) |
2567 |
|
2568 |
vnc_bind_address = hvparams[constants.HV_VNC_BIND_ADDRESS] |
2569 |
if vnc_bind_address and instance.network_port > constants.VNC_BASE_PORT: |
2570 |
display = instance.network_port - constants.VNC_BASE_PORT |
2571 |
return objects.InstanceConsole(instance=instance.name,
|
2572 |
kind=constants.CONS_VNC, |
2573 |
host=vnc_bind_address, |
2574 |
port=instance.network_port, |
2575 |
display=display) |
2576 |
|
2577 |
spice_bind = hvparams[constants.HV_KVM_SPICE_BIND] |
2578 |
if spice_bind:
|
2579 |
return objects.InstanceConsole(instance=instance.name,
|
2580 |
kind=constants.CONS_SPICE, |
2581 |
host=spice_bind, |
2582 |
port=instance.network_port) |
2583 |
|
2584 |
return objects.InstanceConsole(instance=instance.name,
|
2585 |
kind=constants.CONS_MESSAGE, |
2586 |
message=("No serial shell for instance %s" %
|
2587 |
instance.name)) |
2588 |
|
2589 |
def Verify(self, hvparams=None): |
2590 |
"""Verify the hypervisor.
|
2591 |
|
2592 |
Check that the required binaries exist.
|
2593 |
|
2594 |
@type hvparams: dict of strings
|
2595 |
@param hvparams: hypervisor parameters to be verified against, not used here
|
2596 |
|
2597 |
@return: Problem description if something is wrong, C{None} otherwise
|
2598 |
|
2599 |
"""
|
2600 |
msgs = [] |
2601 |
kvmpath = constants.KVM_PATH |
2602 |
if hvparams is not None: |
2603 |
kvmpath = hvparams.get(constants.HV_KVM_PATH, constants.KVM_PATH) |
2604 |
if not os.path.exists(kvmpath): |
2605 |
msgs.append("The KVM binary ('%s') does not exist" % kvmpath)
|
2606 |
if not os.path.exists(constants.SOCAT_PATH): |
2607 |
msgs.append("The socat binary ('%s') does not exist" %
|
2608 |
constants.SOCAT_PATH) |
2609 |
|
2610 |
return self._FormatVerifyResults(msgs) |
2611 |
|
2612 |
@classmethod
|
2613 |
def CheckParameterSyntax(cls, hvparams): |
2614 |
"""Check the given parameters for validity.
|
2615 |
|
2616 |
@type hvparams: dict
|
2617 |
@param hvparams: dictionary with parameter names/value
|
2618 |
@raise errors.HypervisorError: when a parameter is not valid
|
2619 |
|
2620 |
"""
|
2621 |
super(KVMHypervisor, cls).CheckParameterSyntax(hvparams)
|
2622 |
|
2623 |
kernel_path = hvparams[constants.HV_KERNEL_PATH] |
2624 |
if kernel_path:
|
2625 |
if not hvparams[constants.HV_ROOT_PATH]: |
2626 |
raise errors.HypervisorError("Need a root partition for the instance," |
2627 |
" if a kernel is defined")
|
2628 |
|
2629 |
if (hvparams[constants.HV_VNC_X509_VERIFY] and |
2630 |
not hvparams[constants.HV_VNC_X509]):
|
2631 |
raise errors.HypervisorError("%s must be defined, if %s is" % |
2632 |
(constants.HV_VNC_X509, |
2633 |
constants.HV_VNC_X509_VERIFY)) |
2634 |
|
2635 |
if hvparams[constants.HV_SERIAL_CONSOLE]:
|
2636 |
serial_speed = hvparams[constants.HV_SERIAL_SPEED] |
2637 |
valid_speeds = constants.VALID_SERIAL_SPEEDS |
2638 |
if not serial_speed or serial_speed not in valid_speeds: |
2639 |
raise errors.HypervisorError("Invalid serial console speed, must be" |
2640 |
" one of: %s" %
|
2641 |
utils.CommaJoin(valid_speeds)) |
2642 |
|
2643 |
boot_order = hvparams[constants.HV_BOOT_ORDER] |
2644 |
if (boot_order == constants.HT_BO_CDROM and |
2645 |
not hvparams[constants.HV_CDROM_IMAGE_PATH]):
|
2646 |
raise errors.HypervisorError("Cannot boot from cdrom without an" |
2647 |
" ISO path")
|
2648 |
|
2649 |
security_model = hvparams[constants.HV_SECURITY_MODEL] |
2650 |
if security_model == constants.HT_SM_USER:
|
2651 |
if not hvparams[constants.HV_SECURITY_DOMAIN]: |
2652 |
raise errors.HypervisorError("A security domain (user to run kvm as)" |
2653 |
" must be specified")
|
2654 |
elif (security_model == constants.HT_SM_NONE or |
2655 |
security_model == constants.HT_SM_POOL): |
2656 |
if hvparams[constants.HV_SECURITY_DOMAIN]:
|
2657 |
raise errors.HypervisorError("Cannot have a security domain when the" |
2658 |
" security model is 'none' or 'pool'")
|
2659 |
|
2660 |
spice_bind = hvparams[constants.HV_KVM_SPICE_BIND] |
2661 |
spice_ip_version = hvparams[constants.HV_KVM_SPICE_IP_VERSION] |
2662 |
if spice_bind:
|
2663 |
if spice_ip_version != constants.IFACE_NO_IP_VERSION_SPECIFIED:
|
2664 |
# if an IP version is specified, the spice_bind parameter must be an
|
2665 |
# IP of that family
|
2666 |
if (netutils.IP4Address.IsValid(spice_bind) and |
2667 |
spice_ip_version != constants.IP4_VERSION): |
2668 |
raise errors.HypervisorError("SPICE: Got an IPv4 address (%s), but" |
2669 |
" the specified IP version is %s" %
|
2670 |
(spice_bind, spice_ip_version)) |
2671 |
|
2672 |
if (netutils.IP6Address.IsValid(spice_bind) and |
2673 |
spice_ip_version != constants.IP6_VERSION): |
2674 |
raise errors.HypervisorError("SPICE: Got an IPv6 address (%s), but" |
2675 |
" the specified IP version is %s" %
|
2676 |
(spice_bind, spice_ip_version)) |
2677 |
else:
|
2678 |
# All the other SPICE parameters depend on spice_bind being set. Raise an
|
2679 |
# error if any of them is set without it.
|
2680 |
for param in _SPICE_ADDITIONAL_PARAMS: |
2681 |
if hvparams[param]:
|
2682 |
raise errors.HypervisorError("SPICE: %s requires %s to be set" % |
2683 |
(param, constants.HV_KVM_SPICE_BIND)) |
2684 |
|
2685 |
@classmethod
|
2686 |
def ValidateParameters(cls, hvparams): |
2687 |
"""Check the given parameters for validity.
|
2688 |
|
2689 |
@type hvparams: dict
|
2690 |
@param hvparams: dictionary with parameter names/value
|
2691 |
@raise errors.HypervisorError: when a parameter is not valid
|
2692 |
|
2693 |
"""
|
2694 |
super(KVMHypervisor, cls).ValidateParameters(hvparams)
|
2695 |
|
2696 |
kvm_path = hvparams[constants.HV_KVM_PATH] |
2697 |
|
2698 |
security_model = hvparams[constants.HV_SECURITY_MODEL] |
2699 |
if security_model == constants.HT_SM_USER:
|
2700 |
username = hvparams[constants.HV_SECURITY_DOMAIN] |
2701 |
try:
|
2702 |
pwd.getpwnam(username) |
2703 |
except KeyError: |
2704 |
raise errors.HypervisorError("Unknown security domain user %s" |
2705 |
% username) |
2706 |
vnc_bind_address = hvparams[constants.HV_VNC_BIND_ADDRESS] |
2707 |
if vnc_bind_address:
|
2708 |
bound_to_addr = netutils.IP4Address.IsValid(vnc_bind_address) |
2709 |
is_interface = netutils.IsValidInterface(vnc_bind_address) |
2710 |
is_path = utils.IsNormAbsPath(vnc_bind_address) |
2711 |
if not bound_to_addr and not is_interface and not is_path: |
2712 |
raise errors.HypervisorError("VNC: The %s parameter must be either" |
2713 |
" a valid IP address, an interface name,"
|
2714 |
" or an absolute path" %
|
2715 |
constants.HV_KVM_SPICE_BIND) |
2716 |
|
2717 |
spice_bind = hvparams[constants.HV_KVM_SPICE_BIND] |
2718 |
if spice_bind:
|
2719 |
# only one of VNC and SPICE can be used currently.
|
2720 |
if hvparams[constants.HV_VNC_BIND_ADDRESS]:
|
2721 |
raise errors.HypervisorError("Both SPICE and VNC are configured, but" |
2722 |
" only one of them can be used at a"
|
2723 |
" given time")
|
2724 |
|
2725 |
# check that KVM supports SPICE
|
2726 |
kvmhelp = cls._GetKVMOutput(kvm_path, cls._KVMOPT_HELP) |
2727 |
if not cls._SPICE_RE.search(kvmhelp): |
2728 |
raise errors.HypervisorError("SPICE is configured, but it is not" |
2729 |
" supported according to 'kvm --help'")
|
2730 |
|
2731 |
# if spice_bind is not an IP address, it must be a valid interface
|
2732 |
bound_to_addr = (netutils.IP4Address.IsValid(spice_bind) or
|
2733 |
netutils.IP6Address.IsValid(spice_bind)) |
2734 |
if not bound_to_addr and not netutils.IsValidInterface(spice_bind): |
2735 |
raise errors.HypervisorError("SPICE: The %s parameter must be either" |
2736 |
" a valid IP address or interface name" %
|
2737 |
constants.HV_KVM_SPICE_BIND) |
2738 |
|
2739 |
machine_version = hvparams[constants.HV_KVM_MACHINE_VERSION] |
2740 |
if machine_version:
|
2741 |
output = cls._GetKVMOutput(kvm_path, cls._KVMOPT_MLIST) |
2742 |
if not cls._CHECK_MACHINE_VERSION_RE(machine_version).search(output): |
2743 |
raise errors.HypervisorError("Unsupported machine version: %s" % |
2744 |
machine_version) |
2745 |
|
2746 |
@classmethod
|
2747 |
def PowercycleNode(cls, hvparams=None): |
2748 |
"""KVM powercycle, just a wrapper over Linux powercycle.
|
2749 |
|
2750 |
@type hvparams: dict of strings
|
2751 |
@param hvparams: hypervisor params to be used on this node
|
2752 |
|
2753 |
"""
|
2754 |
cls.LinuxPowercycle() |