Debian Codegraph @

glanceclient/v1/shell.py

raw symbols SCIP
1 # Copyright 2012 OpenStack Foundation
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import copy
17 import functools
18 import os
19 import sys
20
21 from oslo_utils import encodeutils
22 from oslo_utils import strutils
23
24 from glanceclient.common import progressbar
25 from glanceclient.common import utils
26 from glanceclient import exc
27 import glanceclient.v1.images
28
29 CONTAINER_FORMATS = ('Acceptable formats: ami, ari, aki, bare, ovf, ova,'
30 'docker.')
31 DISK_FORMATS = ('Acceptable formats: ami, ari, aki, vhd, vhdx, vmdk, raw, '
32 'qcow2, vdi, iso, and ploop.')
33 DATA_FIELDS = ('location', 'copy_from', 'file')
34
35 _bool_strict = functools.partial(strutils.bool_from_string, strict=True)
36
37
38 @utils.arg('--name', metavar='<NAME>',
39 help='Filter images to those that have this name.')
40 @utils.arg('--status', metavar='<STATUS>',
41 help='Filter images to those that have this status.')
42 @utils.arg('--changes-since', metavar='<CHANGES_SINCE>',
43 help='Filter images to those that changed since the given time'
44 ', which will include the deleted images.')
45 @utils.arg('--container-format', metavar='<CONTAINER_FORMAT>',
46 help='Filter images to those that have this container format. ' +
47 CONTAINER_FORMATS)
48 @utils.arg('--disk-format', metavar='<DISK_FORMAT>',
49 help='Filter images to those that have this disk format. ' +
50 DISK_FORMATS)
51 @utils.arg('--size-min', metavar='<SIZE>', type=int,
52 help='Filter images to those with a size greater than this.')
53 @utils.arg('--size-max', metavar='<SIZE>', type=int,
54 help='Filter images to those with a size less than this.')
55 @utils.arg('--property-filter', metavar='<KEY=VALUE>',
56 help="Filter images by a user-defined image property.",
57 action='append', dest='properties', default=[])
58 @utils.arg('--page-size', metavar='<SIZE>', default=None, type=int,
59 help='Number of images to request in each paginated request.')
60 @utils.arg('--human-readable', action='store_true', default=False,
61 help='Print image size in a human-friendly format.')
62 @utils.arg('--sort-key', default='name',
63 choices=glanceclient.v1.images.SORT_KEY_VALUES,
64 help='Sort image list by specified field.')
65 @utils.arg('--sort-dir', default='asc',
66 choices=glanceclient.v1.images.SORT_DIR_VALUES,
67 help='Sort image list in specified direction.')
68 @utils.arg('--is-public',
69 type=_bool_strict, metavar='{True,False}',
70 help=('Allows the user to select a listing of public or non '
71 'public images.'))
72 @utils.arg('--owner', default=None, metavar='<TENANT_ID>',
73 help='Display only images owned by this tenant id. Filtering '
74 'occurs on the client side so may be inefficient. This option '
75 'is mainly intended for admin use. Use an empty string (\'\') '
76 'to list images with no owner. Note: This option overrides '
77 'the --is-public argument if present. Note: the v2 API '
78 'supports more efficient server-side owner based filtering.')
79 @utils.arg('--all-tenants', action='store_true', default=False,
80 help=('Allows the admin user to list all images '
81 'irrespective of the image\'s owner or is_public value.'))
82 def do_image_list(gc, args):
83 """List images you can access."""
84 filter_keys = ['name', 'status', 'container_format', 'disk_format',
85 'size_min', 'size_max', 'is_public', 'changes_since']
86 filter_items = [(key, getattr(args, key)) for key in filter_keys]
87 filters = dict([item for item in filter_items if item[1] is not None])
88
89 if 'changes_since' in filters:
90 filters['changes-since'] = filters.pop('changes_since')
91
92 if args.properties:
93 property_filter_items = [p.split('=', 1) for p in args.properties]
94 if any(len(pair) != 2 for pair in property_filter_items):
95 utils.exit('Argument --property-filter requires properties in the'
96 ' format KEY=VALUE')
97
98 filters['properties'] = dict(property_filter_items)
99
100 kwargs = {'filters': filters}
101 if args.page_size is not None:
102 kwargs['page_size'] = args.page_size
103
104 kwargs['sort_key'] = args.sort_key
105 kwargs['sort_dir'] = args.sort_dir
106 kwargs['owner'] = args.owner
107 if args.all_tenants is True:
108 kwargs['is_public'] = None
109
110 images = gc.images.list(**kwargs)
111
112 if args.human_readable:
113 def convert_size(image):
114 image.size = utils.make_size_human_readable(image.size)
115 return image
116
117 images = (convert_size(image) for image in images)
118
119 columns = ['ID', 'Name', 'Disk Format', 'Container Format',
120 'Size', 'Status']
121 utils.print_list(images, columns)
122
123
124 def _image_show(image, human_readable=False, max_column_width=80):
125 # Flatten image properties dict for display
126 info = copy.deepcopy(image._info)
127 if human_readable:
128 info['size'] = utils.make_size_human_readable(info['size'])
129 for (k, v) in info.pop('properties').items():
130 info['Property \'%s\'' % k] = v
131
132 utils.print_dict(info, max_column_width=max_column_width)
133
134
135 def _set_data_field(fields, args):
136 if 'location' not in fields and 'copy_from' not in fields:
137 fields['data'] = utils.get_data_file(args)
138
139
140 @utils.arg('image', metavar='<IMAGE>', help='Name or ID of image to describe.')
141 @utils.arg('--human-readable', action='store_true', default=False,
142 help='Print image size in a human-friendly format.')
143 @utils.arg('--max-column-width', metavar='<integer>', default=80,
144 help='The max column width of the printed table.')
145 def do_image_show(gc, args):
146 """Describe a specific image."""
147 image_id = utils.find_resource(gc.images, args.image).id
148 image = gc.images.get(image_id)
149 _image_show(image, args.human_readable,
150 max_column_width=int(args.max_column_width))
151
152
153 @utils.arg('--file', metavar='<FILE>',
154 help='Local file to save downloaded image data to. '
155 'If this is not specified and there is no redirection '
156 'the image data will not be saved.')
157 @utils.arg('image', metavar='<IMAGE>', help='Name or ID of image to download.')
158 @utils.arg('--progress', action='store_true', default=False,
159 help='Show download progress bar.')
160 def do_image_download(gc, args):
161 """Download a specific image."""
162 image = utils.find_resource(gc.images, args.image)
163 body = image.data()
164 if args.progress:
165 body = progressbar.VerboseIteratorWrapper(body, len(body))
166 if not (sys.stdout.isatty() and args.file is None):
167 utils.save_image(body, args.file)
168 else:
169 print('No redirection or local file specified for downloaded image '
170 'data. Please specify a local file with --file to save '
171 'downloaded image or redirect output to another source.')
172
173
174 @utils.arg('--id', metavar='<IMAGE_ID>',
175 help='ID of image to reserve.')
176 @utils.arg('--name', metavar='<NAME>',
177 help='Name of image.')
178 @utils.arg('--store', metavar='<STORE>',
179 help='Store to upload image to.')
180 @utils.arg('--disk-format', metavar='<DISK_FORMAT>',
181 help='Disk format of image. ' + DISK_FORMATS)
182 @utils.arg('--container-format', metavar='<CONTAINER_FORMAT>',
183 help='Container format of image. ' + CONTAINER_FORMATS)
184 @utils.arg('--owner', metavar='<TENANT_ID>',
185 help='Tenant who should own image.')
186 @utils.arg('--size', metavar='<SIZE>', type=int,
187 help=('Size of image data (in bytes). Only used with'
188 ' \'--location\' and \'--copy_from\'.'))
189 @utils.arg('--min-disk', metavar='<DISK_GB>', type=int,
190 help='Minimum size of disk needed to boot image (in gigabytes).')
191 @utils.arg('--min-ram', metavar='<DISK_RAM>', type=int,
192 help='Minimum amount of ram needed to boot image (in megabytes).')
193 @utils.arg('--location', metavar='<IMAGE_URL>',
194 help=('URL where the data for this image already resides. For '
195 'example, if the image data is stored in swift, you could '
196 'specify \'swift+http://tenant%%3Aaccount:key@auth_url/'
197 'v2.0/container/obj\'. '
198 '(Note: \'%%3A\' is \':\' URL encoded.)'))
199 @utils.arg('--file', metavar='<FILE>',
200 help=('Local file that contains disk image to be uploaded during'
201 ' creation. Alternatively, images can be passed to the client'
202 ' via stdin.'))
203 @utils.arg('--checksum', metavar='<CHECKSUM>',
204 help=('Hash of image data used Glance can use for verification.'
205 ' Provide a md5 checksum here.'))
206 @utils.arg('--copy-from', metavar='<IMAGE_URL>',
207 help=('Similar to \'--location\' in usage, but this indicates that'
208 ' the Glance server should immediately copy the data and'
209 ' store it in its configured image store.'))
210 @utils.arg('--is-public',
211 type=_bool_strict, metavar='{True,False}',
212 help='Make image accessible to the public.')
213 @utils.arg('--is-protected',
214 type=_bool_strict, metavar='{True,False}',
215 help='Prevent image from being deleted.')
216 @utils.arg('--property', metavar="<key=value>", action='append', default=[],
217 help=("Arbitrary property to associate with image. "
218 "May be used multiple times."))
219 @utils.arg('--human-readable', action='store_true', default=False,
220 help='Print image size in a human-friendly format.')
221 @utils.arg('--progress', action='store_true', default=False,
222 help='Show upload progress bar.')
223 @utils.on_data_require_fields(DATA_FIELDS)
224 def do_image_create(gc, args):
225 """Create a new image."""
226 # Filter out None values
227 fields = dict(filter(lambda x: x[1] is not None, vars(args).items()))
228
229 fields['is_public'] = fields.get('is_public')
230
231 if 'is_protected' in fields:
232 fields['protected'] = fields.pop('is_protected')
233
234 raw_properties = fields.pop('property')
235 fields['properties'] = {}
236 for datum in raw_properties:
237 key, value = datum.split('=', 1)
238 fields['properties'][key] = value
239
240 # Filter out values we can't use
241 CREATE_PARAMS = glanceclient.v1.images.CREATE_PARAMS
242 fields = dict(filter(lambda x: x[0] in CREATE_PARAMS, fields.items()))
243
244 _set_data_field(fields, args)
245
246 # Only show progress bar for local image files
247 if fields.get('data') and args.progress:
248 filesize = utils.get_file_size(fields['data'])
249 if filesize is not None:
250 # NOTE(kragniz): do not show a progress bar if the size of the
251 # input is unknown (most likely a piped input)
252 fields['data'] = progressbar.VerboseFileWrapper(
253 fields['data'], filesize
254 )
255
256 image = gc.images.create(**fields)
257 _image_show(image, args.human_readable)
258
259
260 def _is_image_data_provided(args):
261 """Return True if some image data has probably been provided by the user"""
262 # NOTE(kragniz): Check stdin works, then check is there is any data
263 # on stdin or a filename has been provided with --file
264 try:
265 os.fstat(0)
266 except OSError:
267 return False
268 return not sys.stdin.isatty() or args.file or args.copy_from
269
270
271 @utils.arg('image', metavar='<IMAGE>', help='Name or ID of image to modify.')
272 @utils.arg('--name', metavar='<NAME>',
273 help='Name of image.')
274 @utils.arg('--disk-format', metavar='<DISK_FORMAT>',
275 help='Disk format of image. ' + DISK_FORMATS)
276 @utils.arg('--container-format', metavar='<CONTAINER_FORMAT>',
277 help='Container format of image. ' + CONTAINER_FORMATS)
278 @utils.arg('--owner', metavar='<TENANT_ID>',
279 help='Tenant who should own image.')
280 @utils.arg('--size', metavar='<SIZE>', type=int,
281 help='Size of image data (in bytes).')
282 @utils.arg('--min-disk', metavar='<DISK_GB>', type=int,
283 help='Minimum size of disk needed to boot image (in gigabytes).')
284 @utils.arg('--min-ram', metavar='<DISK_RAM>', type=int,
285 help='Minimum amount of ram needed to boot image (in megabytes).')
286 @utils.arg('--location', metavar='<IMAGE_URL>',
287 help=('URL where the data for this image already resides. For '
288 'example, if the image data is stored in swift, you could '
289 'specify \'swift+http://tenant%%3Aaccount:key@auth_url/'
290 'v2.0/container/obj\'. '
291 '(Note: \'%%3A\' is \':\' URL encoded.) '
292 'This option only works for images in \'queued\' status.'))
293 @utils.arg('--file', metavar='<FILE>',
294 help=('Local file that contains disk image to be uploaded during'
295 ' update. Alternatively, images can be passed to the client'
296 ' via stdin.'))
297 @utils.arg('--checksum', metavar='<CHECKSUM>',
298 help='Hash of image data used Glance can use for verification.')
299 @utils.arg('--copy-from', metavar='<IMAGE_URL>',
300 help=('Similar to \'--location\' in usage, but this indicates that'
301 ' the Glance server should immediately copy the data and'
302 ' store it in its configured image store.'
303 ' This option only works for images in \'queued\' status.'))
304 @utils.arg('--is-public',
305 type=_bool_strict, metavar='{True,False}',
306 help='Make image accessible to the public.')
307 @utils.arg('--is-protected',
308 type=_bool_strict, metavar='{True,False}',
309 help='Prevent image from being deleted.')
310 @utils.arg('--property', metavar="<key=value>", action='append', default=[],
311 help=("Arbitrary property to associate with image. "
312 "May be used multiple times."))
313 @utils.arg('--purge-props', action='store_true', default=False,
314 help=("If this flag is present, delete all image properties "
315 "not explicitly set in the update request. Otherwise, "
316 "those properties not referenced are preserved."))
317 @utils.arg('--human-readable', action='store_true', default=False,
318 help='Print image size in a human-friendly format.')
319 @utils.arg('--progress', action='store_true', default=False,
320 help='Show upload progress bar.')
321 def do_image_update(gc, args):
322 """Update a specific image."""
323 # Filter out None values
324 fields = dict(filter(lambda x: x[1] is not None, vars(args).items()))
325
326 image_arg = fields.pop('image')
327 image = utils.find_resource(gc.images, image_arg)
328
329 if 'is_protected' in fields:
330 fields['protected'] = fields.pop('is_protected')
331
332 raw_properties = fields.pop('property')
333 fields['properties'] = {}
334 for datum in raw_properties:
335 key, value = datum.split('=', 1)
336 fields['properties'][key] = value
337
338 # Filter out values we can't use
339 UPDATE_PARAMS = glanceclient.v1.images.UPDATE_PARAMS
340 fields = dict(filter(lambda x: x[0] in UPDATE_PARAMS, fields.items()))
341
342 if image.status == 'queued':
343 _set_data_field(fields, args)
344
345 if args.progress:
346 filesize = utils.get_file_size(fields['data'])
347 fields['data'] = progressbar.VerboseFileWrapper(
348 fields['data'], filesize
349 )
350
351 elif _is_image_data_provided(args):
352 # NOTE(kragniz): Exit with an error if the status is not queued
353 # and image data was provided
354 utils.exit('Unable to upload image data to an image which '
355 'is %s.' % image.status)
356
357 image = gc.images.update(image, purge_props=args.purge_props, **fields)
358 _image_show(image, args.human_readable)
359
360
361 @utils.arg('images', metavar='<IMAGE>', nargs='+',
362 help='Name or ID of image(s) to delete.')
363 def do_image_delete(gc, args):
364 """Delete specified image(s)."""
365 for args_image in args.images:
366 image = utils.find_resource(gc.images, args_image)
367 if image and image.status == "deleted":
368 msg = "No image with an ID of '%s' exists." % image.id
369 raise exc.CommandError(msg)
370 try:
371 if args.verbose:
372 print('Requesting image delete for %s ...' %
373 encodeutils.safe_decode(args_image), end=' ')
374
375 gc.images.delete(image)
376
377 if args.verbose:
378 print('[Done]')
379
380 except exc.HTTPException as e:
381 if args.verbose:
382 print('[Fail]')
383 print('%s: Unable to delete image %s' % (e, args_image))
384
385
386 @utils.arg('--image-id', metavar='<IMAGE_ID>',
387 help='Filter results by an image ID.')
388 @utils.arg('--tenant-id', metavar='<TENANT_ID>',
389 help='Filter results by a tenant ID.')
390 def do_member_list(gc, args):
391 """Describe sharing permissions by image or tenant."""
392 if args.image_id and args.tenant_id:
393 utils.exit('Unable to filter members by both --image-id and'
394 ' --tenant-id.')
395 elif args.image_id:
396 kwargs = {'image': args.image_id}
397 elif args.tenant_id:
398 kwargs = {'member': args.tenant_id}
399 else:
400 utils.exit('Unable to list all members. Specify --image-id or'
401 ' --tenant-id')
402
403 members = gc.image_members.list(**kwargs)
404 columns = ['Image ID', 'Member ID', 'Can Share']
405 utils.print_list(members, columns)
406
407
408 @utils.arg('image', metavar='<IMAGE>',
409 help='Image to add member to.')
410 @utils.arg('tenant_id', metavar='<TENANT_ID>',
411 help='Tenant to add as member.')
412 @utils.arg('--can-share', action='store_true', default=False,
413 help='Allow the specified tenant to share this image.')
414 def do_member_create(gc, args):
415 """Share a specific image with a tenant."""
416 image = utils.find_resource(gc.images, args.image)
417 gc.image_members.create(image, args.tenant_id, args.can_share)
418
419
420 @utils.arg('image', metavar='<IMAGE>',
421 help='Image from which to remove member.')
422 @utils.arg('tenant_id', metavar='<TENANT_ID>',
423 help='Tenant to remove as member.')
424 def do_member_delete(gc, args):
425 """Remove a shared image from a tenant."""
426 image_id = utils.find_resource(gc.images, args.image).id
427 gc.image_members.delete(image_id, args.tenant_id)