blob: 9a487918fee4d5b71c95fe0156ba764fbe89b767 [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# 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
tiernob24258a2018-10-04 18:39:49 +020016import logging
17from uuid import uuid4
18from http import HTTPStatus
19from time import time
20from osm_common.dbbase import deep_update_rfc7396
delacruzramoc061f562019-04-05 11:00:02 +020021from validation import validate_input, ValidationError, is_valid_uuid
tiernob24258a2018-10-04 18:39:49 +020022
23__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
24
25
26class 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
33def 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
44def 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
52class 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
tierno65ca36d2019-02-12 19:27:52 +010058 multiproject = True # True if this Topic can be shared by several projects. Then it contains _admin.projects_read
tiernob24258a2018-10-04 18:39:49 +020059
delacruzramoc061f562019-04-05 11:00:02 +020060 # Alternative ID Fields for some Topics
61 alt_id_field = {
62 "projects": "name",
tiernocf042d32019-06-13 09:06:40 +000063 "users": "username",
64 "roles": "name"
delacruzramoc061f562019-04-05 11:00:02 +020065 }
66
tiernob24258a2018-10-04 18:39:49 +020067 def __init__(self, db, fs, msg):
68 self.db = db
69 self.fs = fs
70 self.msg = msg
71 self.logger = logging.getLogger("nbi.engine")
72
73 @staticmethod
delacruzramoc061f562019-04-05 11:00:02 +020074 def id_field(topic, value):
tierno65ca36d2019-02-12 19:27:52 +010075 """Returns ID Field for given topic and field value"""
delacruzramoc061f562019-04-05 11:00:02 +020076 if topic in ["projects", "users"] and not is_valid_uuid(value):
77 return BaseTopic.alt_id_field[topic]
78 else:
79 return "_id"
80
81 @staticmethod
tiernob24258a2018-10-04 18:39:49 +020082 def _remove_envelop(indata=None):
83 if not indata:
84 return {}
85 return indata
86
87 def _validate_input_new(self, input, force=False):
88 """
89 Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind
90 :param input: user input content for the new topic
91 :param force: may be used for being more tolerant
92 :return: The same input content, or a changed version of it.
93 """
94 if self.schema_new:
95 validate_input(input, self.schema_new)
96 return input
97
98 def _validate_input_edit(self, input, force=False):
99 """
100 Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
101 :param input: user input content for the new topic
102 :param force: may be used for being more tolerant
103 :return: The same input content, or a changed version of it.
104 """
105 if self.schema_edit:
106 validate_input(input, self.schema_edit)
107 return input
108
109 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +0100110 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +0200111 """
112 Generates a filter dictionary for querying database, so that only allowed items for this project can be
113 addressed. Only propietary or public can be used. Allowed projects are at _admin.project_read/write. If it is
114 not present or contains ANY mean public.
tierno65ca36d2019-02-12 19:27:52 +0100115 :param session: contains:
116 project_id: project list this session has rights to access. Can be empty, one or several
117 set_project: items created will contain this project list
118 force: True or False
119 public: True, False or None
120 method: "list", "show", "write", "delete"
121 admin: True or False
122 :return: dictionary with project filter
tiernob24258a2018-10-04 18:39:49 +0200123 """
tierno65ca36d2019-02-12 19:27:52 +0100124 p_filter = {}
125 project_filter_n = []
126 project_filter = list(session["project_id"])
tiernob24258a2018-10-04 18:39:49 +0200127
tierno65ca36d2019-02-12 19:27:52 +0100128 if session["method"] not in ("list", "delete"):
129 if project_filter:
130 project_filter.append("ANY")
131 elif session["public"] is not None:
132 if session["public"]:
133 project_filter.append("ANY")
134 else:
135 project_filter_n.append("ANY")
136
137 if session.get("PROJECT.ne"):
138 project_filter_n.append(session["PROJECT.ne"])
139
140 if project_filter:
141 if session["method"] in ("list", "show", "delete") or session.get("set_project"):
142 p_filter["_admin.projects_read.cont"] = project_filter
143 else:
144 p_filter["_admin.projects_write.cont"] = project_filter
145 if project_filter_n:
146 if session["method"] in ("list", "show", "delete") or session.get("set_project"):
147 p_filter["_admin.projects_read.ncont"] = project_filter_n
148 else:
149 p_filter["_admin.projects_write.ncont"] = project_filter_n
150
151 return p_filter
152
153 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200154 """
155 Check that the data to be inserted is valid
tierno65ca36d2019-02-12 19:27:52 +0100156 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200157 :param indata: data to be inserted
tiernob24258a2018-10-04 18:39:49 +0200158 :return: None or raises EngineException
159 """
160 pass
161
tierno65ca36d2019-02-12 19:27:52 +0100162 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernob24258a2018-10-04 18:39:49 +0200163 """
164 Check that the data to be edited/uploaded is valid
tierno65ca36d2019-02-12 19:27:52 +0100165 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
166 :param final_content: data once modified. This methdo may change it.
tiernob24258a2018-10-04 18:39:49 +0200167 :param edit_content: incremental data that contains the modifications to apply
168 :param _id: internal _id
tiernob24258a2018-10-04 18:39:49 +0200169 :return: None or raises EngineException
170 """
tierno65ca36d2019-02-12 19:27:52 +0100171 if not self.multiproject:
172 return
173 # Change public status
174 if session["public"] is not None:
175 if session["public"] and "ANY" not in final_content["_admin"]["projects_read"]:
176 final_content["_admin"]["projects_read"].append("ANY")
177 final_content["_admin"]["projects_write"].clear()
178 if not session["public"] and "ANY" in final_content["_admin"]["projects_read"]:
179 final_content["_admin"]["projects_read"].remove("ANY")
180
181 # Change project status
182 if session.get("set_project"):
183 for p in session["set_project"]:
184 if p not in final_content["_admin"]["projects_read"]:
185 final_content["_admin"]["projects_read"].append(p)
tiernob24258a2018-10-04 18:39:49 +0200186
187 def check_unique_name(self, session, name, _id=None):
188 """
189 Check that the name is unique for this project
tierno65ca36d2019-02-12 19:27:52 +0100190 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200191 :param name: name to be checked
192 :param _id: If not None, ignore this entry that are going to change
193 :return: None or raises EngineException
194 """
tierno1f029d82019-06-13 22:37:04 +0000195 if not self.multiproject:
196 _filter = {}
197 else:
198 _filter = self._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +0200199 _filter["name"] = name
200 if _id:
201 _filter["_id.neq"] = _id
202 if self.db.get_one(self.topic, _filter, fail_on_empty=False, fail_on_more=False):
203 raise EngineException("name '{}' already exists for {}".format(name, self.topic), HTTPStatus.CONFLICT)
204
205 @staticmethod
206 def format_on_new(content, project_id=None, make_public=False):
207 """
208 Modifies content descriptor to include _admin
209 :param content: descriptor to be modified
tierno65ca36d2019-02-12 19:27:52 +0100210 :param project_id: if included, it add project read/write permissions. Can be None or a list
tiernob24258a2018-10-04 18:39:49 +0200211 :param make_public: if included it is generated as public for reading.
212 :return: None, but content is modified
213 """
214 now = time()
215 if "_admin" not in content:
216 content["_admin"] = {}
217 if not content["_admin"].get("created"):
218 content["_admin"]["created"] = now
219 content["_admin"]["modified"] = now
220 if not content.get("_id"):
221 content["_id"] = str(uuid4())
tierno65ca36d2019-02-12 19:27:52 +0100222 if project_id is not None:
tiernob24258a2018-10-04 18:39:49 +0200223 if not content["_admin"].get("projects_read"):
tierno65ca36d2019-02-12 19:27:52 +0100224 content["_admin"]["projects_read"] = list(project_id)
tiernob24258a2018-10-04 18:39:49 +0200225 if make_public:
226 content["_admin"]["projects_read"].append("ANY")
227 if not content["_admin"].get("projects_write"):
tierno65ca36d2019-02-12 19:27:52 +0100228 content["_admin"]["projects_write"] = list(project_id)
tiernob24258a2018-10-04 18:39:49 +0200229
230 @staticmethod
231 def format_on_edit(final_content, edit_content):
232 if final_content.get("_admin"):
233 now = time()
234 final_content["_admin"]["modified"] = now
235
236 def _send_msg(self, action, content):
237 if self.topic_msg:
238 content.pop("_admin", None)
239 self.msg.write(self.topic_msg, action, content)
240
tiernob4844ab2019-05-23 08:42:12 +0000241 def check_conflict_on_del(self, session, _id, db_content):
tiernob24258a2018-10-04 18:39:49 +0200242 """
243 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100244 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
245 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000246 :param db_content: The database content of this item _id
tiernob24258a2018-10-04 18:39:49 +0200247 :return: None if ok or raises EngineException with the conflict
248 """
249 pass
250
251 @staticmethod
252 def _update_input_with_kwargs(desc, kwargs):
253 """
254 Update descriptor with the kwargs. It contains dot separated keys
255 :param desc: dictionary to be updated
256 :param kwargs: plain dictionary to be used for updating.
delacruzramoc061f562019-04-05 11:00:02 +0200257 :return: None, 'desc' is modified. It raises EngineException.
tiernob24258a2018-10-04 18:39:49 +0200258 """
259 if not kwargs:
260 return
261 try:
262 for k, v in kwargs.items():
263 update_content = desc
264 kitem_old = None
265 klist = k.split(".")
266 for kitem in klist:
267 if kitem_old is not None:
268 update_content = update_content[kitem_old]
269 if isinstance(update_content, dict):
270 kitem_old = kitem
271 elif isinstance(update_content, list):
272 kitem_old = int(kitem)
273 else:
274 raise EngineException(
275 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
276 update_content[kitem_old] = v
277 except KeyError:
278 raise EngineException(
279 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
280 except ValueError:
281 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
282 k, kitem))
283 except IndexError:
284 raise EngineException(
285 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
286
287 def show(self, session, _id):
288 """
289 Get complete information on an topic
tierno65ca36d2019-02-12 19:27:52 +0100290 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200291 :param _id: server internal id
292 :return: dictionary, raise exception if not found.
293 """
tierno1f029d82019-06-13 22:37:04 +0000294 if not self.multiproject:
295 filter_db = {}
296 else:
297 filter_db = self._get_project_filter(session)
delacruzramoc061f562019-04-05 11:00:02 +0200298 # To allow project&user addressing by name AS WELL AS _id
299 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
tiernob24258a2018-10-04 18:39:49 +0200300 return self.db.get_one(self.topic, filter_db)
301 # TODO transform data for SOL005 URL requests
302 # TODO remove _admin if not admin
303
304 def get_file(self, session, _id, path=None, accept_header=None):
305 """
306 Only implemented for descriptor topics. Return the file content of a descriptor
tierno65ca36d2019-02-12 19:27:52 +0100307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200308 :param _id: Identity of the item to get content
309 :param path: artifact path or "$DESCRIPTOR" or None
310 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
311 :return: opened file or raises an exception
312 """
313 raise EngineException("Method get_file not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
314
315 def list(self, session, filter_q=None):
316 """
317 Get a list of the topic that matches a filter
318 :param session: contains the used login username and working project
319 :param filter_q: filter of data to be applied
320 :return: The list, it can be empty if no one match the filter.
321 """
322 if not filter_q:
323 filter_q = {}
tierno1f029d82019-06-13 22:37:04 +0000324 if self.multiproject:
325 filter_q.update(self._get_project_filter(session))
tiernob24258a2018-10-04 18:39:49 +0200326
327 # TODO transform data for SOL005 URL requests. Transform filtering
328 # TODO implement "field-type" query string SOL005
329 return self.db.get_list(self.topic, filter_q)
330
tierno65ca36d2019-02-12 19:27:52 +0100331 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200332 """
333 Creates a new entry into database.
334 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100335 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200336 :param indata: data to be inserted
337 :param kwargs: used to override the indata descriptor
338 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200339 :return: _id: identity of the inserted data.
340 """
341 try:
342 content = self._remove_envelop(indata)
343
344 # Override descriptor with query string kwargs
345 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100346 content = self._validate_input_new(content, force=session["force"])
347 self.check_conflict_on_new(session, content)
348 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200349 _id = self.db.create(self.topic, content)
350 rollback.append({"topic": self.topic, "_id": _id})
351 self._send_msg("create", content)
352 return _id
353 except ValidationError as e:
354 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
355
tierno65ca36d2019-02-12 19:27:52 +0100356 def upload_content(self, session, _id, indata, kwargs, headers):
tiernob24258a2018-10-04 18:39:49 +0200357 """
358 Only implemented for descriptor topics. Used for receiving content by chunks (with a transaction_id header
359 and/or gzip file. It will store and extract)
tierno65ca36d2019-02-12 19:27:52 +0100360 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200361 :param _id : the database id of entry to be updated
362 :param indata: http body request
363 :param kwargs: user query string to override parameters. NOT USED
364 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200365 :return: True package has is completely uploaded or False if partial content has been uplodaed.
366 Raise exception on error
367 """
368 raise EngineException("Method upload_content not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
369
370 def delete_list(self, session, filter_q=None):
371 """
372 Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API
tierno65ca36d2019-02-12 19:27:52 +0100373 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200374 :param filter_q: filter of data to be applied
375 :return: The deleted list, it can be empty if no one match the filter.
376 """
377 # TODO add admin to filter, validate rights
378 if not filter_q:
379 filter_q = {}
tierno1f029d82019-06-13 22:37:04 +0000380 if self.multiproject:
381 filter_q.update(self._get_project_filter(session))
tiernob24258a2018-10-04 18:39:49 +0200382 return self.db.del_list(self.topic, filter_q)
383
tiernob4844ab2019-05-23 08:42:12 +0000384 def delete_extra(self, session, _id, db_content):
tierno65ca36d2019-02-12 19:27:52 +0100385 """
386 Delete other things apart from database entry of a item _id.
387 e.g.: other associated elements at database and other file system storage
388 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
389 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +0000390 :param db_content: The database content of the _id. It is already deleted when reached this method, but the
391 content is needed in same cases
392 :return: None if ok or raises EngineException with the problem
tierno65ca36d2019-02-12 19:27:52 +0100393 """
394 pass
395
396 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200397 """
398 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100399 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200400 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200401 :param dry_run: make checking but do not delete
402 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
403 """
tiernob4844ab2019-05-23 08:42:12 +0000404
405 # To allow addressing projects and users by name AS WELL AS by _id
406 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
407 item_content = self.db.get_one(self.topic, filter_q)
408
tiernob24258a2018-10-04 18:39:49 +0200409 # TODO add admin to filter, validate rights
410 # data = self.get_item(topic, _id)
tiernob4844ab2019-05-23 08:42:12 +0000411 self.check_conflict_on_del(session, _id, item_content)
tierno65ca36d2019-02-12 19:27:52 +0100412 if dry_run:
413 return None
tiernob4844ab2019-05-23 08:42:12 +0000414
tierno1f029d82019-06-13 22:37:04 +0000415 if self.multiproject:
416 filter_q.update(self._get_project_filter(session))
tierno65ca36d2019-02-12 19:27:52 +0100417 if self.multiproject and session["project_id"]:
418 # remove reference from project_read. If not last delete
419 self.db.set_one(self.topic, filter_q, update_dict=None,
420 pull={"_admin.projects_read": {"$in": session["project_id"]}})
421 # try to delete if there is not any more reference from projects. Ignore if it is not deleted
422 filter_q = {'_id': _id, '_admin.projects_read': [[], ["ANY"]]}
423 v = self.db.del_one(self.topic, filter_q, fail_on_empty=False)
424 if not v or not v["deleted"]:
425 return v
426 else:
tiernob24258a2018-10-04 18:39:49 +0200427 v = self.db.del_one(self.topic, filter_q)
tiernob4844ab2019-05-23 08:42:12 +0000428 self.delete_extra(session, _id, item_content)
tierno65ca36d2019-02-12 19:27:52 +0100429 self._send_msg("deleted", {"_id": _id})
430 return v
tiernob24258a2018-10-04 18:39:49 +0200431
tierno65ca36d2019-02-12 19:27:52 +0100432 def edit(self, session, _id, indata=None, kwargs=None, content=None):
433 """
434 Change the content of an item
435 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
436 :param _id: server internal id
437 :param indata: contains the changes to apply
438 :param kwargs: modifies indata
439 :param content: original content of the item
440 :return:
441 """
tiernob24258a2018-10-04 18:39:49 +0200442 indata = self._remove_envelop(indata)
443
444 # Override descriptor with query string kwargs
445 if kwargs:
446 self._update_input_with_kwargs(indata, kwargs)
447 try:
tierno65ca36d2019-02-12 19:27:52 +0100448 if indata and session.get("set_project"):
449 raise EngineException("Cannot edit content and set to project (query string SET_PROJECT) at same time",
450 HTTPStatus.UNPROCESSABLE_ENTITY)
451 indata = self._validate_input_edit(indata, force=session["force"])
tiernob24258a2018-10-04 18:39:49 +0200452
453 # TODO self._check_edition(session, indata, _id, force)
454 if not content:
455 content = self.show(session, _id)
456 deep_update_rfc7396(content, indata)
tierno65ca36d2019-02-12 19:27:52 +0100457 self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernob24258a2018-10-04 18:39:49 +0200458 self.format_on_edit(content, indata)
delacruzramoc061f562019-04-05 11:00:02 +0200459 # To allow project addressing by name AS WELL AS _id
460 # self.db.replace(self.topic, _id, content)
461 cid = content.get("_id")
462 self.db.replace(self.topic, cid if cid else _id, content)
tiernob24258a2018-10-04 18:39:49 +0200463
464 indata.pop("_admin", None)
465 indata["_id"] = _id
466 self._send_msg("edit", indata)
tierno65ca36d2019-02-12 19:27:52 +0100467 return _id
tiernob24258a2018-10-04 18:39:49 +0200468 except ValidationError as e:
469 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)