forked from cblument/puppetlabs-nova
/
connection.py
2488 lines (2073 loc) · 97.1 KB
/
connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
A connection to a hypervisor through libvirt.
Supports KVM, LXC, QEMU, UML, and XEN.
**Related Flags**
:libvirt_type: Libvirt domain type. Can be kvm, qemu, uml, xen
(default: kvm).
:libvirt_uri: Override for the default libvirt URI (depends on libvirt_type).
:libvirt_xml_template: Libvirt XML Template.
:libvirt_disk_prefix: Override the default disk prefix for the devices
attached to a server.
:rescue_image_id: Rescue ami image (None = original image).
:rescue_kernel_id: Rescue aki image (None = original image).
:rescue_ramdisk_id: Rescue ari image (None = original image).
:injected_network_template: Template file for injected network
:allow_same_net_traffic: Whether to allow in project network traffic
"""
import errno
import hashlib
import functools
import glob
import multiprocessing
import os
import shutil
import sys
import time
import uuid
from eventlet import greenthread
from eventlet import tpool
from xml.dom import minidom
from xml.etree import ElementTree
from nova import block_device
from nova.compute import instance_types
from nova.compute import power_state
from nova import context as nova_context
from nova import db
from nova import exception
from nova import flags
import nova.image
from nova import log as logging
from nova.openstack.common import cfg
from nova import utils
from nova.virt import driver
from nova.virt.disk import api as disk
from nova.virt.libvirt import firewall
from nova.virt.libvirt import imagecache
from nova.virt.libvirt import utils as libvirt_utils
libvirt = None
Template = None
LOG = logging.getLogger(__name__)
libvirt_opts = [
cfg.StrOpt('rescue_image_id',
default=None,
help='Rescue ami image'),
cfg.StrOpt('rescue_kernel_id',
default=None,
help='Rescue aki image'),
cfg.StrOpt('rescue_ramdisk_id',
default=None,
help='Rescue ari image'),
cfg.StrOpt('libvirt_xml_template',
default='$pybasedir/nova/virt/libvirt.xml.template',
help='Libvirt XML Template'),
cfg.StrOpt('libvirt_type',
default='kvm',
help='Libvirt domain type (valid options are: '
'kvm, lxc, qemu, uml, xen)'),
cfg.StrOpt('libvirt_uri',
default='',
help='Override the default libvirt URI '
'(which is dependent on libvirt_type)'),
cfg.BoolOpt('libvirt_inject_password',
default=False,
help='Inject the admin password at boot time, '
'without an agent.'),
cfg.BoolOpt('use_usb_tablet',
default=True,
help='Sync virtual and real mouse cursors in Windows VMs'),
cfg.StrOpt('cpuinfo_xml_template',
default='$pybasedir/nova/virt/cpuinfo.xml.template',
help='CpuInfo XML Template (Used only live migration now)'),
cfg.StrOpt('live_migration_uri',
default="qemu+tcp://%s/system",
help='Define protocol used by live_migration feature'),
cfg.StrOpt('live_migration_flag',
default='VIR_MIGRATE_UNDEFINE_SOURCE, VIR_MIGRATE_PEER2PEER',
help='Define live migration behavior.'),
cfg.StrOpt('block_migration_flag',
default='VIR_MIGRATE_UNDEFINE_SOURCE, VIR_MIGRATE_PEER2PEER, '
'VIR_MIGRATE_NON_SHARED_INC',
help='Define block migration behavior.'),
cfg.IntOpt('live_migration_bandwidth',
default=0,
help='Define live migration behavior'),
cfg.StrOpt('snapshot_image_format',
default=None,
help='Snapshot image format (valid options are : '
'raw, qcow2, vmdk, vdi). '
'Defaults to same as source image'),
cfg.StrOpt('libvirt_vif_type',
default='bridge',
help='Type of VIF to create.'),
cfg.StrOpt('libvirt_vif_driver',
default='nova.virt.libvirt.vif.LibvirtBridgeDriver',
help='The libvirt VIF driver to configure the VIFs.'),
cfg.ListOpt('libvirt_volume_drivers',
default=[
'iscsi=nova.virt.libvirt.volume.LibvirtISCSIVolumeDriver',
'local=nova.virt.libvirt.volume.LibvirtVolumeDriver',
'fake=nova.virt.libvirt.volume.LibvirtFakeVolumeDriver',
'rbd=nova.virt.libvirt.volume.LibvirtNetVolumeDriver',
'sheepdog=nova.virt.libvirt.volume.LibvirtNetVolumeDriver'
],
help='Libvirt handlers for remote volumes.'),
cfg.BoolOpt('libvirt_use_virtio_for_bridges',
default=False,
help='Use virtio for bridge interfaces'),
cfg.StrOpt('libvirt_disk_prefix',
default=None,
help='Override the default disk prefix for the devices attached'
' to a server, which is dependent on libvirt_type. '
'(valid options are: sd, xvd, uvd, vd)'),
cfg.IntOpt('libvirt_wait_soft_reboot_seconds',
default=120,
help='Number of seconds to wait for instance to shut down after'
' soft reboot request is made. We fall back to hard reboot'
' if instance does not shutdown within this window.'),
cfg.BoolOpt('libvirt_nonblocking',
default=False,
help='Use a separated OS thread pool to realize non-blocking'
' libvirt calls')
]
FLAGS = flags.FLAGS
FLAGS.register_opts(libvirt_opts)
flags.DECLARE('live_migration_retry_count', 'nova.compute.manager')
flags.DECLARE('vncserver_proxyclient_address', 'nova.vnc')
def patch_tpool_proxy():
"""eventlet.tpool.Proxy doesn't work with old-style class in __str__()
or __repr__() calls. See bug #962840 for details.
We perform a monkey patch to replace those two instance methods.
"""
def str_method(self):
return str(self._obj)
def repr_method(self):
return repr(self._obj)
tpool.Proxy.__str__ = str_method
tpool.Proxy.__repr__ = repr_method
patch_tpool_proxy()
def get_connection(read_only):
# These are loaded late so that there's no need to install these
# libraries when not using libvirt.
# Cheetah is separate because the unit tests want to load Cheetah,
# but not libvirt.
global libvirt
if libvirt is None:
libvirt = __import__('libvirt')
_late_load_cheetah()
return LibvirtConnection(read_only)
def _late_load_cheetah():
global Template
if Template is None:
t = __import__('Cheetah.Template', globals(), locals(),
['Template'], -1)
Template = t.Template
def _get_eph_disk(ephemeral):
return 'disk.eph' + str(ephemeral['num'])
class LibvirtConnection(driver.ComputeDriver):
def __init__(self, read_only):
super(LibvirtConnection, self).__init__()
self._host_state = None
self._initiator = None
self._wrapped_conn = None
self.container = None
self.read_only = read_only
if FLAGS.firewall_driver not in firewall.drivers:
FLAGS.set_default('firewall_driver', firewall.drivers[0])
fw_class = utils.import_class(FLAGS.firewall_driver)
self.firewall_driver = fw_class(get_connection=self._get_connection)
self.vif_driver = utils.import_object(FLAGS.libvirt_vif_driver)
self.volume_drivers = {}
for driver_str in FLAGS.libvirt_volume_drivers:
driver_type, _sep, driver = driver_str.partition('=')
driver_class = utils.import_class(driver)
self.volume_drivers[driver_type] = driver_class(self)
self._host_state = None
disk_prefix_map = {"lxc": "", "uml": "ubd", "xen": "sd"}
if FLAGS.libvirt_disk_prefix:
self._disk_prefix = FLAGS.libvirt_disk_prefix
else:
self._disk_prefix = disk_prefix_map.get(FLAGS.libvirt_type, 'vd')
self.default_root_device = self._disk_prefix + 'a'
self.default_second_device = self._disk_prefix + 'b'
self.default_third_device = self._disk_prefix + 'c'
self._disk_cachemode = None
self.image_cache_manager = imagecache.ImageCacheManager()
@property
def disk_cachemode(self):
if self._disk_cachemode is None:
# We prefer 'none' for consistent performance, host crash
# safety & migration correctness by avoiding host page cache.
# Some filesystems (eg GlusterFS via FUSE) don't support
# O_DIRECT though. For those we fallback to 'writethrough'
# which gives host crash safety, and is safe for migration
# provided the filesystem is cache coherant (cluster filesystems
# typically are, but things like NFS are not).
self._disk_cachemode = "none"
if not self._supports_direct_io(FLAGS.instances_path):
self._disk_cachemode = "writethrough"
return self._disk_cachemode
@property
def host_state(self):
if not self._host_state:
self._host_state = HostState(self.read_only)
return self._host_state
def init_host(self, host):
# NOTE(nsokolov): moved instance restarting to ComputeManager
pass
@property
def libvirt_xml(self):
if not hasattr(self, '_libvirt_xml_cache_info'):
self._libvirt_xml_cache_info = {}
return utils.read_cached_file(FLAGS.libvirt_xml_template,
self._libvirt_xml_cache_info)
@property
def cpuinfo_xml(self):
if not hasattr(self, '_cpuinfo_xml_cache_info'):
self._cpuinfo_xml_cache_info = {}
return utils.read_cached_file(FLAGS.cpuinfo_xml_template,
self._cpuinfo_xml_cache_info)
def _get_connection(self):
if not self._wrapped_conn or not self._test_connection():
LOG.debug(_('Connecting to libvirt: %s'), self.uri)
if not FLAGS.libvirt_nonblocking:
self._wrapped_conn = self._connect(self.uri,
self.read_only)
else:
self._wrapped_conn = tpool.proxy_call(
(libvirt.virDomain, libvirt.virConnect),
self._connect, self.uri, self.read_only)
return self._wrapped_conn
_conn = property(_get_connection)
def _test_connection(self):
try:
self._wrapped_conn.getCapabilities()
return True
except libvirt.libvirtError as e:
if (e.get_error_code() == libvirt.VIR_ERR_SYSTEM_ERROR and
e.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
LOG.debug(_('Connection to libvirt broke'))
return False
raise
@property
def uri(self):
if FLAGS.libvirt_type == 'uml':
uri = FLAGS.libvirt_uri or 'uml:///system'
elif FLAGS.libvirt_type == 'xen':
uri = FLAGS.libvirt_uri or 'xen:///'
elif FLAGS.libvirt_type == 'lxc':
uri = FLAGS.libvirt_uri or 'lxc:///'
else:
uri = FLAGS.libvirt_uri or 'qemu:///system'
return uri
@staticmethod
def _connect(uri, read_only):
auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT],
'root',
None]
if read_only:
return libvirt.openReadOnly(uri)
else:
return libvirt.openAuth(uri, auth, 0)
def get_num_instances(self):
"""Efficient override of base instance_exists method."""
return self._conn.numOfDomains()
def instance_exists(self, instance_id):
"""Efficient override of base instance_exists method."""
try:
self._conn.lookupByName(instance_id)
return True
except libvirt.libvirtError:
return False
def list_instances(self):
return [self._conn.lookupByID(x).name()
for x in self._conn.listDomainsID()
if x != 0] # We skip domains with ID 0 (hypervisors).
@staticmethod
def _map_to_instance_info(domain):
"""Gets info from a virsh domain object into an InstanceInfo"""
# domain.info() returns a list of:
# state: one of the state values (virDomainState)
# maxMemory: the maximum memory used by the domain
# memory: the current amount of memory used by the domain
# nbVirtCPU: the number of virtual CPU
# puTime: the time used by the domain in nanoseconds
(state, _max_mem, _mem, _num_cpu, _cpu_time) = domain.info()
name = domain.name()
return driver.InstanceInfo(name, state)
def list_instances_detail(self):
infos = []
for domain_id in self._conn.listDomainsID():
domain = self._conn.lookupByID(domain_id)
info = self._map_to_instance_info(domain)
infos.append(info)
return infos
def plug_vifs(self, instance, network_info):
"""Plug VIFs into networks."""
for (network, mapping) in network_info:
self.vif_driver.plug(instance, network, mapping)
def unplug_vifs(self, instance, network_info):
"""Unplug VIFs from networks."""
for (network, mapping) in network_info:
self.vif_driver.unplug(instance, network, mapping)
def _destroy(self, instance, network_info, block_device_info=None,
cleanup=True):
try:
virt_dom = self._lookup_by_name(instance['name'])
except exception.NotFound:
virt_dom = None
# If the instance is already terminated, we're still happy
# Otherwise, destroy it
if virt_dom is not None:
try:
virt_dom.destroy()
except libvirt.libvirtError as e:
is_okay = False
errcode = e.get_error_code()
if errcode == libvirt.VIR_ERR_OPERATION_INVALID:
# If the instance if already shut off, we get this:
# Code=55 Error=Requested operation is not valid:
# domain is not running
(state, _max_mem, _mem, _cpus, _t) = virt_dom.info()
if state == power_state.SHUTOFF:
is_okay = True
if not is_okay:
LOG.warning(_("Error from libvirt during destroy. "
"Code=%(errcode)s Error=%(e)s") %
locals(), instance=instance)
raise
try:
# NOTE(derekh): we can switch to undefineFlags and
# VIR_DOMAIN_UNDEFINE_MANAGED_SAVE once we require 0.9.4
if virt_dom.hasManagedSaveImage(0):
virt_dom.managedSaveRemove(0)
except libvirt.libvirtError as e:
errcode = e.get_error_code()
LOG.warning(_("Error from libvirt during saved instance "
"removal. Code=%(errcode)s Error=%(e)s") %
locals(), instance=instance)
try:
# NOTE(justinsb): We remove the domain definition. We probably
# would do better to keep it if cleanup=False (e.g. volumes?)
# (e.g. #2 - not losing machines on failure)
virt_dom.undefine()
except libvirt.libvirtError as e:
errcode = e.get_error_code()
LOG.warning(_("Error from libvirt during undefine. "
"Code=%(errcode)s Error=%(e)s") %
locals(), instance=instance)
raise
self.unplug_vifs(instance, network_info)
def _wait_for_destroy():
"""Called at an interval until the VM is gone."""
try:
self.get_info(instance)
except exception.NotFound:
LOG.info(_("Instance destroyed successfully."),
instance=instance)
raise utils.LoopingCallDone
timer = utils.LoopingCall(_wait_for_destroy)
timer.start(interval=0.5, now=True)
try:
self.firewall_driver.unfilter_instance(instance,
network_info=network_info)
except libvirt.libvirtError as e:
errcode = e.get_error_code()
LOG.warning(_("Error from libvirt during unfilter. "
"Code=%(errcode)s Error=%(e)s") %
locals(), instance=instance)
reason = "Error unfiltering instance."
raise exception.InstanceTerminationFailure(reason=reason)
# NOTE(vish): we disconnect from volumes regardless
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
for vol in block_device_mapping:
connection_info = vol['connection_info']
mountpoint = vol['mount_device']
self.volume_driver_method('disconnect_volume',
connection_info,
mountpoint)
if cleanup:
self._cleanup(instance)
return True
def destroy(self, instance, network_info, block_device_info=None):
return self._destroy(instance, network_info, block_device_info,
cleanup=True)
def _cleanup(self, instance):
target = os.path.join(FLAGS.instances_path, instance['name'])
LOG.info(_('Deleting instance files %(target)s') % locals(),
instance=instance)
if FLAGS.libvirt_type == 'lxc':
disk.destroy_container(self.container)
if os.path.exists(target):
shutil.rmtree(target)
def get_volume_connector(self, instance):
if not self._initiator:
self._initiator = libvirt_utils.get_iscsi_initiator()
if not self._initiator:
LOG.warn(_('Could not determine iscsi initiator name'),
instance=instance)
return {
'ip': FLAGS.my_ip,
'initiator': self._initiator,
}
def _cleanup_resize(self, instance):
target = os.path.join(FLAGS.instances_path,
instance['name'] + "_resize")
if os.path.exists(target):
shutil.rmtree(target)
def volume_driver_method(self, method_name, connection_info,
*args, **kwargs):
driver_type = connection_info.get('driver_volume_type')
if not driver_type in self.volume_drivers:
raise exception.VolumeDriverNotFound(driver_type=driver_type)
driver = self.volume_drivers[driver_type]
method = getattr(driver, method_name)
return method(connection_info, *args, **kwargs)
@exception.wrap_exception()
def attach_volume(self, connection_info, instance_name, mountpoint):
virt_dom = self._lookup_by_name(instance_name)
mount_device = mountpoint.rpartition("/")[2]
xml = self.volume_driver_method('connect_volume',
connection_info,
mount_device)
if FLAGS.libvirt_type == 'lxc':
self._attach_lxc_volume(xml, virt_dom, instance_name)
else:
try:
# The attaching command were patched by Puppet
LOG.info("Attaching device with virsh because attachDevice does not work")
device_path = connection_info['data']['device_path']
utils.execute('virsh', "attach-disk", instance_name, device_path, mount_device, run_as_root=True)
except Exception, ex:
self.volume_driver_method('disconnect_volume',
connection_info,
mount_device)
if isinstance(ex, libvirt.libvirtError):
errcode = ex.get_error_code()
if errcode == libvirt.VIR_ERR_OPERATION_FAILED:
raise exception.DeviceIsBusy(device=mount_device)
raise
@staticmethod
def _get_disk_xml(xml, device):
"""Returns the xml for the disk mounted at device"""
try:
doc = ElementTree.fromstring(xml)
except Exception:
return None
ret = doc.findall('./devices/disk')
for node in ret:
for child in node.getchildren():
if child.tag == 'target':
if child.get('dev') == device:
return ElementTree.tostring(node)
@exception.wrap_exception()
def detach_volume(self, connection_info, instance_name, mountpoint):
mount_device = mountpoint.rpartition("/")[2]
try:
# NOTE(vish): This is called to cleanup volumes after live
# migration, so we should still logout even if
# the instance doesn't exist here anymore.
virt_dom = self._lookup_by_name(instance_name)
xml = self._get_disk_xml(virt_dom.XMLDesc(0), mount_device)
if not xml:
raise exception.DiskNotFound(location=mount_device)
if FLAGS.libvirt_type == 'lxc':
self._detach_lxc_volume(xml, virt_dom, instance_name)
else:
virt_dom.detachDevice(xml)
finally:
self.volume_driver_method('disconnect_volume',
connection_info,
mount_device)
@exception.wrap_exception()
def _attach_lxc_volume(self, xml, virt_dom, instance_name):
LOG.info(_('attaching LXC block device'))
lxc_container_root = self.get_lxc_container_root(virt_dom)
lxc_host_volume = self.get_lxc_host_device(xml)
lxc_container_device = self.get_lxc_container_target(xml)
lxc_container_target = "%s/%s" % (lxc_container_root,
lxc_container_device)
if lxc_container_target:
disk.bind(lxc_host_volume, lxc_container_target, instance_name)
@exception.wrap_exception()
def _detach_lxc_volume(self, xml, virt_dom, instance_name):
LOG.info(_('detaching LXC block device'))
lxc_container_root = self.get_lxc_container_root(virt_dom)
lxc_container_device = self.get_lxc_container_target(xml)
lxc_container_target = "%s/%s" % (lxc_container_root,
lxc_container_device)
if lxc_container_target:
disk.unbind(lxc_container_target)
@staticmethod
def get_lxc_container_root(virt_dom):
xml = virt_dom.XMLDesc(0)
doc = ElementTree.fromstring(xml)
filesystem_block = doc.findall('./devices/filesystem')
for cnt, filesystem_nodes in enumerate(filesystem_block):
return filesystem_nodes[cnt].get('dir')
@staticmethod
def get_lxc_host_device(xml):
dom = minidom.parseString(xml)
for device in dom.getElementsByTagName('source'):
return device.getAttribute('dev')
@staticmethod
def get_lxc_container_target(xml):
dom = minidom.parseString(xml)
for device in dom.getElementsByTagName('target'):
filesystem = device.getAttribute('dev')
return 'dev/%s' % filesystem
@exception.wrap_exception()
def snapshot(self, context, instance, image_href):
"""Create snapshot from a running VM instance.
This command only works with qemu 0.14+
"""
try:
virt_dom = self._lookup_by_name(instance['name'])
except exception.InstanceNotFound:
raise exception.InstanceNotRunning()
(image_service, image_id) = nova.image.get_image_service(
context, instance['image_ref'])
try:
base = image_service.show(context, image_id)
except exception.ImageNotFound:
base = {}
_image_service = nova.image.get_image_service(context, image_href)
snapshot_image_service, snapshot_image_id = _image_service
snapshot = snapshot_image_service.show(context, snapshot_image_id)
metadata = {'is_public': False,
'status': 'active',
'name': snapshot['name'],
'properties': {
'kernel_id': instance['kernel_id'],
'image_location': 'snapshot',
'image_state': 'available',
'owner_id': instance['project_id'],
'ramdisk_id': instance['ramdisk_id'],
}
}
if 'architecture' in base.get('properties', {}):
arch = base['properties']['architecture']
metadata['properties']['architecture'] = arch
source_format = base.get('disk_format') or 'raw'
if source_format == 'ami':
# NOTE(vish): assume amis are raw
source_format = 'raw'
image_format = FLAGS.snapshot_image_format or source_format
if FLAGS.use_cow_images:
source_format = 'qcow2'
# NOTE(vish): glance forces ami disk format to be ami
if base.get('disk_format') == 'ami':
metadata['disk_format'] = 'ami'
else:
metadata['disk_format'] = image_format
if 'container_format' in base:
metadata['container_format'] = base['container_format']
# Find the disk
xml_desc = virt_dom.XMLDesc(0)
domain = ElementTree.fromstring(xml_desc)
source = domain.find('devices/disk/source')
disk_path = source.get('file')
snapshot_name = uuid.uuid4().hex
(state, _max_mem, _mem, _cpus, _t) = virt_dom.info()
if state == power_state.RUNNING:
virt_dom.managedSave(0)
# Make the snapshot
libvirt_utils.create_snapshot(disk_path, snapshot_name)
# Export the snapshot to a raw image
with utils.tempdir() as tmpdir:
try:
out_path = os.path.join(tmpdir, snapshot_name)
libvirt_utils.extract_snapshot(disk_path, source_format,
snapshot_name, out_path,
image_format)
finally:
libvirt_utils.delete_snapshot(disk_path, snapshot_name)
if state == power_state.RUNNING:
virt_dom.create()
# Upload that image to the image service
with libvirt_utils.file_open(out_path) as image_file:
image_service.update(context,
image_href,
metadata,
image_file)
@exception.wrap_exception()
def reboot(self, instance, network_info, reboot_type='SOFT'):
"""Reboot a virtual machine, given an instance reference."""
if reboot_type == 'SOFT':
# NOTE(vish): This will attempt to do a graceful shutdown/restart.
if self._soft_reboot(instance):
LOG.info(_("Instance soft rebooted successfully."),
instance=instance)
return
else:
LOG.info(_("Failed to soft reboot instance."),
instance=instance)
return self._hard_reboot(instance, network_info)
def _soft_reboot(self, instance):
"""Attempt to shutdown and restart the instance gracefully.
We use shutdown and create here so we can return if the guest
responded and actually rebooted. Note that this method only
succeeds if the guest responds to acpi. Therefore we return
success or failure so we can fall back to a hard reboot if
necessary.
:returns: True if the reboot succeeded
"""
dom = self._lookup_by_name(instance.name)
(state, _max_mem, _mem, _cpus, _t) = dom.info()
# NOTE(vish): This check allows us to reboot an instance that
# is already shutdown.
if state == power_state.RUNNING:
dom.shutdown()
# NOTE(vish): This actually could take slighty longer than the
# FLAG defines depending on how long the get_info
# call takes to return.
for x in xrange(FLAGS.libvirt_wait_soft_reboot_seconds):
(state, _max_mem, _mem, _cpus, _t) = dom.info()
if state in [power_state.SHUTDOWN,
power_state.SHUTOFF,
power_state.CRASHED]:
LOG.info(_("Instance shutdown successfully."),
instance=instance)
dom.create()
timer = utils.LoopingCall(self._wait_for_running, instance)
return timer.start(interval=0.5, now=True)
greenthread.sleep(1)
return False
def _hard_reboot(self, instance, network_info, xml=None):
"""Reboot a virtual machine, given an instance reference.
This method actually destroys and re-creates the domain to ensure the
reboot happens, as the guest OS cannot ignore this action.
If xml is set, it uses the passed in xml in place of the xml from the
existing domain.
"""
virt_dom = self._conn.lookupByName(instance['name'])
# NOTE(itoumsn): Use XML delived from the running instance
# instead of using to_xml(instance, network_info). This is almost
# the ultimate stupid workaround.
if not xml:
xml = virt_dom.XMLDesc(0)
self._destroy(instance, network_info, cleanup=False)
self.plug_vifs(instance, network_info)
self.firewall_driver.setup_basic_filtering(instance, network_info)
self.firewall_driver.prepare_instance_filter(instance, network_info)
self._create_new_domain(xml)
self.firewall_driver.apply_instance_filter(instance, network_info)
def _wait_for_reboot():
"""Called at an interval until the VM is running again."""
try:
state = self.get_info(instance)['state']
except exception.NotFound:
LOG.error(_("During reboot, instance disappeared."),
instance=instance)
raise utils.LoopingCallDone
if state == power_state.RUNNING:
LOG.info(_("Instance rebooted successfully."),
instance=instance)
raise utils.LoopingCallDone
timer = utils.LoopingCall(_wait_for_reboot)
return timer.start(interval=0.5, now=True)
@exception.wrap_exception()
def pause(self, instance):
"""Pause VM instance"""
dom = self._lookup_by_name(instance.name)
dom.suspend()
@exception.wrap_exception()
def unpause(self, instance):
"""Unpause paused VM instance"""
dom = self._lookup_by_name(instance.name)
dom.resume()
@exception.wrap_exception()
def suspend(self, instance):
"""Suspend the specified instance"""
dom = self._lookup_by_name(instance.name)
dom.managedSave(0)
@exception.wrap_exception()
def resume(self, instance):
"""resume the specified instance"""
dom = self._lookup_by_name(instance.name)
dom.create()
@exception.wrap_exception()
def rescue(self, context, instance, network_info, image_meta):
"""Loads a VM using rescue images.
A rescue is normally performed when something goes wrong with the
primary images and data needs to be corrected/recovered. Rescuing
should not edit or over-ride the original image, only allow for
data recovery.
"""
virt_dom = self._conn.lookupByName(instance['name'])
unrescue_xml = virt_dom.XMLDesc(0)
unrescue_xml_path = os.path.join(FLAGS.instances_path,
instance['name'],
'unrescue.xml')
libvirt_utils.write_to_file(unrescue_xml_path, unrescue_xml)
xml = self.to_xml(instance, network_info, image_meta, rescue=True)
rescue_images = {
'image_id': FLAGS.rescue_image_id or instance['image_ref'],
'kernel_id': FLAGS.rescue_kernel_id or instance['kernel_id'],
'ramdisk_id': FLAGS.rescue_ramdisk_id or instance['ramdisk_id'],
}
self._create_image(context, instance, xml, '.rescue', rescue_images,
network_info=network_info)
self._hard_reboot(instance, network_info, xml=xml)
@exception.wrap_exception()
def unrescue(self, instance, network_info):
"""Reboot the VM which is being rescued back into primary images.
Because reboot destroys and re-creates instances, unresue should
simply call reboot.
"""
unrescue_xml_path = os.path.join(FLAGS.instances_path,
instance['name'],
'unrescue.xml')
xml = libvirt_utils.load_file(unrescue_xml_path)
libvirt_utils.file_delete(unrescue_xml_path)
self._hard_reboot(instance, network_info, xml=xml)
rescue_files = os.path.join(FLAGS.instances_path, instance['name'],
"*.rescue")
for rescue_file in glob.iglob(rescue_files):
libvirt_utils.file_delete(rescue_file)
@exception.wrap_exception()
def poll_rebooting_instances(self, timeout):
pass
@exception.wrap_exception()
def poll_rescued_instances(self, timeout):
pass
@exception.wrap_exception()
def poll_unconfirmed_resizes(self, resize_confirm_window):
"""Poll for unconfirmed resizes.
Look for any unconfirmed resizes that are older than
`resize_confirm_window` and automatically confirm them.
"""
ctxt = nova_context.get_admin_context()
migrations = db.migration_get_all_unconfirmed(ctxt,
resize_confirm_window)
migrations_info = dict(migration_count=len(migrations),
confirm_window=FLAGS.resize_confirm_window)
if migrations_info["migration_count"] > 0:
LOG.info(_("Found %(migration_count)d unconfirmed migrations "
"older than %(confirm_window)d seconds") % migrations_info)
for migration in migrations:
LOG.info(_("Automatically confirming migration %d"), migration.id)
self.compute_api.confirm_resize(ctxt, migration.instance_uuid)
def _enable_hairpin(self, instance):
interfaces = self.get_interfaces(instance['name'])
for interface in interfaces:
utils.execute('tee',
'/sys/class/net/%s/brport/hairpin_mode' % interface,
process_input='1',
run_as_root=True,
check_exit_code=[0, 1])
# NOTE(ilyaalekseyev): Implementation like in multinics
# for xenapi(tr3buchet)
@exception.wrap_exception()
def spawn(self, context, instance, image_meta, network_info,
block_device_info=None):
xml = self.to_xml(instance, network_info, image_meta, False,
block_device_info=block_device_info)
self.firewall_driver.setup_basic_filtering(instance, network_info)
self.firewall_driver.prepare_instance_filter(instance, network_info)
self._create_image(context, instance, xml, network_info=network_info,
block_device_info=block_device_info)
self._create_new_domain(xml)
LOG.debug(_("Instance is running"), instance=instance)
self._enable_hairpin(instance)
self.firewall_driver.apply_instance_filter(instance, network_info)
def _wait_for_boot():
"""Called at an interval until the VM is running."""
try:
state = self.get_info(instance)['state']
except exception.NotFound:
LOG.error(_("During reboot, instance disappeared."),
instance=instance)
raise utils.LoopingCallDone
if state == power_state.RUNNING:
LOG.info(_("Instance spawned successfully."),
instance=instance)
raise utils.LoopingCallDone
timer = utils.LoopingCall(_wait_for_boot)
return timer.start(interval=0.5, now=True)
def _flush_libvirt_console(self, pty):
out, err = utils.execute('dd',
'if=%s' % pty,
'iflag=nonblock',
run_as_root=True,
check_exit_code=False)
return out
def _append_to_file(self, data, fpath):
LOG.info(_('data: %(data)r, fpath: %(fpath)r') % locals())
fp = open(fpath, 'a+')
fp.write(data)
return fpath
def _inject_files(self, instance, files, partition):
disk_path = os.path.join(FLAGS.instances_path,
instance['name'], 'disk')
disk.inject_files(disk_path, files, partition=partition,
use_cow=FLAGS.use_cow_images)
@exception.wrap_exception()
def get_console_output(self, instance):
virt_dom = self._lookup_by_name(instance['name'])
xml = virt_dom.XMLDesc(0)
tree = ElementTree.fromstring(xml)
console_types = {}
# NOTE(comstud): We want to try 'file' types first, then try 'pty'
# types. We can't use Python 2.7 syntax of:
# tree.find("./devices/console[@type='file']/source")
# because we need to support 2.6.
console_nodes = tree.findall('./devices/console')
for console_node in console_nodes:
console_type = console_node.get('type')
console_types.setdefault(console_type, [])
console_types[console_type].append(console_node)
# If the guest has a console logging to a file prefer to use that
if console_types.get('file'):
for file_console in console_types.get('file'):
source_node = file_console.find('./source')
if source_node is None:
continue
path = source_node.get("path")
if not path:
continue
libvirt_utils.chown(path, os.getuid())
return libvirt_utils.load_file(path)
# Try 'pty' types
if console_types.get('pty'):
for pty_console in console_types.get('pty'):
source_node = pty_console.find('./source')