Debian Codegraph @

adjutantclient/common/base.py

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