-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathshell_base.py
More file actions
2436 lines (2117 loc) · 87.4 KB
/
shell_base.py
File metadata and controls
2436 lines (2117 loc) · 87.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2013-2014 OpenStack Foundation
# 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 collections
import copy
import os
from oslo_utils import strutils
from cinderclient import base
from cinderclient import exceptions
from cinderclient import shell_utils
from cinderclient import utils
from cinderclient.v3 import availability_zones
def _translate_attachments(info):
attachments = []
attached_servers = []
for attachment in info['attachments']:
attachments.append(attachment['attachment_id'])
attached_servers.append(attachment['server_id'])
info.pop('attachments', None)
info['attachment_ids'] = attachments
info['attached_servers'] = attached_servers
return info
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--all_tenants',
nargs='?',
type=int,
const=1,
help=argparse.SUPPRESS)
@utils.arg('--name',
metavar='<name>',
default=None,
help='Filters results by a name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.arg('--status',
metavar='<status>',
default=None,
help='Filters results by a status. Default=None.')
@utils.arg('--bootable',
metavar='<True|true|False|false>',
const=True,
nargs='?',
choices=['True', 'true', 'False', 'false'],
help='Filters results by bootable status. Default=None.')
@utils.arg('--migration_status',
metavar='<migration_status>',
default=None,
help='Filters results by a migration status. Default=None. '
'Admin only.')
@utils.arg('--metadata',
nargs='*',
metavar='<key=value>',
default=None,
help='Filters results by a image metadata key and value pair. '
'Default=None.')
@utils.arg('--marker',
metavar='<marker>',
default=None,
help='Begin returning volumes that appear later in the volume '
'list than that represented by this volume id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
help='Maximum number of volumes to return. Default=None.')
@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. '
'Unavailable/non-existent fields will be ignored. '
'Default=None.')
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
@utils.arg('--tenant',
type=str,
dest='tenant',
nargs='?',
metavar='<tenant>',
help='Display information from single tenant (Admin only).')
def do_list(cs, args):
"""Lists all volumes."""
# NOTE(thingee): Backwards-compatibility with v1 args
if args.display_name is not None:
args.name = args.display_name
all_tenants = 1 if args.tenant else \
int(os.environ.get("ALL_TENANTS", args.all_tenants))
search_opts = {
'all_tenants': all_tenants,
'project_id': args.tenant,
'name': args.name,
'status': args.status,
'bootable': args.bootable,
'migration_status': args.migration_status,
'metadata': (shell_utils.extract_metadata(args) if args.metadata
else None),
}
# If unavailable/non-existent fields are specified, these fields will
# be removed from key_list at the print_list() during key validation.
field_titles = []
if args.fields:
for field_title in args.fields.split(','):
field_titles.append(field_title)
volumes = cs.volumes.list(search_opts=search_opts, marker=args.marker,
limit=args.limit, sort=args.sort)
shell_utils.translate_volume_keys(volumes)
# Create a list of servers to which the volume is attached
for vol in volumes:
servers = [s.get('server_id') for s in vol.attachments]
setattr(vol, 'attached_to', ','.join(map(str, servers)))
if field_titles:
# Remove duplicate fields
key_list = ['ID']
unique_titles = [k for k in collections.OrderedDict.fromkeys(
[x.title().strip() for x in field_titles]) if k != 'Id']
key_list.extend(unique_titles)
else:
key_list = ['ID', 'Status', 'Name', 'Size', 'Volume Type',
'Bootable', 'Attached to']
# If all_tenants is specified, print
# Tenant ID as well.
if search_opts['all_tenants']:
key_list.insert(1, 'Tenant ID')
if args.sort:
sortby_index = None
else:
sortby_index = 0
shell_utils.print_list(volumes, key_list, exclude_unavailable=True,
sortby_index=sortby_index)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume.')
def do_show(cs, args):
"""Shows volume details."""
info = dict()
volume = utils.find_volume(cs, args.volume)
info.update(volume._info)
if 'readonly' in info['metadata']:
info['readonly'] = info['metadata']['readonly']
info.pop('links', None)
info = _translate_attachments(info)
shell_utils.print_dict(info,
formatters=['metadata', 'volume_image_metadata',
'attachment_ids', 'attached_servers'])
class CheckSizeArgForCreate(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if ((args.snapshot_id or args.source_volid)
is None and values is None):
if not hasattr(args, 'backup_id') or args.backup_id is None:
parser.error('Size is a required parameter if snapshot '
'or source volume or backup is not specified.')
setattr(args, self.dest, values)
@utils.arg('size',
metavar='<size>',
nargs='?',
type=int,
action=CheckSizeArgForCreate,
help='Size of volume, in GiBs. (Required unless '
'snapshot-id/source-volid is specified).')
@utils.arg('--consisgroup-id',
metavar='<consistencygroup-id>',
default=None,
help='ID of a consistency group where the new volume belongs to. '
'Default=None.')
@utils.arg('--snapshot-id',
metavar='<snapshot-id>',
default=None,
help='Creates volume from snapshot ID. Default=None.')
@utils.arg('--snapshot_id',
help=argparse.SUPPRESS)
@utils.arg('--source-volid',
metavar='<source-volid>',
default=None,
help='Creates volume from volume ID. Default=None.')
@utils.arg('--source_volid',
help=argparse.SUPPRESS)
@utils.arg('--image-id',
metavar='<image-id>',
default=None,
help='Creates volume from image ID. Default=None.')
@utils.arg('--image_id',
help=argparse.SUPPRESS)
@utils.arg('--image',
metavar='<image>',
default=None,
help='Creates a volume from image (ID or name). Default=None.')
@utils.arg('--image_ref',
help=argparse.SUPPRESS)
@utils.arg('--name',
metavar='<name>',
default=None,
help='Volume name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.arg('--display_name',
help=argparse.SUPPRESS)
@utils.arg('--description',
metavar='<description>',
default=None,
help='Volume description. Default=None.')
@utils.arg('--display-description',
help=argparse.SUPPRESS)
@utils.arg('--display_description',
help=argparse.SUPPRESS)
@utils.arg('--volume-type',
metavar='<volume-type>',
default=None,
help='Volume type. Default=None.')
@utils.arg('--volume_type',
help=argparse.SUPPRESS)
@utils.arg('--availability-zone',
metavar='<availability-zone>',
default=None,
help='Availability zone for volume. Default=None.')
@utils.arg('--availability_zone',
help=argparse.SUPPRESS)
@utils.arg('--metadata',
nargs='*',
metavar='<key=value>',
default=None,
help='Metadata key and value pairs. Default=None.')
@utils.arg('--hint',
metavar='<key=value>',
dest='scheduler_hints',
action='append',
default=[],
help='Scheduler hint, similar to nova. Repeat option to set '
'multiple hints. Values with the same key will be stored '
'as a list.')
def do_create(cs, args):
"""Creates a volume."""
# NOTE(thingee): Backwards-compatibility with v1 args
if args.display_name is not None:
args.name = args.display_name
if args.display_description is not None:
args.description = args.display_description
volume_metadata = None
if args.metadata is not None:
volume_metadata = shell_utils.extract_metadata(args)
# NOTE(N.S.): take this piece from novaclient
hints = {}
if args.scheduler_hints:
for hint in args.scheduler_hints:
key, _sep, value = hint.partition('=')
# NOTE(vish): multiple copies of same hint will
# result in a list of values
if key in hints:
if isinstance(hints[key], str):
hints[key] = [hints[key]]
hints[key] += [value]
else:
hints[key] = value
# NOTE(N.S.): end of taken piece
# Keep backward compatibility with image_id, favoring explicit ID
image_ref = args.image_id or args.image or args.image_ref
volume = cs.volumes.create(args.size,
args.consisgroup_id,
args.snapshot_id,
args.source_volid,
args.name,
args.description,
args.volume_type,
availability_zone=args.availability_zone,
imageRef=image_ref,
metadata=volume_metadata,
scheduler_hints=hints)
info = dict()
volume = cs.volumes.get(volume.id)
info.update(volume._info)
if 'readonly' in info['metadata']:
info['readonly'] = info['metadata']['readonly']
info.pop('links', None)
info = _translate_attachments(info)
shell_utils.print_dict(info)
@utils.arg('--cascade',
action='store_true',
default=False,
help='Remove any snapshots along with volume. Default=False.')
@utils.arg('volume',
metavar='<volume>', nargs='+',
help='Name or ID of volume or volumes to delete.')
def do_delete(cs, args):
"""Removes one or more volumes."""
failure_count = 0
for volume in args.volume:
try:
utils.find_volume(cs, volume).delete(cascade=args.cascade)
print("Request to delete volume %s has been accepted." % (volume))
except Exception as e:
failure_count += 1
print("Delete for volume %s failed: %s" % (volume, e))
if failure_count == len(args.volume):
raise exceptions.CommandError("Unable to delete any of the specified "
"volumes.")
@utils.arg('volume',
metavar='<volume>', nargs='+',
help='Name or ID of volume or volumes to delete.')
def do_force_delete(cs, args):
"""Attempts force-delete of volume, regardless of state."""
failure_count = 0
for volume in args.volume:
try:
utils.find_volume(cs, volume).force_delete()
except Exception as e:
failure_count += 1
print("Delete for volume %s failed: %s" % (volume, e))
if failure_count == len(args.volume):
raise exceptions.CommandError("Unable to force delete any of the "
"specified volumes.")
@utils.arg('volume', metavar='<volume>', nargs='+',
help='Name or ID of volume to modify.')
@utils.arg('--state', metavar='<state>', default=None,
help=('The state to assign to the volume. Valid values are '
'"available", "error", "creating", "deleting", "in-use", '
'"attaching", "detaching", "error_deleting" and '
'"maintenance". '
'NOTE: This command simply changes the state of the '
'Volume in the DataBase with no regard to actual status, '
'exercise caution when using. Default=None, that means the '
'state is unchanged.'))
@utils.arg('--attach-status', metavar='<attach-status>', default=None,
help=('The attach status to assign to the volume in the DataBase, '
'with no regard to the actual status. Valid values are '
'"attached" and "detached". Default=None, that means the '
'status is unchanged.'))
@utils.arg('--reset-migration-status',
action='store_true',
help=('Clears the migration status of the volume in the DataBase '
'that indicates the volume is source or destination of '
'volume migration, with no regard to the actual status.'))
def do_reset_state(cs, args):
"""Explicitly updates the volume state in the Cinder database.
Note that this does not affect whether the volume is actually attached to
the Nova compute host or instance and can result in an unusable volume.
Being a database change only, this has no impact on the true state of the
volume and may not match the actual state. This can render a volume
unusable in the case of change to the 'available' state.
"""
failure_flag = False
migration_status = 'none' if args.reset_migration_status else None
if not (args.state or args.attach_status or migration_status):
# Nothing specified, default to resetting state
args.state = 'available'
for volume in args.volume:
try:
utils.find_volume(cs, volume).reset_state(args.state,
args.attach_status,
migration_status)
except Exception as e:
failure_flag = True
msg = "Reset state for volume %s failed: %s" % (volume, e)
print(msg)
if failure_flag:
msg = "Unable to reset the state for the specified volume(s)."
raise exceptions.CommandError(msg)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume to rename.')
@utils.arg('name',
nargs='?',
metavar='<name>',
help='New name for volume.')
@utils.arg('--description', metavar='<description>',
help='Volume description. Default=None.',
default=None)
@utils.arg('--display-description',
help=argparse.SUPPRESS)
@utils.arg('--display_description',
help=argparse.SUPPRESS)
def do_rename(cs, args):
"""Renames a volume."""
kwargs = {}
if args.name is not None:
kwargs['name'] = args.name
if args.display_description is not None:
kwargs['description'] = args.display_description
elif args.description is not None:
kwargs['description'] = args.description
if not any(kwargs):
msg = 'Must supply either name or description.'
raise exceptions.ClientException(code=1, message=msg)
utils.find_volume(cs, args.volume).update(**kwargs)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume for which to update metadata.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help='The action. Valid values are "set" or "unset."')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='Metadata key and value pair to set or unset. '
'For unset, specify only the key.')
def do_metadata(cs, args):
"""Sets or deletes volume metadata."""
volume = utils.find_volume(cs, args.volume)
metadata = shell_utils.extract_metadata(args)
if args.action == 'set':
cs.volumes.set_metadata(volume, metadata)
elif args.action == 'unset':
# NOTE(zul): Make sure py2/py3 sorting is the same
cs.volumes.delete_metadata(volume, sorted(metadata.keys(),
reverse=True))
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume for which to update metadata.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help="The action. Valid values are 'set' or 'unset.'")
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='Metadata key and value pair to set or unset. '
'For unset, specify only the key.')
def do_image_metadata(cs, args):
"""Sets or deletes volume image metadata."""
volume = utils.find_volume(cs, args.volume)
metadata = shell_utils.extract_metadata(args)
if args.action == 'set':
cs.volumes.set_image_metadata(volume, metadata)
elif args.action == 'unset':
cs.volumes.delete_image_metadata(volume, sorted(metadata.keys(),
reverse=True))
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--all_tenants',
nargs='?',
type=int,
const=1,
help=argparse.SUPPRESS)
@utils.arg('--name',
metavar='<name>',
default=None,
help='Filters results by a name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.arg('--display_name',
help=argparse.SUPPRESS)
@utils.arg('--status',
metavar='<status>',
default=None,
help='Filters results by a status. Default=None.')
@utils.arg('--volume-id',
metavar='<volume-id>',
default=None,
help='Filters results by a volume ID. Default=None.')
@utils.arg('--volume_id',
help=argparse.SUPPRESS)
@utils.arg('--marker',
metavar='<marker>',
default=None,
help='Begin returning snapshots that appear later in the snapshot '
'list than that represented by this id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
help='Maximum number of snapshots to return. Default=None.')
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
@utils.arg('--tenant',
type=str,
dest='tenant',
nargs='?',
metavar='<tenant>',
help='Display information from single tenant (Admin only).')
def do_snapshot_list(cs, args):
"""Lists all snapshots."""
all_tenants = (1 if args.tenant else
int(os.environ.get("ALL_TENANTS", args.all_tenants)))
if args.display_name is not None:
args.name = args.display_name
search_opts = {
'all_tenants': all_tenants,
'name': args.name,
'status': args.status,
'volume_id': args.volume_id,
'project_id': args.tenant,
}
snapshots = cs.volume_snapshots.list(search_opts=search_opts,
marker=args.marker,
limit=args.limit,
sort=args.sort)
shell_utils.translate_volume_snapshot_keys(snapshots)
if args.sort:
sortby_index = None
else:
sortby_index = 0
shell_utils.print_list(snapshots,
['ID', 'Volume ID', 'Status', 'Name', 'Size'],
sortby_index=sortby_index)
@utils.arg('snapshot',
metavar='<snapshot>',
help='Name or ID of snapshot.')
def do_snapshot_show(cs, args):
"""Shows snapshot details."""
snapshot = shell_utils.find_volume_snapshot(cs, args.snapshot)
shell_utils.print_volume_snapshot(snapshot)
@utils.arg('snapshot',
metavar='<snapshot>', nargs='+',
help='Name or ID of the snapshot(s) to delete.')
@utils.arg('--force',
action="store_true",
help='Allows deleting snapshot of a volume '
'when its status is other than "available" or "error". '
'Default=False.')
def do_snapshot_delete(cs, args):
"""Removes one or more snapshots."""
failure_count = 0
for snapshot in args.snapshot:
try:
shell_utils.find_volume_snapshot(cs, snapshot).delete(args.force)
except Exception as e:
failure_count += 1
print("Delete for snapshot %s failed: %s" % (snapshot, e))
if failure_count == len(args.snapshot):
raise exceptions.CommandError("Unable to delete any of the specified "
"snapshots.")
@utils.arg('snapshot', metavar='<snapshot>',
help='Name or ID of snapshot.')
@utils.arg('name', nargs='?', metavar='<name>',
help='New name for snapshot.')
@utils.arg('--description', metavar='<description>',
default=None,
help='Snapshot description. Default=None.')
@utils.arg('--display-description',
help=argparse.SUPPRESS)
@utils.arg('--display_description',
help=argparse.SUPPRESS)
def do_snapshot_rename(cs, args):
"""Renames a snapshot."""
kwargs = {}
if args.name is not None:
kwargs['name'] = args.name
if args.description is not None:
kwargs['description'] = args.description
elif args.display_description is not None:
kwargs['description'] = args.display_description
if not any(kwargs):
msg = 'Must supply either name or description.'
raise exceptions.ClientException(code=1, message=msg)
shell_utils.find_volume_snapshot(cs, args.snapshot).update(**kwargs)
print("Request to rename snapshot '%s' has been accepted." % (
args.snapshot))
@utils.arg('snapshot', metavar='<snapshot>', nargs='+',
help='Name or ID of snapshot to modify.')
@utils.arg('--state', metavar='<state>',
default='available',
help=('The state to assign to the snapshot. Valid values are '
'"available", "error", "creating", "deleting", and '
'"error_deleting". NOTE: This command simply changes '
'the state of the Snapshot in the DataBase with no regard '
'to actual status, exercise caution when using. '
'Default=available.'))
def do_snapshot_reset_state(cs, args):
"""Explicitly updates the snapshot state."""
failure_count = 0
single = (len(args.snapshot) == 1)
for snapshot in args.snapshot:
try:
shell_utils.find_volume_snapshot(
cs, snapshot).reset_state(args.state)
except Exception as e:
failure_count += 1
msg = "Reset state for snapshot %s failed: %s" % (snapshot, e)
if not single:
print(msg)
if failure_count == len(args.snapshot):
if not single:
msg = ("Unable to reset the state for any of the specified "
"snapshots.")
raise exceptions.CommandError(msg)
def do_type_list(cs, args):
"""Lists available 'volume types'.
(Only admin and tenant users will see private types)
"""
vtypes = cs.volume_types.list()
shell_utils.print_volume_type_list(vtypes)
def do_type_default(cs, args):
"""List the default volume type.
The Block Storage service allows configuration of a default
type for each project, as well as the system default, so use
this command to determine what your effective default volume
type is.
"""
vtype = cs.volume_types.default()
shell_utils.print_volume_type_list([vtype])
@utils.arg('volume_type',
metavar='<volume_type>',
help='Name or ID of the volume type.')
def do_type_show(cs, args):
"""Show volume type details."""
vtype = shell_utils.find_vtype(cs, args.volume_type)
info = dict()
info.update(vtype._info)
info.pop('links', None)
shell_utils.print_dict(info, formatters=['extra_specs'])
@utils.arg('id',
metavar='<id>',
help='ID of the volume type.')
@utils.arg('--name',
metavar='<name>',
help='Name of the volume type.')
@utils.arg('--description',
metavar='<description>',
help='Description of the volume type.')
@utils.arg('--is-public',
metavar='<is-public>',
help='Make type accessible to the public or not.')
def do_type_update(cs, args):
"""Updates volume type name, description, and/or is_public."""
is_public = args.is_public
if args.name is None and args.description is None and is_public is None:
raise exceptions.CommandError('Specify a new type name, description, '
'is_public or a combination thereof.')
if is_public is not None:
is_public = strutils.bool_from_string(args.is_public, strict=True)
vtype = cs.volume_types.update(args.id, args.name, args.description,
is_public)
shell_utils.print_volume_type_list([vtype])
def do_extra_specs_list(cs, args):
"""Lists current volume types and extra specs."""
vtypes = cs.volume_types.list()
shell_utils.print_list(vtypes, ['ID', 'Name', 'extra_specs'])
@utils.arg('name',
metavar='<name>',
help='Name of new volume type.')
@utils.arg('--description',
metavar='<description>',
help='Description of new volume type.')
@utils.arg('--is-public',
metavar='<is-public>',
default=True,
help='Make type accessible to the public (default true).')
def do_type_create(cs, args):
"""Creates a volume type."""
is_public = strutils.bool_from_string(args.is_public, strict=True)
vtype = cs.volume_types.create(args.name, args.description, is_public)
shell_utils.print_volume_type_list([vtype])
@utils.arg('vol_type',
metavar='<vol_type>', nargs='+',
help='Name or ID of volume type or types to delete.')
def do_type_delete(cs, args):
"""Deletes volume type or types."""
failure_count = 0
for vol_type in args.vol_type:
try:
vtype = shell_utils.find_volume_type(cs, vol_type)
cs.volume_types.delete(vtype)
print("Request to delete volume type %s has been accepted."
% (vol_type))
except Exception as e:
failure_count += 1
print("Delete for volume type %s failed: %s" % (vol_type, e))
if failure_count == len(args.vol_type):
raise exceptions.CommandError("Unable to delete any of the "
"specified types.")
@utils.arg('vtype',
metavar='<vtype>',
help='Name or ID of volume type.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help='The action. Valid values are "set" or "unset."')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='The extra specs key and value pair to set or unset. '
'For unset, specify only the key.')
def do_type_key(cs, args):
"""Sets or unsets extra_spec for a volume type."""
vtype = shell_utils.find_volume_type(cs, args.vtype)
keypair = shell_utils.extract_metadata(args)
if args.action == 'set':
vtype.set_keys(keypair)
elif args.action == 'unset':
vtype.unset_keys(list(keypair))
@utils.arg('--volume-type', metavar='<volume_type>', required=True,
help='Filter results by volume type name or ID.')
def do_type_access_list(cs, args):
"""Print access information about the given volume type."""
volume_type = shell_utils.find_volume_type(cs, args.volume_type)
if volume_type.is_public:
raise exceptions.CommandError("Failed to get access list "
"for public volume type.")
access_list = cs.volume_type_access.list(volume_type)
columns = ['Volume_type_ID', 'Project_ID']
shell_utils.print_list(access_list, columns)
@utils.arg('--volume-type', metavar='<volume_type>', required=True,
help='Volume type name or ID to add access for the given project.')
@utils.arg('--project-id', metavar='<project_id>', required=True,
help='Project ID to add volume type access for.')
def do_type_access_add(cs, args):
"""Adds volume type access for the given project."""
vtype = shell_utils.find_volume_type(cs, args.volume_type)
cs.volume_type_access.add_project_access(vtype, args.project_id)
@utils.arg('--volume-type', metavar='<volume_type>', required=True,
help=('Volume type name or ID to remove access '
'for the given project.'))
@utils.arg('--project-id', metavar='<project_id>', required=True,
help='Project ID to remove volume type access for.')
def do_type_access_remove(cs, args):
"""Removes volume type access for the given project."""
vtype = shell_utils.find_volume_type(cs, args.volume_type)
cs.volume_type_access.remove_project_access(
vtype, args.project_id)
@utils.arg('tenant',
metavar='<tenant_id>',
help='ID of tenant for which to list quotas.')
def do_quota_show(cs, args):
"""Lists quotas for a tenant."""
shell_utils.quota_show(cs.quotas.get(args.tenant))
@utils.arg('tenant', metavar='<tenant_id>',
help='ID of tenant for which to list quota usage.')
def do_quota_usage(cs, args):
"""Lists quota usage for a tenant."""
shell_utils.quota_usage_show(cs.quotas.get(args.tenant, usage=True))
@utils.arg('tenant',
metavar='<tenant_id>',
help='ID of tenant for which to list quota defaults.')
def do_quota_defaults(cs, args):
"""Lists default quotas for a tenant."""
shell_utils.quota_show(cs.quotas.defaults(args.tenant))
@utils.arg('tenant',
metavar='<tenant_id>',
help='ID of tenant for which to set quotas.')
@utils.arg('--volumes',
metavar='<volumes>',
type=int, default=None,
help='The new "volumes" quota value. Default=None.')
@utils.arg('--snapshots',
metavar='<snapshots>',
type=int, default=None,
help='The new "snapshots" quota value. Default=None.')
@utils.arg('--gigabytes',
metavar='<gigabytes>',
type=int, default=None,
help='The new "gigabytes" quota value. Default=None.')
@utils.arg('--backups',
metavar='<backups>',
type=int, default=None,
help='The new "backups" quota value. Default=None.')
@utils.arg('--backup-gigabytes',
metavar='<backup_gigabytes>',
type=int, default=None,
help='The new "backup_gigabytes" quota value. Default=None.')
@utils.arg('--volume-type',
metavar='<volume_type_name>',
default=None,
help='Volume type. Default=None.')
@utils.arg('--per-volume-gigabytes',
metavar='<per_volume_gigabytes>',
type=int, default=None,
help='Set max volume size limit. Default=None.')
def do_quota_update(cs, args):
"""Updates quotas for a tenant."""
shell_utils.quota_update(cs.quotas, args.tenant, args)
@utils.arg('tenant', metavar='<tenant_id>',
help='UUID of tenant to delete the quotas for.')
def do_quota_delete(cs, args):
"""Delete the quotas for a tenant."""
cs.quotas.delete(args.tenant)
@utils.arg('class_name',
metavar='<class>',
help='Name of quota class for which to list quotas.')
def do_quota_class_show(cs, args):
"""Lists quotas for a quota class."""
shell_utils.quota_show(cs.quota_classes.get(args.class_name))
@utils.arg('class_name',
metavar='<class_name>',
help='Name of quota class for which to set quotas.')
@utils.arg('--volumes',
metavar='<volumes>',
type=int, default=None,
help='The new "volumes" quota value. Default=None.')
@utils.arg('--snapshots',
metavar='<snapshots>',
type=int, default=None,
help='The new "snapshots" quota value. Default=None.')
@utils.arg('--gigabytes',
metavar='<gigabytes>',
type=int, default=None,
help='The new "gigabytes" quota value. Default=None.')
@utils.arg('--backups',
metavar='<backups>',
type=int, default=None,
help='The new "backups" quota value. Default=None.')
@utils.arg('--backup-gigabytes',
metavar='<backup_gigabytes>',
type=int, default=None,
help='The new "backup_gigabytes" quota value. Default=None.')
@utils.arg('--volume-type',
metavar='<volume_type_name>',
default=None,
help='Volume type. Default=None.')
@utils.arg('--per-volume-gigabytes',
metavar='<per_volume_gigabytes>',
type=int, default=None,
help='Set max volume size limit. Default=None.')
def do_quota_class_update(cs, args):
"""Updates quotas for a quota class."""
shell_utils.quota_update(cs.quota_classes, args.class_name, args)
@utils.arg('tenant',
metavar='<tenant_id>',
nargs='?',
default=None,
help='Display information for a single tenant (Admin only).')
def do_absolute_limits(cs, args):
"""Lists absolute limits for a user."""
limits = cs.limits.get(args.tenant).absolute
columns = ['Name', 'Value']
shell_utils.print_list(limits, columns)
@utils.arg('tenant',
metavar='<tenant_id>',
nargs='?',
default=None,
help='Display information for a single tenant (Admin only).')
def do_rate_limits(cs, args):
"""Lists rate limits for a user."""
limits = cs.limits.get(args.tenant).rate
columns = ['Verb', 'URI', 'Value', 'Remain', 'Unit', 'Next_Available']
shell_utils.print_list(limits, columns)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume to snapshot.')
@utils.arg('--force',
metavar='<True|False>',
const=True,
nargs='?',
default=False,
help='Enables or disables upload of '
'a volume that is attached to an instance. '
'Default=False. '