/
glance
executable file
·1208 lines (960 loc) · 38.3 KB
/
glance
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
#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack, LLC
# 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.
"""
This is the administration program for Glance. It is simply a command-line
interface for adding, modifying, and retrieving information about the images
stored in one or more Glance nodes.
"""
import functools
import gettext
import optparse
import os
import re
import sys
import time
# If ../glance/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')):
sys.path.insert(0, possible_topdir)
gettext.install('glance', unicode=1)
from glance import client as glance_client
from glance import version
from glance.common import exception
from glance.common import utils as common_utils
from glance import utils
SUCCESS = 0
FAILURE = 1
#TODO(sirp): make more of the actions use this decorator
def catch_error(action):
"""Decorator to provide sensible default error handling for actions."""
def wrap(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
ret = func(*args, **kwargs)
return SUCCESS if ret is None else ret
except exception.NotAuthorized:
print "Not authorized to make this request. Check "\
"your credentials (OS_AUTH_USER, OS_AUTH_KEY, ...)."
return FAILURE
except Exception, e:
options = args[0]
if options.debug:
raise
print "Failed to %s. Got error:" % action
pieces = unicode(e).split('\n')
for piece in pieces:
print piece
return FAILURE
return wrapper
return wrap
def get_percent_done(image):
try:
pct_done = image['size'] * 100 / int(image['expected_size'])
except (ValueError, ZeroDivisionError):
# NOTE(sirp): Ignore if expected_size isn't a number, or if it's 0
pct_done = "UNKNOWN"
return pct_done
def get_image_fields_from_args(args):
"""
Validate the set of arguments passed as field name/value pairs
and return them as a mapping.
"""
fields = {}
for arg in args:
pieces = arg.strip(',').split('=')
if len(pieces) != 2:
msg = ("Arguments should be in the form of field=value. "
"You specified %s." % arg)
raise RuntimeError(msg)
fields[pieces[0]] = pieces[1]
fields = dict([(k.lower().replace('-', '_'), v)
for k, v in fields.items()])
return fields
def get_image_filters_from_args(args):
"""Build a dictionary of query filters based on the supplied args."""
try:
fields = get_image_fields_from_args(args)
except RuntimeError, e:
print e
return FAILURE
SUPPORTED_FILTERS = ['name', 'disk_format', 'container_format', 'status',
'min_ram', 'min_disk', 'size_min', 'size_max']
filters = {}
for (key, value) in fields.items():
if key not in SUPPORTED_FILTERS:
key = 'property-%s' % (key,)
filters[key] = value
return filters
def print_image_formatted(client, image):
"""
Formatted print of image metadata.
:param client: The Glance client object
:param image: The image metadata
"""
print "URI: %s://%s:%s/v1/images/%s" % (
client.use_ssl and "https" or "http",
client.host,
client.port,
image['id'])
print "Id: %s" % image['id']
print "Public: " + (image['is_public'] and "Yes" or "No")
print "Name: %s" % image['name']
print "Status: %s" % image['status']
print "Size: %d" % int(image['size'])
print "Disk format: %s" % image['disk_format']
print "Container format: %s" % image['container_format']
print "Minimum Ram Required (MB): %s" % image['min_ram']
print "Minimum Disk Required (GB): %s" % image['min_disk']
if image['owner']:
print "Owner: %s" % image['owner']
if len(image['properties']) > 0:
for k, v in image['properties'].items():
print "Property '%s': %s" % (k, v)
def image_add(options, args):
"""
%(prog)s add [options] <field1=value1 field2=value2 ...> [ < /path/to/image ]
Adds a new image to Glance. Specify metadata fields as arguments.
SPECIFYING IMAGE METADATA
===============================================================================
All field/value pairs are converted into a mapping that is passed
to Glance that represents the metadata for an image.
Field names of note:
id Optional. If not specified, an image identifier will be
automatically assigned.
name Required. A name for the image.
size Optional. Should be size in bytes of the image if
specified.
is_public Optional. If specified, interpreted as a boolean value
and sets or unsets the image's availability to the public.
The default value is False.
disk_format Optional. Possible values are 'vhd','vmdk','raw', 'qcow2',
and 'ami'. Default value is 'raw'.
container_format Optional. Possible values are 'ovf' and 'ami'.
Default value is 'ovf'.
location Optional. When specified, should be a readable location
in the form of a URI: $STORE://LOCATION. For example, if
the image data is stored in a file on the local
filesystem at /usr/share/images/some.image.tar.gz
you would specify:
location=file:///usr/share/images/some.image.tar.gz
Any other field names are considered to be custom properties so be careful
to spell field names correctly. :)
STREAMING IMAGE DATA
===============================================================================
If the location field is not specified, you can stream an image file on
the command line using standard redirection. For example:
%(prog)s add name="Ubuntu 10.04 LTS 5GB" < /tmp/images/myimage.tar.gz
EXAMPLES
===============================================================================
%(prog)s add name="My Image" disk_format=raw container_format=ovf \\
location=http://images.ubuntu.org/images/lucid-10.04-i686.iso \\
distro="Ubuntu 10.04 LTS"
%(prog)s add name="My Image" distro="Ubuntu 10.04 LTS" < /tmp/myimage.iso"""
c = get_client(options)
try:
fields = get_image_fields_from_args(args)
except RuntimeError, e:
print e
return FAILURE
if 'name' not in fields.keys():
print "Please specify a name for the image using name=VALUE"
return FAILURE
image_meta = {'name': fields.pop('name'),
'is_public': common_utils.bool_from_string(
fields.pop('is_public', False)),
'disk_format': fields.pop('disk_format', 'raw'),
'min_disk': fields.pop('min_disk', 0),
'min_ram': fields.pop('min_ram', 0),
'container_format': fields.pop('container_format', 'ovf')}
# Strip any args that are not supported
unsupported_fields = ['status', 'size']
for field in unsupported_fields:
if field in fields.keys():
print 'Found non-settable field %s. Removing.' % field
fields.pop(field)
if 'location' in fields.keys():
image_meta['location'] = fields.pop('location')
# We need either a location or image data/stream to add...
image_location = image_meta.get('location')
image_data = None
if not image_location:
# Grab the image data stream from stdin or redirect,
# otherwise error out
image_data = sys.stdin
# Add custom attributes, which are all the arguments remaining
image_meta['properties'] = fields
if not options.dry_run:
try:
image_meta = c.add_image(image_meta, image_data)
image_id = image_meta['id']
print "Added new image with ID: %s" % image_id
if options.verbose:
print "Returned the following metadata for the new image:"
for k, v in sorted(image_meta.items()):
print " %(k)30s => %(v)s" % locals()
except exception.ClientConnectionError, e:
host = options.host
port = options.port
print ("Failed to connect to the Glance API server "
"%(host)s:%(port)d. Is the server running?" % locals())
if options.verbose:
pieces = unicode(e).split('\n')
for piece in pieces:
print piece
return FAILURE
except Exception, e:
print "Failed to add image. Got error:"
pieces = unicode(e).split('\n')
for piece in pieces:
print piece
print ("Note: Your image metadata may still be in the registry, "
"but the image's status will likely be 'killed'.")
return FAILURE
else:
print "Dry run. We would have done the following:"
print "Add new image with metadata:"
for k, v in sorted(image_meta.items()):
print " %(k)30s => %(v)s" % locals()
return SUCCESS
def image_update(options, args):
"""
%(prog)s update [options] <ID> <field1=value1 field2=value2 ...>
Updates an image's metadata in Glance. Specify metadata fields as arguments.
Metadata fields that are not specified in the update command will be deleted.
All field/value pairs are converted into a mapping that is passed
to Glance that represents the metadata for an image.
Field names that can be specified:
name A name for the image.
location The location of the image.
is_public If specified, interpreted as a boolean value
and sets or unsets the image's availability to the public.
disk_format Format of the disk image
container_format Format of the container
All other field names are considered to be custom properties so be careful
to spell field names correctly. :)"""
c = get_client(options)
try:
image_id = args.pop(0)
except IndexError:
print "Please specify the ID of the image you wish to update "
print "as the first argument"
return FAILURE
try:
fields = get_image_fields_from_args(args)
except RuntimeError, e:
print e
return FAILURE
image_meta = {}
# Strip any args that are not supported
nonmodifiable_fields = ['created_on', 'deleted_on', 'deleted',
'updated_on', 'size', 'status']
for field in nonmodifiable_fields:
if field in fields.keys():
print 'Found non-modifiable field %s. Removing.' % field
fields.pop(field)
base_image_fields = ['disk_format', 'container_format', 'name',
'min_disk', 'min_ram', 'location', 'owner']
for field in base_image_fields:
fvalue = fields.pop(field, None)
if fvalue is not None:
image_meta[field] = fvalue
# Have to handle "boolean" values specially...
if 'is_public' in fields:
image_meta['is_public'] = common_utils.bool_from_string(
fields.pop('is_public'))
# Add custom attributes, which are all the arguments remaining
image_meta['properties'] = fields
if not options.dry_run:
try:
image_meta = c.update_image(image_id, image_meta=image_meta)
print "Updated image %s" % image_id
if options.verbose:
print "Updated image metadata for image %s:" % image_id
print_image_formatted(c, image_meta)
except exception.NotFound:
print "No image with ID %s was found" % image_id
return FAILURE
except Exception, e:
print "Failed to update image. Got error:"
pieces = unicode(e).split('\n')
for piece in pieces:
print piece
return FAILURE
else:
print "Dry run. We would have done the following:"
print "Update existing image with metadata:"
for k, v in sorted(image_meta.items()):
print " %(k)30s => %(v)s" % locals()
return SUCCESS
def image_delete(options, args):
"""
%(prog)s delete [options] <ID>
Deletes an image from Glance"""
try:
image_id = args.pop()
except IndexError:
print "Please specify the ID of the image you wish to delete "
print "as the first argument"
return FAILURE
if not options.force and \
not user_confirm("Delete image %s?" % (image_id,), default=False):
print 'Not deleting image %s' % (image_id,)
return FAILURE
c = get_client(options)
try:
c.delete_image(image_id)
print "Deleted image %s" % image_id
return SUCCESS
except exception.NotFound:
print "No image with ID %s was found" % image_id
return FAILURE
def image_show(options, args):
"""
%(prog)s show [options] <ID>
Shows image metadata for an image in Glance"""
c = get_client(options)
try:
if len(args) > 0:
image_id = args[0]
else:
print "Please specify the image identifier as the "
print "first argument. Example: "
print "$> glance-admin show 12345"
return FAILURE
image = c.get_image_meta(image_id)
print_image_formatted(c, image)
return SUCCESS
except exception.NotFound:
print "No image with ID %s was found" % image_id
return FAILURE
except Exception, e:
print "Failed to show image. Got error:"
pieces = unicode(e).split('\n')
for piece in pieces:
print piece
return FAILURE
def _images_index(client, filters, limit, print_header=False, **kwargs):
"""Driver function for images_index"""
parameters = {
"filters": filters,
"limit": limit,
}
optional_kwargs = ['marker', 'sort_key', 'sort_dir']
for kwarg in optional_kwargs:
if kwarg in kwargs:
parameters[kwarg] = kwargs[kwarg]
images = client.get_images(**parameters)
if not images:
return SUCCESS
pretty_table = utils.PrettyTable()
pretty_table.add_column(16, label="ID")
pretty_table.add_column(30, label="Name")
pretty_table.add_column(20, label="Disk Format")
pretty_table.add_column(20, label="Container Format")
pretty_table.add_column(14, label="Size", just="r")
if print_header:
print pretty_table.make_header()
for image in images:
print pretty_table.make_row(image['id'],
image['name'],
image['disk_format'],
image['container_format'],
image['size'])
if not options.force and len(images) == limit and \
not user_confirm("Fetch next page?", True):
return SUCCESS
parameters['marker'] = images[-1]['id']
return _images_index(client, **parameters)
@catch_error('show index')
def images_index(options, args):
"""
%(prog)s index [options] <field1=value1 field2=value2 ...>
Returns basic information for all public images
a Glance server knows about. Provided fields are
handled as query filters. Supported filters
include 'name', 'disk_format', 'container_format',
'status', 'size_min', and 'size_max.' Any extra
fields are treated as image metadata properties"""
client = get_client(options)
filters = get_image_filters_from_args(args)
limit = options.limit
marker = options.marker
sort_key = options.sort_key
sort_dir = options.sort_dir
return _images_index(client,
filters,
limit,
marker=marker,
sort_key=sort_key,
sort_dir=sort_dir,
print_header=True)
def _images_details(client, filters, limit, print_header=False, **kwargs):
"""Driver function for images_details"""
parameters = {
"filters": filters,
"limit": limit,
}
optional_kwargs = ['marker', 'sort_key', 'sort_dir']
for kwarg in optional_kwargs:
if kwarg in kwargs:
parameters[kwarg] = kwargs[kwarg]
images = client.get_images_detailed(**parameters)
if len(images) == 0:
return SUCCESS
if print_header:
print "=" * 80
for image in images:
print_image_formatted(client, image)
print "=" * 80
if not options.force and len(images) == limit and \
not user_confirm("Fetch next page?", True):
return SUCCESS
parameters["marker"] = images[-1]['id']
return _images_details(client, **parameters)
@catch_error('show details')
def images_details(options, args):
"""
%(prog)s details [options]
Returns detailed information for all public images
a Glance server knows about. Provided fields are
handled as query filters. Supported filters
include 'name', 'disk_format', 'container_format',
'status', 'size_min', and 'size_max.' Any extra
fields are treated as image metadata properties"""
client = get_client(options)
filters = get_image_filters_from_args(args)
limit = options.limit
marker = options.marker
sort_key = options.sort_key
sort_dir = options.sort_dir
return _images_details(client,
filters,
limit,
marker=marker,
sort_key=sort_key,
sort_dir=sort_dir,
print_header=True)
def images_clear(options, args):
"""
%(prog)s clear [options]
Deletes all images from a Glance server"""
if not options.force and \
not user_confirm("Delete all images?", default=False):
print 'Not deleting any images'
return FAILURE
c = get_client(options)
images = c.get_images()
for image in images:
if options.verbose:
print 'Deleting image %s "%s" ...' % (image['id'], image['name']),
try:
c.delete_image(image['id'])
if options.verbose:
print 'done'
except Exception, e:
print 'Failed to delete image %s' % image['id']
print e
return FAILURE
return SUCCESS
@catch_error('show cached images')
def cache_index(options, args):
"""
%(prog)s cache-index [options]
List all images currently cached"""
client = get_client(options)
images = client.get_cached_images()
if not images:
print "No cached images."
return SUCCESS
print "Found %d cached images..." % len(images)
pretty_table = utils.PrettyTable()
pretty_table.add_column(16, label="ID")
pretty_table.add_column(30, label="Name")
pretty_table.add_column(19, label="Last Accessed (UTC)")
# 1 TB takes 13 characters to display: len(str(2**40)) == 13
pretty_table.add_column(14, label="Size", just="r")
pretty_table.add_column(10, label="Hits", just="r")
print pretty_table.make_header()
for image in images:
print pretty_table.make_row(
image['id'],
image['name'],
image['last_accessed'],
image['size'],
image['hits'])
@catch_error('show invalid cache images')
def cache_invalid(options, args):
"""
%(prog)s cache-invalid [options]
List current invalid cache images"""
client = get_client(options)
images = client.get_invalid_cached_images()
if not images:
print "No invalid cached images."
return SUCCESS
print "Found %d invalid cached images..." % len(images)
pretty_table = utils.PrettyTable()
pretty_table.add_column(16, label="ID")
pretty_table.add_column(30, label="Name")
pretty_table.add_column(30, label="Error")
pretty_table.add_column(19, label="Last Modified (UTC)")
# 1 TB takes 13 characters to display: len(str(2**40)) == 13
pretty_table.add_column(14, label="Size", just="r")
pretty_table.add_column(14, label="Expected Size", just="r")
pretty_table.add_column(7, label="% Done", just="r")
print pretty_table.make_header()
for image in images:
print pretty_table.make_row(
image['id'],
image['name'],
image['error'],
image['last_accessed'],
image['size'],
image['expected_size'],
get_percent_done(image))
@catch_error('show incomplete cache images')
def cache_incomplete(options, args):
"""
%(prog)s cache-incomplete [options]
List images currently being fetched"""
client = get_client(options)
images = client.get_incomplete_cached_images()
if not images:
print "No incomplete cached images."
return SUCCESS
print "Found %d incomplete cached images..." % len(images)
pretty_table = utils.PrettyTable()
pretty_table.add_column(16, label="ID")
pretty_table.add_column(30, label="Name")
pretty_table.add_column(19, label="Last Modified (UTC)")
# 1 TB takes 13 characters to display: len(str(2**40)) == 13
pretty_table.add_column(14, label="Size", just="r")
pretty_table.add_column(14, label="Expected Size", just="r")
pretty_table.add_column(7, label="% Done", just="r")
print pretty_table.make_header()
for image in images:
print pretty_table.make_row(
image['id'],
image['name'],
image['last_modified'],
image['size'],
image['expected_size'],
get_percent_done(image))
@catch_error('purge the specified cached image')
def cache_purge(options, args):
"""
%(prog)s cache-purge [options]
Purges an image from the cache"""
try:
image_id = args.pop()
except IndexError:
print "Please specify the ID of the image you wish to purge "
print "from the cache as the first argument"
return FAILURE
if not options.force and \
not user_confirm("Purge cached image %s?" % (image_id,), default=False):
print 'Not purging cached image %s' % (image_id,)
return FAILURE
client = get_client(options)
client.purge_cached_image(image_id)
if options.verbose:
print "done"
@catch_error('clear all cached images')
def cache_clear(options, args):
"""
%(prog)s cache-clear [options]
Removes all images from the cache"""
if not options.force and \
not user_confirm("Clear all cached images?", default=False):
print 'Not purging any cached images.'
return FAILURE
client = get_client(options)
num_purged = client.clear_cached_images()
if options.verbose:
print "Purged %(num_purged)s cached images" % locals()
@catch_error('reap invalid images')
def cache_reap_invalid(options, args):
"""
%(prog)s cache-reap-invalid [options]
Reaps any invalid images that were left for
debugging purposes"""
if not options.force and \
not user_confirm("Reap all invalid cached images?", default=False):
print 'Not reaping any invalid cached images.'
return FAILURE
client = get_client(options)
num_reaped = client.reap_invalid_cached_images()
if options.verbose:
print "Reaped %(num_reaped)s invalid cached images" % locals()
@catch_error('reap stalled images')
def cache_reap_stalled(options, args):
"""
%(prog)s cache-reap-stalled [options]
Reaps any stalled incomplete images"""
if not options.force and \
not user_confirm("Reap all stalled cached images?", default=False):
print 'Not reaping any stalled cached images.'
return FAILURE
client = get_client(options)
num_reaped = client.reap_stalled_cached_images()
if options.verbose:
print "Reaped %(num_reaped)s stalled cached images" % locals()
@catch_error('prefetch the specified cached image')
def cache_prefetch(options, args):
"""
%(prog)s cache-prefetch [options]
Pre-fetch an image or list of images into the cache"""
image_ids = args
if not image_ids:
print "Please specify the ID or a list of image IDs of the images "\
"you wish to "
print "prefetch from the cache as the first argument"
return FAILURE
client = get_client(options)
for image_id in image_ids:
if options.verbose:
print "Prefetching image '%s'" % image_id
try:
client.prefetch_cache_image(image_id)
except exception.NotFound:
print "No image with ID %s was found" % image_id
continue
if options.verbose:
print "done"
@catch_error('show prefetching images')
def cache_prefetching(options, args):
"""
%(prog)s cache-prefetching [options]
List images that are being prefetched"""
client = get_client(options)
images = client.get_prefetching_cache_images()
if not images:
print "No images being prefetched."
return SUCCESS
print "Found %d images being prefetched..." % len(images)
pretty_table = utils.PrettyTable()
pretty_table.add_column(16, label="ID")
pretty_table.add_column(30, label="Name")
pretty_table.add_column(19, label="Last Accessed (UTC)")
pretty_table.add_column(10, label="Status", just="r")
print pretty_table.make_header()
for image in images:
print pretty_table.make_row(
image['id'],
image['name'],
image['last_accessed'],
image['status'])
@catch_error('show image members')
def image_members(options, args):
"""
%(prog)s image-members [options] <ID>
Displays a list of members with which an image is shared"""
try:
image_id = args.pop()
except IndexError:
print "Please specify the ID of the image as the first argument"
return FAILURE
c = get_client(options)
members = c.get_image_members(image_id)
sharers = 0
# Output the list of members
for memb in members:
can_share = ''
if 'can_share' in memb and memb['can_share']:
can_share = ' *'
sharers += 1
print "%s%s" % (memb['member_id'], can_share)
# Emit a footnote
if sharers > 0:
print "\n(*: Can share image)"
@catch_error('show member images')
def member_images(options, args):
"""
%(prog)s member-images [options] <MEMBER>
Displays a list of images shared with a given member"""
try:
member_id = args.pop()
except IndexError:
print "Please specify the ID of the member as the first argument"
return FAILURE
c = get_client(options)
try:
members = c.get_member_images(member_id)
except exception.NotFound:
print "No images shared with member %s" % member_id
return SUCCESS
sharers = 0
# Output the list of images
for memb in members:
can_share = ''
if 'can_share' in memb and memb['can_share']:
can_share = ' *'
sharers += 1
print "%s%s" % (memb['image_id'], can_share)
# Emit a footnote
if sharers > 0:
print "\n(*: Can share image)"
@catch_error('update image members')
def members_replace(options, args):
"""
%(prog)s members-replace [options] <ID> <MEMBER>
Replaces the members of the image <ID> to be solely <MEMBER>. If the
"--can-share" option is given, <MEMBER> will be able to further share
the image."""
try:
member_id = args.pop()
image_id = args.pop()
except IndexError:
print "Please specify the image ID and the member name"
return FAILURE
c = get_client(options)
# Update members
if not options.dry_run:
c.replace_members(image_id, dict(member_id=member_id,
can_share=options.can_share))
else:
print "Dry run. We would have done the following:"
print ('Replace members of image %(image_id)s with "%(member_id)s"'
% locals())
if options.can_share:
print "New member would have been able to further share image."
@catch_error('add image member')
def member_add(options, args):
"""
%(prog)s member-add [options] <ID> <MEMBER>
Adds the member <MEMBER> to the image <ID>. If the "--can-share"
option is given, <MEMBER> will be able to further share the image."""
try:
member_id = args.pop()
image_id = args.pop()
except IndexError:
print "Please specify the image ID and the member name"
return FAILURE
c = get_client(options)
# Replace members
if not options.dry_run:
c.add_member(image_id, member_id, options.can_share)
else:
print "Dry run. We would have done the following:"
print ('Add "%(member_id)s" to membership of image %(image_id)s'
% locals())
if options.can_share:
print "New member would have been able to further share image."
@catch_error('delete image member')
def member_delete(options, args):
"""
%(prog)s member-delete [options] <ID> <MEMBER>
Deletes the specified member of the image <ID>."""
try:
member_id = args.pop()
image_id = args.pop()
except IndexError:
print "Please specify the image ID and the member name"
return FAILURE
c = get_client(options)
# Delete member
if not options.dry_run:
c.delete_member(image_id, member_id)
else:
print "Dry run. We would have done the following:"
print ('Remove "%(member_id)s" from the member list of image '
'"%(image_id)s"' % locals())
def get_client(options):
"""
Returns a new client object to a Glance server
specified by the --host and --port options
supplied to the CLI
"""
creds = dict(username=os.getenv('OS_AUTH_USER'),
password=os.getenv('OS_AUTH_KEY'),
tenant=os.getenv('OS_AUTH_TENANT'),
auth_url=os.getenv('OS_AUTH_URL'),
strategy=os.getenv('OS_AUTH_STRATEGY', 'noauth'))
return glance_client.Client(host=options.host, port=options.port,
auth_tok=options.auth_token, creds=creds)
def create_options(parser):
"""
Sets up the CLI and config-file options that may be
parsed and program commands.
:param parser: The option parser
"""
parser.add_option('-v', '--verbose', default=False, action="store_true",
help="Print more verbose output")
parser.add_option('-d', '--debug', default=False, action="store_true",
help="Print more verbose output")
parser.add_option('-H', '--host', metavar="ADDRESS", default="0.0.0.0",
help="Address of Glance API host. "
"Default: %default")
parser.add_option('-p', '--port', dest="port", metavar="PORT",
type=int, default=9292,
help="Port the Glance API host listens on. "
"Default: %default")