/
shell.py
3046 lines (2537 loc) · 98.7 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.
import argparse
import copy
import datetime
import getpass
import locale
import os
import sys
import time
from novaclient import exceptions
from novaclient.openstack.common import timeutils
from novaclient import utils
from novaclient.v1_1 import availability_zones
from novaclient.v1_1 import servers
def _key_value_pairing(text):
try:
(k, v) = text.split('=', 1)
return (k, v)
except ValueError:
msg = "%r is not in the format of key=value" % text
raise argparse.ArgumentTypeError(msg)
def _match_image(cs, wanted_properties):
image_list = cs.images.list()
images_matched = []
match = set(wanted_properties)
for img in image_list:
try:
if match == match.intersection(set(img.metadata.items())):
images_matched.append(img)
except AttributeError:
pass
return images_matched
def _boot(cs, args, reservation_id=None, min_count=None, max_count=None):
"""Boot a new server."""
if min_count is None:
min_count = 1
if max_count is None:
max_count = min_count
if min_count > max_count:
raise exceptions.CommandError("min_instances should be <= "
"max_instances")
if not min_count or not max_count:
raise exceptions.CommandError("min_instances nor max_instances should"
"be 0")
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 images:
# TODO(harlowja): log a warning that we
# are selecting the first of many?
image = images[0]
if not image and not args.block_device_mapping:
raise exceptions.CommandError("you need to specify an Image ID "
"or a block device mapping "
"or provide a set of properties to match"
" against an image")
if not args.flavor:
raise exceptions.CommandError("you need to specify a Flavor ID ")
if args.num_instances is not None:
if args.num_instances <= 1:
raise exceptions.CommandError("num_instances should be > 1")
max_count = args.num_instances
flavor = _find_flavor(cs, args.flavor)
meta = dict(v.split('=', 1) for v in args.meta)
files = {}
for f in args.files:
dst, src = f.split('=', 1)
try:
files[dst] = open(src)
except IOError as e:
raise exceptions.CommandError("Can't open '%s': %s" % (src, e))
# 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:
userdata = open(args.user_data)
except IOError as e:
raise exceptions.CommandError("Can't open '%s': %s" %
(args.user_data, 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
nics = []
for nic_str in args.nics:
nic_info = {"net-id": "", "v4-fixed-ip": "", "port-id": ""}
for kv_str in nic_str.split(","):
k, v = kv_str.split("=", 1)
nic_info[k] = v
nics.append(nic_info)
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], basestring):
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,
files=files,
key_name=key_name,
reservation_id=reservation_id,
min_count=min_count,
max_count=max_count,
userdata=userdata,
availability_zone=availability_zone,
security_groups=security_groups,
block_device_mapping=block_device_mapping,
nics=nics,
scheduler_hints=hints,
config_drive=config_drive)
return boot_args, boot_kwargs
@utils.arg('--flavor',
default=None,
metavar='<flavor>',
help="Flavor ID (see 'nova flavor-list').")
@utils.arg('--image',
default=None,
metavar='<image>',
help="Image ID (see 'nova image-list'). ")
@utils.arg('--image-with',
default=[],
type=_key_value_pairing,
action='append',
metavar='<key=value>',
help="Image metadata property (see 'nova image-show'). ")
@utils.arg('--num-instances',
default=None,
type=int,
metavar='<number>',
help="boot multi instances at a time")
@utils.arg('--meta',
metavar="<key=value>",
action='append',
default=[],
help="Record arbitrary key/value metadata to /meta.js "
"on the new 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. You may store up to 5 files.")
@utils.arg('--key-name',
metavar='<key-name>',
help="Key name of keypair that should be created earlier with \
the command keypair-add")
@utils.arg('--key_name',
help=argparse.SUPPRESS)
@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('--user_data',
help=argparse.SUPPRESS)
@utils.arg('--availability-zone',
default=None,
metavar='<availability-zone>',
help="The availability zone for instance placement.")
@utils.arg('--availability_zone',
help=argparse.SUPPRESS)
@utils.arg('--security-groups',
default=None,
metavar='<security-groups>',
help="Comma separated list of security group names.")
@utils.arg('--security_groups',
help=argparse.SUPPRESS)
@utils.arg('--block-device-mapping',
metavar="<dev-name=mapping>",
action='append',
default=[],
help="Block device mapping in the format "
"<dev-name>=<id>:<type>:<size(GB)>:<delete-on-terminate>.")
@utils.arg('--block_device_mapping',
action='append',
help=argparse.SUPPRESS)
@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,v4-fixed-ip=ip-addr,port-id=port-uuid>",
action='append',
dest='nics',
default=[],
help="Create a NIC on the server.\n"
"Specify option multiple times to create multiple NICs.\n"
"net-id: attach NIC to network with this UUID (optional)\n"
"v4-fixed-ip: IPv4 fixed address for NIC (optional).\n"
"port-id: attach NIC to port with this UUID (optional)")
@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='Blocks while instance builds so progress can be reported.')
def do_boot(cs, args):
"""Boot a new server."""
boot_args, boot_kwargs = _boot(cs, args)
extra_boot_kwargs = utils.get_resource_manager_extra_kwargs(do_boot, args)
boot_kwargs.update(extra_boot_kwargs)
server = cs.servers.create(*boot_args, **boot_kwargs)
# Keep any information (like adminPass) returned by create
info = server._info
server = cs.servers.get(info['id'])
info.update(server._info)
flavor = info.get('flavor', {})
flavor_id = flavor.get('id', '')
info['flavor'] = _find_flavor(cs, flavor_id).name
image = info.get('image', {})
if image:
image_id = image.get('id', '')
info['image'] = _find_image(cs, image_id).name
else: # Booting from volume
info['image'] = "Attempt to boot from volume - no image supplied"
info.pop('links', None)
info.pop('addresses', None)
utils.print_dict(info)
if args.poll:
_poll_for_status(cs.servers.get, info['id'], 'building', ['active'])
def do_cloudpipe_list(cs, _args):
"""Print a list of all cloudpipe instances."""
cloudpipes = cs.cloudpipe.list()
columns = ['Project Id', "Public IP", "Public Port", "Internal IP"]
utils.print_list(cloudpipes, columns)
@utils.arg('project', metavar='<project>', help='Name of the project.')
def do_cloudpipe_create(cs, args):
"""Create a cloudpipe instance for the given project"""
cs.cloudpipe.create(args.project)
@utils.arg('address', metavar='<ip address>', help='New IP Address.')
@utils.arg('port', metavar='<port>', help='New Port.')
def do_cloudpipe_configure(cs, args):
"""Update the VPN IP/port of a cloudpipe instance"""
cs.cloudpipe.update(args.address, args.port)
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 = ('\rInstance %(action)s... %(progress)s%% complete'
% dict(action=action, progress=progress))
else:
msg = '\rInstance %(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 %(action)s instance" % locals())
break
if not silent:
print_progress(progress)
time.sleep(poll_period)
def _translate_keys(collection, convert):
for item in collection:
keys = item.__dict__.keys()
for from_key, to_key in convert:
if from_key in keys and to_key not in keys:
setattr(item, to_key, item._info[from_key])
def _translate_flavor_keys(collection):
_translate_keys(collection, [('ram', 'memory_mb')])
def _print_flavor_extra_specs(flavor):
try:
return flavor.get_keys()
except exceptions.NotFound:
return "N/A"
def _print_flavor_list(cs, flavors):
_translate_flavor_keys(flavors)
formatters = {'extra_specs': _print_flavor_extra_specs}
utils.print_list(flavors, [
'ID',
'Name',
'Memory_MB',
'Disk',
'Ephemeral',
'Swap',
'VCPUs',
'RXTX_Factor',
'Is_Public',
'extra_specs'], formatters)
def do_flavor_list(cs, _args):
"""Print a list of available 'flavors' (sizes of servers)."""
flavors = cs.flavors.list()
_print_flavor_list(cs, flavors)
@utils.arg('flavor',
metavar='<flavor>',
help="Name or ID of the flavor to delete")
def do_flavor_delete(cs, args):
"""Delete a specific flavor"""
flavorid = _find_flavor(cs, args.flavor)
cs.flavors.delete(flavorid)
@utils.arg('flavor',
metavar='<flavor>',
help="Name or ID of flavor")
def do_flavor_show(cs, args):
"""Show details about the given flavor."""
flavor = _find_flavor(cs, args.flavor)
_print_flavor(cs, flavor)
@utils.arg('name',
metavar='<name>',
help="Name of the new flavor")
@utils.arg('id',
metavar='<id>',
help="Unique ID (integer or UUID) for the new flavor."
" If specifying 'auto', a UUID will be generated as id")
@utils.arg('ram',
metavar='<ram>',
help="Memory size in MB")
@utils.arg('disk',
metavar='<disk>',
help="Disk size in GB")
@utils.arg('--ephemeral',
metavar='<ephemeral>',
help="Ephemeral space size in GB (default 0)",
default=0)
@utils.arg('vcpus',
metavar='<vcpus>',
help="Number of vcpus")
@utils.arg('--swap',
metavar='<swap>',
help="Swap space size in MB (default 0)",
default=0)
@utils.arg('--rxtx-factor',
metavar='<factor>',
help="RX/TX factor (default 1)",
default=1.0)
@utils.arg('--is-public',
metavar='<is-public>',
help="Make flavor accessible to the public (default true)",
type=utils.bool_from_str,
default=True)
def do_flavor_create(cs, args):
"""Create a new flavor"""
f = cs.flavors.create(args.name, args.ram, args.vcpus, args.disk, args.id,
args.ephemeral, args.swap, args.rxtx_factor,
args.is_public)
_print_flavor_list(cs, [f])
@utils.arg('flavor',
metavar='<flavor>',
help="Name or ID of flavor")
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help="Actions: 'set' or 'unset'")
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
action='append',
default=[],
help='Extra_specs to set/unset (only key is necessary on unset)')
def do_flavor_key(cs, args):
"""Set or unset extra_spec for a flavor."""
flavor = _find_flavor(cs, args.flavor)
keypair = _extract_metadata(args)
if args.action == 'set':
flavor.set_keys(keypair)
elif args.action == 'unset':
flavor.unset_keys(keypair.keys())
@utils.arg('--flavor',
metavar='<flavor>',
help="Filter results by flavor name or ID.")
@utils.arg('--tenant', metavar='<tenant_id>',
help='Filter results by tenant ID.')
def do_flavor_access_list(cs, args):
"""Print access information about the given flavor."""
if args.flavor and args.tenant:
raise exceptions.CommandError("Unable to filter results by "
"both --flavor and --tenant.")
elif args.flavor:
flavor = _find_flavor(cs, args.flavor)
if flavor.is_public:
raise exceptions.CommandError("Failed to get access list "
"for public flavor type.")
kwargs = {'flavor': flavor}
elif args.tenant:
kwargs = {'tenant': args.tenant}
else:
raise exceptions.CommandError("Unable to get all access lists. "
"Specify --flavor or --tenant")
try:
access_list = cs.flavor_access.list(**kwargs)
except NotImplementedError as e:
raise exceptions.CommandError("%s" % str(e))
columns = ['Flavor_ID', 'Tenant_ID']
utils.print_list(access_list, columns)
@utils.arg('flavor',
metavar='<flavor>',
help="Filter results by flavor name or ID.")
@utils.arg('tenant', metavar='<tenant_id>',
help='Filter results by tenant ID.')
def do_flavor_access_add(cs, args):
"""Add flavor access for the given tenant."""
flavor = _find_flavor(cs, args.flavor)
access_list = cs.flavor_access.add_tenant_access(flavor, args.tenant)
columns = ['Flavor_ID', 'Tenant_ID']
utils.print_list(access_list, columns)
@utils.arg('flavor',
metavar='<flavor>',
help="Filter results by flavor name or ID.")
@utils.arg('tenant', metavar='<tenant_id>',
help='Filter results by tenant ID.')
def do_flavor_access_remove(cs, args):
"""Remove flavor access for the given tenant."""
flavor = _find_flavor(cs, args.flavor)
access_list = cs.flavor_access.remove_tenant_access(flavor, args.tenant)
columns = ['Flavor_ID', 'Tenant_ID']
utils.print_list(access_list, columns)
@utils.arg('project_id', metavar='<project_id>',
help='The ID of the project.')
def do_scrub(cs, args):
"""Deletes data associated with the project"""
networks_list = cs.networks.list()
networks_list = [network for network in networks_list
if getattr(network, 'project_id', '') == args.project_id]
search_opts = {'all_tenants': 1}
groups = cs.security_groups.list(search_opts)
groups = [group for group in groups
if group.tenant_id == args.project_id]
for network in networks_list:
cs.networks.disassociate(network)
for group in groups:
cs.security_groups.delete(group)
def do_network_list(cs, _args):
"""Print a list of available networks."""
network_list = cs.networks.list()
columns = ['ID', 'Label', 'Cidr']
utils.print_list(network_list, columns)
@utils.arg('network',
metavar='<network>',
help="uuid or label of network")
def do_network_show(cs, args):
"""Show details about the given network."""
network = utils.find_resource(cs.networks, args.network)
utils.print_dict(network._info)
@utils.arg('--host-only',
dest='host_only',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0)
@utils.arg('--project-only',
dest='project_only',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0)
@utils.arg('network',
metavar='<network>',
help="uuid of network")
def do_network_disassociate(cs, args):
"""Disassociate host and/or project from the given network."""
if args.host_only:
cs.networks.disassociate(args.network, True, False)
elif args.project_only:
cs.networks.disassociate(args.network, False, True)
else:
cs.networks.disassociate(args.network, True, True)
@utils.arg('network',
metavar='<network>',
help="uuid of network")
@utils.arg('host',
metavar='<host>',
help="Name of host")
def do_network_associate_host(cs, args):
"""Associate host with network."""
cs.networks.associate_host(args.network, args.host)
@utils.arg('network',
metavar='<network>',
help="uuid of network")
def do_network_associate_project(cs, args):
"""Associate project with network."""
cs.networks.associate_project(args.network)
def _filter_network_create_options(args):
valid_args = ['label', 'cidr', 'vlan', 'vpn_start', 'cidr_v6', 'gateway',
'gateway_v6', 'bridge', 'multi_host', 'dns1', 'dns2', 'uuid',
'fixed_cidr', 'project_id', 'priority']
kwargs = {}
for k, v in args.__dict__.items():
if k in valid_args and v is not None:
kwargs[k] = v
return kwargs
@utils.arg('label',
metavar='<network_label>',
help="Label for network")
@utils.arg('--fixed-range-v4',
dest='cidr',
metavar='<x.x.x.x/yy>',
help="IPv4 subnet (ex: 10.0.0.0/8)")
@utils.arg('--fixed-range-v6',
dest="cidr_v6",
help='IPv6 subnet (ex: fe80::/64')
@utils.arg('--vlan',
dest='vlan',
metavar='<vlan id>',
help="vlan id")
@utils.arg('--vpn',
dest='vpn_start',
metavar='<vpn start>',
help="vpn start")
@utils.arg('--gateway',
dest="gateway",
help='gateway')
@utils.arg('--gateway-v6',
dest="gateway_v6",
help='ipv6 gateway')
@utils.arg('--bridge',
dest="bridge",
metavar='<bridge>',
help='VIFs on this network are connected to this bridge')
@utils.arg('--bridge-interface',
dest="bridge_interface",
metavar='<bridge interface>',
help='the bridge is connected to this interface')
@utils.arg('--multi-host',
dest="multi_host",
metavar="<'T'|'F'>",
help='Multi host')
@utils.arg('--dns1',
dest="dns1",
metavar="<DNS Address>", help='First DNS')
@utils.arg('--dns2',
dest="dns2",
metavar="<DNS Address>",
help='Second DNS')
@utils.arg('--uuid',
dest="uuid",
metavar="<network uuid>",
help='Network UUID')
@utils.arg('--fixed-cidr',
dest="fixed_cidr",
metavar='<x.x.x.x/yy>',
help='IPv4 subnet for fixed IPS (ex: 10.20.0.0/16)')
@utils.arg('--project-id',
dest="project_id",
metavar="<project id>",
help='Project id')
@utils.arg('--priority',
dest="priority",
metavar="<number>",
help='Network interface priority')
def do_network_create(cs, args):
"""Create a network."""
if not (args.cidr or args.cidr_v6):
raise exceptions.CommandError(
"Must specify eith fixed_range_v4 or fixed_range_v6")
kwargs = _filter_network_create_options(args)
cs.networks.create(**kwargs)
@utils.arg('--limit',
dest="limit",
metavar="<limit>",
help='number of images to return per request')
def do_image_list(cs, _args):
"""Print a list of available images to boot from."""
limit = _args.limit
image_list = cs.images.list(limit=limit)
def parse_server_name(image):
try:
return image.server['id']
except (AttributeError, KeyError):
return ''
fmts = {'Server': parse_server_name}
utils.print_list(image_list, ['ID', 'Name', 'Status', 'Server'],
fmts, sortby_index=1)
@utils.arg('image',
metavar='<image>',
help="Name or ID of image")
@utils.arg('action',
metavar='<action>',
choices=['set', 'delete'],
help="Actions: 'set' or 'delete'")
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
action='append',
default=[],
help='Metadata to add/update or delete (only key is necessary on delete)')
def do_image_meta(cs, args):
"""Set or Delete metadata on an image."""
image = _find_image(cs, args.image)
metadata = _extract_metadata(args)
if args.action == 'set':
cs.images.set_meta(image, metadata)
elif args.action == 'delete':
cs.images.delete_meta(image, metadata.keys())
def _extract_metadata(args):
metadata = {}
for metadatum in args.metadata[0]:
# Can only pass the key in on 'delete'
# So this doesn't have to have '='
if metadatum.find('=') > -1:
(key, value) = metadatum.split('=', 1)
else:
key = metadatum
value = None
metadata[key] = value
return metadata
def _print_image(image):
info = image._info.copy()
# ignore links, we don't need to present those
info.pop('links')
# try to replace a server entity to just an id
server = info.pop('server', None)
try:
info['server'] = server['id']
except (KeyError, TypeError):
pass
# break up metadata and display each on its own row
metadata = info.pop('metadata', {})
try:
for key, value in metadata.items():
_key = 'metadata %s' % key
info[_key] = value
except AttributeError:
pass
utils.print_dict(info)
def _print_flavor(cs, flavor):
info = flavor._info.copy()
# ignore links, we don't need to present those
info.pop('links')
info.update({"extra_specs": _print_flavor_extra_specs(flavor)})
utils.print_dict(info)
@utils.arg('image',
metavar='<image>',
help="Name or ID of image")
def do_image_show(cs, args):
"""Show details about the given image."""
image = _find_image(cs, args.image)
_print_image(image)
@utils.arg('image', metavar='<image>', help='Name or ID of image.')
def do_image_delete(cs, args):
"""
Delete an image.
It should go without saying, but you can only delete images you
created.
"""
image = _find_image(cs, args.image)
image.delete()
@utils.arg('--reservation-id',
dest='reservation_id',
metavar='<reservation-id>',
default=None,
help='Only return instances that match reservation-id.')
@utils.arg('--reservation_id',
help=argparse.SUPPRESS)
@utils.arg('--ip',
dest='ip',
metavar='<ip-regexp>',
default=None,
help='Search with regular expression match by IP address (Admin only).')
@utils.arg('--ip6',
dest='ip6',
metavar='<ip6-regexp>',
default=None,
help='Search with regular expression match by IPv6 address (Admin only).')
@utils.arg('--name',
dest='name',
metavar='<name-regexp>',
default=None,
help='Search with regular expression match by name')
@utils.arg('--instance-name',
dest='instance_name',
metavar='<name-regexp>',
default=None,
help='Search with regular expression match by instance name (Admin only).')
@utils.arg('--instance_name',
help=argparse.SUPPRESS)
@utils.arg('--status',
dest='status',
metavar='<status>',
default=None,
help='Search by server status')
@utils.arg('--flavor',
dest='flavor',
metavar='<flavor>',
default=None,
help='Search by flavor name or ID')
@utils.arg('--image',
dest='image',
metavar='<image>',
default=None,
help='Search by image name or ID')
@utils.arg('--host',
dest='host',
metavar='<hostname>',
default=None,
help='Search instances by hostname to which they are assigned '
'(Admin only).')
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=int(utils.bool_from_str(os.environ.get("ALL_TENANTS", 'false'))),
help='Display information from all tenants (Admin only).')
@utils.arg('--all_tenants',
nargs='?',
type=int,
const=1,
help=argparse.SUPPRESS)
@utils.arg('--tenant',
#nova db searches by project_id
dest='tenant',
metavar='<tenant>',
nargs='?',
help='Display information from single tenant (Admin only).')
@utils.arg('--fields',
default=None,
metavar='<fields>',
help='Comma-separated list of fields to display. '
'Use the show command to see which fields are available.')
def do_list(cs, args):
"""List active servers."""
imageid = None
flavorid = None
if args.image:
imageid = _find_image(cs, args.image).id
if args.flavor:
flavorid = _find_flavor(cs, args.flavor).id
search_opts = {
'all_tenants': args.all_tenants,
'reservation_id': args.reservation_id,
'ip': args.ip,
'ip6': args.ip6,
'name': args.name,
'image': imageid,
'flavor': flavorid,
'status': args.status,
'project_id': args.tenant,
'host': args.host,
'instance_name': args.instance_name}
filters = {'flavor': lambda f: f['id'],
'security_groups': utils._format_security_groups}
formatters = {}
field_titles = []
if args.fields:
for field in args.fields.split(','):
field_title, formatter = utils._make_field_formatter(field,
filters)
field_titles.append(field_title)
formatters[field_title] = formatter
id_col = 'ID'
servers = cs.servers.list(search_opts=search_opts)
convert = [('OS-EXT-SRV-ATTR:host', 'host'),
('OS-EXT-STS:task_state', 'task_state'),
('OS-EXT-SRV-ATTR:instance_name', 'instance_name'),
('hostId', 'host_id')]
_translate_keys(servers, convert)
if field_titles:
columns = [id_col] + field_titles
else:
columns = [id_col, 'Name', 'Status', 'Networks']
formatters['Networks'] = utils._format_servers_list_networks
utils.print_list(servers, columns,
formatters, sortby_index=1)
@utils.arg('--hard',
dest='reboot_type',
action='store_const',
const=servers.REBOOT_HARD,
default=servers.REBOOT_SOFT,
help='Perform a hard reboot (instead of a soft one).')
@utils.arg('server', metavar='<server>', help='Name or ID of server.')
@utils.arg('--poll',
dest='poll',
action="store_true",
default=False,
help='Blocks while instance is rebooting.')
def do_reboot(cs, args):
"""Reboot a server."""
server = _find_server(cs, args.server)
server.reboot(args.reboot_type)
if args.poll:
_poll_for_status(cs.servers.get, server.id, 'rebooting', ['active'],
show_progress=False)
@utils.arg('server', metavar='<server>', help='Name or ID of server.')
@utils.arg('image', metavar='<image>', help="Name or ID of new image.")
@utils.arg('--rebuild-password',
dest='rebuild_password',
metavar='<rebuild-password>',
default=False,
help="Set the provided password on the rebuild instance.")
@utils.arg('--rebuild_password',
help=argparse.SUPPRESS)
@utils.arg('--poll',
dest='poll',
action="store_true",
default=False,
help='Blocks while instance rebuilds so progress can be reported.')
@utils.arg('--minimal',
dest='minimal',
action="store_true",
default=False,
help='Skips flavor/image lookups when showing instances')
def do_rebuild(cs, args):
"""Shutdown, re-image, and re-boot a server."""
server = _find_server(cs, args.server)
image = _find_image(cs, args.image)
if args.rebuild_password is not False:
_password = args.rebuild_password
else: