/
server.py
2170 lines (1911 loc) · 71.8 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
import sys
from novaclient.v2 import servers
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
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):
"""Prepare the detailed server dict for printing
:param compute_client: a compute client instance
:param server: a Server resource
:rtype: a dict of server details
"""
info = server._info.copy()
server = utils.find_resource(compute_client.servers, info['id'])
info.update(server._info)
# 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', {})
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
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 meanful 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
def _show_progress(progress):
if progress:
sys.stdout.write('\rProgress: %s' % progress)
sys.stdout.flush()
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(command.Command):
_description = _("Add floating IP address to server")
def get_parser(self, prog_name):
parser = super(AddFloatingIP, self).get_parser(prog_name)
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 server (IP only)"),
)
parser.add_argument(
"--fixed-ip-address",
metavar="<ip-address>",
help=_("Fixed IP address to associate with this floating 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)
server.add_floating_ip(parsed_args.ip_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 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")
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'),
)
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,
)
compute_client.volumes.create_server_volume(
server.id,
volume.id,
parsed_args.device,
)
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(
'--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(
'--availability-zone',
metavar='<zone-name>',
help=_('Select an availability zone for the server'),
)
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>: UUID of the volume or snapshot (required)\n'
'<type>: volume or snapshot; default: volume (optional)\n'
'<size(GB)>: volume size if create from 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=<pord>' "
"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='append',
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):
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,
)
# Lookup parsed_args.volume
volume = None
if parsed_args.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)
boot_args = [parsed_args.server_name, image, 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}
)
block_device_mapping_v2 = []
if volume:
block_device_mapping_v2 = [{'uuid': volume,
'boot_index': '0',
'source_type': 'volume',
'destination_type': 'volume'
}]
# 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')):
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
# 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 or snapshot (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:
# 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 hint in parsed_args.hint:
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
# 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
elif str(parsed_args.config_drive).lower() in ("false", "0",
"", "none"):
config_drive = None
else:
config_drive = parsed_args.config_drive
boot_kwargs = dict(
meta=parsed_args.property,
files=files,
reservation_id=None,
min_count=parsed_args.min,
max_count=parsed_args.max,
security_groups=security_group_names,
userdata=userdata,
key_name=parsed_args.key_name,
availability_zone=parsed_args.availability_zone,
block_device_mapping_v2=block_device_mapping_v2,
nics=nics,
scheduler_hints=hints,
config_drive=config_drive)
LOG.debug('boot_args: %s', boot_args)
LOG.debug('boot_kwargs: %s', boot_kwargs)
# Wrap the call to catch exceptions in order to close files
try:
server = compute_client.servers.create(*boot_args, **boot_kwargs)
finally:
# Clean up open files - make sure they are not strings
for f in files:
if hasattr(f, 'close'):
f.close()
if hasattr(userdata, 'close'):
userdata.close()
if parsed_args.wait:
if utils.wait_for_status(
compute_client.servers.get,
server.id,
callback=_show_progress,
):
sys.stdout.write('\n')
else:
LOG.error(_('Error creating server: %s'),
parsed_args.server_name)
sys.stdout.write(_('Error creating server\n'))
raise SystemExit
details = _prep_server_detail(compute_client, image_client, server)
return zip(*sorted(six.iteritems(details)))
class CreateServerDump(command.Command):
"""Create a dump file in server(s)
Trigger crash dump in server(s) with features like kdump in Linux.
It will create a dump file in the server(s) dumping the server(s)'
memory, and also crash the server(s). OSC sees the dump file
(server dump) as a kind of resource.
"""
def get_parser(self, prog_name):
parser = super(CreateServerDump, self).get_parser(prog_name)
parser.add_argument(
'server',
metavar='<server>',
nargs='+',
help=_('Server(s) to create dump file (name or ID)'),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
for server in parsed_args.server:
utils.find_resource(
compute_client.servers,
server,
).trigger_crash_dump()
class DeleteServer(command.Command):
_description = _("Delete server(s)")
def get_parser(self, prog_name):
parser = super(DeleteServer, self).get_parser(prog_name)
parser.add_argument(
'server',
metavar='<server>',
nargs="+",
help=_('Server(s) to delete (name or ID)'),
)
parser.add_argument(
'--wait',
action='store_true',
help=_('Wait for delete to complete'),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
for server in parsed_args.server:
server_obj = utils.find_resource(
compute_client.servers, server)
compute_client.servers.delete(server_obj.id)
if parsed_args.wait:
if utils.wait_for_delete(
compute_client.servers,
server_obj.id,
callback=_show_progress,
):
sys.stdout.write('\n')
else:
LOG.error(_('Error deleting server: %s'),
server_obj.id)
sys.stdout.write(_('Error deleting server\n'))
raise SystemExit
class ListServer(command.Lister):
_description = _("List servers")
def get_parser(self, prog_name):
parser = super(ListServer, self).get_parser(prog_name)
parser.add_argument(
'--reservation-id',
metavar='<reservation-id>',
help=_('Only return instances that match the reservation'),
)
parser.add_argument(
'--ip',
metavar='<ip-address-regex>',
help=_('Regular expression to match IP addresses'),
)
parser.add_argument(
'--ip6',
metavar='<ip-address-regex>',
help=_('Regular expression to match IPv6 addresses'),
)
parser.add_argument(
'--name',
metavar='<name-regex>',
help=_('Regular expression to match names'),
)
parser.add_argument(
'--instance-name',
metavar='<server-name>',
help=_('Regular expression to match instance name (admin only)'),
)
parser.add_argument(
'--status',
metavar='<status>',
# FIXME(dhellmann): Add choices?
help=_('Search by server status'),
)
parser.add_argument(
'--flavor',
metavar='<flavor>',
help=_('Search by flavor (name or ID)'),
)
parser.add_argument(
'--image',
metavar='<image>',
help=_('Search by image (name or ID)'),
)
parser.add_argument(
'--host',
metavar='<hostname>',
help=_('Search by hostname'),
)
parser.add_argument(
'--all-projects',
action='store_true',
default=bool(int(os.environ.get("ALL_PROJECTS", 0))),
help=_('Include all projects (admin only)'),
)
parser.add_argument(
'--project',
metavar='<project>',
help=_("Search by project (admin only) (name or ID)")
)
identity_common.add_project_domain_option_to_parser(parser)
parser.add_argument(
'--user',
metavar='<user>',
help=_('Search by user (admin only) (name or ID)'),
)
identity_common.add_user_domain_option_to_parser(parser)
parser.add_argument(
'--long',
action='store_true',
default=False,
help=_('List additional fields in output'),
)
parser.add_argument(
'-n', '--no-name-lookup',
action='store_true',
default=False,
help=_('Skip flavor and image name lookup.'),
)
parser.add_argument(
'--marker',
metavar='<server>',
default=None,
help=_('The last server of the previous page. Display '
'list of servers after marker. Display all servers if not '
'specified. (name or ID)')
)
parser.add_argument(
'--limit',
metavar='<num-servers>',
type=int,
default=None,
help=_("Maximum number of servers to display. If limit equals -1, "
"all servers will be displayed. If limit is greater than "
"'osapi_max_limit' option of Nova API, "
"'osapi_max_limit' will be used instead."),
)
parser.add_argument(
'--deleted',
action="store_true",
default=False,
help=_('Only display deleted servers (Admin only).')
)
parser.add_argument(
'--changes-since',
metavar='<changes-since>',
default=None,
help=_("List only servers changed after a certain point of time."
" The provided time should be an ISO 8061 formatted time."
" ex 2016-03-04T06:27:59Z .")
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.compute
identity_client = self.app.client_manager.identity
image_client = self.app.client_manager.image
project_id = None
if parsed_args.project:
project_id = identity_common.find_project(
identity_client,
parsed_args.project,
parsed_args.project_domain,
).id
parsed_args.all_projects = True
user_id = None
if parsed_args.user:
user_id = identity_common.find_user(
identity_client,
parsed_args.user,
parsed_args.user_domain,
).id
# Nova only supports list servers searching by flavor ID. So if a
# flavor name is given, map it to ID.
flavor_id = None