Debian Codegraph @

heatclient/common/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 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 heatclient._i18n import _
30 from heatclient 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:
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().__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):
202 """Delete an object.
203
204 :param url: a partial URL, e.g., '/servers/my-server'
205 """
206 return self.client.delete(url)
207
208
209 class ManagerWithFind(BaseManager, metaclass=abc.ABCMeta):
210 """Manager with additional `find()`/`findall()` methods."""
211
212 @abc.abstractmethod
213 def list(self):
214 pass
215
216 def find(self, **kwargs):
217 """Find a single item with attributes matching ``**kwargs``.
218
219 This isn't very efficient: it loads the entire list then filters on
220 the Python side.
221 """
222 matches = self.findall(**kwargs)
223 num_matches = len(matches)
224 if num_matches == 0:
225 msg = _("No %(name)s matching %(args)s.") % {
226 'name': self.resource_class.__name__,
227 'args': kwargs
228 }
229 raise exceptions.NotFound(msg)
230 elif num_matches > 1:
231 raise exceptions.NoUniqueMatch()
232 else:
233 return matches[0]
234
235 def findall(self, **kwargs):
236 """Find all items with attributes matching ``**kwargs``.
237
238 This isn't very efficient: it loads the entire list then filters on
239 the Python side.
240 """
241 found = []
242 searches = kwargs.items()
243
244 for obj in self.list():
245 try:
246 if all(getattr(obj, attr) == value
247 for (attr, value) in searches):
248 found.append(obj)
249 except AttributeError:
250 continue
251
252 return found
253
254
255 class CrudManager(BaseManager):
256 """Base manager class for manipulating entities.
257
258 Children of this class are expected to define a `collection_key` and `key`.
259 - `collection_key`: Usually a plural noun by convention (e.g. `entities`);
260 used to refer collections in both URL's (e.g. `/v3/entities`) and JSON
261 objects containing a list of member resources (e.g. `{'entities': [{},
262 {}, {}]}`).
263 - `key`: Usually a singular noun by convention (e.g. `entity`); used to
264 refer to an individual member of the collection.
265 """
266 collection_key = None
267 key = None
268
269 def build_url(self, base_url=None, **kwargs):
270 """Builds a resource URL for the given kwargs.
271
272 Given an example collection where `collection_key = 'entities'` and
273 `key = 'entity'`, the following URL's could be generated.
274 By default, the URL will represent a collection of entities, e.g.::
275 /entities
276 If kwargs contains an `entity_id`, then the URL will represent a
277 specific member, e.g.::
278 /entities/{entity_id}
279 :param base_url: if provided, the generated URL will be appended to it
280 """
281 url = base_url if base_url is not None else ''
282 url = '/'.join([url, self.collection_key])
283
284 # do we have a specific entity?
285 entity_id = kwargs.get(f'{self.key}_id')
286 if entity_id is not None:
287 url = '/'.join([url, entity_id])
288
289 return url
290
291 def _filter_kwargs(self, kwargs):
292 """Drop null values and handle ids."""
293 for key, ref in kwargs.copy().items():
294 if ref is None:
295 kwargs.pop(key)
296 else:
297 if isinstance(ref, Resource):
298 kwargs.pop(key)
299 kwargs['{}_id'.firmat(key)] = getid(ref)
300 return kwargs
301
302 def create(self, **kwargs):
303 kwargs = self._filter_kwargs(kwargs)
304 return self._post(
305 self.build_url(**kwargs),
306 {self.key: kwargs},
307 self.key)
308
309 def get(self, **kwargs):
310 kwargs = self._filter_kwargs(kwargs)
311 return self._get(
312 self.build_url(**kwargs),
313 self.key)
314
315 def head(self, **kwargs):
316 kwargs = self._filter_kwargs(kwargs)
317 return self._head(self.build_url(**kwargs))
318
319 def list(self, base_url=None, **kwargs):
320 """List the collection.
321
322 :param base_url: if provided, the generated URL will be appended to it
323 """
324 kwargs = self._filter_kwargs(kwargs)
325 query = f'?{parse.urlencode(kwargs)}' if kwargs else ''
326
327 return self._list(
328 '{base_url}{query}'.format(
329 base_url=self.build_url(base_url=base_url, **kwargs),
330 query=query,
331 ),
332 self.collection_key)
333
334 def put(self, base_url=None, **kwargs):
335 """Update an element.
336
337 :param base_url: if provided, the generated URL will be appended to it
338 """
339 kwargs = self._filter_kwargs(kwargs)
340
341 return self._put(self.build_url(base_url=base_url, **kwargs))
342
343 def update(self, **kwargs):
344 kwargs = self._filter_kwargs(kwargs)
345 params = kwargs.copy()
346 params.pop(f'{self.key}_id')
347
348 return self._patch(
349 self.build_url(**kwargs),
350 {self.key: params},
351 self.key)
352
353 def delete(self, **kwargs):
354 kwargs = self._filter_kwargs(kwargs)
355
356 return self._delete(
357 self.build_url(**kwargs))
358
359 def find(self, base_url=None, **kwargs):
360 """Find a single item with attributes matching ``**kwargs``.
361
362 :param base_url: if provided, the generated URL will be appended to it
363 """
364 kwargs = self._filter_kwargs(kwargs)
365 query = f'?{parse.urlencode(kwargs)}' if kwargs else ''
366
367 rl = self._list(
368 '{base_url}{query}'.format(
369 base_url=self.build_url(base_url=base_url, **kwargs),
370 query=query,
371 ),
372 self.collection_key)
373 num = len(rl)
374
375 if num == 0:
376 msg = _("No %(name)s matching %(args)s.") % {
377 'name': self.resource_class.__name__,
378 'args': kwargs
379 }
380 raise exceptions.NotFound(msg)
381 elif num > 1:
382 raise exceptions.NoUniqueMatch
383 else:
384 return rl[0]
385
386
387 class Extension(HookableMixin):
388 """Extension descriptor."""
389
390 SUPPORTED_HOOKS = ('__pre_parse_args__', '__post_parse_args__')
391 manager_class = None
392
393 def __init__(self, name, module):
394 super().__init__()
395 self.name = name
396 self.module = module
397 self._parse_extension_module()
398
399 def _parse_extension_module(self):
400 self.manager_class = None
401 for attr_name, attr_value in self.module.__dict__.items():
402 if attr_name in self.SUPPORTED_HOOKS:
403 self.add_hook(attr_name, attr_value)
404 else:
405 try:
406 if issubclass(attr_value, BaseManager):
407 self.manager_class = attr_value
408 except TypeError:
409 pass
410
411 def __repr__(self):
412 return f"<Extension '{self.name}'>"
413
414
415 class Resource:
416 """Base class for OpenStack resources (tenant, user, etc.).
417
418 This is pretty much just a bag for attributes.
419 """
420 HUMAN_ID = False
421 NAME_ATTR = 'name'
422
423 def __init__(self, manager, info, loaded=False):
424 """Populate and bind to a manager.
425
426 :param manager: BaseManager object
427 :param info: dictionary representing resource attributes
428 :param loaded: prevent lazy-loading if set to True
429 """
430 self.manager = manager
431 self._info = info
432 self._add_details(info)
433 self._loaded = loaded
434
435 def __repr__(self):
436 reprkeys = sorted(k
437 for k in self.__dict__
438 if k[0] != '_' and k != 'manager')
439 info = ", ".join(f"{k}={getattr(self, k)}" for k in reprkeys)
440 class_name = reflection.get_class_name(self, fully_qualified=False)
441 return f"<{class_name} {info}>"
442
443 @property
444 def human_id(self):
445 """Human-readable ID which can be used for bash completion. """
446 if self.HUMAN_ID:
447 name = getattr(self, self.NAME_ATTR, None)
448 if name is not None:
449 return strutils.to_slug(name)
450 return None
451
452 def _add_details(self, info):
453 for (k, v) in info.items():
454 try:
455 setattr(self, k, v)
456 self._info[k] = v
457 except AttributeError:
458 # In this case we already defined the attribute on the class
459 pass
460
461 def __getattr__(self, k):
462 if k not in self.__dict__:
463 # NOTE(bcwaldon): disallow lazy-loading if already loaded once
464 if not self.is_loaded():
465 self.get()
466 return self.__getattr__(k)
467
468 raise AttributeError(k)
469 else:
470 return self.__dict__[k]
471
472 def get(self):
473 """Support for lazy loading details.
474
475 Some clients, such as novaclient have the option to lazy load the
476 details, details which can be loaded with this function.
477 """
478 # set_loaded() first ... so if we have to bail, we know we tried.
479 self.set_loaded(True)
480 if not hasattr(self.manager, 'get'):
481 return
482
483 new = self.manager.get(self.id)
484 if new:
485 self._add_details(new._info)
486 self._add_details(
487 {'x_request_id': self.manager.client.last_request_id})
488
489 def __eq__(self, other):
490 if not isinstance(other, Resource):
491 return NotImplemented
492 # two resources of different types are not equal
493 if not isinstance(other, self.__class__):
494 return False
495 return self._info == other._info
496
497 def __ne__(self, other):
498 return not self.__eq__(other)
499
500 def is_same_obj(self, other):
501 """Identify the two objects are same one with same id."""
502 if isinstance(other, self.__class__):
503 if hasattr(self, 'id') and hasattr(other, 'id'):
504 return self.id == other.id
505 return False
506
507 def is_loaded(self):
508 return self._loaded
509
510 def set_loaded(self, val):
511 self._loaded = val
512
513 def to_dict(self):
514 return copy.deepcopy(self._info)