/
vmops.py
1817 lines (1540 loc) · 75 KB
/
vmops.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 (c) 2010 Citrix Systems, Inc.
# Copyright 2010 OpenStack LLC.
#
# 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.
"""
Management class for VM-related functions (spawn, reboot, etc).
"""
import base64
import json
import pickle
import random
import sys
import time
import uuid
from eventlet import greenthread
import M2Crypto
from nova.compute import api as compute
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
from nova import log as logging
from nova import utils
from nova.virt import driver
from nova.virt.xenapi import volume_utils
from nova.virt.xenapi import network_utils
from nova.virt.xenapi import vm_utils
VolumeHelper = volume_utils.VolumeHelper
NetworkHelper = network_utils.NetworkHelper
VMHelper = vm_utils.VMHelper
XenAPI = None
LOG = logging.getLogger("nova.virt.xenapi.vmops")
FLAGS = flags.FLAGS
flags.DECLARE('vncserver_proxyclient_address', 'nova.vnc')
flags.DEFINE_integer('agent_version_timeout', 300,
'number of seconds to wait for agent to be fully '
'operational')
flags.DEFINE_integer('xenapi_running_timeout', 60,
'number of seconds to wait for instance to go to '
'running state')
flags.DEFINE_string('xenapi_vif_driver',
'nova.virt.xenapi.vif.XenAPIBridgeDriver',
'The XenAPI VIF driver using XenServer Network APIs.')
flags.DEFINE_bool('xenapi_generate_swap',
False,
'Whether to generate swap (False means fetching it'
' from OVA)')
RESIZE_TOTAL_STEPS = 5
BUILD_TOTAL_STEPS = 4
def cmp_version(a, b):
"""Compare two version strings (eg 0.0.1.10 > 0.0.1.9)"""
a = a.split('.')
b = b.split('.')
# Compare each individual portion of both version strings
for va, vb in zip(a, b):
ret = int(va) - int(vb)
if ret:
return ret
# Fallback to comparing length last
return len(a) - len(b)
class VMOps(object):
"""
Management class for VM-related tasks
"""
def __init__(self, session, product_version):
self.XenAPI = session.get_imported_xenapi()
self.compute_api = compute.API()
self._session = session
self.poll_rescue_last_ran = None
VMHelper.XenAPI = self.XenAPI
fw_class = utils.import_class(FLAGS.firewall_driver)
self.firewall_driver = fw_class(xenapi_session=self._session)
vif_impl = utils.import_class(FLAGS.xenapi_vif_driver)
self.vif_driver = vif_impl(xenapi_session=self._session)
self._product_version = product_version
def list_instances(self):
"""List VM instances."""
# TODO(justinsb): Should we just always use the details method?
# Seems to be the same number of API calls..
name_labels = []
for vm_ref, vm_rec in VMHelper.list_vms(self._session):
name_labels.append(vm_rec["name_label"])
return name_labels
def list_instances_detail(self):
"""List VM instances, returning InstanceInfo objects."""
details = []
for vm_ref, vm_rec in VMHelper.list_vms(self._session):
name = vm_rec["name_label"]
# TODO(justinsb): This a roundabout way to map the state
openstack_format = VMHelper.compile_info(vm_rec)
state = openstack_format['state']
instance_info = driver.InstanceInfo(name, state)
details.append(instance_info)
return details
def confirm_migration(self, migration, instance, network_info):
name_label = self._get_orig_vm_name_label(instance)
vm_ref = VMHelper.lookup(self._session, name_label)
return self._destroy(instance, vm_ref, network_info, shutdown=False)
def finish_revert_migration(self, instance):
# NOTE(sirp): the original vm was suffixed with '-orig'; find it using
# the old suffix, remove the suffix, then power it back on.
name_label = self._get_orig_vm_name_label(instance)
vm_ref = VMHelper.lookup(self._session, name_label)
# Remove the '-orig' suffix (which was added in case the resized VM
# ends up on the source host, common during testing)
name_label = instance.name
VMHelper.set_vm_name_label(self._session, vm_ref, name_label)
self._start(instance, vm_ref)
def finish_migration(self, context, migration, instance, disk_info,
network_info, image_meta, resize_instance):
vdi_uuid = self._move_disks(instance, disk_info)
if resize_instance:
self._resize_instance(instance, vdi_uuid)
vm_ref = self._create_vm(context, instance,
[dict(vdi_type='os', vdi_uuid=vdi_uuid)],
network_info, image_meta)
# 5. Start VM
self._start(instance, vm_ref=vm_ref)
self._update_instance_progress(context, instance,
step=5,
total_steps=RESIZE_TOTAL_STEPS)
def _start(self, instance, vm_ref=None):
"""Power on a VM instance"""
if not vm_ref:
vm_ref = VMHelper.lookup(self._session, instance.name)
if vm_ref is None:
raise Exception(_('Attempted to power on non-existent instance'
' bad instance id %s') % instance.id)
LOG.debug(_("Starting instance %s"), instance.name)
self._session.call_xenapi('VM.start', vm_ref, False, False)
def _create_disks(self, context, instance, image_meta):
disk_image_type = VMHelper.determine_disk_image_type(image_meta)
vdis = VMHelper.fetch_image(context, self._session,
instance, instance.image_ref,
instance.user_id, instance.project_id,
disk_image_type)
for vdi in vdis:
if vdi["vdi_type"] == "os":
self._resize_instance(instance, vdi["vdi_uuid"])
return vdis
def spawn(self, context, instance, image_meta, network_info):
vdis = None
try:
# 1. Vanity Step
# NOTE(sirp): _create_disk will potentially take a *very* long
# time to complete since it has to fetch the image over the
# network and images can be several gigs in size. To avoid
# progress remaining at 0% for too long, which will appear to be
# an error, we insert a "vanity" step to bump the progress up one
# notch above 0.
self._update_instance_progress(context, instance,
step=1,
total_steps=BUILD_TOTAL_STEPS)
# 2. Fetch the Image over the Network
vdis = self._create_disks(context, instance, image_meta)
self._update_instance_progress(context, instance,
step=2,
total_steps=BUILD_TOTAL_STEPS)
# 3. Create the VM records
vm_ref = self._create_vm(context, instance, vdis, network_info,
image_meta)
self._update_instance_progress(context, instance,
step=3,
total_steps=BUILD_TOTAL_STEPS)
# 4. Prepare security group filters
# NOTE(salvatore-orlando): setup_basic_filtering might be empty or
# not implemented at all, as basic filter could be implemented
# with VIF rules created by xapi plugin
try:
self.firewall_driver.setup_basic_filtering(
instance, network_info)
except NotImplementedError:
pass
self.firewall_driver.prepare_instance_filter(instance,
network_info)
# 5. Boot the Instance
self._spawn(instance, vm_ref)
# The VM has started, let's ensure the security groups are enforced
self.firewall_driver.apply_instance_filter(instance, network_info)
self._update_instance_progress(context, instance,
step=4,
total_steps=BUILD_TOTAL_STEPS)
except (self.XenAPI.Failure, OSError, IOError) as spawn_error:
LOG.exception(_("instance %s: Failed to spawn"),
instance.uuid, exc_info=sys.exc_info())
LOG.debug(_('Instance %s failed to spawn - performing clean-up'),
instance.id)
self._handle_spawn_error(vdis, spawn_error)
raise spawn_error
def spawn_rescue(self, context, instance, image_meta, network_info):
"""Spawn a rescue instance."""
self.spawn(context, instance, image_meta, network_info)
def _create_vm(self, context, instance, vdis, network_info, image_meta):
"""Create VM instance."""
instance_name = instance.name
vm_ref = VMHelper.lookup(self._session, instance_name)
if vm_ref is not None:
raise exception.InstanceExists(name=instance_name)
# Ensure enough free memory is available
if not VMHelper.ensure_free_mem(self._session, instance):
raise exception.InsufficientFreeMemory(uuid=instance.uuid)
disk_image_type = VMHelper.determine_disk_image_type(image_meta)
kernel = None
ramdisk = None
try:
if instance.kernel_id:
kernel = VMHelper.fetch_image(context, self._session,
instance, instance.kernel_id, instance.user_id,
instance.project_id, vm_utils.ImageType.KERNEL)[0]
if instance.ramdisk_id:
ramdisk = VMHelper.fetch_image(context, self._session,
instance, instance.ramdisk_id, instance.user_id,
instance.project_id, vm_utils.ImageType.RAMDISK)[0]
# NOTE(jk0): Since vdi_type may contain either 'os' or 'swap', we
# need to ensure that the 'swap' VDI is not chosen as the mount
# point for file injection.
first_vdi_ref = None
for vdi in vdis:
if vdi.get('vdi_type') != 'swap':
# Create the VM ref and attach the first disk
first_vdi_ref = self._session.call_xenapi(
'VDI.get_by_uuid', vdi['vdi_uuid'])
vm_mode = instance.vm_mode and instance.vm_mode.lower()
if vm_mode == 'pv':
use_pv_kernel = True
elif vm_mode in ('hv', 'hvm'):
use_pv_kernel = False
vm_mode = 'hvm' # Normalize
else:
use_pv_kernel = VMHelper.determine_is_pv(self._session,
instance.id, first_vdi_ref, disk_image_type,
instance.os_type)
vm_mode = use_pv_kernel and 'pv' or 'hvm'
if instance.vm_mode != vm_mode:
# Update database with normalized (or determined) value
db.instance_update(nova_context.get_admin_context(),
instance['id'], {'vm_mode': vm_mode})
vm_ref = VMHelper.create_vm(self._session, instance,
kernel and kernel.get('file', None) or None,
ramdisk and ramdisk.get('file', None) or None,
use_pv_kernel)
except (self.XenAPI.Failure, OSError, IOError) as vm_create_error:
# Collect VDI/file resources to clean up;
# These resources will be removed by _handle_spawn_error.
LOG.exception(_("instance %s: Failed to spawn - " +
"Unable to create VM"),
instance.id, exc_info=sys.exc_info())
last_arg = None
resources = []
if vm_create_error.args:
last_arg = vm_create_error.args[-1]
if isinstance(last_arg, list):
resources = last_arg
else:
vm_create_error.args = vm_create_error.args + (resources,)
if kernel:
resources.append(kernel)
if ramdisk:
resources.append(ramdisk)
raise vm_create_error
# Add disks to VM
self._attach_disks(instance, disk_image_type, vm_ref, first_vdi_ref,
vdis)
# Alter the image before VM start for network injection.
if FLAGS.flat_injected:
VMHelper.preconfigure_instance(self._session, instance,
first_vdi_ref, network_info)
self.create_vifs(vm_ref, instance, network_info)
self.inject_network_info(instance, network_info, vm_ref)
self.inject_hostname(instance, vm_ref, instance['hostname'])
return vm_ref
def _attach_disks(self, instance, disk_image_type, vm_ref, first_vdi_ref,
vdis):
ctx = nova_context.get_admin_context()
instance_uuid = instance['uuid']
# device 0 reserved for RW disk
userdevice = 0
# DISK_ISO needs two VBDs: the ISO disk and a blank RW disk
if disk_image_type == vm_utils.ImageType.DISK_ISO:
LOG.debug("detected ISO image type, going to create blank VM for "
"install")
cd_vdi_ref = first_vdi_ref
first_vdi_ref = VMHelper.fetch_blank_disk(session=self._session,
instance_type_id=instance.instance_type_id)
VolumeHelper.create_vbd(session=self._session, vm_ref=vm_ref,
vdi_ref=first_vdi_ref, userdevice=userdevice, bootable=False)
# device 1 reserved for rescue disk and we've used '0'
userdevice = 2
VMHelper.create_cd_vbd(session=self._session, vm_ref=vm_ref,
vdi_ref=cd_vdi_ref, userdevice=userdevice, bootable=True)
# set user device to next free value
userdevice += 1
else:
if instance.auto_disk_config:
LOG.debug(_("Auto configuring disk for instance"
" %(instance_uuid)s, attempting to"
" resize partition...") % locals())
instance_type = db.instance_type_get(ctx,
instance.instance_type_id)
VMHelper.auto_configure_disk(session=self._session,
vdi_ref=first_vdi_ref,
new_gb=instance_type['local_gb'])
VolumeHelper.create_vbd(session=self._session, vm_ref=vm_ref,
vdi_ref=first_vdi_ref,
userdevice=userdevice, bootable=True)
# set user device to next free value
# userdevice 1 is reserved for rescue and we've used '0'
userdevice = 2
instance_type = db.instance_type_get(ctx, instance.instance_type_id)
swap_mb = instance_type['swap']
generate_swap = swap_mb and FLAGS.xenapi_generate_swap
if generate_swap:
VMHelper.generate_swap(session=self._session, instance=instance,
vm_ref=vm_ref, userdevice=userdevice,
swap_mb=swap_mb)
userdevice += 1
# Attach any other disks
for vdi in vdis[1:]:
if generate_swap and vdi['vdi_type'] == 'swap':
continue
vdi_ref = self._session.call_xenapi('VDI.get_by_uuid',
vdi['vdi_uuid'])
VolumeHelper.create_vbd(session=self._session, vm_ref=vm_ref,
vdi_ref=vdi_ref, userdevice=userdevice,
bootable=False)
userdevice += 1
def _configure_instance(self, ctx, instance, vm_ref):
# Inject files, if necessary
injected_files = instance.injected_files
if injected_files:
# Check if this is a JSON-encoded string and convert if needed.
if isinstance(injected_files, basestring):
try:
injected_files = json.loads(injected_files)
except ValueError:
LOG.exception(
_("Invalid value for injected_files: '%s'")
% injected_files)
injected_files = []
# Inject any files, if specified
for path, contents in instance.injected_files:
LOG.debug(_("Injecting file path: '%s'") % path)
self.inject_file(instance, path, contents)
# Set admin password, if necessary
admin_password = instance.admin_pass
if admin_password:
LOG.debug(_("Setting admin password"))
self.set_admin_password(instance, admin_password)
# Reset network config
LOG.debug(_("Resetting network"))
self.reset_network(instance, vm_ref)
# Set VCPU weight
inst_type = db.instance_type_get(ctx, instance.instance_type_id)
vcpu_weight = inst_type["vcpu_weight"]
if str(vcpu_weight) != "None":
LOG.debug(_("Setting VCPU weight"))
self._session.call_xenapi("VM.add_to_VCPUs_params", vm_ref,
"weight", vcpu_weight)
def _spawn(self, instance, vm_ref):
"""Spawn a new instance."""
LOG.debug(_('Starting VM %s...'), vm_ref)
self._start(instance, vm_ref)
instance_name = instance.name
LOG.info(_('Spawning VM %(instance_name)s created %(vm_ref)s.')
% locals())
ctx = nova_context.get_admin_context()
agent_build = db.agent_build_get_by_triple(ctx, 'xen',
instance.os_type, instance.architecture)
if agent_build:
LOG.info(_('Latest agent build for %(hypervisor)s/%(os)s' + \
'/%(architecture)s is %(version)s') % agent_build)
else:
LOG.info(_('No agent build found for %(hypervisor)s/%(os)s' + \
'/%(architecture)s') % {
'hypervisor': 'xen',
'os': instance.os_type,
'architecture': instance.architecture})
# Wait for boot to finish
LOG.debug(_('Instance %s: waiting for running'), instance_name)
expiration = time.time() + FLAGS.xenapi_running_timeout
while time.time() < expiration:
state = self.get_info(instance_name)['state']
if state == power_state.RUNNING:
break
greenthread.sleep(0.5)
LOG.debug(_('Instance %s: running'), instance_name)
# Update agent, if necessary
# This also waits until the agent starts
LOG.debug(_("Querying agent version"))
version = self.get_agent_version(instance)
if version:
LOG.info(_('Instance agent version: %s') % version)
if version and agent_build and \
cmp_version(version, agent_build['version']) < 0:
LOG.info(_('Updating Agent to %s') % agent_build['version'])
self.agent_update(instance, agent_build['url'],
agent_build['md5hash'])
self._configure_instance(ctx, instance, vm_ref)
def _handle_spawn_error(self, vdis, spawn_error):
# Extract resource list from spawn_error.
resources = []
if spawn_error.args:
last_arg = spawn_error.args[-1]
if isinstance(last_arg, list):
resources = last_arg
if vdis:
for vdi in vdis:
resources.append(dict(vdi_type=vdi['vdi_type'],
vdi_uuid=vdi['vdi_uuid'],
file=None))
LOG.debug(_("Resources to remove:%s"), resources)
kernel_file = None
ramdisk_file = None
for item in resources:
vdi_type = item['vdi_type']
vdi_to_remove = item['vdi_uuid']
if vdi_to_remove:
try:
vdi_ref = self._session.call_xenapi('VDI.get_by_uuid',
vdi_to_remove)
LOG.debug(_('Removing VDI %(vdi_ref)s' +
'(uuid:%(vdi_to_remove)s)'), locals())
VMHelper.destroy_vdi(self._session, vdi_ref)
except self.XenAPI.Failure:
# Vdi has already been deleted
LOG.debug(_("Skipping VDI destroy for %s"), vdi_to_remove)
if item['file']:
# There is also a file to remove.
if vdi_type == vm_utils.ImageType.KERNEL_STR:
kernel_file = item['file']
elif vdi_type == vm_utils.ImageType.RAMDISK_STR:
ramdisk_file = item['file']
if kernel_file or ramdisk_file:
LOG.debug(_("Removing kernel/ramdisk files from dom0"))
self._destroy_kernel_ramdisk_plugin_call(kernel_file,
ramdisk_file)
def _get_vm_opaque_ref(self, instance_or_vm):
"""
Refactored out the common code of many methods that receive either
a vm name or a vm instance, and want a vm instance in return.
"""
# if instance_or_vm is a string it must be opaque ref or instance name
if isinstance(instance_or_vm, basestring):
obj = None
try:
# check for opaque ref
obj = self._session.call_xenapi("VM.get_uuid", instance_or_vm)
return instance_or_vm
except self.XenAPI.Failure:
# wasn't an opaque ref, can be an instance name
instance_name = instance_or_vm
# if instance_or_vm is an int/long it must be instance id
elif isinstance(instance_or_vm, (int, long)):
ctx = nova_context.get_admin_context()
instance_obj = db.instance_get(ctx, instance_or_vm)
instance_name = instance_obj.name
else:
instance_name = instance_or_vm.name
vm_ref = VMHelper.lookup(self._session, instance_name)
if vm_ref is None:
raise exception.NotFound(_("No opaque_ref could be determined "
"for '%s'.") % instance_or_vm)
return vm_ref
def _acquire_bootlock(self, vm):
"""Prevent an instance from booting."""
self._session.call_xenapi(
"VM.set_blocked_operations",
vm,
{"start": ""})
def _release_bootlock(self, vm):
"""Allow an instance to boot."""
self._session.call_xenapi(
"VM.remove_from_blocked_operations",
vm,
"start")
def snapshot(self, context, instance, image_id):
"""Create snapshot from a running VM instance.
:param context: request context
:param instance: instance to be snapshotted
:param image_id: id of image to upload to
Steps involved in a XenServer snapshot:
1. XAPI-Snapshot: Snapshotting the instance using XenAPI. This
creates: Snapshot (Template) VM, Snapshot VBD, Snapshot VDI,
Snapshot VHD
2. Wait-for-coalesce: The Snapshot VDI and Instance VDI both point to
a 'base-copy' VDI. The base_copy is immutable and may be chained
with other base_copies. If chained, the base_copies
coalesce together, so, we must wait for this coalescing to occur to
get a stable representation of the data on disk.
3. Push-to-glance: Once coalesced, we call a plugin on the XenServer
that will bundle the VHDs together and then push the bundle into
Glance.
"""
template_vm_ref = None
try:
template_vm_ref, template_vdi_uuids =\
self._create_snapshot(instance)
# call plugin to ship snapshot off to glance
VMHelper.upload_image(context,
self._session, instance, template_vdi_uuids, image_id)
finally:
if template_vm_ref:
self._destroy(instance, template_vm_ref,
shutdown=False, destroy_kernel_ramdisk=False)
logging.debug(_("Finished snapshot and upload for VM %s"), instance)
def _create_snapshot(self, instance):
#TODO(sirp): Add quiesce and VSS locking support when Windows support
# is added
logging.debug(_("Starting snapshot for VM %s"), instance)
vm_ref = VMHelper.lookup(self._session, instance.name)
label = "%s-snapshot" % instance.name
try:
template_vm_ref, template_vdi_uuids = VMHelper.create_snapshot(
self._session, instance, vm_ref, label)
return template_vm_ref, template_vdi_uuids
except self.XenAPI.Failure, exc:
logging.error(_("Unable to Snapshot %(vm_ref)s: %(exc)s")
% locals())
return
def _migrate_vhd(self, instance, vdi_uuid, dest, sr_path):
instance_id = instance['id']
instance_uuid = instance['uuid']
params = {'host': dest,
'vdi_uuid': vdi_uuid,
'instance_uuid': instance_uuid,
'sr_path': sr_path}
try:
_params = {'params': pickle.dumps(params)}
task = self._session.async_call_plugin('migration',
'transfer_vhd',
_params)
self._session.wait_for_task(task, instance_uuid)
except self.XenAPI.Failure:
msg = _("Failed to transfer vhd to new host")
raise exception.MigrationError(reason=msg)
def _get_orig_vm_name_label(self, instance):
return instance.name + '-orig'
def _update_instance_progress(self, context, instance, step, total_steps):
"""Update instance progress percent to reflect current step number
"""
# FIXME(sirp): for now we're taking a KISS approach to instance
# progress:
# Divide the action's workflow into discrete steps and "bump" the
# instance's progress field as each step is completed.
#
# For a first cut this should be fine, however, for large VM images,
# the _create_disks step begins to dominate the equation. A
# better approximation would use the percentage of the VM image that
# has been streamed to the destination host.
progress = round(float(step) / total_steps * 100)
instance_uuid = instance['uuid']
LOG.debug(_("Updating instance '%(instance_uuid)s' progress to"
" %(progress)d") % locals())
db.instance_update(context, instance_uuid, {'progress': progress})
def migrate_disk_and_power_off(self, context, instance, dest,
instance_type):
"""Copies a VHD from one host machine to another, possibly
resizing filesystem before hand.
:param instance: the instance that owns the VHD in question.
:param dest: the destination host machine.
:param disk_type: values are 'primary' or 'cow'.
"""
# 0. Zero out the progress to begin
self._update_instance_progress(context, instance,
step=0,
total_steps=RESIZE_TOTAL_STEPS)
vm_ref = VMHelper.lookup(self._session, instance.name)
# The primary VDI becomes the COW after the snapshot, and we can
# identify it via the VBD. The base copy is the parent_uuid returned
# from the snapshot creation
base_copy_uuid = cow_uuid = None
template_vdi_uuids = template_vm_ref = None
try:
# 1. Create Snapshot
template_vm_ref, template_vdi_uuids =\
self._create_snapshot(instance)
self._update_instance_progress(context, instance,
step=1,
total_steps=RESIZE_TOTAL_STEPS)
base_copy_uuid = template_vdi_uuids['image']
vdi_ref, vm_vdi_rec = \
VMHelper.get_vdi_for_vm_safely(self._session, vm_ref)
cow_uuid = vm_vdi_rec['uuid']
sr_path = VMHelper.get_sr_path(self._session)
if instance['auto_disk_config'] and \
instance['local_gb'] > instance_type['local_gb']:
# Resizing disk storage down
old_gb = instance['local_gb']
new_gb = instance_type['local_gb']
LOG.debug(_("Resizing down VDI %(cow_uuid)s from "
"%(old_gb)dGB to %(new_gb)dGB") % locals())
# 2. Power down the instance before resizing
self._shutdown(instance, vm_ref, hard=False)
self._update_instance_progress(context, instance,
step=2,
total_steps=RESIZE_TOTAL_STEPS)
# 3. Copy VDI, resize partition and filesystem, forget VDI,
# truncate VHD
new_ref, new_uuid = VMHelper.resize_disk(self._session,
vdi_ref,
instance_type)
self._update_instance_progress(context, instance,
step=3,
total_steps=RESIZE_TOTAL_STEPS)
# 4. Transfer the new VHD
self._migrate_vhd(instance, new_uuid, dest, sr_path)
self._update_instance_progress(context, instance,
step=4,
total_steps=RESIZE_TOTAL_STEPS)
# Clean up VDI now that it's been copied
VMHelper.destroy_vdi(self._session, new_ref)
vdis = {'base_copy': new_uuid}
else:
# Resizing disk storage up, will be handled on destination
# As an optimization, we transfer the base VDI first,
# then shut down the VM, followed by transfering the COW
# VDI.
# 2. Transfer the base copy
self._migrate_vhd(instance, base_copy_uuid, dest, sr_path)
self._update_instance_progress(context, instance,
step=2,
total_steps=RESIZE_TOTAL_STEPS)
# 3. Now power down the instance
self._shutdown(instance, vm_ref, hard=False)
self._update_instance_progress(context, instance,
step=3,
total_steps=RESIZE_TOTAL_STEPS)
# 4. Transfer the COW VHD
self._migrate_vhd(instance, cow_uuid, dest, sr_path)
self._update_instance_progress(context, instance,
step=4,
total_steps=RESIZE_TOTAL_STEPS)
# TODO(mdietz): we could also consider renaming these to
# something sensible so we don't need to blindly pass
# around dictionaries
vdis = {'base_copy': base_copy_uuid, 'cow': cow_uuid}
# NOTE(sirp): in case we're resizing to the same host (for dev
# purposes), apply a suffix to name-label so the two VM records
# extant until a confirm_resize don't collide.
name_label = self._get_orig_vm_name_label(instance)
VMHelper.set_vm_name_label(self._session, vm_ref, name_label)
finally:
if template_vm_ref:
self._destroy(instance, template_vm_ref,
shutdown=False, destroy_kernel_ramdisk=False)
return vdis
def _move_disks(self, instance, disk_info):
"""Move and possibly link VHDs via the XAPI plugin."""
base_copy_uuid = disk_info['base_copy']
new_base_copy_uuid = str(uuid.uuid4())
params = {'instance_uuid': instance['uuid'],
'sr_path': VMHelper.get_sr_path(self._session),
'old_base_copy_uuid': base_copy_uuid,
'new_base_copy_uuid': new_base_copy_uuid}
if 'cow' in disk_info:
cow_uuid = disk_info['cow']
new_cow_uuid = str(uuid.uuid4())
params['old_cow_uuid'] = cow_uuid
params['new_cow_uuid'] = new_cow_uuid
new_uuid = new_cow_uuid
else:
new_uuid = new_base_copy_uuid
task = self._session.async_call_plugin('migration',
'move_vhds_into_sr', {'params': pickle.dumps(params)})
self._session.wait_for_task(task, instance['uuid'])
# Now we rescan the SR so we find the VHDs
VMHelper.scan_default_sr(self._session)
# Set name-label so we can find if we need to clean up a failed
# migration
VMHelper.set_vdi_name_label(self._session, new_uuid,
instance.name)
return new_uuid
def _resize_instance(self, instance, vdi_uuid):
"""Resize a running instance by changing its disk size."""
#TODO(mdietz): this will need to be adjusted for swap later
new_disk_size = instance.local_gb * 1024 * 1024 * 1024
if not new_disk_size:
return
# Get current size of VDI
vdi_ref = self._session.call_xenapi('VDI.get_by_uuid', vdi_uuid)
virtual_size = self._session.call_xenapi('VDI.get_virtual_size',
vdi_ref)
virtual_size = int(virtual_size)
instance_name = instance.name
old_gb = virtual_size / (1024 * 1024 * 1024)
new_gb = instance.local_gb
if virtual_size < new_disk_size:
# Resize up. Simple VDI resize will do the trick
LOG.debug(_("Resizing up VDI %(vdi_uuid)s from %(old_gb)dGB to "
"%(new_gb)dGB") % locals())
if self._product_version[0] > 5:
resize_func_name = 'VDI.resize'
else:
resize_func_name = 'VDI.resize_online'
self._session.call_xenapi(resize_func_name, vdi_ref,
str(new_disk_size))
LOG.debug(_("Resize instance %s complete") % (instance.name))
def reboot(self, instance, reboot_type):
"""Reboot VM instance."""
# Note (salvatore-orlando): security group rules are not re-enforced
# upon reboot, since this action on the XenAPI drivers does not
# remove existing filters
vm_ref = self._get_vm_opaque_ref(instance)
if reboot_type == "HARD":
task = self._session.call_xenapi('Async.VM.hard_reboot', vm_ref)
else:
task = self._session.call_xenapi('Async.VM.clean_reboot', vm_ref)
self._session.wait_for_task(task, instance['uuid'])
def get_agent_version(self, instance):
"""Get the version of the agent running on the VM instance."""
# The agent can be slow to start for a variety of reasons. On Windows,
# it will generally perform a setup process on first boot that can
# take a couple of minutes and then reboot. On Linux, the system can
# also take a while to boot. So we need to be more patient than
# normal as well as watch for domid changes
def _call():
# Send the encrypted password
transaction_id = str(uuid.uuid4())
args = {'id': transaction_id}
resp = self._make_agent_call('version', instance, '', args)
if resp['returncode'] != '0':
LOG.error(_('Failed to query agent version: %(resp)r') %
locals())
return None
# Some old versions of the Windows agent have a trailing \\r\\n
# (ie CRLF escaped) for some reason. Strip that off.
return resp['message'].replace('\\r\\n', '')
vm_ref = self._get_vm_opaque_ref(instance)
vm_rec = self._session.call_xenapi("VM.get_record", vm_ref)
domid = vm_rec['domid']
expiration = time.time() + FLAGS.agent_version_timeout
while time.time() < expiration:
ret = _call()
if ret:
return ret
vm_rec = self._session.call_xenapi("VM.get_record", vm_ref)
if vm_rec['domid'] != domid:
LOG.info(_('domid changed from %(olddomid)s to '
'%(newdomid)s') % {
'olddomid': domid,
'newdomid': vm_rec['domid']})
domid = vm_rec['domid']
return None
def agent_update(self, instance, url, md5sum):
"""Update agent on the VM instance."""
# Send the encrypted password
transaction_id = str(uuid.uuid4())
args = {'id': transaction_id, 'url': url, 'md5sum': md5sum}
resp = self._make_agent_call('agentupdate', instance, '', args)
if resp['returncode'] != '0':
LOG.error(_('Failed to update agent: %(resp)r') % locals())
return None
return resp['message']
def set_admin_password(self, instance, new_pass):
"""Set the root/admin password on the VM instance.
This is done via an agent running on the VM. Communication between nova
and the agent is done via writing xenstore records. Since communication
is done over the XenAPI RPC calls, we need to encrypt the password.
We're using a simple Diffie-Hellman class instead of the more advanced
one in M2Crypto for compatibility with the agent code.
"""
# Need to uniquely identify this request.
key_init_transaction_id = str(uuid.uuid4())
# The simple Diffie-Hellman class is used to manage key exchange.
dh = SimpleDH()
key_init_args = {'id': key_init_transaction_id,
'pub': str(dh.get_public())}
resp = self._make_agent_call('key_init', instance, '', key_init_args)
# Successful return code from key_init is 'D0'
if resp['returncode'] != 'D0':
msg = _('Failed to exchange keys: %(resp)r') % locals()
LOG.error(msg)
raise Exception(msg)
# Some old versions of the Windows agent have a trailing \\r\\n
# (ie CRLF escaped) for some reason. Strip that off.
agent_pub = int(resp['message'].replace('\\r\\n', ''))
dh.compute_shared(agent_pub)
# Some old versions of Linux and Windows agent expect trailing \n
# on password to work correctly.
enc_pass = dh.encrypt(new_pass + '\n')
# Send the encrypted password
password_transaction_id = str(uuid.uuid4())
password_args = {'id': password_transaction_id, 'enc_pass': enc_pass}
resp = self._make_agent_call('password', instance, '', password_args)
# Successful return code from password is '0'
if resp['returncode'] != '0':
msg = _('Failed to update password: %(resp)r') % locals()
LOG.error(msg)
raise Exception(msg)
return resp['message']
def inject_file(self, instance, path, contents):
"""Write a file to the VM instance.
The path to which it is to be written and the contents of the file
need to be supplied; both will be base64-encoded to prevent errors
with non-ASCII characters being transmitted. If the agent does not
support file injection, or the user has disabled it, a
NotImplementedError will be raised.
"""
# Files/paths must be base64-encoded for transmission to agent
b64_path = base64.b64encode(path)
b64_contents = base64.b64encode(contents)
# Need to uniquely identify this request.
transaction_id = str(uuid.uuid4())
args = {'id': transaction_id, 'b64_path': b64_path,
'b64_contents': b64_contents}
# If the agent doesn't support file injection, a NotImplementedError
# will be raised with the appropriate message.
resp = self._make_agent_call('inject_file', instance, '', args)
if resp['returncode'] != '0':
LOG.error(_('Failed to inject file: %(resp)r') % locals())
return None
return resp['message']
def _shutdown(self, instance, vm_ref, hard=True):
"""Shutdown an instance."""
state = self.get_info(instance['name'])['state']
if state == power_state.SHUTDOWN:
instance_name = instance.name
LOG.warn(_("VM %(instance_name)s already halted,"
"skipping shutdown...") % locals())
return
instance_uuid = instance['uuid']
LOG.debug(_("Shutting down VM for Instance %(instance_uuid)s")
% locals())
try:
task = None
if hard:
task = self._session.call_xenapi("Async.VM.hard_shutdown",
vm_ref)
else:
task = self._session.call_xenapi("Async.VM.clean_shutdown",
vm_ref)
self._session.wait_for_task(task, instance['uuid'])