-
Notifications
You must be signed in to change notification settings - Fork 211
/
server.py
2907 lines (2582 loc) · 103 KB
/
server.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 2012-2013 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.
#
"""Compute v2 Server action implementations"""
import argparse
import getpass
import io
import logging
import os
from novaclient import api_versions
from novaclient.v2 import servers
from openstack import exceptions as sdk_exceptions
from osc_lib.cli import parseractions
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils
from oslo_utils import timeutils
import six
from openstackclient.i18n import _
from openstackclient.identity import common as identity_common
from openstackclient.network import common as network_common
LOG = logging.getLogger(__name__)
def _format_servers_list_networks(networks):
"""Return a formatted string of a server's networks
:param networks: a Server.networks field
:rtype: a string of formatted network addresses
"""
output = []
for (network, addresses) in networks.items():
if not addresses:
continue
addresses_csv = ', '.join(addresses)
group = "%s=%s" % (network, addresses_csv)
output.append(group)
return '; '.join(output)
def _format_servers_list_power_state(state):
"""Return a formatted string of a server's power state
:param state: the power state number of a server
:rtype: a string mapped to the power state number
"""
power_states = [
'NOSTATE', # 0x00
'Running', # 0x01
'', # 0x02
'Paused', # 0x03
'Shutdown', # 0x04
'', # 0x05
'Crashed', # 0x06
'Suspended' # 0x07
]
try:
return power_states[state]
except Exception:
return 'N/A'
def _get_ip_address(addresses, address_type, ip_address_family):
# Old style addresses
if address_type in addresses:
for addy in addresses[address_type]:
if int(addy['version']) in ip_address_family:
return addy['addr']
# New style addresses
new_address_type = address_type
if address_type == 'public':
new_address_type = 'floating'
if address_type == 'private':
new_address_type = 'fixed'
for network in addresses:
for addy in addresses[network]:
# Case where it is list of strings
if isinstance(addy, six.string_types):
if new_address_type == 'fixed':
return addresses[network][0]
else:
return addresses[network][-1]
# Case where it is a dict
if 'OS-EXT-IPS:type' not in addy:
continue
if addy['OS-EXT-IPS:type'] == new_address_type:
if int(addy['version']) in ip_address_family:
return addy['addr']
msg = _("ERROR: No %(type)s IP version %(family)s address found")
raise exceptions.CommandError(
msg % {"type": address_type,
"family": ip_address_family}
)
def _prefix_checked_value(prefix):
def func(value):
if ',' in value or '=' in value:
msg = _("Invalid argument %s, "
"characters ',' and '=' are not allowed") % value
raise argparse.ArgumentTypeError(msg)
return prefix + value
return func
def _prep_server_detail(compute_client, image_client, server, refresh=True):
"""Prepare the detailed server dict for printing
:param compute_client: a compute client instance
:param image_client: an image client instance
:param server: a Server resource
:param refresh: Flag indicating if ``server`` is already the latest version
or if it needs to be refreshed, for example when showing
the latest details of a server after creating it.
:rtype: a dict of server details
"""
info = server.to_dict()
if refresh:
server = utils.find_resource(compute_client.servers, info['id'])
info.update(server.to_dict())
# Convert the image blob to a name
image_info = info.get('image', {})
if image_info:
image_id = image_info.get('id', '')
try:
image = utils.find_resource(image_client.images, image_id)
info['image'] = "%s (%s)" % (image.name, image_id)
except Exception:
info['image'] = image_id
# Convert the flavor blob to a name
flavor_info = info.get('flavor', {})
# Microversion 2.47 puts the embedded flavor into the server response
# body but omits the id, so if not present we just expose the flavor
# dict in the server output.
if 'id' in flavor_info:
flavor_id = flavor_info.get('id', '')
try:
flavor = utils.find_resource(compute_client.flavors, flavor_id)
info['flavor'] = "%s (%s)" % (flavor.name, flavor_id)
except Exception:
info['flavor'] = flavor_id
else:
info['flavor'] = utils.format_dict(flavor_info)
if 'os-extended-volumes:volumes_attached' in info:
info.update(
{
'volumes_attached': utils.format_list_of_dicts(
info.pop('os-extended-volumes:volumes_attached'))
}
)
if 'security_groups' in info:
info.update(
{
'security_groups': utils.format_list_of_dicts(
info.pop('security_groups'))
}
)
# NOTE(dtroyer): novaclient splits these into separate entries...
# Format addresses in a useful way
info['addresses'] = _format_servers_list_networks(server.networks)
# Map 'metadata' field to 'properties'
info.update(
{'properties': utils.format_dict(info.pop('metadata'))}
)
# Migrate tenant_id to project_id naming
if 'tenant_id' in info:
info['project_id'] = info.pop('tenant_id')
# Map power state num to meaningful string
if 'OS-EXT-STS:power_state' in info:
info['OS-EXT-STS:power_state'] = _format_servers_list_power_state(
info['OS-EXT-STS:power_state'])
# Remove values that are long and not too useful
info.pop('links', None)
return info
class AddFixedIP(command.Command):
_description = _("Add fixed IP address to server")
def get_parser(self, prog_name):
parser = super(AddFixedIP, self).get_parser(prog_name)
parser.add_argument(
"server",
metavar="<server>",
help=_("Server to receive the fixed IP address (name or ID)"),
)
parser.add_argument(
"network",
metavar="<network>",
help=_(
"Network to allocate the fixed IP address from (name or ID)"
),
)
parser.add_argument(
"--fixed-ip-address",
metavar="<ip-address>",
help=_("Requested fixed IP address"),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
server = utils.find_resource(
compute_client.servers, parsed_args.server)
network = compute_client.api.network_find(parsed_args.network)
server.interface_attach(
port_id=None,
net_id=network['id'],
fixed_ip=parsed_args.fixed_ip_address,
)
class AddFloatingIP(network_common.NetworkAndComputeCommand):
_description = _("Add floating IP address to server")
def update_parser_common(self, parser):
parser.add_argument(
"server",
metavar="<server>",
help=_("Server to receive the floating IP address (name or ID)"),
)
parser.add_argument(
"ip_address",
metavar="<ip-address>",
help=_("Floating IP address to assign to the first available "
"server port (IP only)"),
)
parser.add_argument(
"--fixed-ip-address",
metavar="<ip-address>",
help=_(
"Fixed IP address to associate with this floating IP address. "
"The first server port containing the fixed IP address will "
"be used"
),
)
return parser
def take_action_network(self, client, parsed_args):
compute_client = self.app.client_manager.compute
attrs = {}
obj = client.find_ip(
parsed_args.ip_address,
ignore_missing=False,
)
server = utils.find_resource(
compute_client.servers,
parsed_args.server,
)
ports = list(client.ports(device_id=server.id))
# If the fixed IP address was specified, we need to find the
# corresponding port.
if parsed_args.fixed_ip_address:
fip_address = parsed_args.fixed_ip_address
attrs['fixed_ip_address'] = fip_address
for port in ports:
for ip in port.fixed_ips:
if ip['ip_address'] == fip_address:
attrs['port_id'] = port.id
break
else:
continue
break
if 'port_id' not in attrs:
msg = _('No port found for fixed IP address %s')
raise exceptions.CommandError(msg % fip_address)
client.update_ip(obj, **attrs)
else:
# It's possible that one or more ports are not connected to a
# router and thus could fail association with a floating IP.
# Try each port until one succeeds. If none succeed, re-raise the
# last exception.
error = None
for port in ports:
attrs['port_id'] = port.id
try:
client.update_ip(obj, **attrs)
except sdk_exceptions.NotFoundException as exp:
# 404 ExternalGatewayForFloatingIPNotFound from neutron
LOG.info('Skipped port %s because it is not attached to '
'an external gateway', port.id)
error = exp
continue
else:
error = None
break
if error:
raise error
def take_action_compute(self, client, parsed_args):
client.api.floating_ip_add(
parsed_args.server,
parsed_args.ip_address,
fixed_address=parsed_args.fixed_ip_address,
)
class AddPort(command.Command):
_description = _("Add port to server")
def get_parser(self, prog_name):
parser = super(AddPort, self).get_parser(prog_name)
parser.add_argument(
"server",
metavar="<server>",
help=_("Server to add the port to (name or ID)"),
)
parser.add_argument(
"port",
metavar="<port>",
help=_("Port to add to the server (name or ID)"),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
server = utils.find_resource(
compute_client.servers, parsed_args.server)
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
port_id = network_client.find_port(
parsed_args.port, ignore_missing=False).id
else:
port_id = parsed_args.port
server.interface_attach(port_id=port_id, net_id=None, fixed_ip=None)
class AddNetwork(command.Command):
_description = _("Add network to server")
def get_parser(self, prog_name):
parser = super(AddNetwork, self).get_parser(prog_name)
parser.add_argument(
"server",
metavar="<server>",
help=_("Server to add the network to (name or ID)"),
)
parser.add_argument(
"network",
metavar="<network>",
help=_("Network to add to the server (name or ID)"),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
server = utils.find_resource(
compute_client.servers, parsed_args.server)
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
net_id = network_client.find_network(
parsed_args.network, ignore_missing=False).id
else:
net_id = parsed_args.network
server.interface_attach(port_id=None, net_id=net_id, fixed_ip=None)
class AddServerSecurityGroup(command.Command):
_description = _("Add security group to server")
def get_parser(self, prog_name):
parser = super(AddServerSecurityGroup, self).get_parser(prog_name)
parser.add_argument(
'server',
metavar='<server>',
help=_('Server (name or ID)'),
)
parser.add_argument(
'group',
metavar='<group>',
help=_('Security group to add (name or ID)'),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
server = utils.find_resource(
compute_client.servers,
parsed_args.server,
)
security_group = compute_client.api.security_group_find(
parsed_args.group,
)
server.add_security_group(security_group['id'])
class AddServerVolume(command.Command):
_description = _(
"Add volume to server. "
"Specify ``--os-compute-api-version 2.20`` or higher to add a volume "
"to a server with status ``SHELVED`` or ``SHELVED_OFFLOADED``.")
def get_parser(self, prog_name):
parser = super(AddServerVolume, self).get_parser(prog_name)
parser.add_argument(
'server',
metavar='<server>',
help=_('Server (name or ID)'),
)
parser.add_argument(
'volume',
metavar='<volume>',
help=_('Volume to add (name or ID)'),
)
parser.add_argument(
'--device',
metavar='<device>',
help=_('Server internal device name for volume'),
)
termination_group = parser.add_mutually_exclusive_group()
termination_group.add_argument(
'--enable-delete-on-termination',
action='store_true',
help=_("Specify if the attached volume should be deleted when "
"the server is destroyed. (Supported with "
"``--os-compute-api-version`` 2.79 or greater.)"),
)
termination_group.add_argument(
'--disable-delete-on-termination',
action='store_true',
help=_("Specify if the attached volume should not be deleted "
"when the server is destroyed. (Supported with "
"``--os-compute-api-version`` 2.79 or greater.)"),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
volume_client = self.app.client_manager.volume
server = utils.find_resource(
compute_client.servers,
parsed_args.server,
)
volume = utils.find_resource(
volume_client.volumes,
parsed_args.volume,
)
support_set_delete_on_termination = (compute_client.api_version >=
api_versions.APIVersion('2.79'))
if not support_set_delete_on_termination:
if parsed_args.enable_delete_on_termination:
msg = _('--os-compute-api-version 2.79 or greater '
'is required to support the '
'--enable-delete-on-termination option.')
raise exceptions.CommandError(msg)
if parsed_args.disable_delete_on_termination:
msg = _('--os-compute-api-version 2.79 or greater '
'is required to support the '
'--disable-delete-on-termination option.')
raise exceptions.CommandError(msg)
kwargs = {
"device": parsed_args.device
}
if parsed_args.enable_delete_on_termination:
kwargs['delete_on_termination'] = True
if parsed_args.disable_delete_on_termination:
kwargs['delete_on_termination'] = False
compute_client.volumes.create_server_volume(
server.id,
volume.id,
**kwargs
)
class CreateServer(command.ShowOne):
_description = _("Create a new server")
def get_parser(self, prog_name):
parser = super(CreateServer, self).get_parser(prog_name)
parser.add_argument(
'server_name',
metavar='<server-name>',
help=_('New server name'),
)
disk_group = parser.add_mutually_exclusive_group(
required=True,
)
disk_group.add_argument(
'--image',
metavar='<image>',
help=_('Create server boot disk from this image (name or ID)'),
)
disk_group.add_argument(
'--image-property',
metavar='<key=value>',
action=parseractions.KeyValueAction,
help=_("Image property to be matched"),
)
disk_group.add_argument(
'--volume',
metavar='<volume>',
help=_('Create server using this volume as the boot disk (name '
'or ID).\n'
'This option automatically creates a block device mapping '
'with a boot index of 0. On many hypervisors (libvirt/kvm '
'for example) this will be device vda. Do not create a '
'duplicate mapping using --block-device-mapping for this '
'volume.'),
)
parser.add_argument(
'--flavor',
metavar='<flavor>',
required=True,
help=_('Create server with this flavor (name or ID)'),
)
parser.add_argument(
'--security-group',
metavar='<security-group>',
action='append',
default=[],
help=_('Security group to assign to this server (name or ID) '
'(repeat option to set multiple groups)'),
)
parser.add_argument(
'--key-name',
metavar='<key-name>',
help=_('Keypair to inject into this server (optional extension)'),
)
parser.add_argument(
'--property',
metavar='<key=value>',
action=parseractions.KeyValueAction,
help=_('Set a property on this server '
'(repeat option to set multiple values)'),
)
parser.add_argument(
'--file',
metavar='<dest-filename=source-filename>',
action='append',
default=[],
help=_('File to inject into image before boot '
'(repeat option to set multiple files)'),
)
parser.add_argument(
'--user-data',
metavar='<user-data>',
help=_('User data file to serve from the metadata server'),
)
parser.add_argument(
'--description',
metavar='<description>',
help=_('Set description for the server (supported by '
'--os-compute-api-version 2.19 or above)'),
)
parser.add_argument(
'--availability-zone',
metavar='<zone-name>',
help=_('Select an availability zone for the server'),
)
parser.add_argument(
'--host',
metavar='<host>',
help=_('Requested host to create servers. Admin only '
'by default. (supported by --os-compute-api-version 2.74 '
'or above)'),
)
parser.add_argument(
'--hypervisor-hostname',
metavar='<hypervisor-hostname>',
help=_('Requested hypervisor hostname to create servers. Admin '
'only by default. (supported by --os-compute-api-version '
'2.74 or above)'),
)
parser.add_argument(
'--boot-from-volume',
metavar='<volume-size>',
type=int,
help=_('When used in conjunction with the ``--image`` or '
'``--image-property`` option, this option automatically '
'creates a block device mapping with a boot index of 0 '
'and tells the compute service to create a volume of the '
'given size (in GB) from the specified image and use it '
'as the root disk of the server. The root volume will not '
'be deleted when the server is deleted. This option is '
'mutually exclusive with the ``--volume`` option.')
)
parser.add_argument(
'--block-device-mapping',
metavar='<dev-name=mapping>',
action=parseractions.KeyValueAction,
default={},
# NOTE(RuiChen): Add '\n' at the end of line to put each item in
# the separated line, avoid the help message looks
# messy, see _SmartHelpFormatter in cliff.
help=_('Create a block device on the server.\n'
'Block device mapping in the format\n'
'<dev-name>=<id>:<type>:<size(GB)>:<delete-on-terminate>\n'
'<dev-name>: block device name, like: vdb, xvdc '
'(required)\n'
'<id>: Name or ID of the volume, volume snapshot or image '
'(required)\n'
'<type>: volume, snapshot or image; default: volume '
'(optional)\n'
'<size(GB)>: volume size if create from image or snapshot '
'(optional)\n'
'<delete-on-terminate>: true or false; default: false '
'(optional)\n'
'(optional extension)'),
)
parser.add_argument(
'--nic',
metavar="<net-id=net-uuid,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,"
"port-id=port-uuid,auto,none>",
action='append',
help=_("Create a NIC on the server. "
"Specify option multiple times to create multiple NICs. "
"Either net-id or port-id must be provided, but not both. "
"net-id: attach NIC to network with this UUID, "
"port-id: attach NIC to port with this UUID, "
"v4-fixed-ip: IPv4 fixed address for NIC (optional), "
"v6-fixed-ip: IPv6 fixed address for NIC (optional), "
"none: (v2.37+) no network is attached, "
"auto: (v2.37+) the compute service will automatically "
"allocate a network. Specifying a --nic of auto or none "
"cannot be used with any other --nic value."),
)
parser.add_argument(
'--network',
metavar="<network>",
action='append',
dest='nic',
type=_prefix_checked_value('net-id='),
help=_("Create a NIC on the server and connect it to network. "
"Specify option multiple times to create multiple NICs. "
"This is a wrapper for the '--nic net-id=<network>' "
"parameter that provides simple syntax for the standard "
"use case of connecting a new server to a given network. "
"For more advanced use cases, refer to the '--nic' "
"parameter."),
)
parser.add_argument(
'--port',
metavar="<port>",
action='append',
dest='nic',
type=_prefix_checked_value('port-id='),
help=_("Create a NIC on the server and connect it to port. "
"Specify option multiple times to create multiple NICs. "
"This is a wrapper for the '--nic port-id=<port>' "
"parameter that provides simple syntax for the standard "
"use case of connecting a new server to a given port. For "
"more advanced use cases, refer to the '--nic' parameter."),
)
parser.add_argument(
'--hint',
metavar='<key=value>',
action=parseractions.KeyValueAppendAction,
default={},
help=_('Hints for the scheduler (optional extension)'),
)
parser.add_argument(
'--config-drive',
metavar='<config-drive-volume>|True',
default=False,
help=_('Use specified volume as the config drive, '
'or \'True\' to use an ephemeral drive'),
)
parser.add_argument(
'--min',
metavar='<count>',
type=int,
default=1,
help=_('Minimum number of servers to launch (default=1)'),
)
parser.add_argument(
'--max',
metavar='<count>',
type=int,
default=1,
help=_('Maximum number of servers to launch (default=1)'),
)
parser.add_argument(
'--wait',
action='store_true',
help=_('Wait for build to complete'),
)
return parser
def take_action(self, parsed_args):
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
self.app.stdout.flush()
compute_client = self.app.client_manager.compute
volume_client = self.app.client_manager.volume
image_client = self.app.client_manager.image
# Lookup parsed_args.image
image = None
if parsed_args.image:
image = utils.find_resource(
image_client.images,
parsed_args.image,
)
if not image and parsed_args.image_property:
def emit_duplicated_warning(img, image_property):
img_uuid_list = [str(image.id) for image in img]
LOG.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]})
def _match_image(image_api, wanted_properties):
image_list = image_api.image_list()
images_matched = []
for img in image_list:
img_dict = {}
# exclude any unhashable entries
for key, value in img.items():
try:
set([key, value])
except TypeError:
pass
else:
img_dict[key] = value
if all(k in img_dict and img_dict[k] == v
for k, v in wanted_properties.items()):
images_matched.append(img)
else:
return []
return images_matched
images = _match_image(image_client.api, parsed_args.image_property)
if len(images) > 1:
emit_duplicated_warning(images,
parsed_args.image_property)
if images:
image = images[0]
else:
raise exceptions.CommandError(_("No images match the "
"property expected by "
"--image-property"))
# Lookup parsed_args.volume
volume = None
if parsed_args.volume:
# --volume and --boot-from-volume are mutually exclusive.
if parsed_args.boot_from_volume:
raise exceptions.CommandError(
_('--volume is not allowed with --boot-from-volume'))
volume = utils.find_resource(
volume_client.volumes,
parsed_args.volume,
).id
# Lookup parsed_args.flavor
flavor = utils.find_resource(compute_client.flavors,
parsed_args.flavor)
files = {}
for f in parsed_args.file:
dst, src = f.split('=', 1)
try:
files[dst] = io.open(src, 'rb')
except IOError as e:
msg = _("Can't open '%(source)s': %(exception)s")
raise exceptions.CommandError(
msg % {"source": src,
"exception": e}
)
if parsed_args.min > parsed_args.max:
msg = _("min instances should be <= max instances")
raise exceptions.CommandError(msg)
if parsed_args.min < 1:
msg = _("min instances should be > 0")
raise exceptions.CommandError(msg)
if parsed_args.max < 1:
msg = _("max instances should be > 0")
raise exceptions.CommandError(msg)
userdata = None
if parsed_args.user_data:
try:
userdata = io.open(parsed_args.user_data)
except IOError as e:
msg = _("Can't open '%(data)s': %(exception)s")
raise exceptions.CommandError(
msg % {"data": parsed_args.user_data,
"exception": e}
)
if parsed_args.description:
if compute_client.api_version < api_versions.APIVersion("2.19"):
msg = _("Description is not supported for "
"--os-compute-api-version less than 2.19")
raise exceptions.CommandError(msg)
block_device_mapping_v2 = []
if volume:
block_device_mapping_v2 = [{'uuid': volume,
'boot_index': '0',
'source_type': 'volume',
'destination_type': 'volume'
}]
elif parsed_args.boot_from_volume:
# Tell nova to create a root volume from the image provided.
block_device_mapping_v2 = [{
'uuid': image.id,
'boot_index': '0',
'source_type': 'image',
'destination_type': 'volume',
'volume_size': parsed_args.boot_from_volume
}]
# If booting from volume we do not pass an image to compute.
image = None
boot_args = [parsed_args.server_name, image, flavor]
# Handle block device by device name order, like: vdb -> vdc -> vdd
for dev_name in sorted(six.iterkeys(parsed_args.block_device_mapping)):
dev_map = parsed_args.block_device_mapping[dev_name]
dev_map = dev_map.split(':')
if dev_map[0]:
mapping = {'device_name': dev_name}
# 1. decide source and destination type
if (len(dev_map) > 1 and
dev_map[1] in ('volume', 'snapshot', 'image')):
mapping['source_type'] = dev_map[1]
else:
mapping['source_type'] = 'volume'
mapping['destination_type'] = 'volume'
# 2. check target exist, update target uuid according by
# source type
if mapping['source_type'] == 'volume':
volume_id = utils.find_resource(
volume_client.volumes, dev_map[0]).id
mapping['uuid'] = volume_id
elif mapping['source_type'] == 'snapshot':
snapshot_id = utils.find_resource(
volume_client.volume_snapshots, dev_map[0]).id
mapping['uuid'] = snapshot_id
elif mapping['source_type'] == 'image':
# NOTE(mriedem): In case --image is specified with the same
# image, that becomes the root disk for the server. If the
# block device is specified with a root device name, e.g.
# vda, then the compute API will likely fail complaining
# that there is a conflict. So if using the same image ID,
# which doesn't really make sense but it's allowed, the
# device name would need to be a non-root device, e.g. vdb.
# Otherwise if the block device image is different from the
# one specified by --image, then the compute service will
# create a volume from the image and attach it to the
# server as a non-root volume.
image_id = utils.find_resource(
image_client.images, dev_map[0]).id
mapping['uuid'] = image_id
# 3. append size and delete_on_termination if exist
if len(dev_map) > 2 and dev_map[2]:
mapping['volume_size'] = dev_map[2]
if len(dev_map) > 3 and dev_map[3]:
mapping['delete_on_termination'] = dev_map[3]
else:
msg = _("Volume, volume snapshot or image (name or ID) must "
"be specified if --block-device-mapping is specified")
raise exceptions.CommandError(msg)
block_device_mapping_v2.append(mapping)
nics = []
auto_or_none = False
if parsed_args.nic is None:
parsed_args.nic = []
for nic_str in parsed_args.nic:
# Handle the special auto/none cases
if nic_str in ('auto', 'none'):
auto_or_none = True
nics.append(nic_str)
else:
nic_info = {"net-id": "", "v4-fixed-ip": "",
"v6-fixed-ip": "", "port-id": ""}
for kv_str in nic_str.split(","):
k, sep, v = kv_str.partition("=")
if k in nic_info and v:
nic_info[k] = v
else:
msg = (_("Invalid nic argument '%s'. Nic arguments "
"must be of the form --nic <net-id=net-uuid"
",v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,"
"port-id=port-uuid>."))
raise exceptions.CommandError(msg % k)
if bool(nic_info["net-id"]) == bool(nic_info["port-id"]):
msg = _("either network or port should be specified "
"but not both")
raise exceptions.CommandError(msg)
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
if nic_info["net-id"]:
net = network_client.find_network(
nic_info["net-id"], ignore_missing=False)
nic_info["net-id"] = net.id
if nic_info["port-id"]:
port = network_client.find_port(
nic_info["port-id"], ignore_missing=False)
nic_info["port-id"] = port.id
else:
if nic_info["net-id"]:
nic_info["net-id"] = compute_client.api.network_find(
nic_info["net-id"]
)['id']
if nic_info["port-id"]:
msg = _("can't create server with port specified "
"since network endpoint not enabled")
raise exceptions.CommandError(msg)
nics.append(nic_info)
if nics:
if auto_or_none:
if len(nics) > 1:
msg = _('Specifying a --nic of auto or none cannot '
'be used with any other --nic, --network '
'or --port value.')
raise exceptions.CommandError(msg)
nics = nics[0]
else:
# Compute API version >= 2.37 requires a value, so default to
# 'auto' to maintain legacy behavior if a nic wasn't specified.
if compute_client.api_version >= api_versions.APIVersion('2.37'):
nics = 'auto'
else:
# Default to empty list if nothing was specified, let nova
# side to decide the default behavior.
nics = []
# Check security group exist and convert ID to name
security_group_names = []
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
for each_sg in parsed_args.security_group:
sg = network_client.find_security_group(each_sg,
ignore_missing=False)
# Use security group ID to avoid multiple security group have
# same name in neutron networking backend
security_group_names.append(sg.id)
else:
# Handle nova-network case
for each_sg in parsed_args.security_group:
sg = compute_client.api.security_group_find(each_sg)
security_group_names.append(sg['name'])
hints = {}
for key, values in parsed_args.hint.items():
# only items with multiple values will result in a list
if len(values) == 1:
hints[key] = values[0]
else:
hints[key] = values
# What does a non-boolean value for config-drive do?
# --config-drive argument is either a volume id or
# 'True' (or '1') to use an ephemeral volume
if str(parsed_args.config_drive).lower() in ("true", "1"):
config_drive = True