Newer
Older
# This file is part of CloudControl.
#
# CloudControl is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CloudControl is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with CloudControl. If not, see <http://www.gnu.org/licenses/>.
from StringIO import StringIO
from xml.etree import cElementTree as et
from itertools import izip, count
from functools import partial
from cloudcontrol.common.client.tags import Tag, tag_inspector, TagDB
from cloudcontrol.node.hypervisor.lib import DOMAIN_STATES as STATE, BoundVolumeProxy
from cloudcontrol.node.hypervisor.domains import vm_tags
from cloudcontrol.node.exc import ConsoleAlreadyOpened, ConsoleError
REGEX_TAG_NAME = '[a-zA-Z0-9_-]+'
REGEX_TAG_VALUE = '.+'
REGEX_TAG_IN_DESCRIPTION = '^@(' + REGEX_TAG_NAME + ')[ ]*?=[ ]*?(' + REGEX_TAG_VALUE + ')$'
REGEX_TAG_REPLACE = '^@%s[ ]*?=[ ]*?(' + REGEX_TAG_VALUE + ')$'
class NetworkInterface(object):
def __init__(self, source=None, mac=None, model=None, untagged_vlan=None, tagged_vlans=None):
self.source = source
self.mac = mac
self.model = model
self.untagged_vlan = untagged_vlan
self.tagged_vlans = set() if tagged_vlans is None else set(tagged_vlans)
@property
def vlans(self):
if self.untagged_vlan is not None:
yield self.untagged_vlan
for vlan in self.tagged_vlans:
yield vlan
class VirtualMachine(object):
"""Represent a VM instance."""
#: buffer size for console connection handling
BUFFER_LEN = 1024
"""
:param dom: libvirt domain instance
self.hypervisor = weakref.proxy(hypervisor)
#: UUID string of domain
self.uuid = dom.UUIDString()
#: state of VM: started, stoped, paused
self.tag_db = TagDB(tags=tag_inspector(vm_tags, self))
#: Driver cache behavior for each VM storage, see
#: http://libvirt.org/formatdomain.html#elementsDisks
self.cache_behaviour = dict()
for i, v in izip(count(), self.iter_disks()):
Tag('disk%s_size' % i, v.capacity, 10),
Tag('disk%s_path' % i, v.path, 10),
Tag('disk%s_pool' % i, v.storage.name, 10), # FIXME: change
Tag('disk%s_cache' % i, partial(lambda x: self.cache_behaviour.get(x.path), v), 10),
Tag('disk%s_shared' % i, partial(lambda x: {True: 'yes', False: 'no'}[x.storage.is_shared], v)),
Tag('disk%s_dev' % i, v.device, 10),
Tag('disk%s_bus' % i, v.bus, 10)
for i, nic in izip(count(), self.iter_nics()):
Tag('nic%s_mac' % i, nic.mac),
Tag('nic%s_source' % i, nic.source),
Tag('nic%s_model' % i, nic.model),
Tag('nic%s_untagged_vlan' % i, nic.untagged_vlan),
Tag('nic%s_tagged_vlans' % i, ' '.join(str(x) for x in nic.tagged_vlans)),
Tag('nic%s_vlans' % i, ' '.join(str(x) for x in nic.vlans)),
#: keep record of CPU stats (libev timestamp, cpu time)
self.cpu_stats = (hypervisor.handler.main.evloop.now(), dom.info()[4])
# attributes related to console handling
self.stream = None
self.sock = None # socketpair endpoint
self.read_watcher = None # ev watcher for sock
self.write_watcher = None # ev watcher for sock
self.from_tunnel = None # buffer
self.from_stream = None # buffer
self.stream_handling = 0 # libvirt stream event mask
self.redefine_on_stop = False # for XML update (see KVM class)
self._description_tags_db = TagDB(parent_db=self.tag_db)
self.sync_description_tags()
@property
def state(self):
return self._state
@state.setter
def state(self, value):
self._state = value
self.tag_db['__main__']['status'].update_value()
self.tag_db['__main__']['vncport'].update_value()
@property
def title(self):
try:
return self.lv_dom.metadata(libvirt.VIR_DOMAIN_METADATA_TITLE, None)
except (libvirt.libvirtError, AttributeError):
# libvirtError handle the case where the title is not defined on the
# vm, AttributeError handle the case where the libvirt is too old
# to allow metadata handling
return None
@title.setter
def title(self, value):
try:
self.lv_dom.setMetadata(libvirt.VIR_DOMAIN_METADATA_TITLE, value,
None, None, (libvirt.VIR_DOMAIN_AFFECT_LIVE |
libvirt.VIR_DOMAIN_AFFECT_CONFIG))
except AttributeError:
raise NotImplementedError('This hv doesn\'t handle VM titles')
else:
self.tag_db['__main__']['t'].update_value()
xml = self.lv_dom.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
descriptions = et.ElementTree().parse(StringIO(xml)).findall('description')
if descriptions:
return descriptions[0].text
else:
return ''
@description.setter
def description(self, value):
try:
xml = self.lv_dom.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
except libvirt.libvirtError:
logger.exception('Error while getting domain XML from libvirt, %s',
self.name)
raise
xml_tree = et.ElementTree()
if desc is None:
desc = et.SubElement(root, 'description')
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
desc.text = value
# write back the XML tree
out = StringIO()
xml_tree.write(out)
try:
self.hypervisor.vir_con.defineXML(out.getvalue())
except libvirt.libvirtError:
logger.exception('Cannot update XML file for domain %s', self.name)
raise
@property
def tags(self):
return dict(re.findall(REGEX_TAG_IN_DESCRIPTION, self.description, re.MULTILINE))
def set_tag(self, tag, value):
if not re.match(REGEX_TAG_NAME + '$', tag):
raise RuntimeError('Bad tag name')
elif not re.match(REGEX_TAG_VALUE + '$', value):
raise RuntimeError('Bad tag value')
tags = self.tags
if tag in tags:
self.description = re.sub(REGEX_TAG_REPLACE % re.escape(tag),
'@%s=%s' % (tag, value),
self.description,
flags=re.MULTILINE)
else:
self.description += '\n@%s=%s' % (tag, value)
def delete_tag(self, tag):
tags = self.tags
if tag in tags:
self.description = re.sub(REGEX_TAG_REPLACE % tag,
'',
self.description,
flags=re.MULTILINE)
@property
def lv_dom(self):
"""Libvirt domain instance."""
return self.hypervisor.vir_con.lookupByUUIDString(self.uuid)
Anael Beutot
committed
def start(self, pause=False):
flags = 0
if pause:
flags |= libvirt.VIR_DOMAIN_START_PAUSED
self.lv_dom.createWithFlags(flags)
def sync_description_tags(self):
tags = dict(re.findall(REGEX_TAG_IN_DESCRIPTION, self.description, re.MULTILINE))
# Add/update static tags:
for k, v in tags.iteritems():
tag = self._description_tags_db['__main__'].get(k)
if tag is None:
self._description_tags_db.add_tag(Tag(k, v, -1))
else:
tag.value = v
# Purge not more defined static tags:
for k in self._description_tags_db['__main__']:
if k not in tags:
self._description_tags_db.remove_tag(k)
def suspend(self):
self.lv_dom.suspend()
def destroy(self):
self.lv_dom.destroy()
def undefine(self):
self.lv_dom.undefine()
@property
def disks(self):
return list(self.iter_disks())
def iter_disks(self):
for d in et.ElementTree().parse(
StringIO(self.lv_dom.XMLDesc(0))
).findall('devices/disk'):
if d.get('device') != 'disk':
continue
type_ = d.get('type')
if type_ in ('file', 'block'):
path = d.find('source').get(dict(file='file', block='dev')[type_])
volume = self.hypervisor.storage.get_volume(path)
if volume is None:
continue
elif type_ == 'volume':
pool = d.find('source').get('pool')
vol = d.find('source').get('volume')
volume = self.hypervisor.storage.get_volume_by_pool(pool, vol)
elif type_ == 'network':
vol = d.find('source').get('name')
volume = self.hypervisor.storage.get_volume_by_pool('_standalone', vol)
# Ignore unknown volumes:
if volume is None:
logger.warn('Unknown volume for vm %s', self.name)
continue
# Get target device & bus
target = d.find('target')
device = target.get('dev')
bus = target.get('bus')
# update cache behaviour
driver = d.find('driver')
if driver is None:
driver = {}
self.cache_behaviour[path] = driver.get('cache', 'default')
yield BoundVolumeProxy(volume, device, bus)
@property
def nics(self):
return list(self.iter_nics())
def iter_nics(self):
for nic in et.ElementTree().parse(
StringIO(self.lv_dom.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE))
).findall('devices/interface'):
if nic.get('type') == 'bridge':
try:
mac = nic.find('mac').get('address')
except AttributeError:
mac = None
try:
model = nic.find('model').get('type')
except AttributeError:
model = None
try:
source = nic.find('source').get('bridge')
except AttributeError:
source = None
untagged_vlan = None
tagged_vlans = set()
vlan = nic.find('vlan')
if vlan is None:
untagged_vlan = source[2:]
tags = vlan.findall('tag')
trunk = vlan.get('trunk') == 'yes' or len(tags) > 1
default_mode = 'tagged' if trunk else 'untagged'
for tag in tags:
if tag.get('nativeMode', default_mode) == 'untagged':
untagged_vlan = int(tag.get('id'))
else:
tagged_vlans.add(int(tag.get('id')))
yield NetworkInterface(
mac=mac,
source=source,
model=model,
untagged_vlan=untagged_vlan,
tagged_vlans=tagged_vlans,
def open_console(self):
if self.stream is not None:
raise ConsoleAlreadyOpened('Console for this VM is already'
' opened')
if str(
self.hypervisor.handler.tag_db['__main__']['libvirtver'].value,
).startswith('8'):
raise ConsoleError(
'Cannot open console, not compatible with this version of libvirt')
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
logger.info('Opening console stream on VM %s', self.name)
try:
self.stream = self.hypervisor.vir_con.newStream(
libvirt.VIR_STREAM_NONBLOCK)
except libvirt.libvirtError:
logger.error('Cannot create new stream for console %s', self.name)
self.close_console()
raise
self.stream_handling = libvirt.VIR_STREAM_EVENT_READABLE | (
libvirt.VIR_STREAM_EVENT_ERROR | libvirt.VIR_STREAM_EVENT_HANGUP)
try:
self.lv_dom.openConsole(None, self.stream, 0)
self.stream.eventAddCallback(self.stream_handling,
self.virt_console_stream_cb,
None)
except libvirt.libvirtError:
logger.error('Cannot open console on domain %s', self.name)
self.close_console()
raise
try:
self.sock, tunnel_endpoint = socket.socketpair()
except socket.error:
logger.error('Cannot create socket pair for console on domain %s',
self.name)
self.close_console()
raise
try:
self.sock.setblocking(0)
except socket.error:
logger.error('Cannot set socket to non blocking for console on'
' domain %s', self.name)
self.close_console()
raise
self.read_watcher = self.hypervisor.handler.main.evloop.io(
self.sock, pyev.EV_READ, self.read_from_tun_cb)
self.read_watcher.start()
self.write_watcher = self.hypervisor.handler.main.evloop.io(
self.sock, pyev.EV_WRITE, self.write_to_tun_cb)
# self.write_watcher.start()
self.from_tunnel = SocketBuffer(4096)
self.from_stream = SocketBuffer(4096)
return tunnel_endpoint
def virt_console_stream_cb(self, stream, events, opaque):
"""Handles read/write from/to libvirt stream."""
if events & libvirt.VIR_EVENT_HANDLE_ERROR or (
events & libvirt.VIR_EVENT_HANDLE_HANGUP):
# error/hangup
# logger.debug('Received error on stream')
self.close_console()
return
if events & libvirt.VIR_EVENT_HANDLE_WRITABLE:
# logger.debug('Write to stream')
# logger.debug('Event %s', self.stream_handling)
while True:
try:
to_send = self.from_tunnel.popleft()
except IndexError:
# update libvirt event mask
self.stream_handling ^= libvirt.VIR_STREAM_EVENT_WRITABLE
self.stream.eventUpdateCallback(self.stream_handling)
break
send_buffer = to_send
total_sent = 0
while True:
try:
written = self.stream.send(send_buffer)
except:
# libvirt send error
logger.exception('Error while writing to stream')
self.close_console()
return
if written == -2: # equivalent to EAGAIN
self.from_tunnel.appendleft(to_send[total_sent:])
break
elif written == len(send_buffer):
break
total_sent += written
send_buffer = buffer(to_send, total_sent)
if not self.from_tunnel.is_full():
self.read_watcher.start()
if events & libvirt.VIR_EVENT_HANDLE_READABLE:
# logger.debug('Read from stream')
# logger.debug('Event %s', self.stream_handling)
while True:
try:
incoming = self.stream.recv(self.BUFFER_LEN)
except:
pass
if incoming == -2:
# equivalent to EAGAIN
break
elif not incoming:
# EOF
self.close_console()
return
self.from_stream.append(incoming)
if self.from_stream.is_full():
# update libvirt event mask
self.stream_handling ^= libvirt.VIR_STREAM_EVENT_READABLE
self.stream.eventUpdateCallback(self.stream_handling)
break
if not self.from_stream.is_empty():
self.write_watcher.start()
def read_from_tun_cb(self, watcher, revents):
"""Read data from tunnel and save into buffer."""
# logger.debug('Read from tunnel')
# logger.debug('Event %s', self.stream_handling)
while True:
try:
incoming = self.sock.recv(self.BUFFER_LEN)
except socket.error as exc:
if exc.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
break
logger.exception('Error reading on socket for vm console')
self.close_console()
return
if not incoming:
# EOF (we could wait before closing console stream)
self.close_console()
return
self.from_tunnel.append(incoming)
if self.from_tunnel.is_full():
self.read_watcher.stop()
break
if not self.from_tunnel.is_empty():
# update libvirt event callback
self.stream_handling |= libvirt.VIR_STREAM_EVENT_WRITABLE
self.stream.eventUpdateCallback(self.stream_handling)
def write_to_tun_cb(self, watcher, revents):
"""Write data from buffer to tunnel."""
# logger.debug('Write to tunnel')
# logger.debug('Event %s', self.stream_handling)
while True:
try:
to_send = self.from_stream.popleft()
except IndexError:
self.write_watcher.stop()
break
send_buffer = to_send
total_sent = 0
while True:
try:
written = self.sock.send(send_buffer)
except socket.error as exc:
if exc.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
self.from_stream.appenleft(to_send[total_sent:])
break
logger.exception('Error writing on socket for vm console')
self.close_console()
return
if written == len(send_buffer):
break
total_sent += written
send_buffer = buffer(to_send, total_sent)
if not self.from_stream.is_full():
# update libvirt event callback
self.stream_handling |= libvirt.VIR_STREAM_EVENT_READABLE
self.stream.eventUpdateCallback(self.stream_handling)
def close_console(self):
logger.info('Closing console stream on VM %s', self.name)
if self.stream is not None:
try:
self.stream.eventRemoveCallback()
except Exception:
logger.error('Error while removing callback on stream')
try:
self.stream.finish()
except Exception:
logger.error('Cannot finnish console stream')
self.stream = None
if self.sock is not None:
try:
self.sock.close()
except socket.error:
logger.error('Cannot close socket')
self.sock = None
if self.read_watcher is not None:
self.read_watcher.stop()
self.read_watcher = None
if self.write_watcher is not None:
self.write_watcher.stop()
self.write_watcher = None
self.from_tunnel = None
self.from_stream = None
def migrate(self, dest_uri, live=False):
volumes = list(self.iter_disks()) # Store volumes for future cleanup
migration_params = {}
# Get the list of shared, non shared disks and shared pools:
shared = set()
shared_pools = set()
nonshared = set()
for volume in volumes:
if volume.storage.is_shared:
shared.add(volume.device)
shared_pools.add(volume.storage.name)
else:
nonshared.add(volume.device)
flags = (libvirt.VIR_MIGRATE_PEER2PEER
| libvirt.VIR_MIGRATE_PERSIST_DEST
| libvirt.VIR_MIGRATE_UNDEFINE_SOURCE)
if live:
flags |= (libvirt.VIR_MIGRATE_LIVE | libvirt.VIR_MIGRATE_NON_SHARED_DISK)
migration_params[libvirt.VIR_MIGRATE_PARAM_MIGRATE_DISKS] = list(nonshared)
else:
flags |= libvirt.VIR_MIGRATE_OFFLINE
dconn = libvirt.open(dest_uri)
# Refresh shared pools on the destination to avoid unknown volumes:
for pool_name in shared_pools:
if pool_name.startswith('_'):
continue # Ignore internal storages
pool = dconn.storagePoolLookupByName(pool_name)
pool.refresh()
# Note that we don't reuse the existing connection to target
# because the migrate3 API doesn't support P2P migrations.
error = self.lv_dom.migrateToURI3(dest_uri, migration_params, flags)
if error:
raise RuntimeError('Unable to migrate VM')
else:
if live: # In live mode, we are responsible for source volume cleaning
for volume in volumes:
if not volume.storage.is_shared:
# Delete VM storage after migration success:
self.hypervisor.storage.delete_volume(volume.storage.name, volume.name)