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
, db_content
):
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 :param db_content: The database content of this item _id
243 :return: None if ok or raises EngineException with the conflict
248 def _update_input_with_kwargs(desc
, kwargs
):
250 Update descriptor with the kwargs. It contains dot separated keys
251 :param desc: dictionary to be updated
252 :param kwargs: plain dictionary to be used for updating.
253 :return: None, 'desc' is modified. It raises EngineException.
258 for k
, v
in kwargs
.items():
259 update_content
= desc
263 if kitem_old
is not None:
264 update_content
= update_content
[kitem_old
]
265 if isinstance(update_content
, dict):
267 elif isinstance(update_content
, list):
268 kitem_old
= int(kitem
)
270 raise EngineException(
271 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k
, kitem
))
272 update_content
[kitem_old
] = v
274 raise EngineException(
275 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k
, kitem_old
))
277 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
280 raise EngineException(
281 "Invalid query string '{}'. Index '{}' out of range".format(k
, kitem_old
))
283 def show(self
, session
, _id
):
285 Get complete information on an topic
286 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
287 :param _id: server internal id
288 :return: dictionary, raise exception if not found.
290 filter_db
= self
._get
_project
_filter
(session
)
291 # To allow project&user addressing by name AS WELL AS _id
292 filter_db
[BaseTopic
.id_field(self
.topic
, _id
)] = _id
293 return self
.db
.get_one(self
.topic
, filter_db
)
294 # TODO transform data for SOL005 URL requests
295 # TODO remove _admin if not admin
297 def get_file(self
, session
, _id
, path
=None, accept_header
=None):
299 Only implemented for descriptor topics. Return the file content of a descriptor
300 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
301 :param _id: Identity of the item to get content
302 :param path: artifact path or "$DESCRIPTOR" or None
303 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
304 :return: opened file or raises an exception
306 raise EngineException("Method get_file not valid for this topic", HTTPStatus
.INTERNAL_SERVER_ERROR
)
308 def list(self
, session
, filter_q
=None):
310 Get a list of the topic that matches a filter
311 :param session: contains the used login username and working project
312 :param filter_q: filter of data to be applied
313 :return: The list, it can be empty if no one match the filter.
318 filter_q
.update(self
._get
_project
_filter
(session
))
320 # TODO transform data for SOL005 URL requests. Transform filtering
321 # TODO implement "field-type" query string SOL005
322 return self
.db
.get_list(self
.topic
, filter_q
)
324 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
326 Creates a new entry into database.
327 :param rollback: list to append created items at database in case a rollback may to be done
328 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
329 :param indata: data to be inserted
330 :param kwargs: used to override the indata descriptor
331 :param headers: http request headers
332 :return: _id: identity of the inserted data.
335 content
= self
._remove
_envelop
(indata
)
337 # Override descriptor with query string kwargs
338 self
._update
_input
_with
_kwargs
(content
, kwargs
)
339 content
= self
._validate
_input
_new
(content
, force
=session
["force"])
340 self
.check_conflict_on_new(session
, content
)
341 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
342 _id
= self
.db
.create(self
.topic
, content
)
343 rollback
.append({"topic": self
.topic
, "_id": _id
})
344 self
._send
_msg
("create", content
)
346 except ValidationError
as e
:
347 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
349 def upload_content(self
, session
, _id
, indata
, kwargs
, headers
):
351 Only implemented for descriptor topics. Used for receiving content by chunks (with a transaction_id header
352 and/or gzip file. It will store and extract)
353 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
354 :param _id : the database id of entry to be updated
355 :param indata: http body request
356 :param kwargs: user query string to override parameters. NOT USED
357 :param headers: http request headers
358 :return: True package has is completely uploaded or False if partial content has been uplodaed.
359 Raise exception on error
361 raise EngineException("Method upload_content not valid for this topic", HTTPStatus
.INTERNAL_SERVER_ERROR
)
363 def delete_list(self
, session
, filter_q
=None):
365 Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API
366 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
367 :param filter_q: filter of data to be applied
368 :return: The deleted list, it can be empty if no one match the filter.
370 # TODO add admin to filter, validate rights
373 filter_q
.update(self
._get
_project
_filter
(session
))
374 return self
.db
.del_list(self
.topic
, filter_q
)
376 def delete_extra(self
, session
, _id
, db_content
):
378 Delete other things apart from database entry of a item _id.
379 e.g.: other associated elements at database and other file system storage
380 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
381 :param _id: server internal id
382 :param db_content: The database content of the _id. It is already deleted when reached this method, but the
383 content is needed in same cases
384 :return: None if ok or raises EngineException with the problem
388 def delete(self
, session
, _id
, dry_run
=False):
390 Delete item by its internal _id
391 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
392 :param _id: server internal id
393 :param dry_run: make checking but do not delete
394 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
397 # To allow addressing projects and users by name AS WELL AS by _id
398 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
399 item_content
= self
.db
.get_one(self
.topic
, filter_q
)
401 # TODO add admin to filter, validate rights
402 # data = self.get_item(topic, _id)
403 self
.check_conflict_on_del(session
, _id
, item_content
)
407 filter_q
.update(self
._get
_project
_filter
(session
))
408 if self
.multiproject
and session
["project_id"]:
409 # remove reference from project_read. If not last delete
410 self
.db
.set_one(self
.topic
, filter_q
, update_dict
=None,
411 pull
={"_admin.projects_read": {"$in": session
["project_id"]}})
412 # try to delete if there is not any more reference from projects. Ignore if it is not deleted
413 filter_q
= {'_id': _id
, '_admin.projects_read': [[], ["ANY"]]}
414 v
= self
.db
.del_one(self
.topic
, filter_q
, fail_on_empty
=False)
415 if not v
or not v
["deleted"]:
418 v
= self
.db
.del_one(self
.topic
, filter_q
)
419 self
.delete_extra(session
, _id
, item_content
)
420 self
._send
_msg
("deleted", {"_id": _id
})
423 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
425 Change the content of an item
426 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
427 :param _id: server internal id
428 :param indata: contains the changes to apply
429 :param kwargs: modifies indata
430 :param content: original content of the item
433 indata
= self
._remove
_envelop
(indata
)
435 # Override descriptor with query string kwargs
437 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
439 if indata
and session
.get("set_project"):
440 raise EngineException("Cannot edit content and set to project (query string SET_PROJECT) at same time",
441 HTTPStatus
.UNPROCESSABLE_ENTITY
)
442 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
444 # TODO self._check_edition(session, indata, _id, force)
446 content
= self
.show(session
, _id
)
447 deep_update_rfc7396(content
, indata
)
448 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
449 self
.format_on_edit(content
, indata
)
450 # To allow project addressing by name AS WELL AS _id
451 # self.db.replace(self.topic, _id, content)
452 cid
= content
.get("_id")
453 self
.db
.replace(self
.topic
, cid
if cid
else _id
, content
)
455 indata
.pop("_admin", None)
457 self
._send
_msg
("edit", indata
)
459 except ValidationError
as e
:
460 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)