| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
| tierno | d125caf | 2018-11-22 16:05:54 +0000 | [diff] [blame] | 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 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 16 | import logging |
| 17 | from uuid import uuid4 |
| 18 | from http import HTTPStatus |
| 19 | from time import time |
| aticig | 2b5e123 | 2022-08-10 17:30:12 +0300 | [diff] [blame] | 20 | from osm_common.dbbase import deep_update_rfc7396, DbException |
| tierno | 23acf40 | 2019-08-28 13:36:34 +0000 | [diff] [blame] | 21 | from osm_nbi.validation import validate_input, ValidationError, is_valid_uuid |
| tierno | 1c38f2f | 2020-03-24 11:51:39 +0000 | [diff] [blame] | 22 | from yaml import safe_load, YAMLError |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 23 | |
| 24 | __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>" |
| 25 | |
| 26 | |
| 27 | class EngineException(Exception): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 28 | def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST): |
| 29 | self.http_code = http_code |
| tierno | 23acf40 | 2019-08-28 13:36:34 +0000 | [diff] [blame] | 30 | super(Exception, self).__init__(message) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 31 | |
| garciadeblas | f2af4a1 | 2023-01-24 16:56:54 +0100 | [diff] [blame] | 32 | |
| aticig | 2b5e123 | 2022-08-10 17:30:12 +0300 | [diff] [blame] | 33 | class NBIBadArgumentsException(Exception): |
| 34 | """ |
| 35 | Bad argument values exception |
| 36 | """ |
| 37 | |
| 38 | def __init__(self, message: str = "", bad_args: list = None): |
| 39 | Exception.__init__(self, message) |
| 40 | self.message = message |
| 41 | self.bad_args = bad_args |
| 42 | |
| 43 | def __str__(self): |
| garciadeblas | f2af4a1 | 2023-01-24 16:56:54 +0100 | [diff] [blame] | 44 | return "{}, Bad arguments: {}".format(self.message, self.bad_args) |
| 45 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 46 | |
| tierno | 714954e | 2019-11-29 13:43:26 +0000 | [diff] [blame] | 47 | def deep_get(target_dict, key_list): |
| 48 | """ |
| 49 | Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None |
| 50 | 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 |
| 51 | :param target_dict: dictionary to be read |
| 52 | :param key_list: list of keys to read from target_dict |
| 53 | :return: The wanted value if exist, None otherwise |
| 54 | """ |
| 55 | for key in key_list: |
| 56 | if not isinstance(target_dict, dict) or key not in target_dict: |
| 57 | return None |
| 58 | target_dict = target_dict[key] |
| 59 | return target_dict |
| 60 | |
| 61 | |
| garciadeblas | f2af4a1 | 2023-01-24 16:56:54 +0100 | [diff] [blame] | 62 | def detect_descriptor_usage(descriptor: dict, db_collection: str, db: object) -> bool: |
| aticig | 2b5e123 | 2022-08-10 17:30:12 +0300 | [diff] [blame] | 63 | """Detect the descriptor usage state. |
| 64 | |
| 65 | Args: |
| 66 | descriptor (dict): VNF or NS Descriptor as dictionary |
| 67 | db_collection (str): collection name which is looked for in DB |
| 68 | db (object): name of db object |
| 69 | |
| 70 | Returns: |
| 71 | True if descriptor is in use else None |
| 72 | |
| 73 | """ |
| 74 | try: |
| 75 | if not descriptor: |
| 76 | raise NBIBadArgumentsException( |
| 77 | "Argument is mandatory and can not be empty", "descriptor" |
| 78 | ) |
| 79 | |
| 80 | if not db: |
| 81 | raise NBIBadArgumentsException("A valid DB object should be provided", "db") |
| 82 | |
| 83 | search_dict = { |
| 84 | "vnfds": ("vnfrs", "vnfd-id"), |
| 85 | "nsds": ("nsrs", "nsd-id"), |
| kayal2001 | f71c2e8 | 2024-06-25 15:26:24 +0530 | [diff] [blame^] | 86 | "ns_config_template": ("ns_config_template", "_id"), |
| aticig | 2b5e123 | 2022-08-10 17:30:12 +0300 | [diff] [blame] | 87 | } |
| 88 | |
| 89 | if db_collection not in search_dict: |
| garciadeblas | f2af4a1 | 2023-01-24 16:56:54 +0100 | [diff] [blame] | 90 | raise NBIBadArgumentsException( |
| 91 | "db_collection should be equal to vnfds or nsds", "db_collection" |
| 92 | ) |
| aticig | 2b5e123 | 2022-08-10 17:30:12 +0300 | [diff] [blame] | 93 | |
| 94 | record_list = db.get_list( |
| 95 | search_dict[db_collection][0], |
| 96 | {search_dict[db_collection][1]: descriptor["_id"]}, |
| 97 | ) |
| 98 | |
| 99 | if record_list: |
| 100 | return True |
| 101 | |
| 102 | except (DbException, KeyError, NBIBadArgumentsException) as error: |
| garciadeblas | f2af4a1 | 2023-01-24 16:56:54 +0100 | [diff] [blame] | 103 | raise EngineException( |
| 104 | f"Error occured while detecting the descriptor usage: {error}" |
| 105 | ) |
| aticig | 2b5e123 | 2022-08-10 17:30:12 +0300 | [diff] [blame] | 106 | |
| 107 | |
| 108 | def update_descriptor_usage_state( |
| 109 | descriptor: dict, db_collection: str, db: object |
| 110 | ) -> None: |
| 111 | """Updates the descriptor usage state. |
| 112 | |
| 113 | Args: |
| 114 | descriptor (dict): VNF or NS Descriptor as dictionary |
| 115 | db_collection (str): collection name which is looked for in DB |
| 116 | db (object): name of db object |
| 117 | |
| 118 | Returns: |
| 119 | None |
| 120 | |
| 121 | """ |
| 122 | try: |
| 123 | descriptor_update = { |
| 124 | "_admin.usageState": "NOT_IN_USE", |
| 125 | } |
| 126 | |
| 127 | if detect_descriptor_usage(descriptor, db_collection, db): |
| 128 | descriptor_update = { |
| 129 | "_admin.usageState": "IN_USE", |
| 130 | } |
| 131 | |
| garciadeblas | f2af4a1 | 2023-01-24 16:56:54 +0100 | [diff] [blame] | 132 | db.set_one( |
| 133 | db_collection, {"_id": descriptor["_id"]}, update_dict=descriptor_update |
| 134 | ) |
| aticig | 2b5e123 | 2022-08-10 17:30:12 +0300 | [diff] [blame] | 135 | |
| 136 | except (DbException, KeyError, NBIBadArgumentsException) as error: |
| garciadeblas | f2af4a1 | 2023-01-24 16:56:54 +0100 | [diff] [blame] | 137 | raise EngineException( |
| 138 | f"Error occured while updating the descriptor usage state: {error}" |
| 139 | ) |
| aticig | 2b5e123 | 2022-08-10 17:30:12 +0300 | [diff] [blame] | 140 | |
| 141 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 142 | def get_iterable(input_var): |
| 143 | """ |
| 144 | Returns an iterable, in case input_var is None it just returns an empty tuple |
| 145 | :param input_var: can be a list, tuple or None |
| 146 | :return: input_var or () if it is None |
| 147 | """ |
| 148 | if input_var is None: |
| 149 | return () |
| 150 | return input_var |
| 151 | |
| 152 | |
| 153 | def versiontuple(v): |
| 154 | """utility for compare dot separate versions. Fills with zeros to proper number comparison""" |
| 155 | filled = [] |
| 156 | for point in v.split("."): |
| 157 | filled.append(point.zfill(8)) |
| 158 | return tuple(filled) |
| 159 | |
| 160 | |
| tierno | cddb07d | 2020-10-06 08:28:00 +0000 | [diff] [blame] | 161 | def increment_ip_mac(ip_mac, vm_index=1): |
| 162 | if not isinstance(ip_mac, str): |
| 163 | return ip_mac |
| 164 | try: |
| 165 | # try with ipv4 look for last dot |
| 166 | i = ip_mac.rfind(".") |
| 167 | if i > 0: |
| 168 | i += 1 |
| 169 | return "{}{}".format(ip_mac[:i], int(ip_mac[i:]) + vm_index) |
| 170 | # try with ipv6 or mac look for last colon. Operate in hex |
| 171 | i = ip_mac.rfind(":") |
| 172 | if i > 0: |
| 173 | i += 1 |
| 174 | # format in hex, len can be 2 for mac or 4 for ipv6 |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 175 | return ("{}{:0" + str(len(ip_mac) - i) + "x}").format( |
| 176 | ip_mac[:i], int(ip_mac[i:], 16) + vm_index |
| 177 | ) |
| tierno | cddb07d | 2020-10-06 08:28:00 +0000 | [diff] [blame] | 178 | except Exception: |
| 179 | pass |
| 180 | return None |
| 181 | |
| 182 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 183 | class BaseTopic: |
| 184 | # static variables for all instance classes |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 185 | topic = None # to_override |
| 186 | topic_msg = None # to_override |
| 187 | quota_name = None # to_override. If not provided topic will be used for quota_name |
| 188 | schema_new = None # to_override |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 189 | schema_edit = None # to_override |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 190 | multiproject = True # True if this Topic can be shared by several projects. Then it contains _admin.projects_read |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 191 | |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 192 | default_quota = 500 |
| 193 | |
| delacruzramo | c061f56 | 2019-04-05 11:00:02 +0200 | [diff] [blame] | 194 | # Alternative ID Fields for some Topics |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 195 | alt_id_field = {"projects": "name", "users": "username", "roles": "name"} |
| delacruzramo | c061f56 | 2019-04-05 11:00:02 +0200 | [diff] [blame] | 196 | |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 197 | def __init__(self, db, fs, msg, auth): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 198 | self.db = db |
| 199 | self.fs = fs |
| 200 | self.msg = msg |
| 201 | self.logger = logging.getLogger("nbi.engine") |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 202 | self.auth = auth |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 203 | |
| 204 | @staticmethod |
| delacruzramo | c061f56 | 2019-04-05 11:00:02 +0200 | [diff] [blame] | 205 | def id_field(topic, value): |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 206 | """Returns ID Field for given topic and field value""" |
| delacruzramo | ceb8baf | 2019-06-21 14:25:38 +0200 | [diff] [blame] | 207 | if topic in BaseTopic.alt_id_field.keys() and not is_valid_uuid(value): |
| delacruzramo | c061f56 | 2019-04-05 11:00:02 +0200 | [diff] [blame] | 208 | return BaseTopic.alt_id_field[topic] |
| 209 | else: |
| 210 | return "_id" |
| 211 | |
| 212 | @staticmethod |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 213 | def _remove_envelop(indata=None): |
| 214 | if not indata: |
| 215 | return {} |
| 216 | return indata |
| 217 | |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 218 | def check_quota(self, session): |
| 219 | """ |
| 220 | Check whether topic quota is exceeded by the given project |
| 221 | Used by relevant topics' 'new' function to decide whether or not creation of the new item should be allowed |
| tierno | 6b02b05 | 2020-06-02 10:07:41 +0000 | [diff] [blame] | 222 | :param session[project_id]: projects (tuple) for which quota should be checked |
| 223 | :param session[force]: boolean. If true, skip quota checking |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 224 | :return: None |
| 225 | :raise: |
| 226 | DbException if project not found |
| tierno | 6b02b05 | 2020-06-02 10:07:41 +0000 | [diff] [blame] | 227 | ValidationError if quota exceeded in one of the projects |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 228 | """ |
| tierno | d774958 | 2020-05-28 10:41:10 +0000 | [diff] [blame] | 229 | if session["force"]: |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 230 | return |
| 231 | projects = session["project_id"] |
| 232 | for project in projects: |
| 233 | proj = self.auth.get_project(project) |
| 234 | pid = proj["_id"] |
| tierno | 6b02b05 | 2020-06-02 10:07:41 +0000 | [diff] [blame] | 235 | quota_name = self.quota_name or self.topic |
| 236 | quota = proj.get("quotas", {}).get(quota_name, self.default_quota) |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 237 | count = self.db.count(self.topic, {"_admin.projects_read": pid}) |
| 238 | if count >= quota: |
| 239 | name = proj["name"] |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 240 | raise ValidationError( |
| 241 | "quota ({}={}) exceeded for project {} ({})".format( |
| 242 | quota_name, quota, name, pid |
| 243 | ), |
| 244 | http_code=HTTPStatus.UNPROCESSABLE_ENTITY, |
| 245 | ) |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 246 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 247 | def _validate_input_new(self, input, force=False): |
| 248 | """ |
| 249 | Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind |
| 250 | :param input: user input content for the new topic |
| 251 | :param force: may be used for being more tolerant |
| 252 | :return: The same input content, or a changed version of it. |
| 253 | """ |
| 254 | if self.schema_new: |
| 255 | validate_input(input, self.schema_new) |
| 256 | return input |
| 257 | |
| Frank Bryden | deba68e | 2020-07-27 13:55:11 +0000 | [diff] [blame] | 258 | def _validate_input_edit(self, input, content, force=False): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 259 | """ |
| 260 | Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind |
| 261 | :param input: user input content for the new topic |
| 262 | :param force: may be used for being more tolerant |
| 263 | :return: The same input content, or a changed version of it. |
| 264 | """ |
| 265 | if self.schema_edit: |
| 266 | validate_input(input, self.schema_edit) |
| 267 | return input |
| 268 | |
| 269 | @staticmethod |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 270 | def _get_project_filter(session): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 271 | """ |
| 272 | Generates a filter dictionary for querying database, so that only allowed items for this project can be |
| tierno | f5f2e3f | 2020-03-23 14:42:10 +0000 | [diff] [blame] | 273 | addressed. Only proprietary or public can be used. Allowed projects are at _admin.project_read/write. If it is |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 274 | not present or contains ANY mean public. |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 275 | :param session: contains: |
| 276 | project_id: project list this session has rights to access. Can be empty, one or several |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 277 | set_project: items created will contain this project list |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 278 | force: True or False |
| 279 | public: True, False or None |
| 280 | method: "list", "show", "write", "delete" |
| 281 | admin: True or False |
| 282 | :return: dictionary with project filter |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 283 | """ |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 284 | p_filter = {} |
| 285 | project_filter_n = [] |
| 286 | project_filter = list(session["project_id"]) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 287 | |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 288 | if session["method"] not in ("list", "delete"): |
| 289 | if project_filter: |
| 290 | project_filter.append("ANY") |
| 291 | elif session["public"] is not None: |
| 292 | if session["public"]: |
| 293 | project_filter.append("ANY") |
| 294 | else: |
| 295 | project_filter_n.append("ANY") |
| 296 | |
| 297 | if session.get("PROJECT.ne"): |
| 298 | project_filter_n.append(session["PROJECT.ne"]) |
| 299 | |
| 300 | if project_filter: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 301 | if session["method"] in ("list", "show", "delete") or session.get( |
| 302 | "set_project" |
| 303 | ): |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 304 | p_filter["_admin.projects_read.cont"] = project_filter |
| 305 | else: |
| 306 | p_filter["_admin.projects_write.cont"] = project_filter |
| 307 | if project_filter_n: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 308 | if session["method"] in ("list", "show", "delete") or session.get( |
| 309 | "set_project" |
| 310 | ): |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 311 | p_filter["_admin.projects_read.ncont"] = project_filter_n |
| 312 | else: |
| 313 | p_filter["_admin.projects_write.ncont"] = project_filter_n |
| 314 | |
| 315 | return p_filter |
| 316 | |
| 317 | def check_conflict_on_new(self, session, indata): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 318 | """ |
| 319 | Check that the data to be inserted is valid |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 320 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 321 | :param indata: data to be inserted |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 322 | :return: None or raises EngineException |
| 323 | """ |
| 324 | pass |
| 325 | |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 326 | def check_conflict_on_edit(self, session, final_content, edit_content, _id): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 327 | """ |
| 328 | Check that the data to be edited/uploaded is valid |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 329 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 330 | :param final_content: data once modified. This method may change it. |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 331 | :param edit_content: incremental data that contains the modifications to apply |
| 332 | :param _id: internal _id |
| bravof | b995ea2 | 2021-02-10 10:57:52 -0300 | [diff] [blame] | 333 | :return: final_content or raises EngineException |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 334 | """ |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 335 | if not self.multiproject: |
| bravof | b995ea2 | 2021-02-10 10:57:52 -0300 | [diff] [blame] | 336 | return final_content |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 337 | # Change public status |
| 338 | if session["public"] is not None: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 339 | if ( |
| 340 | session["public"] |
| 341 | and "ANY" not in final_content["_admin"]["projects_read"] |
| 342 | ): |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 343 | final_content["_admin"]["projects_read"].append("ANY") |
| 344 | final_content["_admin"]["projects_write"].clear() |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 345 | if ( |
| 346 | not session["public"] |
| 347 | and "ANY" in final_content["_admin"]["projects_read"] |
| 348 | ): |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 349 | final_content["_admin"]["projects_read"].remove("ANY") |
| 350 | |
| 351 | # Change project status |
| 352 | if session.get("set_project"): |
| 353 | for p in session["set_project"]: |
| 354 | if p not in final_content["_admin"]["projects_read"]: |
| 355 | final_content["_admin"]["projects_read"].append(p) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 356 | |
| bravof | b995ea2 | 2021-02-10 10:57:52 -0300 | [diff] [blame] | 357 | return final_content |
| 358 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 359 | def check_unique_name(self, session, name, _id=None): |
| 360 | """ |
| 361 | Check that the name is unique for this project |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 362 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 363 | :param name: name to be checked |
| 364 | :param _id: If not None, ignore this entry that are going to change |
| 365 | :return: None or raises EngineException |
| 366 | """ |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 367 | if not self.multiproject: |
| 368 | _filter = {} |
| 369 | else: |
| 370 | _filter = self._get_project_filter(session) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 371 | _filter["name"] = name |
| 372 | if _id: |
| 373 | _filter["_id.neq"] = _id |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 374 | if self.db.get_one( |
| 375 | self.topic, _filter, fail_on_empty=False, fail_on_more=False |
| 376 | ): |
| 377 | raise EngineException( |
| 378 | "name '{}' already exists for {}".format(name, self.topic), |
| 379 | HTTPStatus.CONFLICT, |
| 380 | ) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 381 | |
| 382 | @staticmethod |
| 383 | def format_on_new(content, project_id=None, make_public=False): |
| 384 | """ |
| 385 | Modifies content descriptor to include _admin |
| 386 | :param content: descriptor to be modified |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 387 | :param project_id: if included, it add project read/write permissions. Can be None or a list |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 388 | :param make_public: if included it is generated as public for reading. |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 389 | :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 390 | """ |
| 391 | now = time() |
| 392 | if "_admin" not in content: |
| 393 | content["_admin"] = {} |
| 394 | if not content["_admin"].get("created"): |
| 395 | content["_admin"]["created"] = now |
| 396 | content["_admin"]["modified"] = now |
| 397 | if not content.get("_id"): |
| 398 | content["_id"] = str(uuid4()) |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 399 | if project_id is not None: |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 400 | if not content["_admin"].get("projects_read"): |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 401 | content["_admin"]["projects_read"] = list(project_id) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 402 | if make_public: |
| 403 | content["_admin"]["projects_read"].append("ANY") |
| 404 | if not content["_admin"].get("projects_write"): |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 405 | content["_admin"]["projects_write"] = list(project_id) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 406 | return None |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 407 | |
| 408 | @staticmethod |
| 409 | def format_on_edit(final_content, edit_content): |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 410 | """ |
| 411 | Modifies final_content to admin information upon edition |
| 412 | :param final_content: final content to be stored at database |
| 413 | :param edit_content: user requested update content |
| 414 | :return: operation id, if this edit implies an asynchronous operation; None otherwise |
| 415 | """ |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 416 | if final_content.get("_admin"): |
| 417 | now = time() |
| 418 | final_content["_admin"]["modified"] = now |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 419 | return None |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 420 | |
| tierno | bee3bad | 2019-12-05 12:26:01 +0000 | [diff] [blame] | 421 | def _send_msg(self, action, content, not_send_msg=None): |
| 422 | if self.topic_msg and not_send_msg is not False: |
| agarwalat | 5347198 | 2020-10-08 13:06:14 +0000 | [diff] [blame] | 423 | content = content.copy() |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 424 | content.pop("_admin", None) |
| tierno | bee3bad | 2019-12-05 12:26:01 +0000 | [diff] [blame] | 425 | if isinstance(not_send_msg, list): |
| 426 | not_send_msg.append((self.topic_msg, action, content)) |
| 427 | else: |
| 428 | self.msg.write(self.topic_msg, action, content) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 429 | |
| tierno | b4844ab | 2019-05-23 08:42:12 +0000 | [diff] [blame] | 430 | def check_conflict_on_del(self, session, _id, db_content): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 431 | """ |
| 432 | Check if deletion can be done because of dependencies if it is not force. To override |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 433 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| 434 | :param _id: internal _id |
| tierno | b4844ab | 2019-05-23 08:42:12 +0000 | [diff] [blame] | 435 | :param db_content: The database content of this item _id |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 436 | :return: None if ok or raises EngineException with the conflict |
| 437 | """ |
| 438 | pass |
| 439 | |
| 440 | @staticmethod |
| tierno | 1c38f2f | 2020-03-24 11:51:39 +0000 | [diff] [blame] | 441 | def _update_input_with_kwargs(desc, kwargs, yaml_format=False): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 442 | """ |
| 443 | Update descriptor with the kwargs. It contains dot separated keys |
| 444 | :param desc: dictionary to be updated |
| 445 | :param kwargs: plain dictionary to be used for updating. |
| tierno | 1c38f2f | 2020-03-24 11:51:39 +0000 | [diff] [blame] | 446 | :param yaml_format: get kwargs values as yaml format. |
| delacruzramo | c061f56 | 2019-04-05 11:00:02 +0200 | [diff] [blame] | 447 | :return: None, 'desc' is modified. It raises EngineException. |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 448 | """ |
| 449 | if not kwargs: |
| 450 | return |
| 451 | try: |
| 452 | for k, v in kwargs.items(): |
| 453 | update_content = desc |
| 454 | kitem_old = None |
| 455 | klist = k.split(".") |
| 456 | for kitem in klist: |
| 457 | if kitem_old is not None: |
| 458 | update_content = update_content[kitem_old] |
| 459 | if isinstance(update_content, dict): |
| 460 | kitem_old = kitem |
| tierno | ac55f06 | 2020-06-17 07:42:30 +0000 | [diff] [blame] | 461 | if not isinstance(update_content.get(kitem_old), (dict, list)): |
| 462 | update_content[kitem_old] = {} |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 463 | elif isinstance(update_content, list): |
| tierno | ac55f06 | 2020-06-17 07:42:30 +0000 | [diff] [blame] | 464 | # key must be an index of the list, must be integer |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 465 | kitem_old = int(kitem) |
| tierno | ac55f06 | 2020-06-17 07:42:30 +0000 | [diff] [blame] | 466 | # if index greater than list, extend the list |
| 467 | if kitem_old >= len(update_content): |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 468 | update_content += [None] * ( |
| 469 | kitem_old - len(update_content) + 1 |
| 470 | ) |
| tierno | ac55f06 | 2020-06-17 07:42:30 +0000 | [diff] [blame] | 471 | if not isinstance(update_content[kitem_old], (dict, list)): |
| 472 | update_content[kitem_old] = {} |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 473 | else: |
| 474 | raise EngineException( |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 475 | "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format( |
| 476 | k, kitem |
| 477 | ) |
| 478 | ) |
| tierno | ac55f06 | 2020-06-17 07:42:30 +0000 | [diff] [blame] | 479 | if v is None: |
| 480 | del update_content[kitem_old] |
| 481 | else: |
| 482 | update_content[kitem_old] = v if not yaml_format else safe_load(v) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 483 | except KeyError: |
| 484 | raise EngineException( |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 485 | "Invalid query string '{}'. Descriptor does not contain '{}'".format( |
| 486 | k, kitem_old |
| 487 | ) |
| 488 | ) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 489 | except ValueError: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 490 | raise EngineException( |
| 491 | "Invalid query string '{}'. Expected integer index list instead of '{}'".format( |
| 492 | k, kitem |
| 493 | ) |
| 494 | ) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 495 | except IndexError: |
| 496 | raise EngineException( |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 497 | "Invalid query string '{}'. Index '{}' out of range".format( |
| 498 | k, kitem_old |
| 499 | ) |
| 500 | ) |
| tierno | 1c38f2f | 2020-03-24 11:51:39 +0000 | [diff] [blame] | 501 | except YAMLError: |
| 502 | raise EngineException("Invalid query string '{}' yaml format".format(k)) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 503 | |
| Frank Bryden | 19b9752 | 2020-07-10 12:32:02 +0000 | [diff] [blame] | 504 | def sol005_projection(self, data): |
| 505 | # Projection was moved to child classes |
| 506 | return data |
| 507 | |
| K Sai Kiran | 5758955 | 2021-01-27 21:38:34 +0530 | [diff] [blame] | 508 | def show(self, session, _id, filter_q=None, api_req=False): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 509 | """ |
| 510 | Get complete information on an topic |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 511 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 512 | :param _id: server internal id |
| K Sai Kiran | 5758955 | 2021-01-27 21:38:34 +0530 | [diff] [blame] | 513 | :param filter_q: dict: query parameter |
| Frank Bryden | 19b9752 | 2020-07-10 12:32:02 +0000 | [diff] [blame] | 514 | :param api_req: True if this call is serving an external API request. False if serving internal request. |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 515 | :return: dictionary, raise exception if not found. |
| 516 | """ |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 517 | if not self.multiproject: |
| 518 | filter_db = {} |
| 519 | else: |
| 520 | filter_db = self._get_project_filter(session) |
| delacruzramo | c061f56 | 2019-04-05 11:00:02 +0200 | [diff] [blame] | 521 | # To allow project&user addressing by name AS WELL AS _id |
| 522 | filter_db[BaseTopic.id_field(self.topic, _id)] = _id |
| Frank Bryden | 19b9752 | 2020-07-10 12:32:02 +0000 | [diff] [blame] | 523 | data = self.db.get_one(self.topic, filter_db) |
| 524 | |
| 525 | # Only perform SOL005 projection if we are serving an external request |
| 526 | if api_req: |
| 527 | self.sol005_projection(data) |
| 528 | |
| 529 | return data |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 530 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 531 | # TODO transform data for SOL005 URL requests |
| 532 | # TODO remove _admin if not admin |
| 533 | |
| 534 | def get_file(self, session, _id, path=None, accept_header=None): |
| 535 | """ |
| 536 | Only implemented for descriptor topics. Return the file content of a descriptor |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 537 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 538 | :param _id: Identity of the item to get content |
| 539 | :param path: artifact path or "$DESCRIPTOR" or None |
| 540 | :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain |
| 541 | :return: opened file or raises an exception |
| 542 | """ |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 543 | raise EngineException( |
| 544 | "Method get_file not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR |
| 545 | ) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 546 | |
| Frank Bryden | 19b9752 | 2020-07-10 12:32:02 +0000 | [diff] [blame] | 547 | def list(self, session, filter_q=None, api_req=False): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 548 | """ |
| 549 | Get a list of the topic that matches a filter |
| 550 | :param session: contains the used login username and working project |
| 551 | :param filter_q: filter of data to be applied |
| Frank Bryden | 19b9752 | 2020-07-10 12:32:02 +0000 | [diff] [blame] | 552 | :param api_req: True if this call is serving an external API request. False if serving internal request. |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 553 | :return: The list, it can be empty if no one match the filter. |
| 554 | """ |
| 555 | if not filter_q: |
| 556 | filter_q = {} |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 557 | if self.multiproject: |
| 558 | filter_q.update(self._get_project_filter(session)) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 559 | |
| 560 | # TODO transform data for SOL005 URL requests. Transform filtering |
| 561 | # TODO implement "field-type" query string SOL005 |
| Frank Bryden | 19b9752 | 2020-07-10 12:32:02 +0000 | [diff] [blame] | 562 | data = self.db.get_list(self.topic, filter_q) |
| 563 | |
| 564 | # Only perform SOL005 projection if we are serving an external request |
| 565 | if api_req: |
| 566 | data = [self.sol005_projection(inst) for inst in data] |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 567 | |
| Frank Bryden | 19b9752 | 2020-07-10 12:32:02 +0000 | [diff] [blame] | 568 | return data |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 569 | |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 570 | def new(self, rollback, session, indata=None, kwargs=None, headers=None): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 571 | """ |
| 572 | Creates a new entry into database. |
| 573 | :param rollback: list to append created items at database in case a rollback may to be done |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 574 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 575 | :param indata: data to be inserted |
| 576 | :param kwargs: used to override the indata descriptor |
| 577 | :param headers: http request headers |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 578 | :return: _id, op_id: |
| 579 | _id: identity of the inserted data. |
| 580 | op_id: operation id if this is asynchronous, None otherwise |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 581 | """ |
| 582 | try: |
| delacruzramo | 32bab47 | 2019-09-13 12:24:22 +0200 | [diff] [blame] | 583 | if self.multiproject: |
| 584 | self.check_quota(session) |
| 585 | |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 586 | content = self._remove_envelop(indata) |
| 587 | |
| 588 | # Override descriptor with query string kwargs |
| 589 | self._update_input_with_kwargs(content, kwargs) |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 590 | content = self._validate_input_new(content, force=session["force"]) |
| 591 | self.check_conflict_on_new(session, content) |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 592 | op_id = self.format_on_new( |
| 593 | content, project_id=session["project_id"], make_public=session["public"] |
| 594 | ) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 595 | _id = self.db.create(self.topic, content) |
| 596 | rollback.append({"topic": self.topic, "_id": _id}) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 597 | if op_id: |
| 598 | content["op_id"] = op_id |
| tierno | 15a1f68 | 2019-10-16 09:00:13 +0000 | [diff] [blame] | 599 | self._send_msg("created", content) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 600 | return _id, op_id |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 601 | except ValidationError as e: |
| 602 | raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY) |
| 603 | |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 604 | def upload_content(self, session, _id, indata, kwargs, headers): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 605 | """ |
| 606 | Only implemented for descriptor topics. Used for receiving content by chunks (with a transaction_id header |
| 607 | and/or gzip file. It will store and extract) |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 608 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 609 | :param _id : the database id of entry to be updated |
| 610 | :param indata: http body request |
| 611 | :param kwargs: user query string to override parameters. NOT USED |
| 612 | :param headers: http request headers |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 613 | :return: True package has is completely uploaded or False if partial content has been uplodaed. |
| 614 | Raise exception on error |
| 615 | """ |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 616 | raise EngineException( |
| 617 | "Method upload_content not valid for this topic", |
| 618 | HTTPStatus.INTERNAL_SERVER_ERROR, |
| 619 | ) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 620 | |
| 621 | def delete_list(self, session, filter_q=None): |
| 622 | """ |
| 623 | Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 624 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 625 | :param filter_q: filter of data to be applied |
| 626 | :return: The deleted list, it can be empty if no one match the filter. |
| 627 | """ |
| 628 | # TODO add admin to filter, validate rights |
| 629 | if not filter_q: |
| 630 | filter_q = {} |
| tierno | 1f029d8 | 2019-06-13 22:37:04 +0000 | [diff] [blame] | 631 | if self.multiproject: |
| 632 | filter_q.update(self._get_project_filter(session)) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 633 | return self.db.del_list(self.topic, filter_q) |
| 634 | |
| tierno | bee3bad | 2019-12-05 12:26:01 +0000 | [diff] [blame] | 635 | def delete_extra(self, session, _id, db_content, not_send_msg=None): |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 636 | """ |
| 637 | Delete other things apart from database entry of a item _id. |
| 638 | e.g.: other associated elements at database and other file system storage |
| 639 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| 640 | :param _id: server internal id |
| tierno | b4844ab | 2019-05-23 08:42:12 +0000 | [diff] [blame] | 641 | :param db_content: The database content of the _id. It is already deleted when reached this method, but the |
| 642 | content is needed in same cases |
| tierno | bee3bad | 2019-12-05 12:26:01 +0000 | [diff] [blame] | 643 | :param not_send_msg: To not send message (False) or store content (list) instead |
| tierno | b4844ab | 2019-05-23 08:42:12 +0000 | [diff] [blame] | 644 | :return: None if ok or raises EngineException with the problem |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 645 | """ |
| 646 | pass |
| 647 | |
| tierno | bee3bad | 2019-12-05 12:26:01 +0000 | [diff] [blame] | 648 | def delete(self, session, _id, dry_run=False, not_send_msg=None): |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 649 | """ |
| 650 | Delete item by its internal _id |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 651 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 652 | :param _id: server internal id |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 653 | :param dry_run: make checking but do not delete |
| tierno | bee3bad | 2019-12-05 12:26:01 +0000 | [diff] [blame] | 654 | :param not_send_msg: To not send message (False) or store content (list) instead |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 655 | :return: operation id (None if there is not operation), raise exception if error or not found, conflict, ... |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 656 | """ |
| tierno | b4844ab | 2019-05-23 08:42:12 +0000 | [diff] [blame] | 657 | # To allow addressing projects and users by name AS WELL AS by _id |
| tierno | f5f2e3f | 2020-03-23 14:42:10 +0000 | [diff] [blame] | 658 | if not self.multiproject: |
| 659 | filter_q = {} |
| 660 | else: |
| 661 | filter_q = self._get_project_filter(session) |
| 662 | filter_q[self.id_field(self.topic, _id)] = _id |
| tierno | b4844ab | 2019-05-23 08:42:12 +0000 | [diff] [blame] | 663 | item_content = self.db.get_one(self.topic, filter_q) |
| kayal2001 | f71c2e8 | 2024-06-25 15:26:24 +0530 | [diff] [blame^] | 664 | nsd_id = item_content.get("_id") |
| tierno | b4844ab | 2019-05-23 08:42:12 +0000 | [diff] [blame] | 665 | |
| tierno | b4844ab | 2019-05-23 08:42:12 +0000 | [diff] [blame] | 666 | self.check_conflict_on_del(session, _id, item_content) |
| kayal2001 | f71c2e8 | 2024-06-25 15:26:24 +0530 | [diff] [blame^] | 667 | |
| 668 | # While deteling ns descriptor associated ns config template should also get deleted. |
| 669 | if self.topic == "nsds": |
| 670 | ns_config_template_content = self.db.get_list( |
| 671 | "ns_config_template", {"nsdId": _id} |
| 672 | ) |
| 673 | for template_content in ns_config_template_content: |
| 674 | if template_content is not None: |
| 675 | if template_content.get("nsdId") == nsd_id: |
| 676 | ns_config_template_id = template_content.get("_id") |
| 677 | self.db.del_one("ns_config_template", {"nsdId": nsd_id}) |
| 678 | self.delete_extra( |
| 679 | session, |
| 680 | ns_config_template_id, |
| 681 | template_content, |
| 682 | not_send_msg=not_send_msg, |
| 683 | ) |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 684 | if dry_run: |
| 685 | return None |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 686 | |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 687 | if self.multiproject and session["project_id"]: |
| tierno | f5f2e3f | 2020-03-23 14:42:10 +0000 | [diff] [blame] | 688 | # remove reference from project_read if there are more projects referencing it. If it last one, |
| 689 | # do not remove reference, but delete |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 690 | other_projects_referencing = next( |
| 691 | ( |
| 692 | p |
| 693 | for p in item_content["_admin"]["projects_read"] |
| 694 | if p not in session["project_id"] and p != "ANY" |
| 695 | ), |
| 696 | None, |
| 697 | ) |
| tierno | f5f2e3f | 2020-03-23 14:42:10 +0000 | [diff] [blame] | 698 | |
| 699 | # check if there are projects referencing it (apart from ANY, that means, public).... |
| 700 | if other_projects_referencing: |
| 701 | # remove references but not delete |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 702 | update_dict_pull = { |
| 703 | "_admin.projects_read": session["project_id"], |
| 704 | "_admin.projects_write": session["project_id"], |
| 705 | } |
| 706 | self.db.set_one( |
| 707 | self.topic, filter_q, update_dict=None, pull_list=update_dict_pull |
| 708 | ) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 709 | return None |
| tierno | f5f2e3f | 2020-03-23 14:42:10 +0000 | [diff] [blame] | 710 | else: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 711 | can_write = next( |
| 712 | ( |
| 713 | p |
| 714 | for p in item_content["_admin"]["projects_write"] |
| 715 | if p == "ANY" or p in session["project_id"] |
| 716 | ), |
| 717 | None, |
| 718 | ) |
| tierno | f5f2e3f | 2020-03-23 14:42:10 +0000 | [diff] [blame] | 719 | if not can_write: |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 720 | raise EngineException( |
| 721 | "You have not write permission to delete it", |
| 722 | http_code=HTTPStatus.UNAUTHORIZED, |
| 723 | ) |
| tierno | f5f2e3f | 2020-03-23 14:42:10 +0000 | [diff] [blame] | 724 | |
| 725 | # delete |
| 726 | self.db.del_one(self.topic, filter_q) |
| tierno | bee3bad | 2019-12-05 12:26:01 +0000 | [diff] [blame] | 727 | self.delete_extra(session, _id, item_content, not_send_msg=not_send_msg) |
| 728 | self._send_msg("deleted", {"_id": _id}, not_send_msg=not_send_msg) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 729 | return None |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 730 | |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 731 | def edit(self, session, _id, indata=None, kwargs=None, content=None): |
| 732 | """ |
| 733 | Change the content of an item |
| 734 | :param session: contains "username", "admin", "force", "public", "project_id", "set_project" |
| 735 | :param _id: server internal id |
| 736 | :param indata: contains the changes to apply |
| 737 | :param kwargs: modifies indata |
| 738 | :param content: original content of the item |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 739 | :return: op_id: operation id if this is processed asynchronously, None otherwise |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 740 | """ |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 741 | indata = self._remove_envelop(indata) |
| 742 | |
| 743 | # Override descriptor with query string kwargs |
| 744 | if kwargs: |
| 745 | self._update_input_with_kwargs(indata, kwargs) |
| 746 | try: |
| tierno | 65ca36d | 2019-02-12 19:27:52 +0100 | [diff] [blame] | 747 | if indata and session.get("set_project"): |
| garciadeblas | 4568a37 | 2021-03-24 09:19:48 +0100 | [diff] [blame] | 748 | raise EngineException( |
| 749 | "Cannot edit content and set to project (query string SET_PROJECT) at same time", |
| 750 | HTTPStatus.UNPROCESSABLE_ENTITY, |
| 751 | ) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 752 | # TODO self._check_edition(session, indata, _id, force) |
| 753 | if not content: |
| 754 | content = self.show(session, _id) |
| Frank Bryden | deba68e | 2020-07-27 13:55:11 +0000 | [diff] [blame] | 755 | indata = self._validate_input_edit(indata, content, force=session["force"]) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 756 | deep_update_rfc7396(content, indata) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 757 | |
| 758 | # To allow project addressing by name AS WELL AS _id. Get the _id, just in case the provided one is a name |
| 759 | _id = content.get("_id") or _id |
| 760 | |
| bravof | b995ea2 | 2021-02-10 10:57:52 -0300 | [diff] [blame] | 761 | content = self.check_conflict_on_edit(session, content, indata, _id=_id) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 762 | op_id = self.format_on_edit(content, indata) |
| 763 | |
| 764 | self.db.replace(self.topic, _id, content) |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 765 | |
| 766 | indata.pop("_admin", None) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 767 | if op_id: |
| 768 | indata["op_id"] = op_id |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 769 | indata["_id"] = _id |
| tierno | 15a1f68 | 2019-10-16 09:00:13 +0000 | [diff] [blame] | 770 | self._send_msg("edited", indata) |
| tierno | bdebce9 | 2019-07-01 15:36:49 +0000 | [diff] [blame] | 771 | return op_id |
| tierno | b24258a | 2018-10-04 18:39:49 +0200 | [diff] [blame] | 772 | except ValidationError as e: |
| 773 | raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY) |