Debian Codegraph @

glanceclient/v2/metadefs.py

raw symbols SCIP
1 # Copyright 2014 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 from oslo_utils import encodeutils
17 import urllib.parse
18 import warlock
19
20 from glanceclient.common import utils
21 from glanceclient.v2 import schemas
22
23 DEFAULT_PAGE_SIZE = 20
24 SORT_DIR_VALUES = ('asc', 'desc')
25 SORT_KEY_VALUES = ('created_at', 'namespace')
26
27
28 class NamespaceController(object):
29 def __init__(self, http_client, schema_client):
30 self.http_client = http_client
31 self.schema_client = schema_client
32
33 @utils.memoized_property
34 def model(self):
35 schema = self.schema_client.get('metadefs/namespace')
36 return warlock.model_factory(schema.raw(),
37 base_class=schemas.SchemaBasedModel)
38
39 @utils.add_req_id_to_object()
40 def create(self, **kwargs):
41 """Create a namespace.
42
43 :param kwargs: Unpacked namespace object.
44 """
45 url = '/v2/metadefs/namespaces'
46 try:
47 namespace = self.model(kwargs)
48 except (warlock.InvalidOperation, ValueError) as e:
49 raise TypeError(str(e))
50
51 resp, body = self.http_client.post(url, data=namespace)
52 body.pop('self', None)
53 return self.model(**body), resp
54
55 def update(self, namespace_name, **kwargs):
56 """Update a namespace.
57
58 :param namespace_name: Name of a namespace (old one).
59 :param kwargs: Unpacked namespace object.
60 """
61 namespace = self.get(namespace_name)
62 for (key, value) in kwargs.items():
63 try:
64 setattr(namespace, key, value)
65 except warlock.InvalidOperation as e:
66 raise TypeError(str(e))
67
68 # Remove read-only parameters.
69 read_only = ['schema', 'updated_at', 'created_at']
70 for elem in read_only:
71 if elem in namespace:
72 del namespace[elem]
73
74 url = '/v2/metadefs/namespaces/%(namespace)s' % {
75 'namespace': namespace_name}
76 # Pass the original wrapped value to http client.
77 resp, _ = self.http_client.put(url, data=namespace.wrapped)
78 # Get request id from `put` request so it can be passed to the
79 # following `get` call
80 req_id_hdr = {
81 'x-openstack-request-id': utils._extract_request_id(resp)
82 }
83 return self._get(namespace.namespace, header=req_id_hdr)
84
85 def get(self, namespace, **kwargs):
86 return self._get(namespace, **kwargs)
87
88 @utils.add_req_id_to_object()
89 def _get(self, namespace, header=None, **kwargs):
90 """Get one namespace."""
91 query_params = urllib.parse.urlencode(kwargs)
92 if kwargs:
93 query_params = '?%s' % query_params
94
95 url = '/v2/metadefs/namespaces/%(namespace)s%(query_params)s' % {
96 'namespace': namespace, 'query_params': query_params}
97 header = header or {}
98 resp, body = self.http_client.get(url, headers=header)
99 # NOTE(bcwaldon): remove 'self' for now until we have an elegant
100 # way to pass it into the model constructor without conflict
101 body.pop('self', None)
102 return self.model(**body), resp
103
104 @utils.add_req_id_to_generator()
105 def list(self, **kwargs):
106 """Retrieve a listing of Namespace objects.
107
108 :param page_size: Number of items to request in each paginated request
109 :param limit: Use to request a specific page size. Expect a response
110 to a limited request to return between zero and limit
111 items.
112 :param marker: Specifies the namespace of the last-seen namespace.
113 The typical pattern of limit and marker is to make an
114 initial limited request and then to use the last
115 namespace from the response as the marker parameter
116 in a subsequent limited request.
117 :param sort_key: The field to sort on (for example, 'created_at')
118 :param sort_dir: The direction to sort ('asc' or 'desc')
119 :returns: generator over list of Namespaces
120
121 """
122
123 ori_validate_fun = self.model.validate
124 empty_fun = lambda *args, **kwargs: None
125
126 def paginate(url):
127 resp, body = self.http_client.get(url)
128 for namespace in body['namespaces']:
129 # NOTE(bcwaldon): remove 'self' for now until we have
130 # an elegant way to pass it into the model constructor
131 # without conflict.
132 namespace.pop('self', None)
133 yield self.model(**namespace), resp
134 # NOTE(zhiyan): In order to resolve the performance issue
135 # of JSON schema validation for image listing case, we
136 # don't validate each image entry but do it only on first
137 # image entry for each page.
138 self.model.validate = empty_fun
139
140 # NOTE(zhiyan); Reset validation function.
141 self.model.validate = ori_validate_fun
142
143 try:
144 next_url = body['next']
145 except KeyError:
146 return
147 else:
148 for namespace, resp in paginate(next_url):
149 yield namespace, resp
150
151 filters = kwargs.get('filters', {})
152 filters = {} if filters is None else filters
153
154 if not kwargs.get('page_size'):
155 filters['limit'] = DEFAULT_PAGE_SIZE
156 else:
157 filters['limit'] = kwargs['page_size']
158
159 if 'marker' in kwargs:
160 filters['marker'] = kwargs['marker']
161
162 sort_key = kwargs.get('sort_key')
163 if sort_key is not None:
164 if sort_key in SORT_KEY_VALUES:
165 filters['sort_key'] = sort_key
166 else:
167 raise ValueError('sort_key must be one of the following: %s.'
168 % ', '.join(SORT_KEY_VALUES))
169
170 sort_dir = kwargs.get('sort_dir')
171 if sort_dir is not None:
172 if sort_dir in SORT_DIR_VALUES:
173 filters['sort_dir'] = sort_dir
174 else:
175 raise ValueError('sort_dir must be one of the following: %s.'
176 % ', '.join(SORT_DIR_VALUES))
177
178 for param, value in filters.items():
179 if isinstance(value, list):
180 filters[param] = encodeutils.safe_encode(','.join(value))
181 elif isinstance(value, str):
182 filters[param] = encodeutils.safe_encode(value)
183
184 url = '/v2/metadefs/namespaces?%s' % urllib.parse.urlencode(filters)
185
186 for namespace, resp in paginate(url):
187 yield namespace, resp
188
189 @utils.add_req_id_to_object()
190 def delete(self, namespace):
191 """Delete a namespace."""
192 url = '/v2/metadefs/namespaces/%(namespace)s' % {
193 'namespace': namespace}
194 resp, body = self.http_client.delete(url)
195 return (resp, body), resp
196
197
198 class ResourceTypeController(object):
199 def __init__(self, http_client, schema_client):
200 self.http_client = http_client
201 self.schema_client = schema_client
202
203 @utils.memoized_property
204 def model(self):
205 schema = self.schema_client.get('metadefs/resource_type')
206 return warlock.model_factory(schema.raw(),
207 base_class=schemas.SchemaBasedModel)
208
209 @utils.add_req_id_to_object()
210 def associate(self, namespace, **kwargs):
211 """Associate a resource type with a namespace."""
212 try:
213 res_type = self.model(kwargs)
214 except (warlock.InvalidOperation, ValueError) as e:
215 raise TypeError(str(e))
216
217 url = '/v2/metadefs/namespaces/%(namespace)s/resource_types' % {
218 'namespace': namespace}
219 resp, body = self.http_client.post(url, data=res_type)
220 body.pop('self', None)
221 return self.model(**body), resp
222
223 @utils.add_req_id_to_object()
224 def deassociate(self, namespace, resource):
225 """Deassociate a resource type with a namespace."""
226 url = ('/v2/metadefs/namespaces/%(namespace)s/'
227 'resource_types/%(resource)s') % {
228 'namespace': namespace, 'resource': resource}
229 resp, body = self.http_client.delete(url)
230 return (resp, body), resp
231
232 @utils.add_req_id_to_generator()
233 def list(self):
234 """Retrieve a listing of available resource types.
235
236 :returns: generator over list of resource_types
237 """
238
239 url = '/v2/metadefs/resource_types'
240 resp, body = self.http_client.get(url)
241 for resource_type in body['resource_types']:
242 yield self.model(**resource_type), resp
243
244 @utils.add_req_id_to_generator()
245 def get(self, namespace):
246 url = '/v2/metadefs/namespaces/%(namespace)s/resource_types' % {
247 'namespace': namespace}
248 resp, body = self.http_client.get(url)
249 body.pop('self', None)
250 for resource_type in body['resource_type_associations']:
251 yield self.model(**resource_type), resp
252
253
254 class PropertyController(object):
255 def __init__(self, http_client, schema_client):
256 self.http_client = http_client
257 self.schema_client = schema_client
258
259 @utils.memoized_property
260 def model(self):
261 schema = self.schema_client.get('metadefs/property')
262 return warlock.model_factory(schema.raw(),
263 base_class=schemas.SchemaBasedModel)
264
265 @utils.add_req_id_to_object()
266 def create(self, namespace, **kwargs):
267 """Create a property.
268
269 :param namespace: Name of a namespace the property will belong.
270 :param kwargs: Unpacked property object.
271 """
272 try:
273 prop = self.model(kwargs)
274 except (warlock.InvalidOperation, ValueError) as e:
275 raise TypeError(str(e))
276
277 url = '/v2/metadefs/namespaces/%(namespace)s/properties' % {
278 'namespace': namespace}
279 resp, body = self.http_client.post(url, data=prop)
280 body.pop('self', None)
281 return self.model(**body), resp
282
283 def update(self, namespace, prop_name, **kwargs):
284 """Update a property.
285
286 :param namespace: Name of a namespace the property belongs.
287 :param prop_name: Name of a property (old one).
288 :param kwargs: Unpacked property object.
289 """
290 prop = self.get(namespace, prop_name)
291 for (key, value) in kwargs.items():
292 try:
293 setattr(prop, key, value)
294 except warlock.InvalidOperation as e:
295 raise TypeError(str(e))
296
297 url = ('/v2/metadefs/namespaces/%(namespace)s/'
298 'properties/%(prop_name)s') % {
299 'namespace': namespace, 'prop_name': prop_name}
300 # Pass the original wrapped value to http client.
301 resp, _ = self.http_client.put(url, data=prop.wrapped)
302 # Get request id from `put` request so it can be passed to the
303 # following `get` call
304 req_id_hdr = {
305 'x-openstack-request-id': utils._extract_request_id(resp)}
306
307 return self._get(namespace, prop.name, req_id_hdr)
308
309 def get(self, namespace, prop_name):
310 return self._get(namespace, prop_name)
311
312 @utils.add_req_id_to_object()
313 def _get(self, namespace, prop_name, header=None):
314 url = ('/v2/metadefs/namespaces/%(namespace)s/'
315 'properties/%(prop_name)s') % {
316 'namespace': namespace, 'prop_name': prop_name}
317 header = header or {}
318 resp, body = self.http_client.get(url, headers=header)
319 body.pop('self', None)
320 body['name'] = prop_name
321 return self.model(**body), resp
322
323 @utils.add_req_id_to_generator()
324 def list(self, namespace, **kwargs):
325 """Retrieve a listing of metadata properties.
326
327 :returns: generator over list of objects
328 """
329 url = '/v2/metadefs/namespaces/%(namespace)s/properties' % {
330 'namespace': namespace}
331
332 resp, body = self.http_client.get(url)
333
334 for key, value in body['properties'].items():
335 value['name'] = key
336 yield self.model(value), resp
337
338 @utils.add_req_id_to_object()
339 def delete(self, namespace, prop_name):
340 """Delete a property."""
341 url = ('/v2/metadefs/namespaces/%(namespace)s/'
342 'properties/%(prop_name)s') % {
343 'namespace': namespace, 'prop_name': prop_name}
344 resp, body = self.http_client.delete(url)
345 return (resp, body), resp
346
347 @utils.add_req_id_to_object()
348 def delete_all(self, namespace):
349 """Delete all properties in a namespace."""
350 url = '/v2/metadefs/namespaces/%(namespace)s/properties' % {
351 'namespace': namespace}
352 resp, body = self.http_client.delete(url)
353 return (resp, body), resp
354
355
356 class ObjectController(object):
357 def __init__(self, http_client, schema_client):
358 self.http_client = http_client
359 self.schema_client = schema_client
360
361 @utils.memoized_property
362 def model(self):
363 schema = self.schema_client.get('metadefs/object')
364 return warlock.model_factory(schema.raw(),
365 base_class=schemas.SchemaBasedModel)
366
367 @utils.add_req_id_to_object()
368 def create(self, namespace, **kwargs):
369 """Create an object.
370
371 :param namespace: Name of a namespace the object belongs.
372 :param kwargs: Unpacked object.
373 """
374 try:
375 obj = self.model(kwargs)
376 except (warlock.InvalidOperation, ValueError) as e:
377 raise TypeError(str(e))
378
379 url = '/v2/metadefs/namespaces/%(namespace)s/objects' % {
380 'namespace': namespace}
381
382 resp, body = self.http_client.post(url, data=obj)
383 body.pop('self', None)
384 return self.model(**body), resp
385
386 def update(self, namespace, object_name, **kwargs):
387 """Update an object.
388
389 :param namespace: Name of a namespace the object belongs.
390 :param object_name: Name of an object (old one).
391 :param kwargs: Unpacked object.
392 """
393 obj = self.get(namespace, object_name)
394 for (key, value) in kwargs.items():
395 try:
396 setattr(obj, key, value)
397 except warlock.InvalidOperation as e:
398 raise TypeError(str(e))
399
400 # Remove read-only parameters.
401 read_only = ['schema', 'updated_at', 'created_at']
402 for elem in read_only:
403 if elem in obj:
404 del obj[elem]
405
406 url = ('/v2/metadefs/namespaces/%(namespace)s/'
407 'objects/%(object_name)s') % {
408 'namespace': namespace, 'object_name': object_name}
409 # Pass the original wrapped value to http client.
410 resp, _ = self.http_client.put(url, data=obj.wrapped)
411 # Get request id from `put` request so it can be passed to the
412 # following `get` call
413 req_id_hdr = {
414 'x-openstack-request-id': utils._extract_request_id(resp)}
415
416 return self._get(namespace, obj.name, req_id_hdr)
417
418 def get(self, namespace, object_name):
419 return self._get(namespace, object_name)
420
421 @utils.add_req_id_to_object()
422 def _get(self, namespace, object_name, header=None):
423 url = ('/v2/metadefs/namespaces/%(namespace)s/'
424 'objects/%(object_name)s') % {
425 'namespace': namespace, 'object_name': object_name}
426 header = header or {}
427 resp, body = self.http_client.get(url, headers=header)
428 body.pop('self', None)
429 return self.model(**body), resp
430
431 @utils.add_req_id_to_generator()
432 def list(self, namespace, **kwargs):
433 """Retrieve a listing of metadata objects.
434
435 :returns: generator over list of objects
436 """
437 url = '/v2/metadefs/namespaces/%(namespace)s/objects' % {
438 'namespace': namespace}
439 resp, body = self.http_client.get(url)
440
441 for obj in body['objects']:
442 yield self.model(obj), resp
443
444 @utils.add_req_id_to_object()
445 def delete(self, namespace, object_name):
446 """Delete an object."""
447 url = ('/v2/metadefs/namespaces/%(namespace)s/'
448 'objects/%(object_name)s') % {
449 'namespace': namespace, 'object_name': object_name}
450 resp, body = self.http_client.delete(url)
451 return (resp, body), resp
452
453 @utils.add_req_id_to_object()
454 def delete_all(self, namespace):
455 """Delete all objects in a namespace."""
456 url = '/v2/metadefs/namespaces/%(namespace)s/objects' % {
457 'namespace': namespace}
458 resp, body = self.http_client.delete(url)
459 return (resp, body), resp
460
461
462 class TagController(object):
463 def __init__(self, http_client, schema_client):
464 self.http_client = http_client
465 self.schema_client = schema_client
466
467 @utils.memoized_property
468 def model(self):
469 schema = self.schema_client.get('metadefs/tag')
470 return warlock.model_factory(schema.raw(),
471 base_class=schemas.SchemaBasedModel)
472
473 @utils.add_req_id_to_object()
474 def create(self, namespace, tag_name):
475 """Create a tag.
476
477 :param namespace: Name of a namespace the Tag belongs.
478 :param tag_name: The name of the new tag to create.
479 """
480
481 url = '/v2/metadefs/namespaces/%(namespace)s/tags/%(tag_name)s' % {
482 'namespace': namespace, 'tag_name': tag_name}
483
484 resp, body = self.http_client.post(url)
485 body.pop('self', None)
486 return self.model(**body), resp
487
488 @utils.add_req_id_to_generator()
489 def create_multiple(self, namespace, **kwargs):
490 """Create the list of tags.
491
492 :param namespace: Name of a namespace to which the Tags belong.
493 :param kwargs: list of tags, optional parameter append.
494 """
495 tag_names = kwargs.pop('tags', [])
496 md_tag_list = []
497
498 for tag_name in tag_names:
499 try:
500 md_tag_list.append(self.model(name=tag_name))
501 except (warlock.InvalidOperation) as e:
502 raise TypeError(str(e))
503 tags = {'tags': md_tag_list}
504 headers = {}
505
506 url = '/v2/metadefs/namespaces/%(namespace)s/tags' % {
507 'namespace': namespace}
508
509 append = kwargs.pop('append', False)
510 if append:
511 headers['X-Openstack-Append'] = True
512 resp, body = self.http_client.post(url, headers=headers, data=tags)
513 body.pop('self', None)
514 for tag in body['tags']:
515 yield self.model(tag), resp
516
517 def update(self, namespace, tag_name, **kwargs):
518 """Update a tag.
519
520 :param namespace: Name of a namespace the Tag belongs.
521 :param tag_name: Name of the Tag (old one).
522 :param kwargs: Unpacked tag.
523 """
524 tag = self.get(namespace, tag_name)
525 for (key, value) in kwargs.items():
526 try:
527 setattr(tag, key, value)
528 except warlock.InvalidOperation as e:
529 raise TypeError(str(e))
530
531 # Remove read-only parameters.
532 read_only = ['updated_at', 'created_at']
533 for elem in read_only:
534 if elem in tag:
535 del tag[elem]
536
537 url = '/v2/metadefs/namespaces/%(namespace)s/tags/%(tag_name)s' % {
538 'namespace': namespace, 'tag_name': tag_name}
539 # Pass the original wrapped value to http client.
540 resp, _ = self.http_client.put(url, data=tag.wrapped)
541 # Get request id from `put` request so it can be passed to the
542 # following `get` call
543 req_id_hdr = {
544 'x-openstack-request-id': utils._extract_request_id(resp)}
545
546 return self._get(namespace, tag.name, req_id_hdr)
547
548 def get(self, namespace, tag_name):
549 return self._get(namespace, tag_name)
550
551 @utils.add_req_id_to_object()
552 def _get(self, namespace, tag_name, header=None):
553 url = '/v2/metadefs/namespaces/%(namespace)s/tags/%(tag_name)s' % {
554 'namespace': namespace, 'tag_name': tag_name}
555 header = header or {}
556 resp, body = self.http_client.get(url, headers=header)
557 body.pop('self', None)
558 return self.model(**body), resp
559
560 @utils.add_req_id_to_generator()
561 def list(self, namespace, **kwargs):
562 """Retrieve a listing of metadata tags.
563
564 :returns: generator over list of tags.
565 """
566 url = '/v2/metadefs/namespaces/%(namespace)s/tags' % {
567 'namespace': namespace}
568 resp, body = self.http_client.get(url)
569
570 for tag in body['tags']:
571 yield self.model(tag), resp
572
573 @utils.add_req_id_to_object()
574 def delete(self, namespace, tag_name):
575 """Delete a tag."""
576 url = '/v2/metadefs/namespaces/%(namespace)s/tags/%(tag_name)s' % {
577 'namespace': namespace, 'tag_name': tag_name}
578 resp, body = self.http_client.delete(url)
579 return (resp, body), resp
580
581 @utils.add_req_id_to_object()
582 def delete_all(self, namespace):
583 """Delete all tags in a namespace."""
584 url = '/v2/metadefs/namespaces/%(namespace)s/tags' % {
585 'namespace': namespace}
586 resp, body = self.http_client.delete(url)
587 return (resp, body), resp