Debian Codegraph @

neutron_lib/db/resource_extend.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 """
14 NOTE: This module shall not be used by external projects. It will be moved
15 to neutron-lib in due course, and then it can be used from there.
16 """
17
18 import collections
19 import inspect
20
21 from oslo_log import log as logging
22 from oslo_utils import timeutils
23
24 from neutron_lib.utils import helpers
25
26
27 LOG = logging.getLogger(__name__)
28
29
30 # This dictionary will store methods for extending API resources.
31 # Extensions can add their own methods by invoking register_funcs().
32 _resource_extend_functions = {
33 # <resource1> : [<func1>, <func2>, ...],
34 # <resource2> : [<func1>, <func2>, ...],
35 # ...
36 }
37
38 # This dictionary will store @extends decorated methods with a list of
39 # resources that each method will extend on class initialization.
40 _DECORATED_EXTEND_METHODS = collections.defaultdict(list)
41 _DECORATED_METHODS_REGISTERED = '_DECORATED_METHODS_REGISTERED'
42
43
44 def register_funcs(resource, funcs):
45 """Add functions to extend a resource.
46
47 :param resource: A resource collection name.
48 :type resource: str
49
50 :param funcs: A list of functions.
51 :type funcs: list of callable
52
53 These functions take a resource dict and a resource object and
54 update the resource dict with extension data (possibly retrieved
55 from the resource db object).
56 def _extend_foo_with_bar(foo_res, foo_db):
57 foo_res['bar'] = foo_db.bar_info # example
58 return foo_res
59
60 """
61 funcs = [helpers.make_weak_ref(f) if callable(f) else f for f in funcs]
62 existing_funcs = _resource_extend_functions.setdefault(resource, [])
63
64 for func in funcs:
65 if func not in existing_funcs:
66 existing_funcs.append(func)
67
68
69 def get_funcs(resource):
70 """Retrieve a list of functions extending a resource.
71
72 :param resource: A resource collection name.
73 :type resource: str
74
75 :return: A list (possibly empty) of functions extending resource.
76 :rtype: list of callable
77
78 """
79 return _resource_extend_functions.get(resource, [])
80
81
82 @timeutils.time_it(LOG, min_duration=0.1)
83 def apply_funcs(resource_type, response, db_object):
84 """Appy registered functions for the said resource type.
85
86 :param resource_type: The resource type to apply funcs for.
87 :param response: The response object.
88 :param db_object: The Database object.
89 :returns: None
90 """
91 for func in get_funcs(resource_type):
92 resolved_func = helpers.resolve_ref(func)
93 if resolved_func:
94 resolved_func(response, db_object)
95
96
97 def extends(resources):
98 """Use to decorate methods on classes before initialization.
99
100 Any classes that use this must themselves be decorated with the
101 @has_resource_extenders decorator to setup the __new__ method to
102 actually register the instance methods after initialization.
103
104 :param resources: Resource collection names. The decorated method will
105 be registered with each resource as an extend function.
106 :type resources: list of str
107
108 """
109 def decorator(method):
110 _DECORATED_EXTEND_METHODS[method].extend(resources)
111 return method
112 return decorator
113
114
115 def has_resource_extenders(klass):
116 """Decorator to setup __new__ method in classes to extend resources.
117
118 Any method decorated with @extends above is an unbound method on a class.
119 This decorator sets up the class __new__ method to add the bound
120 method to _resource_extend_functions after object instantiation.
121 """
122 orig_new = klass.__new__
123 new_inherited = '__new__' not in klass.__dict__
124
125 @staticmethod
126 def replacement_new(cls, *args, **kwargs):
127 if new_inherited:
128 # class didn't define __new__ so we need to call inherited __new__
129 super_new = super(klass, cls).__new__
130 if super_new is object.__new__:
131 # object.__new__ doesn't accept args nor kwargs
132 # pylint: disable=no-value-for-parameter
133 instance = super_new(cls)
134 else:
135 instance = super_new(cls, *args, **kwargs)
136 else:
137 instance = orig_new(cls, *args, **kwargs)
138 if getattr(instance, _DECORATED_METHODS_REGISTERED, False):
139 # Avoid running this logic twice for classes inheriting other
140 # classes with this same decorator. Only one needs to execute
141 # to subscribe all decorated methods.
142 return instance
143 for name, unbound_method in inspect.getmembers(cls):
144 if (not inspect.ismethod(unbound_method) and
145 not inspect.isfunction(unbound_method)):
146 continue
147 # Handle py27/py34 difference
148 method = getattr(unbound_method, 'im_func', unbound_method)
149 if method not in _DECORATED_EXTEND_METHODS:
150 continue
151 for resource in _DECORATED_EXTEND_METHODS[method]:
152 # Register the bound method for the resourse
153 register_funcs(resource, [method])
154 setattr(instance, _DECORATED_METHODS_REGISTERED, True)
155 return instance
156 klass.__new__ = replacement_new
157 return klass