/
shell.py
5478 lines (4835 loc) · 184 KB
/
shell.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 2010 Jacob Kaplan-Moss
# Copyright 2011 OpenStack Foundation
# Copyright 2013 IBM Corp.
# All Rights Reserved.
#
# 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.
from __future__ import print_function
import argparse
import codecs
import collections
import datetime
import getpass
import logging
import os
import pprint
import sys
import time
from oslo_utils import netutils
from oslo_utils import strutils
from oslo_utils import timeutils
import six
import novaclient
from novaclient import api_versions
from novaclient import base
from novaclient import client
from novaclient import exceptions
from novaclient.i18n import _
from novaclient import shell
from novaclient import utils
from novaclient.v2 import availability_zones
from novaclient.v2 import quotas
from novaclient.v2 import servers
logger = logging.getLogger(__name__)
def emit_duplicated_image_with_warning(img, image_with):
img_uuid_list = [str(image.id) for image in img]
print(_('WARNING: Multiple matching images: %(img_uuid_list)s\n'
'Using image: %(chosen_one)s') %
{'img_uuid_list': img_uuid_list,
'chosen_one': img_uuid_list[0]},
file=sys.stderr)
CLIENT_BDM2_KEYS = {
'id': 'uuid',
'source': 'source_type',
'dest': 'destination_type',
'bus': 'disk_bus',
'device': 'device_name',
'size': 'volume_size',
'format': 'guest_format',
'bootindex': 'boot_index',
'type': 'device_type',
'shutdown': 'delete_on_termination',
'tag': 'tag',
'volume_type': 'volume_type' # added in 2.67
}
def _key_value_pairing(text):
try:
(k, v) = text.split('=', 1)
return (k, v)
except ValueError:
msg = _("'%s' is not in the format of 'key=value'") % text
raise argparse.ArgumentTypeError(msg)
def _meta_parsing(metadata):
try:
return dict(v.split('=', 1) for v in metadata)
except ValueError:
msg = _("'%s' is not in the format of 'key=value'") % metadata
raise argparse.ArgumentTypeError(msg)
def _match_image(cs, wanted_properties):
image_list = cs.glance.list()
images_matched = []
match = set(wanted_properties)
for img in image_list:
img_dict = {}
# exclude any unhashable entries
for key, value in img.to_dict().items():
try:
set([key, value])
except TypeError:
pass
else:
img_dict[key] = value
if match == match.intersection(set(img_dict.items())):
images_matched.append(img)
return images_matched
def _supports_block_device_tags(cs):
if (cs.api_version == api_versions.APIVersion('2.32') or
cs.api_version >= api_versions.APIVersion('2.42')):
return True
else:
return False
def _parse_device_spec(device_spec):
spec_dict = {}
for arg in device_spec.split(','):
if '=' in arg:
spec_dict.update([arg.split('=')])
else:
raise argparse.ArgumentTypeError(
_("Expected a comma-separated list of key=value pairs. '%s' "
"is not a key=value pair.") % arg)
return spec_dict
def _parse_block_device_mapping_v2(cs, args, image):
bdm = []
if args.boot_volume:
bdm_dict = {'uuid': args.boot_volume, 'source_type': 'volume',
'destination_type': 'volume', 'boot_index': 0,
'delete_on_termination': False}
bdm.append(bdm_dict)
if args.snapshot:
bdm_dict = {'uuid': args.snapshot, 'source_type': 'snapshot',
'destination_type': 'volume', 'boot_index': 0,
'delete_on_termination': False}
bdm.append(bdm_dict)
supports_volume_type = cs.api_version == api_versions.APIVersion('2.67')
for device_spec in args.block_device:
spec_dict = _parse_device_spec(device_spec)
bdm_dict = {}
if ('tag' in spec_dict and not _supports_block_device_tags(cs)):
raise exceptions.CommandError(
_("'tag' in block device mapping is not supported "
"in API version %(version)s.")
% {'version': cs.api_version.get_string()})
if 'volume_type' in spec_dict and not supports_volume_type:
raise exceptions.CommandError(
_("'volume_type' in block device mapping is not supported "
"in API version %(version)s.")
% {'version': cs.api_version.get_string()})
for key, value in spec_dict.items():
bdm_dict[CLIENT_BDM2_KEYS[key]] = value
source_type = bdm_dict.get('source_type')
if not source_type:
bdm_dict['source_type'] = 'blank'
elif source_type not in (
'volume', 'image', 'snapshot', 'blank'):
raise exceptions.CommandError(
_("The value of source_type key of --block-device "
"should be one of 'volume', 'image', 'snapshot' "
"or 'blank' but it was '%(action)s'")
% {'action': source_type})
destination_type = bdm_dict.get('destination_type')
if not destination_type:
source_type = bdm_dict['source_type']
if source_type in ('image', 'blank'):
bdm_dict['destination_type'] = 'local'
if source_type in ('snapshot', 'volume'):
bdm_dict['destination_type'] = 'volume'
elif destination_type not in ('local', 'volume'):
raise exceptions.CommandError(
_("The value of destination_type key of --block-device "
"should be either 'local' or 'volume' but it "
"was '%(action)s'")
% {'action': destination_type})
# Convert the delete_on_termination to a boolean or set it to true by
# default for local block devices when not specified.
if 'delete_on_termination' in bdm_dict:
action = bdm_dict['delete_on_termination']
if action not in ['remove', 'preserve']:
raise exceptions.CommandError(
_("The value of shutdown key of --block-device shall be "
"either 'remove' or 'preserve' but it was '%(action)s'")
% {'action': action})
bdm_dict['delete_on_termination'] = (action == 'remove')
elif bdm_dict.get('destination_type') == 'local':
bdm_dict['delete_on_termination'] = True
bdm.append(bdm_dict)
for ephemeral_spec in args.ephemeral:
bdm_dict = {'source_type': 'blank', 'destination_type': 'local',
'boot_index': -1, 'delete_on_termination': True}
try:
eph_dict = _parse_device_spec(ephemeral_spec)
except ValueError:
err_msg = (_("Invalid ephemeral argument '%s'.") % args.ephemeral)
raise argparse.ArgumentTypeError(err_msg)
if 'size' in eph_dict:
bdm_dict['volume_size'] = eph_dict['size']
if 'format' in eph_dict:
bdm_dict['guest_format'] = eph_dict['format']
bdm.append(bdm_dict)
if args.swap:
bdm_dict = {'source_type': 'blank', 'destination_type': 'local',
'boot_index': -1, 'delete_on_termination': True,
'guest_format': 'swap', 'volume_size': args.swap}
bdm.append(bdm_dict)
return bdm
def _supports_nic_tags(cs):
if ((cs.api_version >= api_versions.APIVersion('2.32') and
cs.api_version <= api_versions.APIVersion('2.36')) or
cs.api_version >= api_versions.APIVersion('2.42')):
return True
else:
return False
def _parse_nics(cs, args):
supports_auto_alloc = cs.api_version >= api_versions.APIVersion('2.37')
supports_nic_tags = _supports_nic_tags(cs)
nic_keys = {'net-id', 'v4-fixed-ip', 'v6-fixed-ip', 'port-id', 'net-name'}
if supports_auto_alloc and supports_nic_tags:
# API version >= 2.42
nic_keys.add('tag')
err_msg = (_("Invalid nic argument '%s'. Nic arguments must be of "
"the form --nic <auto,none,net-id=net-uuid,"
"net-name=network-name,v4-fixed-ip=ip-addr,"
"v6-fixed-ip=ip-addr,port-id=port-uuid,tag=tag>, "
"with only one of net-id, net-name or port-id "
"specified. Specifying a --nic of auto or none cannot "
"be used with any other --nic value."))
elif supports_auto_alloc and not supports_nic_tags:
# 2.41 >= API version >= 2.37
err_msg = (_("Invalid nic argument '%s'. Nic arguments must be of "
"the form --nic <auto,none,net-id=net-uuid,"
"net-name=network-name,v4-fixed-ip=ip-addr,"
"v6-fixed-ip=ip-addr,port-id=port-uuid>, "
"with only one of net-id, net-name or port-id "
"specified. Specifying a --nic of auto or none cannot "
"be used with any other --nic value."))
elif not supports_auto_alloc and supports_nic_tags:
# 2.36 >= API version >= 2.32
nic_keys.add('tag')
err_msg = (_("Invalid nic argument '%s'. Nic arguments must be of "
"the form --nic <net-id=net-uuid,"
"net-name=network-name,v4-fixed-ip=ip-addr,"
"v6-fixed-ip=ip-addr,port-id=port-uuid,tag=tag>, "
"with only one of net-id, net-name or port-id "
"specified."))
else:
# API version <= 2.31
err_msg = (_("Invalid nic argument '%s'. Nic arguments must be of "
"the form --nic <net-id=net-uuid,"
"net-name=network-name,v4-fixed-ip=ip-addr,"
"v6-fixed-ip=ip-addr,port-id=port-uuid>, "
"with only one of net-id, net-name or port-id "
"specified."))
auto_or_none = False
nics = []
for nic_str in args.nics:
nic_info = {}
nic_info_set = False
for kv_str in nic_str.split(","):
if auto_or_none:
# Since we start with auto_or_none being False, it being true
# means we've parsed an auto or none argument, then continued
# after the comma to another key=value pair. Since auto or none
# can only be given by themselves, raise.
raise exceptions.CommandError(_("'auto' or 'none' cannot be "
"used with any other nic "
"arguments"))
try:
# handle the special auto/none cases
if kv_str in ('auto', 'none'):
if not supports_auto_alloc:
raise exceptions.CommandError(err_msg % nic_str)
if nic_info_set:
# Since we start with nic_info_set being False, it
# being true means we've parsed a key=value pair, then
# landed on a auto or none argument after the comma.
# Since auto or none can only be given by themselves,
# raise.
raise exceptions.CommandError(
_("'auto' or 'none' cannot be used with any "
"other nic arguments"))
nics.append(kv_str)
auto_or_none = True
continue
k, v = kv_str.split("=", 1)
except ValueError:
raise exceptions.CommandError(err_msg % nic_str)
if k in nic_keys:
# if user has given a net-name resolve it to network ID
if k == 'net-name':
k = 'net-id'
v = _find_network_id(cs, v)
# if some argument was given multiple times
if k in nic_info:
raise exceptions.CommandError(err_msg % nic_str)
nic_info[k] = v
nic_info_set = True
else:
raise exceptions.CommandError(err_msg % nic_str)
if auto_or_none:
continue
if 'v4-fixed-ip' in nic_info and not netutils.is_valid_ipv4(
nic_info['v4-fixed-ip']):
raise exceptions.CommandError(_("Invalid ipv4 address."))
if 'v6-fixed-ip' in nic_info and not netutils.is_valid_ipv6(
nic_info['v6-fixed-ip']):
raise exceptions.CommandError(_("Invalid ipv6 address."))
if bool(nic_info.get('net-id')) == bool(nic_info.get('port-id')):
raise exceptions.CommandError(err_msg % nic_str)
nics.append(nic_info)
if nics:
if auto_or_none:
if len(nics) > 1:
raise exceptions.CommandError(err_msg % nic_str)
# change the single list entry to a string
nics = nics[0]
else:
# Default to 'auto' if API version >= 2.37 and nothing was specified
if supports_auto_alloc:
nics = 'auto'
return nics
def _boot(cs, args):
"""Boot a new server."""
if not args.flavor:
raise exceptions.CommandError(_("you need to specify a Flavor ID."))
if args.image:
image = _find_image(cs, args.image)
else:
image = None
if not image and args.image_with:
images = _match_image(cs, args.image_with)
if len(images) > 1:
emit_duplicated_image_with_warning(images, args.image_with)
if images:
image = images[0]
else:
raise exceptions.CommandError(_("No images match the property "
"expected by --image-with"))
min_count = 1
max_count = 1
if args.min_count is not None:
if args.min_count < 1:
raise exceptions.CommandError(_("min_count should be >= 1"))
min_count = args.min_count
max_count = min_count
if args.max_count is not None:
if args.max_count < 1:
raise exceptions.CommandError(_("max_count should be >= 1"))
max_count = args.max_count
if (args.min_count is not None and
args.max_count is not None and
args.min_count > args.max_count):
raise exceptions.CommandError(_("min_count should be <= max_count"))
flavor = _find_flavor(cs, args.flavor)
meta = _meta_parsing(args.meta)
include_files = cs.api_version < api_versions.APIVersion('2.57')
if include_files:
files = {}
for f in args.files:
try:
dst, src = f.split('=', 1)
with open(src) as fo:
files[dst] = fo.read()
except IOError as e:
raise exceptions.CommandError(
_("Can't open '%(src)s': %(exc)s") %
{'src': src, 'exc': e})
except ValueError:
raise exceptions.CommandError(
_("Invalid file argument '%s'. "
"File arguments must be of the "
"form '--file <dst-path=src-path>'") % f)
# use the os-keypair extension
key_name = None
if args.key_name is not None:
key_name = args.key_name
if args.user_data:
try:
with open(args.user_data) as f:
userdata = f.read()
except IOError as e:
raise exceptions.CommandError(_("Can't open '%(user_data)s': "
"%(exc)s") %
{'user_data': args.user_data,
'exc': e})
else:
userdata = None
if args.availability_zone:
availability_zone = args.availability_zone
else:
availability_zone = None
if args.security_groups:
security_groups = args.security_groups.split(',')
else:
security_groups = None
block_device_mapping = {}
for bdm in args.block_device_mapping:
device_name, mapping = bdm.split('=', 1)
block_device_mapping[device_name] = mapping
block_device_mapping_v2 = _parse_block_device_mapping_v2(cs, args, image)
n_boot_args = len(list(filter(
bool, (image, args.boot_volume, args.snapshot))))
have_bdm = block_device_mapping_v2 or block_device_mapping
# Fail if more than one boot devices are present
# or if there is no device to boot from.
if n_boot_args > 1 or n_boot_args == 0 and not have_bdm:
raise exceptions.CommandError(
_("you need to specify at least one source ID (Image, Snapshot, "
"or Volume), a block device mapping or provide a set of "
"properties to match against an image"))
if block_device_mapping and block_device_mapping_v2:
raise exceptions.CommandError(
_("you can't mix old block devices (--block-device-mapping) "
"with the new ones (--block-device, --boot-volume, --snapshot, "
"--ephemeral, --swap)"))
nics = _parse_nics(cs, args)
hints = {}
if args.scheduler_hints:
for hint in args.scheduler_hints:
key, _sep, value = hint.partition('=')
# NOTE(vish): multiple copies of the same hint will
# result in a list of values
if key in hints:
if isinstance(hints[key], six.string_types):
hints[key] = [hints[key]]
hints[key] += [value]
else:
hints[key] = value
boot_args = [args.name, image, flavor]
if str(args.config_drive).lower() in ("true", "1"):
config_drive = True
elif str(args.config_drive).lower() in ("false", "0", "", "none"):
config_drive = None
else:
config_drive = args.config_drive
boot_kwargs = dict(
meta=meta,
key_name=key_name,
min_count=min_count,
max_count=max_count,
userdata=userdata,
availability_zone=availability_zone,
security_groups=security_groups,
block_device_mapping=block_device_mapping,
block_device_mapping_v2=block_device_mapping_v2,
nics=nics,
scheduler_hints=hints,
config_drive=config_drive,
admin_pass=args.admin_pass,
access_ip_v4=args.access_ip_v4,
access_ip_v6=args.access_ip_v6,
reservation_id=args.return_reservation_id)
if 'description' in args:
boot_kwargs["description"] = args.description
if 'tags' in args and args.tags:
boot_kwargs["tags"] = args.tags.split(',')
if include_files:
boot_kwargs['files'] = files
if ('trusted_image_certificates' in args and
args.trusted_image_certificates):
boot_kwargs['trusted_image_certificates'] = (
args.trusted_image_certificates)
elif utils.env('OS_TRUSTED_IMAGE_CERTIFICATE_IDS'):
if cs.api_version >= api_versions.APIVersion('2.63'):
boot_kwargs["trusted_image_certificates"] = utils.env(
'OS_TRUSTED_IMAGE_CERTIFICATE_IDS').split(',')
else:
raise exceptions.UnsupportedAttribute(
"OS_TRUSTED_IMAGE_CERTIFICATE_IDS",
"2.63")
return boot_args, boot_kwargs
@utils.arg(
'--flavor',
default=None,
metavar='<flavor>',
help=_("Name or ID of flavor (see 'nova flavor-list')."))
@utils.arg(
'--image',
default=None,
metavar='<image>',
help=_("Name or ID of image (see 'glance image-list'). "))
@utils.arg(
'--image-with',
default=[],
type=_key_value_pairing,
action='append',
metavar='<key=value>',
help=_("Image metadata property (see 'glance image-show'). "))
@utils.arg(
'--boot-volume',
default=None,
metavar="<volume_id>",
help=_("Volume ID to boot from."))
@utils.arg(
'--snapshot',
default=None,
metavar="<snapshot_id>",
help=_("Snapshot ID to boot from (will create a volume)."))
@utils.arg(
'--min-count',
default=None,
type=int,
metavar='<number>',
help=_("Boot at least <number> servers (limited by quota)."))
@utils.arg(
'--max-count',
default=None,
type=int,
metavar='<number>',
help=_("Boot up to <number> servers (limited by quota)."))
@utils.arg(
'--meta',
metavar="<key=value>",
action='append',
default=[],
help=_("Record arbitrary key/value metadata to /meta_data.json "
"on the metadata server. Can be specified multiple times."))
@utils.arg(
'--file',
metavar="<dst-path=src-path>",
action='append',
dest='files',
default=[],
help=_("Store arbitrary files from <src-path> locally to <dst-path> "
"on the new server. More files can be injected using multiple "
"'--file' options. Limited by the 'injected_files' quota value. "
"The default value is 5. You can get the current quota value by "
"'Personality' limit from 'nova limits' command."),
start_version='2.0', end_version='2.56')
@utils.arg(
'--key-name',
default=os.environ.get('NOVACLIENT_DEFAULT_KEY_NAME'),
metavar='<key-name>',
help=_("Key name of keypair that should be created earlier with \
the command keypair-add."))
@utils.arg('name', metavar='<name>', help=_('Name for the new server.'))
@utils.arg(
'--user-data',
default=None,
metavar='<user-data>',
help=_("user data file to pass to be exposed by the metadata server."))
@utils.arg(
'--availability-zone',
default=None,
metavar='<availability-zone>',
help=_("The availability zone for server placement."))
@utils.arg(
'--security-groups',
default=None,
metavar='<security-groups>',
help=_("Comma separated list of security group names."))
@utils.arg(
'--block-device-mapping',
metavar="<dev-name=mapping>",
action='append',
default=[],
help=_("Block device mapping in the format "
"<dev-name>=<id>:<type>:<size(GiB)>:<delete-on-terminate>."))
@utils.arg(
'--block-device',
metavar="key1=value1[,key2=value2...]",
action='append',
default=[],
start_version='2.0',
end_version='2.31',
help=_("Block device mapping with the keys: "
"id=UUID (image_id, snapshot_id or volume_id only if using source "
"image, snapshot or volume) "
"source=source type (image, snapshot, volume or blank), "
"dest=destination type of the block device (volume or local), "
"bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, "
"hypervisor driver chooses a suitable default, "
"honoured only if device type is supplied) "
"type=device type (e.g. disk, cdrom, ...; defaults to 'disk') "
"device=name of the device (e.g. vda, xda, ...; "
"if omitted, hypervisor driver chooses suitable device "
"depending on selected bus; note the libvirt driver always "
"uses default device names), "
"size=size of the block device in MiB(for swap) and in "
"GiB(for other formats) "
"(if omitted, hypervisor driver calculates size), "
"format=device will be formatted (e.g. swap, ntfs, ...; optional), "
"bootindex=integer used for ordering the boot disks "
"(for image backed instances it is equal to 0, "
"for others need to be specified) and "
"shutdown=shutdown behaviour (either preserve or remove, "
"for local destination set to remove)."))
@utils.arg(
'--block-device',
metavar="key1=value1[,key2=value2...]",
action='append',
default=[],
start_version='2.32',
end_version='2.32',
help=_("Block device mapping with the keys: "
"id=UUID (image_id, snapshot_id or volume_id only if using source "
"image, snapshot or volume) "
"source=source type (image, snapshot, volume or blank), "
"dest=destination type of the block device (volume or local), "
"bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, "
"hypervisor driver chooses a suitable default, "
"honoured only if device type is supplied) "
"type=device type (e.g. disk, cdrom, ...; defaults to 'disk') "
"device=name of the device (e.g. vda, xda, ...; "
"tag=device metadata tag (optional) "
"if omitted, hypervisor driver chooses suitable device "
"depending on selected bus; note the libvirt driver always "
"uses default device names), "
"size=size of the block device in MiB(for swap) and in "
"GiB(for other formats) "
"(if omitted, hypervisor driver calculates size), "
"format=device will be formatted (e.g. swap, ntfs, ...; optional), "
"bootindex=integer used for ordering the boot disks "
"(for image backed instances it is equal to 0, "
"for others need to be specified) and "
"shutdown=shutdown behaviour (either preserve or remove, "
"for local destination set to remove)."))
@utils.arg(
'--block-device',
metavar="key1=value1[,key2=value2...]",
action='append',
default=[],
start_version='2.33',
end_version='2.41',
help=_("Block device mapping with the keys: "
"id=UUID (image_id, snapshot_id or volume_id only if using source "
"image, snapshot or volume) "
"source=source type (image, snapshot, volume or blank), "
"dest=destination type of the block device (volume or local), "
"bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, "
"hypervisor driver chooses a suitable default, "
"honoured only if device type is supplied) "
"type=device type (e.g. disk, cdrom, ...; defaults to 'disk') "
"device=name of the device (e.g. vda, xda, ...; "
"if omitted, hypervisor driver chooses suitable device "
"depending on selected bus; note the libvirt driver always "
"uses default device names), "
"size=size of the block device in MiB(for swap) and in "
"GiB(for other formats) "
"(if omitted, hypervisor driver calculates size), "
"format=device will be formatted (e.g. swap, ntfs, ...; optional), "
"bootindex=integer used for ordering the boot disks "
"(for image backed instances it is equal to 0, "
"for others need to be specified) and "
"shutdown=shutdown behaviour (either preserve or remove, "
"for local destination set to remove)."))
@utils.arg(
'--block-device',
metavar="key1=value1[,key2=value2...]",
action='append',
default=[],
start_version='2.42',
end_version='2.66',
help=_("Block device mapping with the keys: "
"id=UUID (image_id, snapshot_id or volume_id only if using source "
"image, snapshot or volume) "
"source=source type (image, snapshot, volume or blank), "
"dest=destination type of the block device (volume or local), "
"bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, "
"hypervisor driver chooses a suitable default, "
"honoured only if device type is supplied) "
"type=device type (e.g. disk, cdrom, ...; defaults to 'disk') "
"device=name of the device (e.g. vda, xda, ...; "
"if omitted, hypervisor driver chooses suitable device "
"depending on selected bus; note the libvirt driver always "
"uses default device names), "
"size=size of the block device in MiB(for swap) and in "
"GiB(for other formats) "
"(if omitted, hypervisor driver calculates size), "
"format=device will be formatted (e.g. swap, ntfs, ...; optional), "
"bootindex=integer used for ordering the boot disks "
"(for image backed instances it is equal to 0, "
"for others need to be specified), "
"shutdown=shutdown behaviour (either preserve or remove, "
"for local destination set to remove) and "
"tag=device metadata tag (optional)."))
@utils.arg(
'--block-device',
metavar="key1=value1[,key2=value2...]",
action='append',
default=[],
start_version='2.67',
help=_("Block device mapping with the keys: "
"id=UUID (image_id, snapshot_id or volume_id only if using source "
"image, snapshot or volume) "
"source=source type (image, snapshot, volume or blank), "
"dest=destination type of the block device (volume or local), "
"bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, "
"hypervisor driver chooses a suitable default, "
"honoured only if device type is supplied) "
"type=device type (e.g. disk, cdrom, ...; defaults to 'disk') "
"device=name of the device (e.g. vda, xda, ...; "
"if omitted, hypervisor driver chooses suitable device "
"depending on selected bus; note the libvirt driver always "
"uses default device names), "
"size=size of the block device in MiB(for swap) and in "
"GiB(for other formats) "
"(if omitted, hypervisor driver calculates size), "
"format=device will be formatted (e.g. swap, ntfs, ...; optional), "
"bootindex=integer used for ordering the boot disks "
"(for image backed instances it is equal to 0, "
"for others need to be specified), "
"shutdown=shutdown behaviour (either preserve or remove, "
"for local destination set to remove) and "
"tag=device metadata tag (optional), "
"volume_type=type of volume to create (either ID or name) when "
"source is blank, image or snapshot and dest is volume (optional)."
))
@utils.arg(
'--swap',
metavar="<swap_size>",
default=None,
help=_("Create and attach a local swap block device of <swap_size> MiB."))
@utils.arg(
'--ephemeral',
metavar="size=<size>[,format=<format>]",
action='append',
default=[],
help=_("Create and attach a local ephemeral block device of <size> GiB "
"and format it to <format>."))
@utils.arg(
'--hint',
action='append',
dest='scheduler_hints',
default=[],
metavar='<key=value>',
help=_("Send arbitrary key/value pairs to the scheduler for custom "
"use."))
@utils.arg(
'--nic',
metavar="<net-id=net-uuid,net-name=network-name,v4-fixed-ip=ip-addr,"
"v6-fixed-ip=ip-addr,port-id=port-uuid>",
action='append',
dest='nics',
default=[],
start_version='2.0',
end_version='2.31',
help=_("Create a NIC on the server. "
"Specify option multiple times to create multiple NICs. "
"net-id: attach NIC to network with this UUID "
"net-name: attach NIC to network with this name "
"(either port-id or net-id or net-name must be provided), "
"v4-fixed-ip: IPv4 fixed address for NIC (optional), "
"v6-fixed-ip: IPv6 fixed address for NIC (optional), "
"port-id: attach NIC to port with this UUID "
"(either port-id or net-id must be provided)."))
@utils.arg(
'--nic',
metavar="<net-id=net-uuid,net-name=network-name,v4-fixed-ip=ip-addr,"
"v6-fixed-ip=ip-addr,port-id=port-uuid,tag=tag>",
action='append',
dest='nics',
default=[],
start_version='2.32',
end_version='2.36',
help=_("Create a NIC on the server. "
"Specify option multiple times to create multiple nics. "
"net-id: attach NIC to network with this UUID "
"net-name: attach NIC to network with this name "
"(either port-id or net-id or net-name must be provided), "
"v4-fixed-ip: IPv4 fixed address for NIC (optional), "
"v6-fixed-ip: IPv6 fixed address for NIC (optional), "
"port-id: attach NIC to port with this UUID "
"tag: interface metadata tag (optional) "
"(either port-id or net-id must be provided)."))
@utils.arg(
'--nic',
metavar="<auto,none,"
"net-id=net-uuid,net-name=network-name,port-id=port-uuid,"
"v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr>",
action='append',
dest='nics',
default=[],
start_version='2.37',
end_version='2.41',
help=_("Create a NIC on the server. "
"Specify option multiple times to create multiple nics unless "
"using the special 'auto' or 'none' values. "
"auto: automatically allocate network resources if none are "
"available. This cannot be specified with any other nic value and "
"cannot be specified multiple times. "
"none: do not attach a NIC at all. This cannot be specified "
"with any other nic value and cannot be specified multiple times. "
"net-id: attach NIC to network with a specific UUID. "
"net-name: attach NIC to network with this name "
"(either port-id or net-id or net-name must be provided), "
"v4-fixed-ip: IPv4 fixed address for NIC (optional), "
"v6-fixed-ip: IPv6 fixed address for NIC (optional), "
"port-id: attach NIC to port with this UUID "
"(either port-id or net-id must be provided)."))
@utils.arg(
'--nic',
metavar="<auto,none,"
"net-id=net-uuid,net-name=network-name,port-id=port-uuid,"
"v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,tag=tag>",
action='append',
dest='nics',
default=[],
start_version='2.42',
help=_("Create a NIC on the server. "
"Specify option multiple times to create multiple nics unless "
"using the special 'auto' or 'none' values. "
"auto: automatically allocate network resources if none are "
"available. This cannot be specified with any other nic value and "
"cannot be specified multiple times. "
"none: do not attach a NIC at all. This cannot be specified "
"with any other nic value and cannot be specified multiple times. "
"net-id: attach NIC to network with a specific UUID. "
"net-name: attach NIC to network with this name "
"(either port-id or net-id or net-name must be provided), "
"v4-fixed-ip: IPv4 fixed address for NIC (optional), "
"v6-fixed-ip: IPv6 fixed address for NIC (optional), "
"port-id: attach NIC to port with this UUID "
"tag: interface metadata tag (optional) "
"(either port-id or net-id must be provided)."))
@utils.arg(
'--config-drive',
metavar="<value>",
dest='config_drive',
default=False,
help=_("Enable config drive."))
@utils.arg(
'--poll',
dest='poll',
action="store_true",
default=False,
help=_('Report the new server boot progress until it completes.'))
@utils.arg(
'--admin-pass',
dest='admin_pass',
metavar='<value>',
default=None,
help=_('Admin password for the instance.'))
@utils.arg(
'--access-ip-v4',
dest='access_ip_v4',
metavar='<value>',
default=None,
help=_('Alternative access IPv4 of the instance.'))
@utils.arg(
'--access-ip-v6',
dest='access_ip_v6',
metavar='<value>',
default=None,
help=_('Alternative access IPv6 of the instance.'))
@utils.arg(
'--description',
metavar='<description>',
dest='description',
default=None,
help=_('Description for the server.'),
start_version="2.19")
@utils.arg(
'--tags',
metavar='<tags>',
default=None,
help=_('Tags for the server.'
'Tags must be separated by commas: --tags <tag1,tag2>'),
start_version="2.52")
@utils.arg(
'--return-reservation-id',
dest='return_reservation_id',
action="store_true",
default=False,
help=_("Return a reservation id bound to created servers."))
@utils.arg(
'--trusted-image-certificate-id',
metavar='<trusted-image-certificate-id>',
action='append',
dest='trusted_image_certificates',
default=[],
help=_('Trusted image certificate IDs used to validate certificates '
'during the image signature verification process. '
'Defaults to env[OS_TRUSTED_IMAGE_CERTIFICATE_IDS]. '
'May be specified multiple times to pass multiple trusted image '
'certificate IDs.'),
start_version="2.63")
def do_boot(cs, args):
"""Boot a new server."""
boot_args, boot_kwargs = _boot(cs, args)
server = cs.servers.create(*boot_args, **boot_kwargs)
if boot_kwargs['reservation_id']:
new_server = {'reservation_id': server}
utils.print_dict(new_server)
return
else:
_print_server(cs, args, server)
if args.poll:
_poll_for_status(cs.servers.get, server.id, 'building', ['active'])
def _poll_for_status(poll_fn, obj_id, action, final_ok_states,
poll_period=5, show_progress=True,
status_field="status", silent=False):
"""Block while an action is being performed, periodically printing
progress.
"""
def print_progress(progress):
if show_progress:
msg = (_('\rServer %(action)s... %(progress)s%% complete')
% dict(action=action, progress=progress))
else:
msg = _('\rServer %(action)s...') % dict(action=action)
sys.stdout.write(msg)
sys.stdout.flush()
if not silent:
print()
while True:
obj = poll_fn(obj_id)
status = getattr(obj, status_field)
if status:
status = status.lower()
progress = getattr(obj, 'progress', None) or 0
if status in final_ok_states:
if not silent:
print_progress(100)
print(_("\nFinished"))
break
elif status == "error":
if not silent:
print(_("\nError %s server") % action)
raise exceptions.ResourceInErrorState(obj)
elif status == "deleted":
if not silent: