Threading pt 2 (of 3, likely)
[ric-plt/a1.git] / a1 / data.py
1 # ==================================================================================
2 #       Copyright (c) 2019 Nokia
3 #       Copyright (c) 2018-2019 AT&T Intellectual Property.
4 #
5 #   Licensed under the Apache License, Version 2.0 (the "License");
6 #   you may not use this file except in compliance with the License.
7 #   You may obtain a copy of the License at
8 #
9 #          http://www.apache.org/licenses/LICENSE-2.0
10 #
11 #   Unless required by applicable law or agreed to in writing, software
12 #   distributed under the License is distributed on an "AS IS" BASIS,
13 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 #   See the License for the specific language governing permissions and
15 #   limitations under the License.
16 # ==================================================================================
17
18 """
19 Represents A1s database and database access functions.
20 In the future, this may change to use a different backend, possibly dramatically.
21 Hopefully, the access functions are a good api so nothing else has to change when this happens
22
23 For now, the database is in memory.
24 We use dict data structures (KV) with the expectation of having to move this into Redis
25 """
26 import msgpack
27 from a1.exceptions import PolicyTypeNotFound, PolicyInstanceNotFound, PolicyTypeAlreadyExists, CantDeleteNonEmptyType
28 from a1 import get_module_logger
29
30 logger = get_module_logger(__name__)
31
32
33 class SDLWrapper:
34     """
35     This is a wrapper around the expected SDL Python interface.
36     The usage of POLICY_DATA will be replaced with  SDL when SDL for python is available.
37     The eventual SDL API is expected to be very close to what is here.
38
39     We use msgpack for binary (de)serialization: https://msgpack.org/index.html
40     """
41
42     def __init__(self):
43         self.POLICY_DATA = {}
44
45     def set(self, key, value):
46         """set a key"""
47         self.POLICY_DATA[key] = msgpack.packb(value, use_bin_type=True)
48
49     def get(self, key):
50         """get a key"""
51         if key in self.POLICY_DATA:
52             return msgpack.unpackb(self.POLICY_DATA[key], raw=False)
53         return None
54
55     def find_and_get(self, prefix):
56         """get all k v pairs that start with prefix"""
57         return {k: msgpack.unpackb(v, raw=False) for k, v in self.POLICY_DATA.items() if k.startswith(prefix)}
58
59     def delete(self, key):
60         """ delete a key"""
61         del self.POLICY_DATA[key]
62
63
64 SDL = SDLWrapper()
65
66 TYPE_PREFIX = "a1.policy_type."
67 INSTANCE_PREFIX = "a1.policy_instance."
68 HANDLER_PREFIX = "a1.policy_handler."
69
70
71 # Internal helpers
72
73
74 def _generate_type_key(policy_type_id):
75     """
76     generate a key for a policy type
77     """
78     return "{0}{1}".format(TYPE_PREFIX, policy_type_id)
79
80
81 def _generate_instance_key(policy_type_id, policy_instance_id):
82     """
83     generate a key for a policy instance
84     """
85     return "{0}{1}.{2}".format(INSTANCE_PREFIX, policy_type_id, policy_instance_id)
86
87
88 def _generate_handler_prefix(policy_type_id, policy_instance_id):
89     """
90     generate the prefix to a handler key
91     """
92     return "{0}{1}.{2}.".format(HANDLER_PREFIX, policy_type_id, policy_instance_id)
93
94
95 def _generate_handler_key(policy_type_id, policy_instance_id, handler_id):
96     """
97     generate a key for a policy handler
98     """
99     return "{0}{1}".format(_generate_handler_prefix(policy_type_id, policy_instance_id), handler_id)
100
101
102 def _get_statuses(policy_type_id, policy_instance_id):
103     """
104     shared helper to get statuses for an instance
105     """
106     instance_is_valid(policy_type_id, policy_instance_id)
107     prefixes_for_handler = "{0}{1}.{2}.".format(HANDLER_PREFIX, policy_type_id, policy_instance_id)
108     return list(SDL.find_and_get(prefixes_for_handler).values())
109
110
111 def _get_instance_list(policy_type_id):
112     """
113     shared helper to get instance list for a type
114     """
115     type_is_valid(policy_type_id)
116     prefixes_for_type = "{0}{1}.".format(INSTANCE_PREFIX, policy_type_id)
117     instancekeys = SDL.find_and_get(prefixes_for_type).keys()
118     return [k.split(prefixes_for_type)[1] for k in instancekeys]
119
120
121 def _clear_handlers(policy_type_id, policy_instance_id):
122     """
123     delete all the handlers for a policy instance
124     """
125     all_handlers_pref = _generate_handler_prefix(policy_type_id, policy_instance_id)
126     keys = SDL.find_and_get(all_handlers_pref)
127     for k in keys:
128         SDL.delete(k)
129
130
131 # Types
132
133
134 def get_type_list():
135     """
136     retrieve all type ids
137     """
138     typekeys = SDL.find_and_get(TYPE_PREFIX).keys()
139     # policy types are ints but they get butchered to strings in the KV
140     return [int(k.split(TYPE_PREFIX)[1]) for k in typekeys]
141
142
143 def type_is_valid(policy_type_id):
144     """
145     check that a type is valid
146     """
147     if SDL.get(_generate_type_key(policy_type_id)) is None:
148         raise PolicyTypeNotFound()
149
150
151 def store_policy_type(policy_type_id, body):
152     """
153     store a policy type if it doesn't already exist
154     """
155     key = _generate_type_key(policy_type_id)
156     if SDL.get(key) is not None:
157         raise PolicyTypeAlreadyExists()
158     SDL.set(key, body)
159
160
161 def delete_policy_type(policy_type_id):
162     """
163     delete a policy type; can only be done if there are no instances (business logic)
164     """
165     pil = get_instance_list(policy_type_id)
166     if pil == []:  # empty, can delete
167         SDL.delete(_generate_type_key(policy_type_id))
168     else:
169         raise CantDeleteNonEmptyType()
170
171
172 def get_policy_type(policy_type_id):
173     """
174     retrieve a type
175     """
176     type_is_valid(policy_type_id)
177     return SDL.get(_generate_type_key(policy_type_id))
178
179
180 # Instances
181
182
183 def instance_is_valid(policy_type_id, policy_instance_id):
184     """
185     check that an instance is valid
186     """
187     type_is_valid(policy_type_id)
188     if SDL.get(_generate_instance_key(policy_type_id, policy_instance_id)) is None:
189         raise PolicyInstanceNotFound
190
191
192 def store_policy_instance(policy_type_id, policy_instance_id, instance):
193     """
194     Store a policy instance
195     """
196     type_is_valid(policy_type_id)
197     key = _generate_instance_key(policy_type_id, policy_instance_id)
198     if SDL.get(key) is not None:
199         # Reset the statuses because this is a new policy instance, even if it was overwritten
200         _clear_handlers(policy_type_id, policy_instance_id)  # delete all the handlers
201     SDL.set(key, instance)
202
203
204 def get_policy_instance(policy_type_id, policy_instance_id):
205     """
206     Retrieve a policy instance
207     """
208     instance_is_valid(policy_type_id, policy_instance_id)
209     return SDL.get(_generate_instance_key(policy_type_id, policy_instance_id))
210
211
212 def get_policy_instance_statuses(policy_type_id, policy_instance_id):
213     """
214     Retrieve the status vector for a policy instance
215     """
216     return _get_statuses(policy_type_id, policy_instance_id)
217
218
219 def get_instance_list(policy_type_id):
220     """
221     retrieve all instance ids for a type
222     """
223     return _get_instance_list(policy_type_id)
224
225
226 # Statuses
227
228
229 def set_status(policy_type_id, policy_instance_id, handler_id, status):
230     """
231     update the database status for a handler
232     called from a1's rmr thread
233     """
234     type_is_valid(policy_type_id)
235     instance_is_valid(policy_type_id, policy_instance_id)
236     SDL.set(_generate_handler_key(policy_type_id, policy_instance_id, handler_id), status)
237
238
239 def clean_up_instance(policy_type_id, policy_instance_id):
240     """
241     see if we can delete an instance based on it's status
242     """
243     type_is_valid(policy_type_id)
244     instance_is_valid(policy_type_id, policy_instance_id)
245
246     """
247     TODO: not being able to delete if the list is [] is prolematic.
248     There are cases, such as a bad routing file, where this type will never be able to be deleted because it never went to any xapps
249     However, A1 cannot distinguish between the case where [] was never going to work, and the case where it hasn't worked *yet*
250
251     However, removing this constraint also leads to problems.
252     Deleting the instance when the vector is empty, for example doing so “shortly after” the PUT, can lead to a worse race condition where the xapps get the policy after that, implement it, but because the DELETE triggered “too soon”, you can never get the status or do the delete on it again, so the xapps are all implementing the instance roguely.
253
254     This requires some thought to address.
255     For now we stick with the "less bad problem".
256     """
257
258     vector = _get_statuses(policy_type_id, policy_instance_id)
259     if vector != []:
260         all_deleted = True
261         for i in vector:
262             if i != "DELETED":
263                 all_deleted = False
264                 break  # have at least one not DELETED, do nothing
265
266         # blow away from a1 db
267         if all_deleted:
268             _clear_handlers(policy_type_id, policy_instance_id)  # delete all the handlers
269             SDL.delete(_generate_instance_key(policy_type_id, policy_instance_id))  # delete instance
270             logger.debug("type %s instance %s deleted", policy_type_id, policy_instance_id)