/
connection.py
2062 lines (1700 loc) · 79.4 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 hashlib
import functools
import multiprocessing
import os
import shutil
import sys
import tempfile
import uuid
from eventlet import greenthread
from xml.dom import minidom
from xml.etree import ElementTree
from nova.auth import manager
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 import images
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('nova.virt.libvirt_conn')
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=utils.abspath('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('use_cow_images',
default=True,
help='Whether to use cow images'),
cfg.StrOpt('cpuinfo_xml_template',
default=utils.abspath('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)'),
]
FLAGS = flags.FLAGS
FLAGS.add_options(libvirt_opts)
flags.DECLARE('live_migration_retry_count', 'nova.compute.manager')
flags.DECLARE('vncserver_proxyclient_address', 'nova.vnc')
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['firewall_driver'].SetDefault(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.image_cache_manager = imagecache.ImageCacheManager()
@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)
self._wrapped_conn = 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 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):
instance_name = instance['name']
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 of "
"%(instance_name)s. Code=%(errcode)s "
"Error=%(e)s") %
locals())
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 %(instance_name)s. Code=%(errcode)s"
" Error=%(e)s") % locals())
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 of "
"%(instance_name)s. Code=%(errcode)s "
"Error=%(e)s") %
locals())
raise
self.unplug_vifs(instance, network_info)
def _wait_for_destroy():
"""Called at an interval until the VM is gone."""
instance_name = instance['name']
try:
state = self.get_info(instance_name)['state']
except exception.NotFound:
msg = _("Instance %s destroyed successfully.") % instance_name
LOG.info(msg)
raise utils.LoopingCallDone
timer = utils.LoopingCall(_wait_for_destroy)
timer.start(interval=0.5, now=True)
self.firewall_driver.unfilter_instance(instance,
network_info=network_info)
# 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']
xml = 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'])
instance_name = instance['name']
LOG.info(_('instance %(instance_name)s: deleting instance files'
' %(target)s') % locals())
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'))
return {
'ip': FLAGS.my_ip,
'initiator': self._initiator,
}
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)
virt_dom.attachDevice(xml)
@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)
virt_dom.detachDevice(xml)
finally:
self.volume_driver_method('disconnect_volume',
connection_info,
mount_device)
@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'])
base = image_service.show(context, image_id)
_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['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']
# Make the snapshot
snapshot_name = uuid.uuid4().hex
snapshot_xml = """
<domainsnapshot>
<name>%s</name>
</domainsnapshot>
""" % snapshot_name
snapshot_ptr = virt_dom.snapshotCreateXML(snapshot_xml, 0)
# 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')
# Export the snapshot to a raw image
temp_dir = tempfile.mkdtemp()
try:
out_path = os.path.join(temp_dir, snapshot_name)
libvirt_utils.extract_snapshot(disk_path, source_format,
snapshot_name, out_path,
image_format)
# 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)
finally:
# Clean up
shutil.rmtree(temp_dir)
snapshot_ptr.delete(0)
@exception.wrap_exception()
def reboot(self, instance, network_info, reboot_type=None, 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.
"""
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)
# NOTE(itoumsn): self.shutdown() and wait instead of self.destroy() is
# better because we cannot ensure flushing dirty buffers
# in the guest OS. But, in case of KVM, shutdown() does not work...
self._destroy(instance, network_info, cleanup=False)
self.unplug_vifs(instance, network_info)
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."""
instance_name = instance['name']
try:
state = self.get_info(instance_name)['state']
except exception.NotFound:
msg = _("During reboot, %s disappeared.") % instance_name
LOG.error(msg)
raise utils.LoopingCallDone
if state == power_state.RUNNING:
msg = _("Instance %s rebooted successfully.") % instance_name
LOG.info(msg)
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.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')
unrescue_xml = libvirt_utils.load_file(unrescue_xml_path)
libvirt_utils.file_delete(unrescue_xml_path)
self.reboot(instance, network_info, xml=unrescue_xml)
@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)
# 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)
domain = self._create_new_domain(xml)
LOG.debug(_("instance is running"), instance=instance)
self.firewall_driver.apply_instance_filter(instance, network_info)
def _wait_for_boot():
"""Called at an interval until the VM is running."""
instance_name = instance['name']
try:
state = self.get_info(instance_name)['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_xen_console(self, virsh_output):
LOG.info(_('virsh said: %r'), virsh_output)
virsh_output = virsh_output[0].strip()
if virsh_output.startswith('/dev/'):
LOG.info(_("cool, it's a device"))
out, err = utils.execute('dd',
'if=%s' % virsh_output,
'iflag=nonblock',
run_as_root=True,
check_exit_code=False)
return out
else:
return ''
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):
console_log = os.path.join(FLAGS.instances_path, instance['name'],
'console.log')
libvirt_utils.chown(console_log, os.getuid())
if FLAGS.libvirt_type == 'xen':
# Xen is special
virsh_output = utils.execute('virsh',
'ttyconsole',
instance['name'])
data = self._flush_xen_console(virsh_output)
fpath = self._append_to_file(data, console_log)
elif FLAGS.libvirt_type == 'lxc':
# LXC is also special
LOG.info(_("Unable to read LXC console"))
else:
fpath = console_log
return libvirt_utils.load_file(fpath)
@staticmethod
def get_host_ip_addr():
return FLAGS.my_ip
@exception.wrap_exception()
def get_vnc_console(self, instance):
def get_vnc_port_for_instance(instance_name):
virt_dom = self._lookup_by_name(instance_name)
xml = virt_dom.XMLDesc(0)
# TODO: use etree instead of minidom
dom = minidom.parseString(xml)
for graphic in dom.getElementsByTagName('graphics'):
if graphic.getAttribute('type') == 'vnc':
return graphic.getAttribute('port')
port = get_vnc_port_for_instance(instance['name'])
host = FLAGS.vncserver_proxyclient_address
return {'host': host, 'port': port, 'internal_access_path': None}
@staticmethod
def _cache_image(fn, target, fname, cow=False, size=None, *args, **kwargs):
"""Wrapper for a method that creates an image that caches the image.
This wrapper will save the image into a common store and create a
copy for use by the hypervisor.
The underlying method should specify a kwarg of target representing
where the image will be saved.
fname is used as the filename of the base image. The filename needs
to be unique to a given image.
If cow is True, it will make a CoW image instead of a copy.
If size is specified, we attempt to resize up to that size.
"""
generating = 'image_id' not in kwargs
if not os.path.exists(target):
base_dir = os.path.join(FLAGS.instances_path, '_base')
if not os.path.exists(base_dir):
libvirt_utils.ensure_tree(base_dir)
base = os.path.join(base_dir, fname)
@utils.synchronized(fname)
def call_if_not_exists(base, fn, *args, **kwargs):
if not os.path.exists(base):
fn(target=base, *args, **kwargs)
if cow or not generating:
call_if_not_exists(base, fn, *args, **kwargs)
elif generating:
# For raw it's quicker to just generate outside the cache
call_if_not_exists(target, fn, *args, **kwargs)
if cow:
cow_base = base
if size:
size_gb = size / (1024 * 1024 * 1024)
cow_base += "_%d" % size_gb
if not os.path.exists(cow_base):
libvirt_utils.copy_image(base, cow_base)
disk.extend(cow_base, size)
libvirt_utils.create_cow_image(cow_base, target)
elif not generating:
libvirt_utils.copy_image(base, target)
# Resize after the copy, as it's usually much faster
# to make sparse updates, rather than potentially
# naively copying the whole image file.
if size:
disk.extend(target, size)
@staticmethod
def _fetch_image(context, target, image_id, user_id, project_id):
"""Grab image to raw format"""
images.fetch_to_raw(context, image_id, target, user_id, project_id)
if FLAGS.checksum_base_images:
f = open(target, 'r')
checksum = utils.hash_file(f)
f.close()
checksum_fname = '%s.sha1' % target
fd = os.open(checksum_filename, os.O_WRONLY, mode=0444)
os.write(fd, checksum)
os.close(fd)
@staticmethod
def _create_local(target, local_size, unit='G', fs_format=None):
"""Create a blank image of specified size"""
if not fs_format:
fs_format = FLAGS.default_ephemeral_format
libvirt_utils.create_image('raw', target,
'%d%c' % (local_size, unit))
if fs_format:
libvirt_utils.mkfs(fs_format, target)
def _create_ephemeral(self, target, ephemeral_size, fs_label, os_type):
self._create_local(target, ephemeral_size)
disk.mkfs(os_type, fs_label, target)
@staticmethod
def _create_swap(target, swap_mb):
"""Create a swap file of specified size"""
libvirt_utils.create_image('raw', target, '%dM' % swap_mb)
libvirt_utils.mkfs('swap', target)
def _create_image(self, context, instance, libvirt_xml, suffix='',
disk_images=None, network_info=None,
block_device_info=None):
if not suffix:
suffix = ''
# syntactic nicety
def basepath(fname='', suffix=suffix):
return os.path.join(FLAGS.instances_path,
instance['name'],
fname + suffix)
# ensure directories exist and are writable
libvirt_utils.ensure_tree(basepath(suffix=''))
LOG.info(_('Creating image'), instance=instance)
libvirt_utils.write_to_file(basepath('libvirt.xml'), libvirt_xml)
if FLAGS.libvirt_type == 'lxc':
container_dir = '%s/rootfs' % basepath(suffix='')
libvirt_utils.ensure_tree(container_dir)
# NOTE(vish): No need add the suffix to console.log
libvirt_utils.write_to_file(basepath('console.log', ''), '', 007)
if not disk_images:
disk_images = {'image_id': instance['image_ref'],
'kernel_id': instance['kernel_id'],
'ramdisk_id': instance['ramdisk_id']}
if disk_images['kernel_id']:
fname = disk_images['kernel_id']
self._cache_image(fn=libvirt_utils.fetch_image,
context=context,
target=basepath('kernel'),
fname=fname,
image_id=disk_images['kernel_id'],
user_id=instance['user_id'],
project_id=instance['project_id'])
if disk_images['ramdisk_id']:
fname = disk_images['ramdisk_id']
self._cache_image(fn=libvirt_utils.fetch_image,
context=context,
target=basepath('ramdisk'),
fname=fname,
image_id=disk_images['ramdisk_id'],
user_id=instance['user_id'],
project_id=instance['project_id'])
root_fname = hashlib.sha1(str(disk_images['image_id'])).hexdigest()
size = instance['root_gb'] * 1024 * 1024 * 1024
inst_type_id = instance['instance_type_id']
inst_type = instance_types.get_instance_type(inst_type_id)
if size == 0 or suffix == '.rescue':
size = None
if not self._volume_in_mapping(self.default_root_device,
block_device_info):
self._cache_image(fn=libvirt_utils.fetch_image,
context=context,
target=basepath('disk'),
fname=root_fname,
cow=FLAGS.use_cow_images,
image_id=disk_images['image_id'],
user_id=instance['user_id'],
project_id=instance['project_id'],
size=size)
ephemeral_gb = instance['ephemeral_gb']
if ephemeral_gb and not self._volume_in_mapping(
self.default_second_device, block_device_info):
swap_device = self.default_third_device
fn = functools.partial(self._create_ephemeral,
fs_label='ephemeral0',
os_type=instance.os_type)
self._cache_image(fn=fn,
target=basepath('disk.local'),
fname="ephemeral_%s_%s_%s" %
("0", ephemeral_gb, instance.os_type),
cow=FLAGS.use_cow_images,
ephemeral_size=ephemeral_gb)
else:
swap_device = self.default_second_device
for eph in driver.block_device_info_get_ephemerals(block_device_info):
fn = functools.partial(self._create_ephemeral,
fs_label='ephemeral%d' % eph['num'],
os_type=instance.os_type)
self._cache_image(fn=fn,
target=basepath(_get_eph_disk(eph)),
fname="ephemeral_%s_%s_%s" %
(eph['num'], eph['size'], instance.os_type),
cow=FLAGS.use_cow_images,
ephemeral_size=eph['size'])