X-Git-Url: https://osm.etsi.org/gitweb/?p=osm%2FNBI.git;a=blobdiff_plain;f=osm_nbi%2Fbase_topic.py;h=daa7a6b2104efcadc7816ed76f01e920698611b1;hp=72707ad55d7c7fbb042afa7e189f3adaa1ffa335;hb=f417d52971f2b32525b283227e6f7e9d7fdbd133;hpb=65ca36d13f895d0a361d59a5962029d6e3ef7a99 diff --git a/osm_nbi/base_topic.py b/osm_nbi/base_topic.py index 72707ad..daa7a6b 100644 --- a/osm_nbi/base_topic.py +++ b/osm_nbi/base_topic.py @@ -18,7 +18,8 @@ from uuid import uuid4 from http import HTTPStatus from time import time from osm_common.dbbase import deep_update_rfc7396 -from validation import validate_input, ValidationError, is_valid_uuid +from osm_nbi.validation import validate_input, ValidationError, is_valid_uuid +from yaml import safe_load, YAMLError __author__ = "Alfonso Tierno " @@ -27,7 +28,22 @@ class EngineException(Exception): def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST): self.http_code = http_code - Exception.__init__(self, message) + super(Exception, self).__init__(message) + + +def deep_get(target_dict, key_list): + """ + Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None + Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None + :param target_dict: dictionary to be read + :param key_list: list of keys to read from target_dict + :return: The wanted value if exist, None otherwise + """ + for key in key_list: + if not isinstance(target_dict, dict) or key not in target_dict: + return None + target_dict = target_dict[key] + return target_dict def get_iterable(input_var): @@ -53,26 +69,31 @@ class BaseTopic: # static variables for all instance classes topic = None # to_override topic_msg = None # to_override + quota_name = None # to_override. If not provided topic will be used for quota_name schema_new = None # to_override schema_edit = None # to_override multiproject = True # True if this Topic can be shared by several projects. Then it contains _admin.projects_read + default_quota = 500 + # Alternative ID Fields for some Topics alt_id_field = { "projects": "name", - "users": "username" + "users": "username", + "roles": "name" } - def __init__(self, db, fs, msg): + def __init__(self, db, fs, msg, auth): self.db = db self.fs = fs self.msg = msg self.logger = logging.getLogger("nbi.engine") + self.auth = auth @staticmethod def id_field(topic, value): """Returns ID Field for given topic and field value""" - if topic in ["projects", "users"] and not is_valid_uuid(value): + if topic in BaseTopic.alt_id_field.keys() and not is_valid_uuid(value): return BaseTopic.alt_id_field[topic] else: return "_id" @@ -83,6 +104,31 @@ class BaseTopic: return {} return indata + def check_quota(self, session): + """ + Check whether topic quota is exceeded by the given project + Used by relevant topics' 'new' function to decide whether or not creation of the new item should be allowed + :param session[project_id]: projects (tuple) for which quota should be checked + :param session[force]: boolean. If true, skip quota checking + :return: None + :raise: + DbException if project not found + ValidationError if quota exceeded in one of the projects + """ + if session["force"]: + return + projects = session["project_id"] + for project in projects: + proj = self.auth.get_project(project) + pid = proj["_id"] + quota_name = self.quota_name or self.topic + quota = proj.get("quotas", {}).get(quota_name, self.default_quota) + count = self.db.count(self.topic, {"_admin.projects_read": pid}) + if count >= quota: + name = proj["name"] + raise ValidationError("quota ({}={}) exceeded for project {} ({})".format(quota_name, quota, name, pid), + http_code=HTTPStatus.UNAUTHORIZED) + def _validate_input_new(self, input, force=False): """ Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind @@ -109,7 +155,7 @@ class BaseTopic: def _get_project_filter(session): """ Generates a filter dictionary for querying database, so that only allowed items for this project can be - addressed. Only propietary or public can be used. Allowed projects are at _admin.project_read/write. If it is + addressed. Only proprietary or public can be used. Allowed projects are at _admin.project_read/write. If it is not present or contains ANY mean public. :param session: contains: project_id: project list this session has rights to access. Can be empty, one or several @@ -162,7 +208,7 @@ class BaseTopic: """ Check that the data to be edited/uploaded is valid :param session: contains "username", "admin", "force", "public", "project_id", "set_project" - :param final_content: data once modified. This methdo may change it. + :param final_content: data once modified. This method may change it. :param edit_content: incremental data that contains the modifications to apply :param _id: internal _id :return: None or raises EngineException @@ -191,7 +237,10 @@ class BaseTopic: :param _id: If not None, ignore this entry that are going to change :return: None or raises EngineException """ - _filter = self._get_project_filter(session) + if not self.multiproject: + _filter = {} + else: + _filter = self._get_project_filter(session) _filter["name"] = name if _id: _filter["_id.neq"] = _id @@ -205,7 +254,7 @@ class BaseTopic: :param content: descriptor to be modified :param project_id: if included, it add project read/write permissions. Can be None or a list :param make_public: if included it is generated as public for reading. - :return: None, but content is modified + :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified """ now = time() if "_admin" not in content: @@ -222,33 +271,46 @@ class BaseTopic: content["_admin"]["projects_read"].append("ANY") if not content["_admin"].get("projects_write"): content["_admin"]["projects_write"] = list(project_id) + return None @staticmethod def format_on_edit(final_content, edit_content): + """ + Modifies final_content to admin information upon edition + :param final_content: final content to be stored at database + :param edit_content: user requested update content + :return: operation id, if this edit implies an asynchronous operation; None otherwise + """ if final_content.get("_admin"): now = time() final_content["_admin"]["modified"] = now + return None - def _send_msg(self, action, content): - if self.topic_msg: + def _send_msg(self, action, content, not_send_msg=None): + if self.topic_msg and not_send_msg is not False: content.pop("_admin", None) - self.msg.write(self.topic_msg, action, content) + if isinstance(not_send_msg, list): + not_send_msg.append((self.topic_msg, action, content)) + else: + self.msg.write(self.topic_msg, action, content) - def check_conflict_on_del(self, session, _id): + def check_conflict_on_del(self, session, _id, db_content): """ Check if deletion can be done because of dependencies if it is not force. To override :param session: contains "username", "admin", "force", "public", "project_id", "set_project" :param _id: internal _id + :param db_content: The database content of this item _id :return: None if ok or raises EngineException with the conflict """ pass @staticmethod - def _update_input_with_kwargs(desc, kwargs): + def _update_input_with_kwargs(desc, kwargs, yaml_format=False): """ Update descriptor with the kwargs. It contains dot separated keys :param desc: dictionary to be updated :param kwargs: plain dictionary to be used for updating. + :param yaml_format: get kwargs values as yaml format. :return: None, 'desc' is modified. It raises EngineException. """ if not kwargs: @@ -263,12 +325,23 @@ class BaseTopic: update_content = update_content[kitem_old] if isinstance(update_content, dict): kitem_old = kitem + if not isinstance(update_content.get(kitem_old), (dict, list)): + update_content[kitem_old] = {} elif isinstance(update_content, list): + # key must be an index of the list, must be integer kitem_old = int(kitem) + # if index greater than list, extend the list + if kitem_old >= len(update_content): + update_content += [None] * (kitem_old - len(update_content) + 1) + if not isinstance(update_content[kitem_old], (dict, list)): + update_content[kitem_old] = {} else: raise EngineException( "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem)) - update_content[kitem_old] = v + if v is None: + del update_content[kitem_old] + else: + update_content[kitem_old] = v if not yaml_format else safe_load(v) except KeyError: raise EngineException( "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old)) @@ -278,6 +351,8 @@ class BaseTopic: except IndexError: raise EngineException( "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old)) + except YAMLError: + raise EngineException("Invalid query string '{}' yaml format".format(k)) def show(self, session, _id): """ @@ -286,7 +361,10 @@ class BaseTopic: :param _id: server internal id :return: dictionary, raise exception if not found. """ - filter_db = self._get_project_filter(session) + if not self.multiproject: + filter_db = {} + else: + filter_db = self._get_project_filter(session) # To allow project&user addressing by name AS WELL AS _id filter_db[BaseTopic.id_field(self.topic, _id)] = _id return self.db.get_one(self.topic, filter_db) @@ -313,8 +391,8 @@ class BaseTopic: """ if not filter_q: filter_q = {} - - filter_q.update(self._get_project_filter(session)) + if self.multiproject: + filter_q.update(self._get_project_filter(session)) # TODO transform data for SOL005 URL requests. Transform filtering # TODO implement "field-type" query string SOL005 @@ -328,20 +406,27 @@ class BaseTopic: :param indata: data to be inserted :param kwargs: used to override the indata descriptor :param headers: http request headers - :return: _id: identity of the inserted data. + :return: _id, op_id: + _id: identity of the inserted data. + op_id: operation id if this is asynchronous, None otherwise """ try: + if self.multiproject: + self.check_quota(session) + content = self._remove_envelop(indata) # Override descriptor with query string kwargs self._update_input_with_kwargs(content, kwargs) content = self._validate_input_new(content, force=session["force"]) self.check_conflict_on_new(session, content) - self.format_on_new(content, project_id=session["project_id"], make_public=session["public"]) + op_id = self.format_on_new(content, project_id=session["project_id"], make_public=session["public"]) _id = self.db.create(self.topic, content) rollback.append({"topic": self.topic, "_id": _id}) - self._send_msg("create", content) - return _id + if op_id: + content["op_id"] = op_id + self._send_msg("created", content) + return _id, op_id except ValidationError as e: raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY) @@ -369,48 +454,70 @@ class BaseTopic: # TODO add admin to filter, validate rights if not filter_q: filter_q = {} - filter_q.update(self._get_project_filter(session)) + if self.multiproject: + filter_q.update(self._get_project_filter(session)) return self.db.del_list(self.topic, filter_q) - def delete_extra(self, session, _id): + def delete_extra(self, session, _id, db_content, not_send_msg=None): """ Delete other things apart from database entry of a item _id. e.g.: other associated elements at database and other file system storage :param session: contains "username", "admin", "force", "public", "project_id", "set_project" :param _id: server internal id + :param db_content: The database content of the _id. It is already deleted when reached this method, but the + content is needed in same cases + :param not_send_msg: To not send message (False) or store content (list) instead + :return: None if ok or raises EngineException with the problem """ pass - def delete(self, session, _id, dry_run=False): + def delete(self, session, _id, dry_run=False, not_send_msg=None): """ Delete item by its internal _id :param session: contains "username", "admin", "force", "public", "project_id", "set_project" :param _id: server internal id :param dry_run: make checking but do not delete - :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ... + :param not_send_msg: To not send message (False) or store content (list) instead + :return: operation id (None if there is not operation), raise exception if error or not found, conflict, ... """ - # TODO add admin to filter, validate rights - # data = self.get_item(topic, _id) - self.check_conflict_on_del(session, _id) - filter_q = self._get_project_filter(session) - # To allow project addressing by name AS WELL AS _id - filter_q[BaseTopic.id_field(self.topic, _id)] = _id + + # To allow addressing projects and users by name AS WELL AS by _id + if not self.multiproject: + filter_q = {} + else: + filter_q = self._get_project_filter(session) + filter_q[self.id_field(self.topic, _id)] = _id + item_content = self.db.get_one(self.topic, filter_q) + + self.check_conflict_on_del(session, _id, item_content) if dry_run: return None + if self.multiproject and session["project_id"]: - # remove reference from project_read. If not last delete - self.db.set_one(self.topic, filter_q, update_dict=None, - pull={"_admin.projects_read": {"$in": session["project_id"]}}) - # try to delete if there is not any more reference from projects. Ignore if it is not deleted - filter_q = {'_id': _id, '_admin.projects_read': [[], ["ANY"]]} - v = self.db.del_one(self.topic, filter_q, fail_on_empty=False) - if not v or not v["deleted"]: - return v - else: - v = self.db.del_one(self.topic, filter_q) - self.delete_extra(session, _id) - self._send_msg("deleted", {"_id": _id}) - return v + # remove reference from project_read if there are more projects referencing it. If it last one, + # do not remove reference, but delete + other_projects_referencing = next((p for p in item_content["_admin"]["projects_read"] + if p not in session["project_id"] and p != "ANY"), None) + + # check if there are projects referencing it (apart from ANY, that means, public).... + if other_projects_referencing: + # remove references but not delete + update_dict_pull = {"_admin.projects_read": session["project_id"], + "_admin.projects_write": session["project_id"]} + self.db.set_one(self.topic, filter_q, update_dict=None, pull_list=update_dict_pull) + return None + else: + can_write = next((p for p in item_content["_admin"]["projects_write"] if p == "ANY" or + p in session["project_id"]), None) + if not can_write: + raise EngineException("You have not write permission to delete it", + http_code=HTTPStatus.UNAUTHORIZED) + + # delete + self.db.del_one(self.topic, filter_q) + self.delete_extra(session, _id, item_content, not_send_msg=not_send_msg) + self._send_msg("deleted", {"_id": _id}, not_send_msg=not_send_msg) + return None def edit(self, session, _id, indata=None, kwargs=None, content=None): """ @@ -420,7 +527,7 @@ class BaseTopic: :param indata: contains the changes to apply :param kwargs: modifies indata :param content: original content of the item - :return: + :return: op_id: operation id if this is processed asynchronously, None otherwise """ indata = self._remove_envelop(indata) @@ -437,16 +544,20 @@ class BaseTopic: if not content: content = self.show(session, _id) deep_update_rfc7396(content, indata) + + # To allow project addressing by name AS WELL AS _id. Get the _id, just in case the provided one is a name + _id = content.get("_id") or _id + self.check_conflict_on_edit(session, content, indata, _id=_id) - self.format_on_edit(content, indata) - # To allow project addressing by name AS WELL AS _id - # self.db.replace(self.topic, _id, content) - cid = content.get("_id") - self.db.replace(self.topic, cid if cid else _id, content) + op_id = self.format_on_edit(content, indata) + + self.db.replace(self.topic, _id, content) indata.pop("_admin", None) + if op_id: + indata["op_id"] = op_id indata["_id"] = _id - self._send_msg("edit", indata) - return _id + self._send_msg("edited", indata) + return op_id except ValidationError as e: raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)