20d54bbb138eebdf62b344c7bec3cc4cf046c5aa
[osm/NBI.git] / osm_nbi / base_topic.py
1 # -*- coding: utf-8 -*-
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import logging
17 from uuid import uuid4
18 from http import HTTPStatus
19 from time import time
20 from osm_common.dbbase import deep_update_rfc7396
21 from validation import validate_input, ValidationError, is_valid_uuid
22
23 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
24
25
26 class EngineException(Exception):
27
28 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
29 self.http_code = http_code
30 Exception.__init__(self, message)
31
32
33 def get_iterable(input_var):
34 """
35 Returns an iterable, in case input_var is None it just returns an empty tuple
36 :param input_var: can be a list, tuple or None
37 :return: input_var or () if it is None
38 """
39 if input_var is None:
40 return ()
41 return input_var
42
43
44 def versiontuple(v):
45 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
46 filled = []
47 for point in v.split("."):
48 filled.append(point.zfill(8))
49 return tuple(filled)
50
51
52 class BaseTopic:
53 # static variables for all instance classes
54 topic = None # to_override
55 topic_msg = None # to_override
56 schema_new = None # to_override
57 schema_edit = None # to_override
58 multiproject = True # True if this Topic can be shared by several projects. Then it contains _admin.projects_read
59
60 # Alternative ID Fields for some Topics
61 alt_id_field = {
62 "projects": "name",
63 "users": "username",
64 "roles": "name",
65 "roles_operations": "name"
66 }
67
68 def __init__(self, db, fs, msg):
69 self.db = db
70 self.fs = fs
71 self.msg = msg
72 self.logger = logging.getLogger("nbi.engine")
73
74 @staticmethod
75 def id_field(topic, value):
76 """Returns ID Field for given topic and field value"""
77 if topic in BaseTopic.alt_id_field.keys() and not is_valid_uuid(value):
78 return BaseTopic.alt_id_field[topic]
79 else:
80 return "_id"
81
82 @staticmethod
83 def _remove_envelop(indata=None):
84 if not indata:
85 return {}
86 return indata
87
88 def _validate_input_new(self, input, force=False):
89 """
90 Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind
91 :param input: user input content for the new topic
92 :param force: may be used for being more tolerant
93 :return: The same input content, or a changed version of it.
94 """
95 if self.schema_new:
96 validate_input(input, self.schema_new)
97 return input
98
99 def _validate_input_edit(self, input, force=False):
100 """
101 Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
102 :param input: user input content for the new topic
103 :param force: may be used for being more tolerant
104 :return: The same input content, or a changed version of it.
105 """
106 if self.schema_edit:
107 validate_input(input, self.schema_edit)
108 return input
109
110 @staticmethod
111 def _get_project_filter(session):
112 """
113 Generates a filter dictionary for querying database, so that only allowed items for this project can be
114 addressed. Only propietary or public can be used. Allowed projects are at _admin.project_read/write. If it is
115 not present or contains ANY mean public.
116 :param session: contains:
117 project_id: project list this session has rights to access. Can be empty, one or several
118 set_project: items created will contain this project list
119 force: True or False
120 public: True, False or None
121 method: "list", "show", "write", "delete"
122 admin: True or False
123 :return: dictionary with project filter
124 """
125 p_filter = {}
126 project_filter_n = []
127 project_filter = list(session["project_id"])
128
129 if session["method"] not in ("list", "delete"):
130 if project_filter:
131 project_filter.append("ANY")
132 elif session["public"] is not None:
133 if session["public"]:
134 project_filter.append("ANY")
135 else:
136 project_filter_n.append("ANY")
137
138 if session.get("PROJECT.ne"):
139 project_filter_n.append(session["PROJECT.ne"])
140
141 if project_filter:
142 if session["method"] in ("list", "show", "delete") or session.get("set_project"):
143 p_filter["_admin.projects_read.cont"] = project_filter
144 else:
145 p_filter["_admin.projects_write.cont"] = project_filter
146 if project_filter_n:
147 if session["method"] in ("list", "show", "delete") or session.get("set_project"):
148 p_filter["_admin.projects_read.ncont"] = project_filter_n
149 else:
150 p_filter["_admin.projects_write.ncont"] = project_filter_n
151
152 return p_filter
153
154 def check_conflict_on_new(self, session, indata):
155 """
156 Check that the data to be inserted is valid
157 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
158 :param indata: data to be inserted
159 :return: None or raises EngineException
160 """
161 pass
162
163 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
164 """
165 Check that the data to be edited/uploaded is valid
166 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
167 :param final_content: data once modified. This method may change it.
168 :param edit_content: incremental data that contains the modifications to apply
169 :param _id: internal _id
170 :return: None or raises EngineException
171 """
172 if not self.multiproject:
173 return
174 # Change public status
175 if session["public"] is not None:
176 if session["public"] and "ANY" not in final_content["_admin"]["projects_read"]:
177 final_content["_admin"]["projects_read"].append("ANY")
178 final_content["_admin"]["projects_write"].clear()
179 if not session["public"] and "ANY" in final_content["_admin"]["projects_read"]:
180 final_content["_admin"]["projects_read"].remove("ANY")
181
182 # Change project status
183 if session.get("set_project"):
184 for p in session["set_project"]:
185 if p not in final_content["_admin"]["projects_read"]:
186 final_content["_admin"]["projects_read"].append(p)
187
188 def check_unique_name(self, session, name, _id=None):
189 """
190 Check that the name is unique for this project
191 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
192 :param name: name to be checked
193 :param _id: If not None, ignore this entry that are going to change
194 :return: None or raises EngineException
195 """
196 if not self.multiproject:
197 _filter = {}
198 else:
199 _filter = self._get_project_filter(session)
200 _filter["name"] = name
201 if _id:
202 _filter["_id.neq"] = _id
203 if self.db.get_one(self.topic, _filter, fail_on_empty=False, fail_on_more=False):
204 raise EngineException("name '{}' already exists for {}".format(name, self.topic), HTTPStatus.CONFLICT)
205
206 @staticmethod
207 def format_on_new(content, project_id=None, make_public=False):
208 """
209 Modifies content descriptor to include _admin
210 :param content: descriptor to be modified
211 :param project_id: if included, it add project read/write permissions. Can be None or a list
212 :param make_public: if included it is generated as public for reading.
213 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
214 """
215 now = time()
216 if "_admin" not in content:
217 content["_admin"] = {}
218 if not content["_admin"].get("created"):
219 content["_admin"]["created"] = now
220 content["_admin"]["modified"] = now
221 if not content.get("_id"):
222 content["_id"] = str(uuid4())
223 if project_id is not None:
224 if not content["_admin"].get("projects_read"):
225 content["_admin"]["projects_read"] = list(project_id)
226 if make_public:
227 content["_admin"]["projects_read"].append("ANY")
228 if not content["_admin"].get("projects_write"):
229 content["_admin"]["projects_write"] = list(project_id)
230 return None
231
232 @staticmethod
233 def format_on_edit(final_content, edit_content):
234 """
235 Modifies final_content to admin information upon edition
236 :param final_content: final content to be stored at database
237 :param edit_content: user requested update content
238 :return: operation id, if this edit implies an asynchronous operation; None otherwise
239 """
240 if final_content.get("_admin"):
241 now = time()
242 final_content["_admin"]["modified"] = now
243 return None
244
245 def _send_msg(self, action, content):
246 if self.topic_msg:
247 content.pop("_admin", None)
248 self.msg.write(self.topic_msg, action, content)
249
250 def check_conflict_on_del(self, session, _id, db_content):
251 """
252 Check if deletion can be done because of dependencies if it is not force. To override
253 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
254 :param _id: internal _id
255 :param db_content: The database content of this item _id
256 :return: None if ok or raises EngineException with the conflict
257 """
258 pass
259
260 @staticmethod
261 def _update_input_with_kwargs(desc, kwargs):
262 """
263 Update descriptor with the kwargs. It contains dot separated keys
264 :param desc: dictionary to be updated
265 :param kwargs: plain dictionary to be used for updating.
266 :return: None, 'desc' is modified. It raises EngineException.
267 """
268 if not kwargs:
269 return
270 try:
271 for k, v in kwargs.items():
272 update_content = desc
273 kitem_old = None
274 klist = k.split(".")
275 for kitem in klist:
276 if kitem_old is not None:
277 update_content = update_content[kitem_old]
278 if isinstance(update_content, dict):
279 kitem_old = kitem
280 elif isinstance(update_content, list):
281 kitem_old = int(kitem)
282 else:
283 raise EngineException(
284 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
285 update_content[kitem_old] = v
286 except KeyError:
287 raise EngineException(
288 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
289 except ValueError:
290 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
291 k, kitem))
292 except IndexError:
293 raise EngineException(
294 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
295
296 def show(self, session, _id):
297 """
298 Get complete information on an topic
299 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
300 :param _id: server internal id
301 :return: dictionary, raise exception if not found.
302 """
303 if not self.multiproject:
304 filter_db = {}
305 else:
306 filter_db = self._get_project_filter(session)
307 # To allow project&user addressing by name AS WELL AS _id
308 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
309 return self.db.get_one(self.topic, filter_db)
310 # TODO transform data for SOL005 URL requests
311 # TODO remove _admin if not admin
312
313 def get_file(self, session, _id, path=None, accept_header=None):
314 """
315 Only implemented for descriptor topics. Return the file content of a descriptor
316 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
317 :param _id: Identity of the item to get content
318 :param path: artifact path or "$DESCRIPTOR" or None
319 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
320 :return: opened file or raises an exception
321 """
322 raise EngineException("Method get_file not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
323
324 def list(self, session, filter_q=None):
325 """
326 Get a list of the topic that matches a filter
327 :param session: contains the used login username and working project
328 :param filter_q: filter of data to be applied
329 :return: The list, it can be empty if no one match the filter.
330 """
331 if not filter_q:
332 filter_q = {}
333 if self.multiproject:
334 filter_q.update(self._get_project_filter(session))
335
336 # TODO transform data for SOL005 URL requests. Transform filtering
337 # TODO implement "field-type" query string SOL005
338 return self.db.get_list(self.topic, filter_q)
339
340 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
341 """
342 Creates a new entry into database.
343 :param rollback: list to append created items at database in case a rollback may to be done
344 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
345 :param indata: data to be inserted
346 :param kwargs: used to override the indata descriptor
347 :param headers: http request headers
348 :return: _id, op_id:
349 _id: identity of the inserted data.
350 op_id: operation id if this is asynchronous, None otherwise
351 """
352 try:
353 content = self._remove_envelop(indata)
354
355 # Override descriptor with query string kwargs
356 self._update_input_with_kwargs(content, kwargs)
357 content = self._validate_input_new(content, force=session["force"])
358 self.check_conflict_on_new(session, content)
359 op_id = self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
360 _id = self.db.create(self.topic, content)
361 rollback.append({"topic": self.topic, "_id": _id})
362 if op_id:
363 content["op_id"] = op_id
364 self._send_msg("create", content)
365 return _id, op_id
366 except ValidationError as e:
367 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
368
369 def upload_content(self, session, _id, indata, kwargs, headers):
370 """
371 Only implemented for descriptor topics. Used for receiving content by chunks (with a transaction_id header
372 and/or gzip file. It will store and extract)
373 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
374 :param _id : the database id of entry to be updated
375 :param indata: http body request
376 :param kwargs: user query string to override parameters. NOT USED
377 :param headers: http request headers
378 :return: True package has is completely uploaded or False if partial content has been uplodaed.
379 Raise exception on error
380 """
381 raise EngineException("Method upload_content not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
382
383 def delete_list(self, session, filter_q=None):
384 """
385 Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API
386 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
387 :param filter_q: filter of data to be applied
388 :return: The deleted list, it can be empty if no one match the filter.
389 """
390 # TODO add admin to filter, validate rights
391 if not filter_q:
392 filter_q = {}
393 if self.multiproject:
394 filter_q.update(self._get_project_filter(session))
395 return self.db.del_list(self.topic, filter_q)
396
397 def delete_extra(self, session, _id, db_content):
398 """
399 Delete other things apart from database entry of a item _id.
400 e.g.: other associated elements at database and other file system storage
401 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
402 :param _id: server internal id
403 :param db_content: The database content of the _id. It is already deleted when reached this method, but the
404 content is needed in same cases
405 :return: None if ok or raises EngineException with the problem
406 """
407 pass
408
409 def delete(self, session, _id, dry_run=False):
410 """
411 Delete item by its internal _id
412 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
413 :param _id: server internal id
414 :param dry_run: make checking but do not delete
415 :return: operation id (None if there is not operation), raise exception if error or not found, conflict, ...
416 """
417
418 # To allow addressing projects and users by name AS WELL AS by _id
419 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
420 item_content = self.db.get_one(self.topic, filter_q)
421
422 # TODO add admin to filter, validate rights
423 # data = self.get_item(topic, _id)
424 self.check_conflict_on_del(session, _id, item_content)
425 if dry_run:
426 return None
427
428 if self.multiproject:
429 filter_q.update(self._get_project_filter(session))
430 if self.multiproject and session["project_id"]:
431 # remove reference from project_read. If not last delete
432 # if this topic is not part of session["project_id"] no midification at database is done and an exception
433 # is raised
434 self.db.set_one(self.topic, filter_q, update_dict=None,
435 pull={"_admin.projects_read": {"$in": session["project_id"]}})
436 # try to delete if there is not any more reference from projects. Ignore if it is not deleted
437 filter_q = {'_id': _id, '_admin.projects_read': [[], ["ANY"]]}
438 v = self.db.del_one(self.topic, filter_q, fail_on_empty=False)
439 if not v or not v["deleted"]:
440 return None
441 else:
442 self.db.del_one(self.topic, filter_q)
443 self.delete_extra(session, _id, item_content)
444 self._send_msg("deleted", {"_id": _id})
445 return None
446
447 def edit(self, session, _id, indata=None, kwargs=None, content=None):
448 """
449 Change the content of an item
450 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
451 :param _id: server internal id
452 :param indata: contains the changes to apply
453 :param kwargs: modifies indata
454 :param content: original content of the item
455 :return: op_id: operation id if this is processed asynchronously, None otherwise
456 """
457 indata = self._remove_envelop(indata)
458
459 # Override descriptor with query string kwargs
460 if kwargs:
461 self._update_input_with_kwargs(indata, kwargs)
462 try:
463 if indata and session.get("set_project"):
464 raise EngineException("Cannot edit content and set to project (query string SET_PROJECT) at same time",
465 HTTPStatus.UNPROCESSABLE_ENTITY)
466 indata = self._validate_input_edit(indata, force=session["force"])
467
468 # TODO self._check_edition(session, indata, _id, force)
469 if not content:
470 content = self.show(session, _id)
471 deep_update_rfc7396(content, indata)
472
473 # To allow project addressing by name AS WELL AS _id. Get the _id, just in case the provided one is a name
474 _id = content.get("_id") or _id
475
476 self.check_conflict_on_edit(session, content, indata, _id=_id)
477 op_id = self.format_on_edit(content, indata)
478
479 self.db.replace(self.topic, _id, content)
480
481 indata.pop("_admin", None)
482 if op_id:
483 indata["op_id"] = op_id
484 indata["_id"] = _id
485 self._send_msg("edit", indata)
486 return op_id
487 except ValidationError as e:
488 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)