Debian Codegraph @

glanceclient/v1/apiclient/base.py

raw symbols SCIP
1 # Copyright 2010 Jacob Kaplan-Moss
2 # Copyright 2011 OpenStack Foundation
3 # Copyright 2012 Grid Dynamics
4 # Copyright 2013 OpenStack Foundation
5 # All Rights Reserved.
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18
19 """
20 Base utilities to build API operation managers and objects on top of.
21 """
22
23 ########################################################################
24 #
25 # THIS MODULE IS DEPRECATED
26 #
27 # Please refer to
28 # https://etherpad.openstack.org/p/kilo-glanceclient-library-proposals for
29 # the discussion leading to this deprecation.
30 #
31 # We recommend checking out the python-openstacksdk project
32 # (https://launchpad.net/python-openstacksdk) instead.
33 #
34 ########################################################################
35
36
37 # E1102: %s is not callable
38 # pylint: disable=E1102
39
40 import abc
41 import copy
42
43 from oslo_utils import strutils
44 import urllib.parse
45
46 from glanceclient._i18n import _
47 from glanceclient.v1.apiclient import exceptions
48
49
50 def getid(obj):
51 """Return id if argument is a Resource.
52
53 Abstracts the common pattern of allowing both an object or an object's ID
54 (UUID) as a parameter when dealing with relationships.
55 """
56 try:
57 if obj.uuid:
58 return obj.uuid
59 except AttributeError:
60 pass
61 try:
62 return obj.id
63 except AttributeError:
64 return obj
65
66
67 # TODO(aababilov): call run_hooks() in HookableMixin's child classes
68 class HookableMixin(object):
69 """Mixin so classes can register and run hooks."""
70 _hooks_map = {}
71
72 @classmethod
73 def add_hook(cls, hook_type, hook_func):
74 """Add a new hook of specified type.
75
76 :param cls: class that registers hooks
77 :param hook_type: hook type, e.g., '__pre_parse_args__'
78 :param hook_func: hook function
79 """
80 if hook_type not in cls._hooks_map:
81 cls._hooks_map[hook_type] = []
82
83 cls._hooks_map[hook_type].append(hook_func)
84
85 @classmethod
86 def run_hooks(cls, hook_type, *args, **kwargs):
87 """Run all hooks of specified type.
88
89 :param cls: class that registers hooks
90 :param hook_type: hook type, e.g., '__pre_parse_args__'
91 :param args: args to be passed to every hook function
92 :param kwargs: kwargs to be passed to every hook function
93 """
94 hook_funcs = cls._hooks_map.get(hook_type) or []
95 for hook_func in hook_funcs:
96 hook_func(*args, **kwargs)
97
98
99 class BaseManager(HookableMixin):
100 """Basic manager type providing common operations.
101
102 Managers interact with a particular type of API (servers, flavors, images,
103 etc.) and provide CRUD operations for them.
104 """
105 resource_class = None
106
107 def __init__(self, client):
108 """Initializes BaseManager with `client`.
109
110 :param client: instance of BaseClient descendant for HTTP requests
111 """
112 super(BaseManager, self).__init__()
113 self.client = client
114
115 def _list(self, url, response_key=None, obj_class=None, json=None):
116 """List the collection.
117
118 :param url: a partial URL, e.g., '/servers'
119 :param response_key: the key to be looked up in response dictionary,
120 e.g., 'servers'. If response_key is None - all response body
121 will be used.
122 :param obj_class: class for constructing the returned objects
123 (self.resource_class will be used by default)
124 :param json: data that will be encoded as JSON and passed in POST
125 request (GET will be sent by default)
126 """
127 if json:
128 body = self.client.post(url, json=json).json()
129 else:
130 body = self.client.get(url).json()
131
132 if obj_class is None:
133 obj_class = self.resource_class
134
135 data = body[response_key] if response_key is not None else body
136 # NOTE(ja): keystone returns values as list as {'values': [ ... ]}
137 # unlike other services which just return the list...
138 try:
139 data = data['values']
140 except (KeyError, TypeError):
141 pass
142
143 return [obj_class(self, res, loaded=True) for res in data if res]
144
145 def _get(self, url, response_key=None):
146 """Get an object from collection.
147
148 :param url: a partial URL, e.g., '/servers'
149 :param response_key: the key to be looked up in response dictionary,
150 e.g., 'server'. If response_key is None - all response body
151 will be used.
152 """
153 body = self.client.get(url).json()
154 data = body[response_key] if response_key is not None else body
155 return self.resource_class(self, data, loaded=True)
156
157 def _head(self, url):
158 """Retrieve request headers for an object.
159
160 :param url: a partial URL, e.g., '/servers'
161 """
162 resp = self.client.head(url)
163 return resp.status_code == 204
164
165 def _post(self, url, json, response_key=None, return_raw=False):
166 """Create an object.
167
168 :param url: a partial URL, e.g., '/servers'
169 :param json: data that will be encoded as JSON and passed in POST
170 request (GET will be sent by default)
171 :param response_key: the key to be looked up in response dictionary,
172 e.g., 'server'. If response_key is None - all response body
173 will be used.
174 :param return_raw: flag to force returning raw JSON instead of
175 Python object of self.resource_class
176 """
177 body = self.client.post(url, json=json).json()
178 data = body[response_key] if response_key is not None else body
179 if return_raw:
180 return data
181 return self.resource_class(self, data)
182
183 def _put(self, url, json=None, response_key=None):
184 """Update an object with PUT method.
185
186 :param url: a partial URL, e.g., '/servers'
187 :param json: data that will be encoded as JSON and passed in POST
188 request (GET will be sent by default)
189 :param response_key: the key to be looked up in response dictionary,
190 e.g., 'servers'. If response_key is None - all response body
191 will be used.
192 """
193 resp = self.client.put(url, json=json)
194 # PUT requests may not return a body
195 if resp.content:
196 body = resp.json()
197 if response_key is not None:
198 return self.resource_class(self, body[response_key])
199 else:
200 return self.resource_class(self, body)
201
202 def _patch(self, url, json=None, response_key=None):
203 """Update an object with PATCH method.
204
205 :param url: a partial URL, e.g., '/servers'
206 :param json: data that will be encoded as JSON and passed in POST
207 request (GET will be sent by default)
208 :param response_key: the key to be looked up in response dictionary,
209 e.g., 'servers'. If response_key is None - all response body
210 will be used.
211 """
212 body = self.client.patch(url, json=json).json()
213 if response_key is not None:
214 return self.resource_class(self, body[response_key])
215 else:
216 return self.resource_class(self, body)
217
218 def _delete(self, url):
219 """Delete an object.
220
221 :param url: a partial URL, e.g., '/servers/my-server'
222 """
223 return self.client.delete(url)
224
225
226 class ManagerWithFind(BaseManager, metaclass=abc.ABCMeta):
227 """Manager with additional `find()`/`findall()` methods."""
228
229 @abc.abstractmethod
230 def list(self):
231 pass
232
233 def find(self, **kwargs):
234 """Find a single item with attributes matching ``**kwargs``.
235
236 This isn't very efficient: it loads the entire list then filters on
237 the Python side.
238 """
239 matches = self.findall(**kwargs)
240 num_matches = len(matches)
241 if num_matches == 0:
242 msg = _("No %(name)s matching %(args)s.") % {
243 'name': self.resource_class.__name__,
244 'args': kwargs
245 }
246 raise exceptions.NotFound(msg)
247 elif num_matches > 1:
248 raise exceptions.NoUniqueMatch()
249 else:
250 return matches[0]
251
252 def findall(self, **kwargs):
253 """Find all items with attributes matching ``**kwargs``.
254
255 This isn't very efficient: it loads the entire list then filters on
256 the Python side.
257 """
258 found = []
259 searches = kwargs.items()
260
261 for obj in self.list():
262 try:
263 if all(getattr(obj, attr) == value
264 for (attr, value) in searches):
265 found.append(obj)
266 except AttributeError:
267 continue
268
269 return found
270
271
272 class CrudManager(BaseManager):
273 """Base manager class for manipulating entities.
274
275 Children of this class are expected to define a `collection_key` and `key`.
276
277 - `collection_key`: Usually a plural noun by convention (e.g. `entities`);
278 used to refer collections in both URL's (e.g. `/v3/entities`) and JSON
279 objects containing a list of member resources (e.g. `{'entities': [{},
280 {}, {}]}`).
281 - `key`: Usually a singular noun by convention (e.g. `entity`); used to
282 refer to an individual member of the collection.
283
284 """
285 collection_key = None
286 key = None
287
288 def build_url(self, base_url=None, **kwargs):
289 """Builds a resource URL for the given kwargs.
290
291 Given an example collection where `collection_key = 'entities'` and
292 `key = 'entity'`, the following URL's could be generated.
293
294 By default, the URL will represent a collection of entities, e.g.::
295
296 /entities
297
298 If kwargs contains an `entity_id`, then the URL will represent a
299 specific member, e.g.::
300
301 /entities/{entity_id}
302
303 :param base_url: if provided, the generated URL will be appended to it
304 """
305 url = base_url if base_url is not None else ''
306
307 url += '/%s' % self.collection_key
308
309 # do we have a specific entity?
310 entity_id = kwargs.get('%s_id' % self.key)
311 if entity_id is not None:
312 url += '/%s' % entity_id
313
314 return url
315
316 def _filter_kwargs(self, kwargs):
317 """Drop null values and handle ids."""
318 for key, ref in kwargs.copy().items():
319 if ref is None:
320 kwargs.pop(key)
321 else:
322 if isinstance(ref, Resource):
323 kwargs.pop(key)
324 kwargs['%s_id' % key] = getid(ref)
325 return kwargs
326
327 def create(self, **kwargs):
328 kwargs = self._filter_kwargs(kwargs)
329 return self._post(
330 self.build_url(**kwargs),
331 {self.key: kwargs},
332 self.key)
333
334 def get(self, **kwargs):
335 kwargs = self._filter_kwargs(kwargs)
336 return self._get(
337 self.build_url(**kwargs),
338 self.key)
339
340 def head(self, **kwargs):
341 kwargs = self._filter_kwargs(kwargs)
342 return self._head(self.build_url(**kwargs))
343
344 def list(self, base_url=None, **kwargs):
345 """List the collection.
346
347 :param base_url: if provided, the generated URL will be appended to it
348 """
349 kwargs = self._filter_kwargs(kwargs)
350
351 query = urllib.parse.urlencode(kwargs) if kwargs else '',
352 return self._list(
353 '%(base_url)s%(query)s' % {
354 'base_url': self.build_url(base_url=base_url, **kwargs),
355 'query': '?%s' % query,
356 },
357 self.collection_key)
358
359 def put(self, base_url=None, **kwargs):
360 """Update an element.
361
362 :param base_url: if provided, the generated URL will be appended to it
363 """
364 kwargs = self._filter_kwargs(kwargs)
365
366 return self._put(self.build_url(base_url=base_url, **kwargs))
367
368 def update(self, **kwargs):
369 kwargs = self._filter_kwargs(kwargs)
370 params = kwargs.copy()
371 params.pop('%s_id' % self.key)
372
373 return self._patch(
374 self.build_url(**kwargs),
375 {self.key: params},
376 self.key)
377
378 def delete(self, **kwargs):
379 kwargs = self._filter_kwargs(kwargs)
380
381 return self._delete(
382 self.build_url(**kwargs))
383
384 def find(self, base_url=None, **kwargs):
385 """Find a single item with attributes matching ``**kwargs``.
386
387 :param base_url: if provided, the generated URL will be appended to it
388 """
389 kwargs = self._filter_kwargs(kwargs)
390
391 query = urllib.parse.urlencode(kwargs) if kwargs else '',
392 rl = self._list(
393 '%(base_url)s%(query)s' % {
394 'base_url': self.build_url(base_url=base_url, **kwargs),
395 'query': '?%s' % query,
396 },
397 self.collection_key)
398 num = len(rl)
399
400 if num == 0:
401 msg = _("No %(name)s matching %(args)s.") % {
402 'name': self.resource_class.__name__,
403 'args': kwargs
404 }
405 raise exceptions.NotFound(msg)
406 elif num > 1:
407 raise exceptions.NoUniqueMatch
408 else:
409 return rl[0]
410
411
412 class Extension(HookableMixin):
413 """Extension descriptor."""
414
415 SUPPORTED_HOOKS = ('__pre_parse_args__', '__post_parse_args__')
416 manager_class = None
417
418 def __init__(self, name, module):
419 super(Extension, self).__init__()
420 self.name = name
421 self.module = module
422 self._parse_extension_module()
423
424 def _parse_extension_module(self):
425 self.manager_class = None
426 for attr_name, attr_value in self.module.__dict__.items():
427 if attr_name in self.SUPPORTED_HOOKS:
428 self.add_hook(attr_name, attr_value)
429 else:
430 try:
431 if issubclass(attr_value, BaseManager):
432 self.manager_class = attr_value
433 except TypeError:
434 pass
435
436 def __repr__(self):
437 return "<Extension '%s'>" % self.name
438
439
440 class Resource(object):
441 """Base class for OpenStack resources (tenant, user, etc.).
442
443 This is pretty much just a bag for attributes.
444 """
445
446 HUMAN_ID = False
447 NAME_ATTR = 'name'
448
449 def __init__(self, manager, info, loaded=False):
450 """Populate and bind to a manager.
451
452 :param manager: BaseManager object
453 :param info: dictionary representing resource attributes
454 :param loaded: prevent lazy-loading if set to True
455 """
456 self.manager = manager
457 self._info = info
458 self._add_details(info)
459 self._loaded = loaded
460
461 def __repr__(self):
462 reprkeys = sorted(k
463 for k in self.__dict__.keys()
464 if k[0] != '_' and k != 'manager')
465 info = ", ".join("%s=%s" % (k, getattr(self, k)) for k in reprkeys)
466 return "<%s %s>" % (self.__class__.__name__, info)
467
468 @property
469 def human_id(self):
470 """Human-readable ID which can be used for bash completion."""
471 if self.HUMAN_ID:
472 name = getattr(self, self.NAME_ATTR, None)
473 if name is not None:
474 return strutils.to_slug(name)
475 return None
476
477 def _add_details(self, info):
478 for (k, v) in info.items():
479 try:
480 setattr(self, k, v)
481 self._info[k] = v
482 except AttributeError:
483 # In this case we already defined the attribute on the class
484 pass
485
486 def __getattr__(self, k):
487 if k not in self.__dict__:
488 # NOTE(bcwaldon): disallow lazy-loading if already loaded once
489 if not self.is_loaded():
490 self.get()
491 return self.__getattr__(k)
492
493 raise AttributeError(k)
494 else:
495 return self.__dict__[k]
496
497 def get(self):
498 """Support for lazy loading details.
499
500 Some clients, such as novaclient have the option to lazy load the
501 details, details which can be loaded with this function.
502 """
503 # set_loaded() first ... so if we have to bail, we know we tried.
504 self.set_loaded(True)
505 if not hasattr(self.manager, 'get'):
506 return
507
508 new = self.manager.get(self.id)
509 if new:
510 self._add_details(new._info)
511 self._add_details(
512 {'x_request_id': self.manager.client.last_request_id})
513
514 def __eq__(self, other):
515 if not isinstance(other, Resource):
516 return NotImplemented
517 # two resources of different types are not equal
518 if not isinstance(other, self.__class__):
519 return False
520 return self._info == other._info
521
522 def is_loaded(self):
523 return self._loaded
524
525 def set_loaded(self, val):
526 self._loaded = val
527
528 def to_dict(self):
529 return copy.deepcopy(self._info)