X-Git-Url: https://osm.etsi.org/gitweb/?p=osm%2FNBI.git;a=blobdiff_plain;f=osm_nbi%2Fbase_topic.py;h=1bc906c2b4d63594f84a2a129dac715125e35e7e;hp=4fb84a5bd3765064b70df0e7298918af7e6951ff;hb=332e080919376d26f7bb98478d9ebe14b73f4d03;hpb=01b15d3166ea28266fb3d994d0615e4091c43c08 diff --git a/osm_nbi/base_topic.py b/osm_nbi/base_topic.py index 4fb84a5..1bc906c 100644 --- a/osm_nbi/base_topic.py +++ b/osm_nbi/base_topic.py @@ -18,7 +18,7 @@ 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 __author__ = "Alfonso Tierno " @@ -27,7 +27,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): @@ -57,6 +72,8 @@ class BaseTopic: 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", @@ -64,11 +81,12 @@ class BaseTopic: "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): @@ -84,6 +102,29 @@ 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 projects: projects (tuple) for which quota should be checked + :param override: boolean. If true, don't raise ValidationError even though quota be exceeded + :return: None + :raise: + DbException if project not found + ValidationError if quota exceeded and not overridden + """ + if session["force"] or session["admin"]: + return + projects = session["project_id"] + for project in projects: + proj = self.auth.get_project(project) + pid = proj["_id"] + quota = proj.get("quotas", {}).get(self.topic, 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(self.topic, quota, name, pid)) + def _validate_input_new(self, input, force=False): """ Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind @@ -349,6 +390,9 @@ class BaseTopic: 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 @@ -360,7 +404,7 @@ class BaseTopic: rollback.append({"topic": self.topic, "_id": _id}) if op_id: content["op_id"] = op_id - self._send_msg("create", content) + self._send_msg("created", content) return _id, op_id except ValidationError as e: raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY) @@ -481,7 +525,7 @@ class BaseTopic: if op_id: indata["op_id"] = op_id indata["_id"] = _id - self._send_msg("edit", indata) + self._send_msg("edited", indata) return op_id except ValidationError as e: raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)