| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
import hashlib |
| 17 |
import json |
| 18 |
from oslo_utils import encodeutils |
| 19 |
from requests import codes |
| 20 |
import urllib.parse |
| 21 |
import warlock |
| 22 |
|
| 23 |
from glanceclient.common import utils |
| 24 |
from glanceclient import exc |
| 25 |
from glanceclient.v2 import schemas |
| 26 |
|
| 27 |
DEFAULT_PAGE_SIZE = 200 |
| 28 |
|
| 29 |
SORT_DIR_VALUES = ('asc', 'desc') |
| 30 |
SORT_KEY_VALUES = ('name', 'status', 'container_format', 'disk_format', |
| 31 |
'size', 'id', 'created_at', 'updated_at') |
| 32 |
|
| 33 |
|
| 34 |
class Controller(object): |
| 35 |
def __init__(self, http_client, schema_client): |
| 36 |
self.http_client = http_client |
| 37 |
self.schema_client = schema_client |
| 38 |
|
| 39 |
@utils.memoized_property |
| 40 |
def model(self): |
| 41 |
schema = self.schema_client.get('image') |
| 42 |
warlock_model = warlock.model_factory( |
| 43 |
schema.raw(), base_class=schemas.SchemaBasedModel) |
| 44 |
return warlock_model |
| 45 |
|
| 46 |
@utils.memoized_property |
| 47 |
def unvalidated_model(self): |
| 48 |
"""A model which does not validate the image against the v2 schema.""" |
| 49 |
schema = self.schema_client.get('image') |
| 50 |
warlock_model = warlock.model_factory( |
| 51 |
schema.raw(), base_class=schemas.SchemaBasedModel) |
| 52 |
warlock_model.validate = lambda *args, **kwargs: None |
| 53 |
return warlock_model |
| 54 |
|
| 55 |
@staticmethod |
| 56 |
def _wrap(value): |
| 57 |
if isinstance(value, str): |
| 58 |
return [value] |
| 59 |
return value |
| 60 |
|
| 61 |
@staticmethod |
| 62 |
def _validate_sort_param(sort): |
| 63 |
"""Validates sorting argument for invalid keys and directions values. |
| 64 |
|
| 65 |
:param sort: comma-separated list of sort keys with optional <:dir> |
| 66 |
after each key |
| 67 |
""" |
| 68 |
for sort_param in sort.strip().split(','): |
| 69 |
key, _sep, dir = sort_param.partition(':') |
| 70 |
if dir and dir not in SORT_DIR_VALUES: |
| 71 |
msg = ('Invalid sort direction: %(sort_dir)s.' |
| 72 |
' It must be one of the following: %(available)s.' |
| 73 |
) % {'sort_dir': dir, |
| 74 |
'available': ', '.join(SORT_DIR_VALUES)} |
| 75 |
raise exc.HTTPBadRequest(msg) |
| 76 |
if key not in SORT_KEY_VALUES: |
| 77 |
msg = ('Invalid sort key: %(sort_key)s.' |
| 78 |
' It must be one of the following: %(available)s.' |
| 79 |
) % {'sort_key': key, |
| 80 |
'available': ', '.join(SORT_KEY_VALUES)} |
| 81 |
raise exc.HTTPBadRequest(msg) |
| 82 |
return sort |
| 83 |
|
| 84 |
@utils.add_req_id_to_generator() |
| 85 |
def list(self, **kwargs): |
| 86 |
"""Retrieve a listing of Image objects. |
| 87 |
|
| 88 |
:param page_size: Number of images to request in each |
| 89 |
paginated request. |
| 90 |
:returns: generator over list of Images. |
| 91 |
""" |
| 92 |
|
| 93 |
limit = kwargs.get('limit') |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
page_size = kwargs.get('page_size') or DEFAULT_PAGE_SIZE |
| 98 |
|
| 99 |
def paginate(url, page_size, limit=None): |
| 100 |
next_url = url |
| 101 |
req_id_hdr = {} |
| 102 |
|
| 103 |
while True: |
| 104 |
if limit and page_size > limit: |
| 105 |
|
| 106 |
|
| 107 |
next_url = next_url.replace("limit=%s" % page_size, |
| 108 |
"limit=%s" % limit) |
| 109 |
|
| 110 |
resp, body = self.http_client.get(next_url, headers=req_id_hdr) |
| 111 |
|
| 112 |
|
| 113 |
req_id_hdr['x-openstack-request-id'] = \ |
| 114 |
utils._extract_request_id(resp) |
| 115 |
|
| 116 |
for image in body['images']: |
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
image.pop('self', None) |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
yield self.unvalidated_model(**image), resp |
| 125 |
if limit: |
| 126 |
limit -= 1 |
| 127 |
if limit <= 0: |
| 128 |
return |
| 129 |
|
| 130 |
try: |
| 131 |
next_url = body['next'] |
| 132 |
except KeyError: |
| 133 |
return |
| 134 |
|
| 135 |
filters = kwargs.get('filters', {}) |
| 136 |
|
| 137 |
|
| 138 |
filters['limit'] = page_size |
| 139 |
|
| 140 |
tags = filters.pop('tag', []) |
| 141 |
tags_url_params = [] |
| 142 |
|
| 143 |
for tag in tags: |
| 144 |
if not isinstance(tag, str): |
| 145 |
raise exc.HTTPBadRequest("Invalid tag value %s" % tag) |
| 146 |
|
| 147 |
tags_url_params.append({'tag': encodeutils.safe_encode(tag)}) |
| 148 |
|
| 149 |
for param, value in filters.items(): |
| 150 |
if isinstance(value, str): |
| 151 |
filters[param] = encodeutils.safe_encode(value) |
| 152 |
|
| 153 |
url = '/v2/images?%s' % urllib.parse.urlencode(filters) |
| 154 |
|
| 155 |
for param in tags_url_params: |
| 156 |
url = '%s&%s' % (url, urllib.parse.urlencode(param)) |
| 157 |
|
| 158 |
if 'sort' in kwargs: |
| 159 |
if 'sort_key' in kwargs or 'sort_dir' in kwargs: |
| 160 |
raise exc.HTTPBadRequest("The 'sort' argument is not supported" |
| 161 |
" with 'sort_key' or 'sort_dir'.") |
| 162 |
url = '%s&sort=%s' % (url, |
| 163 |
self._validate_sort_param( |
| 164 |
kwargs['sort'])) |
| 165 |
else: |
| 166 |
sort_dir = self._wrap(kwargs.get('sort_dir', [])) |
| 167 |
sort_key = self._wrap(kwargs.get('sort_key', [])) |
| 168 |
|
| 169 |
if len(sort_key) != len(sort_dir) and len(sort_dir) > 1: |
| 170 |
raise exc.HTTPBadRequest( |
| 171 |
"Unexpected number of sort directions: " |
| 172 |
"either provide a single sort direction or an equal " |
| 173 |
"number of sort keys and sort directions.") |
| 174 |
for key in sort_key: |
| 175 |
url = '%s&sort_key=%s' % (url, key) |
| 176 |
|
| 177 |
for dir in sort_dir: |
| 178 |
url = '%s&sort_dir=%s' % (url, dir) |
| 179 |
|
| 180 |
if isinstance(kwargs.get('marker'), str): |
| 181 |
url = '%s&marker=%s' % (url, kwargs['marker']) |
| 182 |
|
| 183 |
for image, resp in paginate(url, page_size, limit): |
| 184 |
yield image, resp |
| 185 |
|
| 186 |
@utils.add_req_id_to_object() |
| 187 |
def _get(self, image_id, header=None): |
| 188 |
url = '/v2/images/%s' % image_id |
| 189 |
header = header or {} |
| 190 |
resp, body = self.http_client.get(url, headers=header) |
| 191 |
|
| 192 |
|
| 193 |
body.pop('self', None) |
| 194 |
return self.unvalidated_model(**body), resp |
| 195 |
|
| 196 |
def get(self, image_id): |
| 197 |
return self._get(image_id) |
| 198 |
|
| 199 |
@utils.add_req_id_to_object() |
| 200 |
def get_associated_image_tasks(self, image_id): |
| 201 |
"""Get the tasks associated with an image. |
| 202 |
|
| 203 |
:param image_id: ID of the image |
| 204 |
:raises: exc.HTTPNotImplemented if Glance is not new enough to support |
| 205 |
this API (v2.12). |
| 206 |
""" |
| 207 |
|
| 208 |
|
| 209 |
if utils.has_version(self.http_client, 'v2.12'): |
| 210 |
url = '/v2/images/%s/tasks' % image_id |
| 211 |
resp, body = self.http_client.get(url) |
| 212 |
body.pop('self', None) |
| 213 |
return body, resp |
| 214 |
else: |
| 215 |
raise exc.HTTPNotImplemented( |
| 216 |
'This operation is not supported by Glance.') |
| 217 |
|
| 218 |
@utils.add_req_id_to_object() |
| 219 |
def data(self, image_id, do_checksum=True, allow_md5_fallback=False): |
| 220 |
"""Retrieve data of an image. |
| 221 |
|
| 222 |
When do_checksum is enabled, validation proceeds as follows: |
| 223 |
|
| 224 |
1. if the image has a 'os_hash_value' property, the algorithm |
| 225 |
specified in the image's 'os_hash_algo' property will be used |
| 226 |
to validate against the 'os_hash_value' value. If the |
| 227 |
specified hash algorithm is not available AND allow_md5_fallback |
| 228 |
is True, then continue to step #2 |
| 229 |
2. else if the image has a checksum property, MD5 is used to |
| 230 |
validate against the 'checksum' value. (If MD5 is not available |
| 231 |
to the client, the download fails.) |
| 232 |
3. else if the download response has a 'content-md5' header, MD5 |
| 233 |
is used to validate against the header value. (If MD5 is not |
| 234 |
available to the client, the download fails.) |
| 235 |
4. if none of 1-3 obtain, the data is **not validated** (this is |
| 236 |
compatible with legacy behavior) |
| 237 |
|
| 238 |
:param image_id: ID of the image to download |
| 239 |
:param do_checksum: Enable/disable checksum validation |
| 240 |
:param allow_md5_fallback: |
| 241 |
Use the MD5 checksum for validation if the algorithm specified by |
| 242 |
the image's 'os_hash_algo' property is not available |
| 243 |
:returns: An iterable body or ``None`` |
| 244 |
""" |
| 245 |
if do_checksum: |
| 246 |
|
| 247 |
|
| 248 |
url = '/v2/images/%s' % image_id |
| 249 |
resp, image_meta = self.http_client.get(url) |
| 250 |
meta_checksum = image_meta.get('checksum', None) |
| 251 |
meta_hash_value = image_meta.get('os_hash_value', None) |
| 252 |
meta_hash_algo = image_meta.get('os_hash_algo', None) |
| 253 |
|
| 254 |
url = '/v2/images/%s/file' % image_id |
| 255 |
resp, body = self.http_client.get(url) |
| 256 |
if resp.status_code == codes.no_content: |
| 257 |
return None, resp |
| 258 |
|
| 259 |
checksum = resp.headers.get('content-md5', None) |
| 260 |
content_length = int(resp.headers.get('content-length', 0)) |
| 261 |
|
| 262 |
check_md5sum = do_checksum |
| 263 |
if do_checksum and meta_hash_value is not None: |
| 264 |
try: |
| 265 |
hasher = hashlib.new(str(meta_hash_algo)) |
| 266 |
body = utils.serious_integrity_iter(body, |
| 267 |
hasher, |
| 268 |
meta_hash_value) |
| 269 |
check_md5sum = False |
| 270 |
except ValueError as ve: |
| 271 |
if (str(ve).startswith('unsupported hash type') and |
| 272 |
allow_md5_fallback): |
| 273 |
check_md5sum = True |
| 274 |
else: |
| 275 |
raise |
| 276 |
|
| 277 |
if do_checksum and check_md5sum: |
| 278 |
if meta_checksum is not None: |
| 279 |
body = utils.integrity_iter(body, meta_checksum) |
| 280 |
elif checksum is not None: |
| 281 |
body = utils.integrity_iter(body, checksum) |
| 282 |
else: |
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
pass |
| 288 |
|
| 289 |
return utils.IterableWithLength(body, content_length), resp |
| 290 |
|
| 291 |
@utils.add_req_id_to_object() |
| 292 |
def upload(self, image_id, image_data, image_size=None, u_url=None, |
| 293 |
backend=None): |
| 294 |
"""Upload the data for an image. |
| 295 |
|
| 296 |
:param image_id: ID of the image to upload data for. |
| 297 |
:param image_data: File-like object supplying the data to upload. |
| 298 |
:param image_size: If present pass it as header |
| 299 |
:param u_url: Upload url to upload the data to. |
| 300 |
:param backend: Backend store to upload image to. |
| 301 |
""" |
| 302 |
url = u_url or '/v2/images/%s/file' % image_id |
| 303 |
hdrs = {'Content-Type': 'application/octet-stream'} |
| 304 |
if image_size is not None: |
| 305 |
if not isinstance(image_size, int): |
| 306 |
raise TypeError("image_size must be an integer, " |
| 307 |
"got %s" % type(image_size).__name__) |
| 308 |
hdrs.update({'x-openstack-image-size': '%i' % image_size}) |
| 309 |
if backend is not None: |
| 310 |
hdrs['x-image-meta-store'] = backend |
| 311 |
|
| 312 |
body = image_data |
| 313 |
resp, body = self.http_client.put(url, headers=hdrs, data=body) |
| 314 |
return (resp, body), resp |
| 315 |
|
| 316 |
@utils.add_req_id_to_object() |
| 317 |
def get_import_info(self): |
| 318 |
"""Get Import info from discovery endpoint.""" |
| 319 |
url = '/v2/info/import' |
| 320 |
resp, body = self.http_client.get(url) |
| 321 |
return body, resp |
| 322 |
|
| 323 |
@utils.add_req_id_to_object() |
| 324 |
def get_stores_info(self): |
| 325 |
"""Get available stores info from discovery endpoint.""" |
| 326 |
url = '/v2/info/stores' |
| 327 |
resp, body = self.http_client.get(url) |
| 328 |
return body, resp |
| 329 |
|
| 330 |
@utils.add_req_id_to_object() |
| 331 |
def get_stores_info_detail(self): |
| 332 |
"""Get available stores info from discovery endpoint.""" |
| 333 |
url = '/v2/info/stores/detail' |
| 334 |
resp, body = self.http_client.get(url) |
| 335 |
return body, resp |
| 336 |
|
| 337 |
@utils.add_req_id_to_object() |
| 338 |
def delete_from_store(self, store_id, image_id): |
| 339 |
"""Delete image data from specific store.""" |
| 340 |
url = ('/v2/stores/%(store)s/%(image)s' % {'store': store_id, |
| 341 |
'image': image_id}) |
| 342 |
resp, body = self.http_client.delete(url) |
| 343 |
return body, resp |
| 344 |
|
| 345 |
@utils.add_req_id_to_object() |
| 346 |
def stage(self, image_id, image_data, image_size=None): |
| 347 |
"""Upload the data to image staging. |
| 348 |
|
| 349 |
:param image_id: ID of the image to upload data for. |
| 350 |
:param image_data: File-like object supplying the data to upload. |
| 351 |
:param image_size: If present pass it to upload call |
| 352 |
""" |
| 353 |
url = '/v2/images/%s/stage' % image_id |
| 354 |
resp, body = self.upload(image_id, |
| 355 |
image_data, |
| 356 |
image_size=image_size, |
| 357 |
u_url=url) |
| 358 |
return body, resp |
| 359 |
|
| 360 |
@utils.add_req_id_to_object() |
| 361 |
def image_import(self, image_id, method='glance-direct', uri=None, |
| 362 |
remote_region=None, remote_image_id=None, |
| 363 |
remote_service_interface=None, backend=None, |
| 364 |
stores=None, allow_failure=True, all_stores=None): |
| 365 |
"""Import Image via method.""" |
| 366 |
headers = {} |
| 367 |
url = '/v2/images/%s/import' % image_id |
| 368 |
data = {'method': {'name': method}} |
| 369 |
if stores: |
| 370 |
data['stores'] = stores |
| 371 |
if allow_failure: |
| 372 |
data['all_stores_must_succeed'] = False |
| 373 |
if backend is not None: |
| 374 |
headers['x-image-meta-store'] = backend |
| 375 |
if all_stores: |
| 376 |
data['all_stores'] = True |
| 377 |
if allow_failure: |
| 378 |
data['all_stores_must_succeed'] = False |
| 379 |
|
| 380 |
if remote_region and remote_image_id: |
| 381 |
if remote_service_interface: |
| 382 |
data['method']['glance_service_interface'] = \ |
| 383 |
remote_service_interface |
| 384 |
data['method']['glance_region'] = remote_region |
| 385 |
data['method']['glance_image_id'] = remote_image_id |
| 386 |
|
| 387 |
if uri: |
| 388 |
if method == 'web-download': |
| 389 |
data['method']['uri'] = uri |
| 390 |
else: |
| 391 |
raise exc.HTTPBadRequest('URI is only supported with method: ' |
| 392 |
'"web-download"') |
| 393 |
resp, body = self.http_client.post(url, data=data, headers=headers) |
| 394 |
return body, resp |
| 395 |
|
| 396 |
@utils.add_req_id_to_object() |
| 397 |
def delete(self, image_id): |
| 398 |
"""Delete an image.""" |
| 399 |
url = '/v2/images/%s' % image_id |
| 400 |
resp, body = self.http_client.delete(url) |
| 401 |
return (resp, body), resp |
| 402 |
|
| 403 |
@utils.add_req_id_to_object() |
| 404 |
def create(self, **kwargs): |
| 405 |
"""Create an image.""" |
| 406 |
headers = {} |
| 407 |
url = '/v2/images' |
| 408 |
backend = kwargs.pop('backend', None) |
| 409 |
if backend is not None: |
| 410 |
headers['x-image-meta-store'] = backend |
| 411 |
|
| 412 |
image = self.model() |
| 413 |
for (key, value) in kwargs.items(): |
| 414 |
try: |
| 415 |
setattr(image, key, value) |
| 416 |
except warlock.InvalidOperation as e: |
| 417 |
raise TypeError(str(e)) |
| 418 |
|
| 419 |
resp, body = self.http_client.post(url, headers=headers, data=image) |
| 420 |
|
| 421 |
|
| 422 |
body.pop('self', None) |
| 423 |
return self.model(**body), resp |
| 424 |
|
| 425 |
@utils.add_req_id_to_object() |
| 426 |
def deactivate(self, image_id): |
| 427 |
"""Deactivate an image.""" |
| 428 |
url = '/v2/images/%s/actions/deactivate' % image_id |
| 429 |
resp, body = self.http_client.post(url) |
| 430 |
return (resp, body), resp |
| 431 |
|
| 432 |
@utils.add_req_id_to_object() |
| 433 |
def reactivate(self, image_id): |
| 434 |
"""Reactivate an image.""" |
| 435 |
url = '/v2/images/%s/actions/reactivate' % image_id |
| 436 |
resp, body = self.http_client.post(url) |
| 437 |
return (resp, body), resp |
| 438 |
|
| 439 |
def update(self, image_id, remove_props=None, **kwargs): |
| 440 |
"""Update attributes of an image. |
| 441 |
|
| 442 |
:param image_id: ID of the image to modify. |
| 443 |
:param remove_props: List of property names to remove |
| 444 |
:param kwargs: Image attribute names and their new values. |
| 445 |
""" |
| 446 |
unvalidated_image = self.get(image_id) |
| 447 |
image = self.model(**unvalidated_image) |
| 448 |
for (key, value) in kwargs.items(): |
| 449 |
try: |
| 450 |
setattr(image, key, value) |
| 451 |
except warlock.InvalidOperation as e: |
| 452 |
raise TypeError(str(e)) |
| 453 |
|
| 454 |
if remove_props: |
| 455 |
cur_props = image.keys() |
| 456 |
new_props = kwargs.keys() |
| 457 |
|
| 458 |
|
| 459 |
props_to_remove = set(cur_props).intersection( |
| 460 |
set(remove_props).difference(new_props)) |
| 461 |
|
| 462 |
for key in props_to_remove: |
| 463 |
delattr(image, key) |
| 464 |
|
| 465 |
url = '/v2/images/%s' % image_id |
| 466 |
hdrs = {'Content-Type': 'application/openstack-images-v2.1-json-patch'} |
| 467 |
resp, _ = self.http_client.patch(url, headers=hdrs, data=image.patch) |
| 468 |
|
| 469 |
|
| 470 |
req_id_hdr = { |
| 471 |
'x-openstack-request-id': utils._extract_request_id(resp)} |
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
return self._get(image_id, req_id_hdr) |
| 477 |
|
| 478 |
def _get_image_with_locations_or_fail(self, image_id): |
| 479 |
image = self.get(image_id) |
| 480 |
if getattr(image, 'locations', None) is None: |
| 481 |
raise exc.HTTPBadRequest('The administrator has disabled ' |
| 482 |
'API access to image locations') |
| 483 |
return image |
| 484 |
|
| 485 |
@utils.add_req_id_to_object() |
| 486 |
def _send_image_update_request(self, image_id, patch_body): |
| 487 |
url = '/v2/images/%s' % image_id |
| 488 |
hdrs = {'Content-Type': 'application/openstack-images-v2.1-json-patch'} |
| 489 |
resp, body = self.http_client.patch(url, headers=hdrs, |
| 490 |
data=json.dumps(patch_body)) |
| 491 |
return (resp, body), resp |
| 492 |
|
| 493 |
def add_location(self, image_id, url, metadata, validation_data=None): |
| 494 |
"""Add a new location entry to an image's list of locations. |
| 495 |
|
| 496 |
It is an error to add a URL that is already present in the list of |
| 497 |
locations. |
| 498 |
|
| 499 |
:param image_id: ID of image to which the location is to be added. |
| 500 |
:param url: URL of the location to add. |
| 501 |
:param metadata: Metadata associated with the location. |
| 502 |
:param validation_data: Validation data for the image. |
| 503 |
:returns: The updated image |
| 504 |
""" |
| 505 |
add_patch = [{'op': 'add', 'path': '/locations/-', |
| 506 |
'value': {'url': url, 'metadata': metadata}}] |
| 507 |
if validation_data: |
| 508 |
add_patch[0]['value']['validation_data'] = validation_data |
| 509 |
response = self._send_image_update_request(image_id, add_patch) |
| 510 |
|
| 511 |
|
| 512 |
req_id_hdr = {'x-openstack-request-id': response.request_ids[0]} |
| 513 |
return self._get(image_id, req_id_hdr) |
| 514 |
|
| 515 |
def delete_locations(self, image_id, url_set): |
| 516 |
"""Remove one or more location entries of an image. |
| 517 |
|
| 518 |
:param image_id: ID of image from which locations are to be removed. |
| 519 |
:param url_set: set of URLs of location entries to remove. |
| 520 |
:returns: None |
| 521 |
""" |
| 522 |
image = self._get_image_with_locations_or_fail(image_id) |
| 523 |
current_urls = [loc['url'] for loc in image.locations] |
| 524 |
|
| 525 |
missing_locs = url_set.difference(set(current_urls)) |
| 526 |
if missing_locs: |
| 527 |
raise exc.HTTPNotFound('Unknown URL(s): %s' % list(missing_locs)) |
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
url_indices = [current_urls.index(url) for url in url_set] |
| 533 |
url_indices.sort(reverse=True) |
| 534 |
patches = [{'op': 'remove', 'path': '/locations/%s' % url_idx} |
| 535 |
for url_idx in url_indices] |
| 536 |
return self._send_image_update_request(image_id, patches) |
| 537 |
|
| 538 |
def update_location(self, image_id, url, metadata): |
| 539 |
"""Update an existing location entry in an image's list of locations. |
| 540 |
|
| 541 |
The URL specified must be already present in the image's list of |
| 542 |
locations. |
| 543 |
|
| 544 |
:param image_id: ID of image whose location is to be updated. |
| 545 |
:param url: URL of the location to update. |
| 546 |
:param metadata: Metadata associated with the location. |
| 547 |
:returns: The updated image |
| 548 |
""" |
| 549 |
image = self._get_image_with_locations_or_fail(image_id) |
| 550 |
url_map = dict([(loc['url'], loc) for loc in image.locations]) |
| 551 |
if url not in url_map: |
| 552 |
raise exc.HTTPNotFound('Unknown URL: %s, the URL must be one of' |
| 553 |
' existing locations of current image' % |
| 554 |
url) |
| 555 |
|
| 556 |
if url_map[url]['metadata'] == metadata: |
| 557 |
return image |
| 558 |
|
| 559 |
url_map[url]['metadata'] = metadata |
| 560 |
patches = [{'op': 'replace', |
| 561 |
'path': '/locations', |
| 562 |
'value': list(url_map.values())}] |
| 563 |
response = self._send_image_update_request(image_id, patches) |
| 564 |
|
| 565 |
|
| 566 |
req_id_hdr = {'x-openstack-request-id': response.request_ids[0]} |
| 567 |
|
| 568 |
return self._get(image_id, req_id_hdr) |
| 569 |
|
| 570 |
def add_image_location(self, image_id, location_url, validation_data={}): |
| 571 |
"""Add a new location to an image. |
| 572 |
|
| 573 |
:param image_id: ID of image to which the location is to be added. |
| 574 |
:param location_url: URL of the location to add. |
| 575 |
:param validation_data: Validation data for the image. |
| 576 |
""" |
| 577 |
if not utils.has_version(self.http_client, 'v2.17'): |
| 578 |
raise exc.HTTPNotImplemented( |
| 579 |
'This operation is not supported by Glance.') |
| 580 |
|
| 581 |
url = '/v2/images/%s/locations' % image_id |
| 582 |
data = {'url': location_url, |
| 583 |
'validation_data': validation_data} |
| 584 |
resp, body = self.http_client.post(url, data=data) |
| 585 |
return self._get(image_id) |
| 586 |
|
| 587 |
@utils.add_req_id_to_object() |
| 588 |
def get_image_locations(self, image_id): |
| 589 |
"""Fetch list of locations associated to the Image. |
| 590 |
|
| 591 |
:param image_id: ID of image to which the location is to be fetched. |
| 592 |
""" |
| 593 |
if not utils.has_version(self.http_client, 'v2.17'): |
| 594 |
raise exc.HTTPNotImplemented( |
| 595 |
'This operation is not supported by Glance.') |
| 596 |
url = '/v2/images/%s/locations' % (image_id) |
| 597 |
resp, locations = self.http_client.get(url) |
| 598 |
return locations, resp |