/
vmops.py
2168 lines (1912 loc) · 101 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
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 VMware, Inc.
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack Foundation
#
# 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.
"""
Class for VM tasks like spawn, snapshot, suspend, resume etc.
"""
import collections
import os
import re
import time
import decorator
from oslo_concurrency import lockutils
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import excutils
from oslo_utils import strutils
from oslo_utils import units
from oslo_utils import uuidutils
from oslo_vmware import exceptions as vexc
from oslo_vmware.objects import datastore as ds_obj
from oslo_vmware import vim_util as vutil
from nova.api.metadata import base as instance_metadata
from nova.compute import api as compute
from nova.compute import power_state
from nova.compute import task_states
import nova.conf
from nova.console import type as ctype
from nova import context as nova_context
from nova import exception
from nova.i18n import _
from nova.network import neutron
from nova import objects
from nova.objects import fields
from nova import utils
from nova import version
from nova.virt import configdrive
from nova.virt import driver
from nova.virt import hardware
from nova.virt.vmwareapi import constants
from nova.virt.vmwareapi import ds_util
from nova.virt.vmwareapi import error_util
from nova.virt.vmwareapi import imagecache
from nova.virt.vmwareapi import images
from nova.virt.vmwareapi import vif as vmwarevif
from nova.virt.vmwareapi import vim_util
from nova.virt.vmwareapi import vm_util
CONF = nova.conf.CONF
LOG = logging.getLogger(__name__)
RESIZE_TOTAL_STEPS = 6
class VirtualMachineInstanceConfigInfo(object):
"""Parameters needed to create and configure a new instance."""
def __init__(self, instance, image_info, datastore, dc_info, image_cache,
extra_specs=None):
# Some methods called during spawn take the instance parameter purely
# for logging purposes.
# TODO(vui) Clean them up, so we no longer need to keep this variable
self.instance = instance
self.ii = image_info
self.root_gb = instance.flavor.root_gb
self.datastore = datastore
self.dc_info = dc_info
self._image_cache = image_cache
self._extra_specs = extra_specs
@property
def cache_image_folder(self):
if self.ii.image_id is None:
return
return self._image_cache.get_image_cache_folder(
self.datastore, self.ii.image_id)
@property
def cache_image_path(self):
if self.ii.image_id is None:
return
cached_image_file_name = "%s.%s" % (self.ii.image_id,
self.ii.file_type)
return self.cache_image_folder.join(cached_image_file_name)
# Note(vui): See https://bugs.launchpad.net/nova/+bug/1363349
# for cases where mocking time.sleep() can have unintended effects on code
# not under test. For now, unblock the affected test cases by providing
# a wrapper function to work around needing to mock time.sleep()
def _time_sleep_wrapper(delay):
time.sleep(delay)
@decorator.decorator
def retry_if_task_in_progress(f, *args, **kwargs):
retries = max(CONF.vmware.api_retry_count, 1)
delay = 1
for attempt in range(1, retries + 1):
if attempt != 1:
_time_sleep_wrapper(delay)
delay = min(2 * delay, 60)
try:
f(*args, **kwargs)
return
except vexc.TaskInProgress:
pass
class VMwareVMOps(object):
"""Management class for VM-related tasks."""
def __init__(self, session, virtapi, volumeops, cluster=None,
datastore_regex=None):
"""Initializer."""
self.compute_api = compute.API()
self._session = session
self._virtapi = virtapi
self._volumeops = volumeops
self._cluster = cluster
self._root_resource_pool = vm_util.get_res_pool_ref(self._session,
self._cluster)
self._datastore_regex = datastore_regex
self._base_folder = self._get_base_folder()
self._tmp_folder = 'vmware_temp'
self._datastore_browser_mapping = {}
self._imagecache = imagecache.ImageCacheManager(self._session,
self._base_folder)
self._network_api = neutron.API()
def _get_base_folder(self):
# Enable more than one compute node to run on the same host
if CONF.vmware.cache_prefix:
base_folder = '%s%s' % (CONF.vmware.cache_prefix,
CONF.image_cache.subdirectory_name)
# Ensure that the base folder is unique per compute node
elif CONF.image_cache.remove_unused_base_images:
base_folder = '%s%s' % (CONF.my_ip,
CONF.image_cache.subdirectory_name)
else:
# Aging disable ensures backward compatibility
base_folder = CONF.image_cache.subdirectory_name
return base_folder
def _extend_virtual_disk(self, instance, requested_size, name, dc_ref):
service_content = self._session.vim.service_content
LOG.debug("Extending root virtual disk to %s", requested_size,
instance=instance)
vmdk_extend_task = self._session._call_method(
self._session.vim,
"ExtendVirtualDisk_Task",
service_content.virtualDiskManager,
name=name,
datacenter=dc_ref,
newCapacityKb=requested_size,
eagerZero=False)
try:
self._session._wait_for_task(vmdk_extend_task)
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error('Extending virtual disk failed with error: %s',
e, instance=instance)
# Clean up files created during the extend operation
files = [name.replace(".vmdk", "-flat.vmdk"), name]
for file in files:
ds_path = ds_obj.DatastorePath.parse(file)
self._delete_datastore_file(ds_path, dc_ref)
LOG.debug("Extended root virtual disk", instance=instance)
def _delete_datastore_file(self, datastore_path, dc_ref):
try:
ds_util.file_delete(self._session, datastore_path, dc_ref)
except (vexc.CannotDeleteFileException,
vexc.FileFaultException,
vexc.FileLockedException,
vexc.FileNotFoundException):
LOG.debug("Unable to delete %(ds)s. There may be more than "
"one process or thread trying to delete the file",
{'ds': datastore_path},
exc_info=True)
def _extend_if_required(self, dc_info, image_info, instance,
root_vmdk_path):
"""Increase the size of the root vmdk if necessary."""
if instance.flavor.root_gb * units.Gi > image_info.file_size:
size_in_kb = instance.flavor.root_gb * units.Mi
self._extend_virtual_disk(instance, size_in_kb,
root_vmdk_path, dc_info.ref)
def _configure_config_drive(self, context, instance, vm_ref, dc_info,
datastore, injected_files, admin_password,
network_info):
session_vim = self._session.vim
cookies = session_vim.client.options.transport.cookiejar
dc_path = vutil.get_inventory_path(session_vim, dc_info.ref)
uploaded_iso_path = self._create_config_drive(context,
instance,
injected_files,
admin_password,
network_info,
datastore.name,
dc_path,
instance.uuid,
cookies)
uploaded_iso_path = datastore.build_path(uploaded_iso_path)
self._attach_cdrom_to_vm(
vm_ref, instance,
datastore.ref,
str(uploaded_iso_path))
def _get_instance_metadata(self, context, instance, flavor=None):
if not flavor:
flavor = instance.flavor
metadata = [('name', instance.display_name),
('userid', context.user_id),
('username', context.user_name),
('projectid', context.project_id),
('projectname', context.project_name),
('flavor:name', flavor.name),
('flavor:memory_mb', flavor.memory_mb),
('flavor:vcpus', flavor.vcpus),
('flavor:ephemeral_gb', flavor.ephemeral_gb),
('flavor:root_gb', flavor.root_gb),
('flavor:swap', flavor.swap),
('imageid', instance.image_ref),
('package', version.version_string_with_package())]
# NOTE: formatted as lines like this: 'name:NAME\nuserid:ID\n...'
return ''.join(['%s:%s\n' % (k, v) for k, v in metadata])
def _create_folders(self, parent_folder, folder_path):
folders = folder_path.split('/')
path_list = []
for folder in folders:
path_list.append(folder)
folder_path = '/'.join(path_list)
folder_ref = vm_util.folder_ref_cache_get(folder_path)
if not folder_ref:
folder_ref = vm_util.create_folder(self._session,
parent_folder,
folder)
vm_util.folder_ref_cache_update(folder_path, folder_ref)
parent_folder = folder_ref
return folder_ref
def _get_folder_name(self, name, id):
# Maximum folder length must be less than 80 characters.
# The 'id' length is 36. The maximum prefix for name is 40.
# We cannot truncate the 'id' as this is unique across OpenStack.
return '%s (%s)' % (name[:40], id[:36])
def build_virtual_machine(self, instance, image_info,
dc_info, datastore, network_info, extra_specs,
metadata):
vif_infos = vmwarevif.get_vif_info(self._session,
self._cluster,
image_info.vif_model,
network_info)
LOG.debug('Instance VIF info %s', vif_infos, instance=instance)
if extra_specs.storage_policy:
profile_spec = vm_util.get_storage_profile_spec(
self._session, extra_specs.storage_policy)
else:
profile_spec = None
# Get the create vm config spec
client_factory = self._session.vim.client.factory
config_spec = vm_util.get_vm_create_spec(client_factory,
instance,
datastore.name,
vif_infos,
extra_specs,
image_info.os_type,
profile_spec=profile_spec,
metadata=metadata)
folder_name = self._get_folder_name('Project',
instance.project_id)
folder_path = 'OpenStack/%s/Instances' % folder_name
folder = self._create_folders(dc_info.vmFolder, folder_path)
# Create the VM
vm_ref = vm_util.create_vm(self._session, instance, folder,
config_spec, self._root_resource_pool)
return vm_ref
def _get_extra_specs(self, flavor, image_meta=None):
image_meta = image_meta or objects.ImageMeta.from_dict({})
extra_specs = vm_util.ExtraSpecs()
for resource in ['cpu', 'memory', 'disk_io', 'vif']:
for (key, type) in (('limit', int),
('reservation', int),
('shares_level', str),
('shares_share', int)):
value = flavor.extra_specs.get('quota:' + resource + '_' + key)
if value:
setattr(getattr(extra_specs, resource + '_limits'),
key, type(value))
extra_specs.cpu_limits.validate()
extra_specs.memory_limits.validate()
extra_specs.disk_io_limits.validate()
extra_specs.vif_limits.validate()
hw_firmware_type = image_meta.properties.get('hw_firmware_type')
if hw_firmware_type == fields.FirmwareType.UEFI:
extra_specs.firmware = 'efi'
elif hw_firmware_type == fields.FirmwareType.BIOS:
extra_specs.firmware = 'bios'
hw_version = flavor.extra_specs.get('vmware:hw_version')
extra_specs.hw_version = hw_version
video_ram = image_meta.properties.get('hw_video_ram', 0)
max_vram = int(flavor.extra_specs.get('hw_video:ram_max_mb', 0))
if video_ram > max_vram:
raise exception.RequestedVRamTooHigh(req_vram=video_ram,
max_vram=max_vram)
if video_ram and max_vram:
extra_specs.hw_video_ram = video_ram * units.Mi / units.Ki
if CONF.vmware.pbm_enabled:
storage_policy = flavor.extra_specs.get('vmware:storage_policy',
CONF.vmware.pbm_default_policy)
extra_specs.storage_policy = storage_policy
topology = hardware.get_best_cpu_topology(flavor, image_meta,
allow_threads=False)
extra_specs.cores_per_socket = topology.cores
return extra_specs
def _get_esx_host_and_cookies(self, datastore, dc_path, file_path):
hosts = datastore.get_connected_hosts(self._session)
host = ds_obj.Datastore.choose_host(hosts)
host_name = self._session._call_method(vutil, 'get_object_property',
host, 'name')
url = ds_obj.DatastoreURL('https', host_name, file_path, dc_path,
datastore.name)
cookie_header = url.get_transfer_ticket(self._session, 'PUT')
name, value = cookie_header.split('=')
# TODO(rgerganov): this is a hack to emulate cookiejar until we fix
# oslo.vmware to accept plain http headers
Cookie = collections.namedtuple('Cookie', ['name', 'value'])
return host_name, [Cookie(name, value)]
def _fetch_vsphere_image(self, context, vi, image_ds_loc):
"""Fetch image which is located on a vSphere datastore."""
location = vi.ii.vsphere_location
LOG.debug("Using vSphere location: %s", location)
LOG.debug("Copying image file data %(image_id)s to "
"%(file_path)s on the data store "
"%(datastore_name)s",
{'image_id': vi.ii.image_id,
'file_path': image_ds_loc,
'datastore_name': vi.datastore.name},
instance=vi.instance)
location_url = ds_obj.DatastoreURL.urlparse(location)
datacenter_path = location_url.datacenter_path
datacenter_moref = ds_util.get_datacenter_ref(
self._session, datacenter_path)
datastore_name = location_url.datastore_name
src_path = ds_obj.DatastorePath(datastore_name, location_url.path)
ds_util.file_copy(
self._session, str(src_path), datacenter_moref,
str(image_ds_loc), vi.dc_info.ref)
LOG.debug("Copied image file data %(image_id)s to "
"%(file_path)s on the data store "
"%(datastore_name)s",
{'image_id': vi.ii.image_id,
'file_path': image_ds_loc,
'datastore_name': vi.datastore.name},
instance=vi.instance)
def _fetch_image_as_file(self, context, vi, image_ds_loc):
"""Download image as an individual file to host via HTTP PUT."""
session = self._session
LOG.debug("Downloading image file data %(image_id)s to "
"%(file_path)s on the data store "
"%(datastore_name)s",
{'image_id': vi.ii.image_id,
'file_path': image_ds_loc,
'datastore_name': vi.datastore.name},
instance=vi.instance)
# try to get esx cookie to upload
try:
dc_path = 'ha-datacenter'
host, cookies = self._get_esx_host_and_cookies(vi.datastore,
dc_path, image_ds_loc.rel_path)
except Exception as e:
LOG.warning("Get esx cookies failed: %s", e,
instance=vi.instance)
dc_path = vutil.get_inventory_path(session.vim, vi.dc_info.ref)
host = self._session._host
cookies = session.vim.client.options.transport.cookiejar
images.fetch_image(
context,
vi.instance,
host,
session._port,
dc_path,
vi.datastore.name,
image_ds_loc.rel_path,
cookies=cookies)
def _fetch_image_as_vapp(self, context, vi, image_ds_loc):
"""Download stream optimized image to host as a vApp."""
# The directory of the imported disk is the unique name
# of the VM use to import it with.
vm_name = image_ds_loc.parent.basename
LOG.debug("Downloading stream optimized image %(image_id)s to "
"%(file_path)s on the data store "
"%(datastore_name)s as vApp",
{'image_id': vi.ii.image_id,
'file_path': image_ds_loc,
'datastore_name': vi.datastore.name},
instance=vi.instance)
image_size = images.fetch_image_stream_optimized(
context,
vi.instance,
self._session,
vm_name,
vi.datastore.name,
vi.dc_info.vmFolder,
self._root_resource_pool)
# The size of the image is different from the size of the virtual disk.
# We want to use the latter. On vSAN this is the only way to get this
# size because there is no VMDK descriptor.
vi.ii.file_size = image_size
def _fetch_image_as_ova(self, context, vi, image_ds_loc):
"""Download root disk of an OVA image as streamOptimized."""
# The directory of the imported disk is the unique name
# of the VM use to import it with.
vm_name = image_ds_loc.parent.basename
image_size = images.fetch_image_ova(context,
vi.instance,
self._session,
vm_name,
vi.datastore.name,
vi.dc_info.vmFolder,
self._root_resource_pool)
# The size of the image is different from the size of the virtual disk.
# We want to use the latter. On vSAN this is the only way to get this
# size because there is no VMDK descriptor.
vi.ii.file_size = image_size
def _prepare_sparse_image(self, vi):
tmp_dir_loc = vi.datastore.build_path(
self._tmp_folder, uuidutils.generate_uuid())
tmp_image_ds_loc = tmp_dir_loc.join(
vi.ii.image_id, "tmp-sparse.vmdk")
ds_util.mkdir(self._session, tmp_image_ds_loc.parent, vi.dc_info.ref)
return tmp_dir_loc, tmp_image_ds_loc
def _prepare_flat_image(self, vi):
tmp_dir_loc = vi.datastore.build_path(
self._tmp_folder, uuidutils.generate_uuid())
tmp_image_ds_loc = tmp_dir_loc.join(
vi.ii.image_id, vi.cache_image_path.basename)
ds_util.mkdir(self._session, tmp_image_ds_loc.parent, vi.dc_info.ref)
vm_util.create_virtual_disk(
self._session, vi.dc_info.ref,
vi.ii.adapter_type,
vi.ii.disk_type,
str(tmp_image_ds_loc),
vi.ii.file_size_in_kb)
flat_vmdk_name = vi.cache_image_path.basename.replace('.vmdk',
'-flat.vmdk')
flat_vmdk_ds_loc = tmp_dir_loc.join(vi.ii.image_id, flat_vmdk_name)
self._delete_datastore_file(str(flat_vmdk_ds_loc), vi.dc_info.ref)
return tmp_dir_loc, flat_vmdk_ds_loc
def _prepare_stream_optimized_image(self, vi):
vm_name = "%s_%s" % (constants.IMAGE_VM_PREFIX,
uuidutils.generate_uuid())
tmp_dir_loc = vi.datastore.build_path(vm_name)
tmp_image_ds_loc = tmp_dir_loc.join("%s.vmdk" % tmp_dir_loc.basename)
return tmp_dir_loc, tmp_image_ds_loc
def _prepare_iso_image(self, vi):
tmp_dir_loc = vi.datastore.build_path(
self._tmp_folder, uuidutils.generate_uuid())
tmp_image_ds_loc = tmp_dir_loc.join(
vi.ii.image_id, vi.cache_image_path.basename)
return tmp_dir_loc, tmp_image_ds_loc
def _move_to_cache(self, dc_ref, src_folder_ds_path, dst_folder_ds_path):
try:
ds_util.file_move(self._session, dc_ref,
src_folder_ds_path, dst_folder_ds_path)
except vexc.FileAlreadyExistsException:
# Folder move has failed. This may be due to the fact that a
# process or thread has already completed the operation.
# Since image caching is synchronized, this can only happen
# due to action external to the process.
# In the event of a FileAlreadyExists we continue,
# all other exceptions will be raised.
LOG.warning("Destination %s already exists! Concurrent moves "
"can lead to unexpected results.",
dst_folder_ds_path)
def _cache_sparse_image(self, vi, tmp_image_ds_loc):
tmp_dir_loc = tmp_image_ds_loc.parent.parent
converted_image_ds_loc = tmp_dir_loc.join(
vi.ii.image_id, vi.cache_image_path.basename)
# converts fetched image to preallocated disk
vm_util.copy_virtual_disk(
self._session,
vi.dc_info.ref,
str(tmp_image_ds_loc),
str(converted_image_ds_loc))
self._delete_datastore_file(str(tmp_image_ds_loc), vi.dc_info.ref)
self._move_to_cache(vi.dc_info.ref,
tmp_image_ds_loc.parent,
vi.cache_image_folder)
def _cache_flat_image(self, vi, tmp_image_ds_loc):
self._move_to_cache(vi.dc_info.ref,
tmp_image_ds_loc.parent,
vi.cache_image_folder)
def _cache_stream_optimized_image(self, vi, tmp_image_ds_loc):
dst_path = vi.cache_image_folder.join("%s.vmdk" % vi.ii.image_id)
ds_util.mkdir(self._session, vi.cache_image_folder, vi.dc_info.ref)
try:
ds_util.disk_move(self._session, vi.dc_info.ref,
tmp_image_ds_loc, dst_path)
except vexc.FileAlreadyExistsException:
pass
def _cache_iso_image(self, vi, tmp_image_ds_loc):
self._move_to_cache(vi.dc_info.ref,
tmp_image_ds_loc.parent,
vi.cache_image_folder)
def _get_vm_config_info(self, instance, image_info,
extra_specs):
"""Captures all relevant information from the spawn parameters."""
if (instance.flavor.root_gb != 0 and
image_info.file_size > instance.flavor.root_gb * units.Gi):
reason = _("Image disk size greater than requested disk size")
raise exception.InstanceUnacceptable(instance_id=instance.uuid,
reason=reason)
allowed_ds_types = ds_util.get_allowed_datastore_types(
image_info.disk_type)
datastore = ds_util.get_datastore(self._session,
self._cluster,
self._datastore_regex,
extra_specs.storage_policy,
allowed_ds_types)
dc_info = self.get_datacenter_ref_and_name(datastore.ref)
return VirtualMachineInstanceConfigInfo(instance,
image_info,
datastore,
dc_info,
self._imagecache,
extra_specs)
def _get_image_callbacks(self, vi):
disk_type = vi.ii.disk_type
if vi.ii.is_ova:
image_fetch = self._fetch_image_as_ova
elif disk_type == constants.DISK_TYPE_STREAM_OPTIMIZED:
image_fetch = self._fetch_image_as_vapp
elif vi.ii.vsphere_location:
image_fetch = self._fetch_vsphere_image
else:
image_fetch = self._fetch_image_as_file
if vi.ii.is_iso:
image_prepare = self._prepare_iso_image
image_cache = self._cache_iso_image
elif disk_type == constants.DISK_TYPE_SPARSE:
image_prepare = self._prepare_sparse_image
image_cache = self._cache_sparse_image
elif disk_type == constants.DISK_TYPE_STREAM_OPTIMIZED:
image_prepare = self._prepare_stream_optimized_image
image_cache = self._cache_stream_optimized_image
elif disk_type in constants.SUPPORTED_FLAT_VARIANTS:
image_prepare = self._prepare_flat_image
image_cache = self._cache_flat_image
else:
reason = _("disk type '%s' not supported") % disk_type
raise exception.InvalidDiskInfo(reason=reason)
return image_prepare, image_fetch, image_cache
def _fetch_image_if_missing(self, context, vi):
image_prepare, image_fetch, image_cache = self._get_image_callbacks(vi)
LOG.debug("Processing image %s", vi.ii.image_id, instance=vi.instance)
with lockutils.lock(str(vi.cache_image_path),
lock_file_prefix='nova-vmware-fetch_image'):
self.check_cache_folder(vi.datastore.name, vi.datastore.ref)
ds_browser = self._get_ds_browser(vi.datastore.ref)
if not ds_util.file_exists(self._session, ds_browser,
vi.cache_image_folder,
vi.cache_image_path.basename):
LOG.debug("Preparing fetch location", instance=vi.instance)
tmp_dir_loc, tmp_image_ds_loc = image_prepare(vi)
LOG.debug("Fetch image to %s", tmp_image_ds_loc,
instance=vi.instance)
image_fetch(context, vi, tmp_image_ds_loc)
LOG.debug("Caching image", instance=vi.instance)
image_cache(vi, tmp_image_ds_loc)
LOG.debug("Cleaning up location %s", str(tmp_dir_loc),
instance=vi.instance)
self._delete_datastore_file(str(tmp_dir_loc), vi.dc_info.ref)
# The size of the sparse image is different from the size of the
# virtual disk. We want to use the latter.
if vi.ii.disk_type == constants.DISK_TYPE_SPARSE:
self._update_image_size(vi)
def _create_and_attach_thin_disk(self, instance, vm_ref, dc_info, size,
adapter_type, path):
disk_type = constants.DISK_TYPE_THIN
vm_util.create_virtual_disk(
self._session, dc_info.ref,
adapter_type,
disk_type,
path,
size)
self._volumeops.attach_disk_to_vm(
vm_ref, instance,
adapter_type, disk_type,
path, size, False)
def _create_ephemeral(self, bdi, instance, vm_ref, dc_info,
datastore, folder, adapter_type):
ephemerals = None
if bdi is not None:
ephemerals = driver.block_device_info_get_ephemerals(bdi)
for idx, eph in enumerate(ephemerals):
size = eph['size'] * units.Mi
at = eph.get('disk_bus') or adapter_type
filename = vm_util.get_ephemeral_name(idx)
path = str(ds_obj.DatastorePath(datastore.name, folder,
filename))
self._create_and_attach_thin_disk(instance, vm_ref, dc_info,
size, at, path)
# There may be block devices defined but no ephemerals. In this case
# we need to allocate an ephemeral disk if required
if not ephemerals and instance.flavor.ephemeral_gb:
size = instance.flavor.ephemeral_gb * units.Mi
filename = vm_util.get_ephemeral_name(0)
path = str(ds_obj.DatastorePath(datastore.name, folder,
filename))
self._create_and_attach_thin_disk(instance, vm_ref, dc_info, size,
adapter_type, path)
def _create_swap(self, bdi, instance, vm_ref, dc_info, datastore,
folder, adapter_type):
swap = None
filename = "swap.vmdk"
path = str(ds_obj.DatastorePath(datastore.name, folder, filename))
if bdi is not None:
swap = driver.block_device_info_get_swap(bdi)
if driver.swap_is_usable(swap):
size = swap['swap_size'] * units.Ki
self._create_and_attach_thin_disk(instance, vm_ref, dc_info,
size, adapter_type, path)
else:
# driver.block_device_info_get_swap returns
# {'device_name': None, 'swap_size': 0} if swap is None
# in block_device_info. If block_device_info does not contain
# a swap device, we need to reset swap to None, so we can
# extract the swap_size from the instance's flavor.
swap = None
size = instance.flavor.swap * units.Ki
if not swap and size > 0:
self._create_and_attach_thin_disk(instance, vm_ref, dc_info, size,
adapter_type, path)
def _update_vnic_index(self, context, instance, network_info):
if network_info:
for index, vif in enumerate(network_info):
self._network_api.update_instance_vnic_index(
context, instance, vif, index)
def _update_image_size(self, vi):
"""Updates the file size of the specified image."""
# The size of the Glance image is different from the deployed VMDK
# size for sparse, streamOptimized and OVA images. We need to retrieve
# the size of the flat VMDK and update the file_size property of the
# image. This ensures that further operations involving size checks
# and disk resizing will work as expected.
ds_browser = self._get_ds_browser(vi.datastore.ref)
flat_file = "%s-flat.vmdk" % vi.ii.image_id
new_size = ds_util.file_size(self._session, ds_browser,
vi.cache_image_folder, flat_file)
if new_size is not None:
vi.ii.file_size = new_size
def spawn(self, context, instance, image_meta, injected_files,
admin_password, network_info, block_device_info=None):
client_factory = self._session.vim.client.factory
image_info = images.VMwareImage.from_image(context,
instance.image_ref,
image_meta)
extra_specs = self._get_extra_specs(instance.flavor, image_meta)
vi = self._get_vm_config_info(instance, image_info,
extra_specs)
metadata = self._get_instance_metadata(context, instance)
# Creates the virtual machine. The virtual machine reference returned
# is unique within Virtual Center.
vm_ref = self.build_virtual_machine(instance,
image_info,
vi.dc_info,
vi.datastore,
network_info,
extra_specs,
metadata)
# Cache the vm_ref. This saves a remote call to the VC. This uses the
# instance uuid.
vm_util.vm_ref_cache_update(instance.uuid, vm_ref)
# Update the Neutron VNIC index
self._update_vnic_index(context, instance, network_info)
# Set the machine.id parameter of the instance to inject
# the NIC configuration inside the VM
if CONF.flat_injected:
self._set_machine_id(client_factory, instance, network_info,
vm_ref=vm_ref)
# Set the vnc configuration of the instance, vnc port starts from 5900
if CONF.vnc.enabled:
self._get_and_set_vnc_config(client_factory, instance, vm_ref)
block_device_mapping = []
if block_device_info is not None:
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
if instance.image_ref:
self._imagecache.enlist_image(
image_info.image_id, vi.datastore, vi.dc_info.ref)
self._fetch_image_if_missing(context, vi)
if image_info.is_iso:
self._use_iso_image(vm_ref, vi)
elif image_info.linked_clone:
self._use_disk_image_as_linked_clone(vm_ref, vi)
else:
self._use_disk_image_as_full_clone(vm_ref, vi)
if block_device_mapping:
msg = "Block device information present: %s" % block_device_info
# NOTE(mriedem): block_device_info can contain an auth_password
# so we have to scrub the message before logging it.
LOG.debug(strutils.mask_password(msg), instance=instance)
# Before attempting to attach any volume, make sure the
# block_device_mapping (i.e. disk_bus) is valid
self._is_bdm_valid(block_device_mapping)
for disk in block_device_mapping:
connection_info = disk['connection_info']
adapter_type = disk.get('disk_bus') or vi.ii.adapter_type
# TODO(hartsocks): instance is unnecessary, remove it
# we still use instance in many locations for no other purpose
# than logging, can we simplify this?
if disk.get('boot_index') == 0:
self._volumeops.attach_root_volume(connection_info,
instance, vi.datastore.ref, adapter_type)
else:
self._volumeops.attach_volume(connection_info,
instance, adapter_type)
# Create ephemeral disks
self._create_ephemeral(block_device_info, instance, vm_ref,
vi.dc_info, vi.datastore, instance.uuid,
vi.ii.adapter_type)
self._create_swap(block_device_info, instance, vm_ref, vi.dc_info,
vi.datastore, instance.uuid, vi.ii.adapter_type)
if configdrive.required_by(instance):
self._configure_config_drive(
context, instance, vm_ref, vi.dc_info, vi.datastore,
injected_files, admin_password, network_info)
# Rename the VM. This is done after the spec is created to ensure
# that all of the files for the instance are under the directory
# 'uuid' of the instance
vm_util.rename_vm(self._session, vm_ref, instance)
vm_util.power_on_instance(self._session, instance, vm_ref=vm_ref)
def _is_bdm_valid(self, block_device_mapping):
"""Checks if the block device mapping is valid."""
valid_bus = (constants.DEFAULT_ADAPTER_TYPE,
constants.ADAPTER_TYPE_BUSLOGIC,
constants.ADAPTER_TYPE_IDE,
constants.ADAPTER_TYPE_LSILOGICSAS,
constants.ADAPTER_TYPE_PARAVIRTUAL)
for disk in block_device_mapping:
adapter_type = disk.get('disk_bus')
if (adapter_type is not None and adapter_type not in valid_bus):
raise exception.UnsupportedHardware(model=adapter_type,
virt="vmware")
def _create_config_drive(self, context, instance, injected_files,
admin_password, network_info, data_store_name,
dc_name, upload_folder, cookies):
if CONF.config_drive_format != 'iso9660':
reason = (_('Invalid config_drive_format "%s"') %
CONF.config_drive_format)
raise exception.InstancePowerOnFailure(reason=reason)
LOG.info('Using config drive for instance', instance=instance)
extra_md = {}
if admin_password:
extra_md['admin_pass'] = admin_password
inst_md = instance_metadata.InstanceMetadata(instance,
content=injected_files,
extra_md=extra_md,
network_info=network_info,
request_context=context)
try:
with configdrive.ConfigDriveBuilder(instance_md=inst_md) as cdb:
with utils.tempdir() as tmp_path:
tmp_file = os.path.join(tmp_path, 'configdrive.iso')
cdb.make_drive(tmp_file)
upload_iso_path = "%s/configdrive.iso" % (
upload_folder)
images.upload_iso_to_datastore(
tmp_file, instance,
host=self._session._host,
port=self._session._port,
data_center_name=dc_name,
datastore_name=data_store_name,
cookies=cookies,
file_path=upload_iso_path)
return upload_iso_path
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error('Creating config drive failed with error: %s',
e, instance=instance)
def _attach_cdrom_to_vm(self, vm_ref, instance,
datastore, file_path):
"""Attach cdrom to VM by reconfiguration."""
client_factory = self._session.vim.client.factory
devices = self._session._call_method(vutil,
"get_object_property",
vm_ref,
"config.hardware.device")
(controller_key, unit_number,
controller_spec) = vm_util.allocate_controller_key_and_unit_number(
client_factory,
devices,
constants.ADAPTER_TYPE_IDE)
cdrom_attach_config_spec = vm_util.get_cdrom_attach_config_spec(
client_factory, datastore, file_path,
controller_key, unit_number)
if controller_spec:
cdrom_attach_config_spec.deviceChange.append(controller_spec)
LOG.debug("Reconfiguring VM instance to attach cdrom %s",
file_path, instance=instance)
vm_util.reconfigure_vm(self._session, vm_ref, cdrom_attach_config_spec)
LOG.debug("Reconfigured VM instance to attach cdrom %s",
file_path, instance=instance)
def _create_vm_snapshot(self, instance, vm_ref):
LOG.debug("Creating Snapshot of the VM instance", instance=instance)
snapshot_task = self._session._call_method(
self._session.vim,
"CreateSnapshot_Task", vm_ref,
name="%s-snapshot" % instance.uuid,
description="Taking Snapshot of the VM",
memory=False,
quiesce=True)
self._session._wait_for_task(snapshot_task)
LOG.debug("Created Snapshot of the VM instance", instance=instance)
task_info = self._session._call_method(vutil,
"get_object_property",
snapshot_task,
"info")
snapshot = task_info.result
return snapshot
@retry_if_task_in_progress
def _delete_vm_snapshot(self, instance, vm_ref, snapshot):
LOG.debug("Deleting Snapshot of the VM instance", instance=instance)
delete_snapshot_task = self._session._call_method(
self._session.vim,
"RemoveSnapshot_Task", snapshot,
removeChildren=False, consolidate=True)
self._session._wait_for_task(delete_snapshot_task)
LOG.debug("Deleted Snapshot of the VM instance", instance=instance)
def _create_linked_clone_from_snapshot(self, instance,
vm_ref, snapshot_ref, dc_info):
"""Create linked clone VM to be deployed to same ds as source VM
"""
client_factory = self._session.vim.client.factory
rel_spec = vm_util.relocate_vm_spec(
client_factory,
datastore=None,
host=None,
disk_move_type="createNewChildDiskBacking")
clone_spec = vm_util.clone_vm_spec(client_factory, rel_spec,
power_on=False, snapshot=snapshot_ref, template=True)
vm_name = "%s_%s" % (constants.SNAPSHOT_VM_PREFIX,
uuidutils.generate_uuid())
LOG.debug("Creating linked-clone VM from snapshot", instance=instance)
vm_clone_task = self._session._call_method(
self._session.vim,
"CloneVM_Task",
vm_ref,
folder=dc_info.vmFolder,
name=vm_name,
spec=clone_spec)
self._session._wait_for_task(vm_clone_task)
LOG.info("Created linked-clone VM from snapshot", instance=instance)
task_info = self._session._call_method(vutil,
"get_object_property",
vm_clone_task,
"info")
return task_info.result
def snapshot(self, context, instance, image_id, update_task_state):
"""Create snapshot from a running VM instance.
Steps followed are:
1. Get the name of the vmdk file which the VM points to right now.
Can be a chain of snapshots, so we need to know the last in the
chain.
2. Create the snapshot. A new vmdk is created which the VM points to
now. The earlier vmdk becomes read-only.
3. Creates a linked clone VM from the snapshot
4. Exports the disk in the link clone VM as a streamOptimized disk.
5. Delete the linked clone VM
6. Deletes the snapshot in original instance.
"""
vm_ref = vm_util.get_vm_ref(self._session, instance)
def _get_vm_and_vmdk_attribs():
# Get the vmdk info that the VM is pointing to
vmdk = vm_util.get_vmdk_info(self._session, vm_ref,
instance.uuid)
if not vmdk.path:
LOG.debug("No root disk defined. Unable to snapshot.",
instance=instance)
raise error_util.NoRootDiskDefined()
lst_properties = ["datastore", "summary.config.guestId"]
props = self._session._call_method(vutil,
"get_object_properties_dict",
vm_ref,
lst_properties)
os_type = props['summary.config.guestId']