1 # -*- coding: utf-8 -*-
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 from uuid
import uuid4
18 from http
import HTTPStatus
20 from osm_common
.dbbase
import deep_update_rfc7396
21 from validation
import validate_input
, ValidationError
, is_valid_uuid
23 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
26 class EngineException(Exception):
28 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
29 self
.http_code
= http_code
30 Exception.__init
__(self
, message
)
33 def get_iterable(input_var
):
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
45 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
47 for point
in v
.split("."):
48 filled
.append(point
.zfill(8))
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
60 # Alternative ID Fields for some Topics
66 def __init__(self
, db
, fs
, msg
):
70 self
.logger
= logging
.getLogger("nbi.engine")
73 def id_field(topic
, value
):
74 """Returns ID Field for given topic and field value"""
75 if topic
in ["projects", "users"] and not is_valid_uuid(value
):
76 return BaseTopic
.alt_id_field
[topic
]
81 def _remove_envelop(indata
=None):
86 def _validate_input_new(self
, input, force
=False):
88 Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind
89 :param input: user input content for the new topic
90 :param force: may be used for being more tolerant
91 :return: The same input content, or a changed version of it.
94 validate_input(input, self
.schema_new
)
97 def _validate_input_edit(self
, input, force
=False):
99 Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
100 :param input: user input content for the new topic
101 :param force: may be used for being more tolerant
102 :return: The same input content, or a changed version of it.
105 validate_input(input, self
.schema_edit
)
109 def _get_project_filter(session
):
111 Generates a filter dictionary for querying database, so that only allowed items for this project can be
112 addressed. Only propietary or public can be used. Allowed projects are at _admin.project_read/write. If it is
113 not present or contains ANY mean public.
114 :param session: contains:
115 project_id: project list this session has rights to access. Can be empty, one or several
116 set_project: items created will contain this project list
118 public: True, False or None
119 method: "list", "show", "write", "delete"
121 :return: dictionary with project filter
124 project_filter_n
= []
125 project_filter
= list(session
["project_id"])
127 if session
["method"] not in ("list", "delete"):
129 project_filter
.append("ANY")
130 elif session
["public"] is not None:
131 if session
["public"]:
132 project_filter
.append("ANY")
134 project_filter_n
.append("ANY")
136 if session
.get("PROJECT.ne"):
137 project_filter_n
.append(session
["PROJECT.ne"])
140 if session
["method"] in ("list", "show", "delete") or session
.get("set_project"):
141 p_filter
["_admin.projects_read.cont"] = project_filter
143 p_filter
["_admin.projects_write.cont"] = project_filter
145 if session
["method"] in ("list", "show", "delete") or session
.get("set_project"):
146 p_filter
["_admin.projects_read.ncont"] = project_filter_n
148 p_filter
["_admin.projects_write.ncont"] = project_filter_n
152 def check_conflict_on_new(self
, session
, indata
):
154 Check that the data to be inserted is valid
155 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
156 :param indata: data to be inserted
157 :return: None or raises EngineException
161 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
163 Check that the data to be edited/uploaded is valid
164 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
165 :param final_content: data once modified. This methdo may change it.
166 :param edit_content: incremental data that contains the modifications to apply
167 :param _id: internal _id
168 :return: None or raises EngineException
170 if not self
.multiproject
:
172 # Change public status
173 if session
["public"] is not None:
174 if session
["public"] and "ANY" not in final_content
["_admin"]["projects_read"]:
175 final_content
["_admin"]["projects_read"].append("ANY")
176 final_content
["_admin"]["projects_write"].clear()
177 if not session
["public"] and "ANY" in final_content
["_admin"]["projects_read"]:
178 final_content
["_admin"]["projects_read"].remove("ANY")
180 # Change project status
181 if session
.get("set_project"):
182 for p
in session
["set_project"]:
183 if p
not in final_content
["_admin"]["projects_read"]:
184 final_content
["_admin"]["projects_read"].append(p
)
186 def check_unique_name(self
, session
, name
, _id
=None):
188 Check that the name is unique for this project
189 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
190 :param name: name to be checked
191 :param _id: If not None, ignore this entry that are going to change
192 :return: None or raises EngineException
194 _filter
= self
._get
_project
_filter
(session
)
195 _filter
["name"] = name
197 _filter
["_id.neq"] = _id
198 if self
.db
.get_one(self
.topic
, _filter
, fail_on_empty
=False, fail_on_more
=False):
199 raise EngineException("name '{}' already exists for {}".format(name
, self
.topic
), HTTPStatus
.CONFLICT
)
202 def format_on_new(content
, project_id
=None, make_public
=False):
204 Modifies content descriptor to include _admin
205 :param content: descriptor to be modified
206 :param project_id: if included, it add project read/write permissions. Can be None or a list
207 :param make_public: if included it is generated as public for reading.
208 :return: None, but content is modified
211 if "_admin" not in content
:
212 content
["_admin"] = {}
213 if not content
["_admin"].get("created"):
214 content
["_admin"]["created"] = now
215 content
["_admin"]["modified"] = now
216 if not content
.get("_id"):
217 content
["_id"] = str(uuid4())
218 if project_id
is not None:
219 if not content
["_admin"].get("projects_read"):
220 content
["_admin"]["projects_read"] = list(project_id
)
222 content
["_admin"]["projects_read"].append("ANY")
223 if not content
["_admin"].get("projects_write"):
224 content
["_admin"]["projects_write"] = list(project_id
)
227 def format_on_edit(final_content
, edit_content
):
228 if final_content
.get("_admin"):
230 final_content
["_admin"]["modified"] = now
232 def _send_msg(self
, action
, content
):
234 content
.pop("_admin", None)
235 self
.msg
.write(self
.topic_msg
, action
, content
)
237 def check_conflict_on_del(self
, session
, _id
):
239 Check if deletion can be done because of dependencies if it is not force. To override
240 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
241 :param _id: internal _id
242 :return: None if ok or raises EngineException with the conflict
247 def _update_input_with_kwargs(desc
, kwargs
):
249 Update descriptor with the kwargs. It contains dot separated keys
250 :param desc: dictionary to be updated
251 :param kwargs: plain dictionary to be used for updating.
252 :return: None, 'desc' is modified. It raises EngineException.
257 for k
, v
in kwargs
.items():
258 update_content
= desc
262 if kitem_old
is not None:
263 update_content
= update_content
[kitem_old
]
264 if isinstance(update_content
, dict):
266 elif isinstance(update_content
, list):
267 kitem_old
= int(kitem
)
269 raise EngineException(
270 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k
, kitem
))
271 update_content
[kitem_old
] = v
273 raise EngineException(
274 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k
, kitem_old
))
276 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
279 raise EngineException(
280 "Invalid query string '{}'. Index '{}' out of range".format(k
, kitem_old
))
282 def show(self
, session
, _id
):
284 Get complete information on an topic
285 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
286 :param _id: server internal id
287 :return: dictionary, raise exception if not found.
289 filter_db
= self
._get
_project
_filter
(session
)
290 # To allow project&user addressing by name AS WELL AS _id
291 filter_db
[BaseTopic
.id_field(self
.topic
, _id
)] = _id
292 return self
.db
.get_one(self
.topic
, filter_db
)
293 # TODO transform data for SOL005 URL requests
294 # TODO remove _admin if not admin
296 def get_file(self
, session
, _id
, path
=None, accept_header
=None):
298 Only implemented for descriptor topics. Return the file content of a descriptor
299 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
300 :param _id: Identity of the item to get content
301 :param path: artifact path or "$DESCRIPTOR" or None
302 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
303 :return: opened file or raises an exception
305 raise EngineException("Method get_file not valid for this topic", HTTPStatus
.INTERNAL_SERVER_ERROR
)
307 def list(self
, session
, filter_q
=None):
309 Get a list of the topic that matches a filter
310 :param session: contains the used login username and working project
311 :param filter_q: filter of data to be applied
312 :return: The list, it can be empty if no one match the filter.
317 filter_q
.update(self
._get
_project
_filter
(session
))
319 # TODO transform data for SOL005 URL requests. Transform filtering
320 # TODO implement "field-type" query string SOL005
321 return self
.db
.get_list(self
.topic
, filter_q
)
323 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
325 Creates a new entry into database.
326 :param rollback: list to append created items at database in case a rollback may to be done
327 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
328 :param indata: data to be inserted
329 :param kwargs: used to override the indata descriptor
330 :param headers: http request headers
331 :return: _id: identity of the inserted data.
334 content
= self
._remove
_envelop
(indata
)
336 # Override descriptor with query string kwargs
337 self
._update
_input
_with
_kwargs
(content
, kwargs
)
338 content
= self
._validate
_input
_new
(content
, force
=session
["force"])
339 self
.check_conflict_on_new(session
, content
)
340 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
341 _id
= self
.db
.create(self
.topic
, content
)
342 rollback
.append({"topic": self
.topic
, "_id": _id
})
343 self
._send
_msg
("create", content
)
345 except ValidationError
as e
:
346 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
348 def upload_content(self
, session
, _id
, indata
, kwargs
, headers
):
350 Only implemented for descriptor topics. Used for receiving content by chunks (with a transaction_id header
351 and/or gzip file. It will store and extract)
352 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
353 :param _id : the database id of entry to be updated
354 :param indata: http body request
355 :param kwargs: user query string to override parameters. NOT USED
356 :param headers: http request headers
357 :return: True package has is completely uploaded or False if partial content has been uplodaed.
358 Raise exception on error
360 raise EngineException("Method upload_content not valid for this topic", HTTPStatus
.INTERNAL_SERVER_ERROR
)
362 def delete_list(self
, session
, filter_q
=None):
364 Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API
365 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
366 :param filter_q: filter of data to be applied
367 :return: The deleted list, it can be empty if no one match the filter.
369 # TODO add admin to filter, validate rights
372 filter_q
.update(self
._get
_project
_filter
(session
))
373 return self
.db
.del_list(self
.topic
, filter_q
)
375 def delete_extra(self
, session
, _id
):
377 Delete other things apart from database entry of a item _id.
378 e.g.: other associated elements at database and other file system storage
379 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
380 :param _id: server internal id
384 def delete(self
, session
, _id
, dry_run
=False):
386 Delete item by its internal _id
387 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
388 :param _id: server internal id
389 :param dry_run: make checking but do not delete
390 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
392 # TODO add admin to filter, validate rights
393 # data = self.get_item(topic, _id)
394 self
.check_conflict_on_del(session
, _id
)
395 filter_q
= self
._get
_project
_filter
(session
)
396 # To allow project addressing by name AS WELL AS _id
397 filter_q
[BaseTopic
.id_field(self
.topic
, _id
)] = _id
400 if self
.multiproject
and session
["project_id"]:
401 # remove reference from project_read. If not last delete
402 self
.db
.set_one(self
.topic
, filter_q
, update_dict
=None,
403 pull
={"_admin.projects_read": {"$in": session
["project_id"]}})
404 # try to delete if there is not any more reference from projects. Ignore if it is not deleted
405 filter_q
= {'_id': _id
, '_admin.projects_read': [[], ["ANY"]]}
406 v
= self
.db
.del_one(self
.topic
, filter_q
, fail_on_empty
=False)
407 if not v
or not v
["deleted"]:
410 v
= self
.db
.del_one(self
.topic
, filter_q
)
411 self
.delete_extra(session
, _id
)
412 self
._send
_msg
("deleted", {"_id": _id
})
415 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
417 Change the content of an item
418 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
419 :param _id: server internal id
420 :param indata: contains the changes to apply
421 :param kwargs: modifies indata
422 :param content: original content of the item
425 indata
= self
._remove
_envelop
(indata
)
427 # Override descriptor with query string kwargs
429 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
431 if indata
and session
.get("set_project"):
432 raise EngineException("Cannot edit content and set to project (query string SET_PROJECT) at same time",
433 HTTPStatus
.UNPROCESSABLE_ENTITY
)
434 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
436 # TODO self._check_edition(session, indata, _id, force)
438 content
= self
.show(session
, _id
)
439 deep_update_rfc7396(content
, indata
)
440 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
441 self
.format_on_edit(content
, indata
)
442 # To allow project addressing by name AS WELL AS _id
443 # self.db.replace(self.topic, _id, content)
444 cid
= content
.get("_id")
445 self
.db
.replace(self
.topic
, cid
if cid
else _id
, content
)
447 indata
.pop("_admin", None)
449 self
._send
_msg
("edit", indata
)
451 except ValidationError
as e
:
452 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)