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
65 "roles_operations": "name"
68 def __init__(self
, db
, fs
, msg
):
72 self
.logger
= logging
.getLogger("nbi.engine")
75 def id_field(topic
, value
):
76 """Returns ID Field for given topic and field value"""
77 if topic
in BaseTopic
.alt_id_field
.keys() and not is_valid_uuid(value
):
78 return BaseTopic
.alt_id_field
[topic
]
83 def _remove_envelop(indata
=None):
88 def _validate_input_new(self
, input, force
=False):
90 Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind
91 :param input: user input content for the new topic
92 :param force: may be used for being more tolerant
93 :return: The same input content, or a changed version of it.
96 validate_input(input, self
.schema_new
)
99 def _validate_input_edit(self
, input, force
=False):
101 Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
102 :param input: user input content for the new topic
103 :param force: may be used for being more tolerant
104 :return: The same input content, or a changed version of it.
107 validate_input(input, self
.schema_edit
)
111 def _get_project_filter(session
):
113 Generates a filter dictionary for querying database, so that only allowed items for this project can be
114 addressed. Only propietary or public can be used. Allowed projects are at _admin.project_read/write. If it is
115 not present or contains ANY mean public.
116 :param session: contains:
117 project_id: project list this session has rights to access. Can be empty, one or several
118 set_project: items created will contain this project list
120 public: True, False or None
121 method: "list", "show", "write", "delete"
123 :return: dictionary with project filter
126 project_filter_n
= []
127 project_filter
= list(session
["project_id"])
129 if session
["method"] not in ("list", "delete"):
131 project_filter
.append("ANY")
132 elif session
["public"] is not None:
133 if session
["public"]:
134 project_filter
.append("ANY")
136 project_filter_n
.append("ANY")
138 if session
.get("PROJECT.ne"):
139 project_filter_n
.append(session
["PROJECT.ne"])
142 if session
["method"] in ("list", "show", "delete") or session
.get("set_project"):
143 p_filter
["_admin.projects_read.cont"] = project_filter
145 p_filter
["_admin.projects_write.cont"] = project_filter
147 if session
["method"] in ("list", "show", "delete") or session
.get("set_project"):
148 p_filter
["_admin.projects_read.ncont"] = project_filter_n
150 p_filter
["_admin.projects_write.ncont"] = project_filter_n
154 def check_conflict_on_new(self
, session
, indata
):
156 Check that the data to be inserted is valid
157 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
158 :param indata: data to be inserted
159 :return: None or raises EngineException
163 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
165 Check that the data to be edited/uploaded is valid
166 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
167 :param final_content: data once modified. This methdo may change it.
168 :param edit_content: incremental data that contains the modifications to apply
169 :param _id: internal _id
170 :return: None or raises EngineException
172 if not self
.multiproject
:
174 # Change public status
175 if session
["public"] is not None:
176 if session
["public"] and "ANY" not in final_content
["_admin"]["projects_read"]:
177 final_content
["_admin"]["projects_read"].append("ANY")
178 final_content
["_admin"]["projects_write"].clear()
179 if not session
["public"] and "ANY" in final_content
["_admin"]["projects_read"]:
180 final_content
["_admin"]["projects_read"].remove("ANY")
182 # Change project status
183 if session
.get("set_project"):
184 for p
in session
["set_project"]:
185 if p
not in final_content
["_admin"]["projects_read"]:
186 final_content
["_admin"]["projects_read"].append(p
)
188 def check_unique_name(self
, session
, name
, _id
=None):
190 Check that the name is unique for this project
191 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
192 :param name: name to be checked
193 :param _id: If not None, ignore this entry that are going to change
194 :return: None or raises EngineException
196 if not self
.multiproject
:
199 _filter
= self
._get
_project
_filter
(session
)
200 _filter
["name"] = name
202 _filter
["_id.neq"] = _id
203 if self
.db
.get_one(self
.topic
, _filter
, fail_on_empty
=False, fail_on_more
=False):
204 raise EngineException("name '{}' already exists for {}".format(name
, self
.topic
), HTTPStatus
.CONFLICT
)
207 def format_on_new(content
, project_id
=None, make_public
=False):
209 Modifies content descriptor to include _admin
210 :param content: descriptor to be modified
211 :param project_id: if included, it add project read/write permissions. Can be None or a list
212 :param make_public: if included it is generated as public for reading.
213 :return: None, but content is modified
216 if "_admin" not in content
:
217 content
["_admin"] = {}
218 if not content
["_admin"].get("created"):
219 content
["_admin"]["created"] = now
220 content
["_admin"]["modified"] = now
221 if not content
.get("_id"):
222 content
["_id"] = str(uuid4())
223 if project_id
is not None:
224 if not content
["_admin"].get("projects_read"):
225 content
["_admin"]["projects_read"] = list(project_id
)
227 content
["_admin"]["projects_read"].append("ANY")
228 if not content
["_admin"].get("projects_write"):
229 content
["_admin"]["projects_write"] = list(project_id
)
232 def format_on_edit(final_content
, edit_content
):
233 if final_content
.get("_admin"):
235 final_content
["_admin"]["modified"] = now
237 def _send_msg(self
, action
, content
):
239 content
.pop("_admin", None)
240 self
.msg
.write(self
.topic_msg
, action
, content
)
242 def check_conflict_on_del(self
, session
, _id
, db_content
):
244 Check if deletion can be done because of dependencies if it is not force. To override
245 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
246 :param _id: internal _id
247 :param db_content: The database content of this item _id
248 :return: None if ok or raises EngineException with the conflict
253 def _update_input_with_kwargs(desc
, kwargs
):
255 Update descriptor with the kwargs. It contains dot separated keys
256 :param desc: dictionary to be updated
257 :param kwargs: plain dictionary to be used for updating.
258 :return: None, 'desc' is modified. It raises EngineException.
263 for k
, v
in kwargs
.items():
264 update_content
= desc
268 if kitem_old
is not None:
269 update_content
= update_content
[kitem_old
]
270 if isinstance(update_content
, dict):
272 elif isinstance(update_content
, list):
273 kitem_old
= int(kitem
)
275 raise EngineException(
276 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k
, kitem
))
277 update_content
[kitem_old
] = v
279 raise EngineException(
280 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k
, kitem_old
))
282 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
285 raise EngineException(
286 "Invalid query string '{}'. Index '{}' out of range".format(k
, kitem_old
))
288 def show(self
, session
, _id
):
290 Get complete information on an topic
291 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
292 :param _id: server internal id
293 :return: dictionary, raise exception if not found.
295 if not self
.multiproject
:
298 filter_db
= self
._get
_project
_filter
(session
)
299 # To allow project&user addressing by name AS WELL AS _id
300 filter_db
[BaseTopic
.id_field(self
.topic
, _id
)] = _id
301 return self
.db
.get_one(self
.topic
, filter_db
)
302 # TODO transform data for SOL005 URL requests
303 # TODO remove _admin if not admin
305 def get_file(self
, session
, _id
, path
=None, accept_header
=None):
307 Only implemented for descriptor topics. Return the file content of a descriptor
308 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
309 :param _id: Identity of the item to get content
310 :param path: artifact path or "$DESCRIPTOR" or None
311 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
312 :return: opened file or raises an exception
314 raise EngineException("Method get_file not valid for this topic", HTTPStatus
.INTERNAL_SERVER_ERROR
)
316 def list(self
, session
, filter_q
=None):
318 Get a list of the topic that matches a filter
319 :param session: contains the used login username and working project
320 :param filter_q: filter of data to be applied
321 :return: The list, it can be empty if no one match the filter.
325 if self
.multiproject
:
326 filter_q
.update(self
._get
_project
_filter
(session
))
328 # TODO transform data for SOL005 URL requests. Transform filtering
329 # TODO implement "field-type" query string SOL005
330 return self
.db
.get_list(self
.topic
, filter_q
)
332 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
334 Creates a new entry into database.
335 :param rollback: list to append created items at database in case a rollback may to be done
336 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
337 :param indata: data to be inserted
338 :param kwargs: used to override the indata descriptor
339 :param headers: http request headers
340 :return: _id: identity of the inserted data.
343 content
= self
._remove
_envelop
(indata
)
345 # Override descriptor with query string kwargs
346 self
._update
_input
_with
_kwargs
(content
, kwargs
)
347 content
= self
._validate
_input
_new
(content
, force
=session
["force"])
348 self
.check_conflict_on_new(session
, content
)
349 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
350 _id
= self
.db
.create(self
.topic
, content
)
351 rollback
.append({"topic": self
.topic
, "_id": _id
})
352 self
._send
_msg
("create", content
)
354 except ValidationError
as e
:
355 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
357 def upload_content(self
, session
, _id
, indata
, kwargs
, headers
):
359 Only implemented for descriptor topics. Used for receiving content by chunks (with a transaction_id header
360 and/or gzip file. It will store and extract)
361 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
362 :param _id : the database id of entry to be updated
363 :param indata: http body request
364 :param kwargs: user query string to override parameters. NOT USED
365 :param headers: http request headers
366 :return: True package has is completely uploaded or False if partial content has been uplodaed.
367 Raise exception on error
369 raise EngineException("Method upload_content not valid for this topic", HTTPStatus
.INTERNAL_SERVER_ERROR
)
371 def delete_list(self
, session
, filter_q
=None):
373 Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API
374 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
375 :param filter_q: filter of data to be applied
376 :return: The deleted list, it can be empty if no one match the filter.
378 # TODO add admin to filter, validate rights
381 if self
.multiproject
:
382 filter_q
.update(self
._get
_project
_filter
(session
))
383 return self
.db
.del_list(self
.topic
, filter_q
)
385 def delete_extra(self
, session
, _id
, db_content
):
387 Delete other things apart from database entry of a item _id.
388 e.g.: other associated elements at database and other file system storage
389 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
390 :param _id: server internal id
391 :param db_content: The database content of the _id. It is already deleted when reached this method, but the
392 content is needed in same cases
393 :return: None if ok or raises EngineException with the problem
397 def delete(self
, session
, _id
, dry_run
=False):
399 Delete item by its internal _id
400 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
401 :param _id: server internal id
402 :param dry_run: make checking but do not delete
403 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
406 # To allow addressing projects and users by name AS WELL AS by _id
407 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
408 item_content
= self
.db
.get_one(self
.topic
, filter_q
)
410 # TODO add admin to filter, validate rights
411 # data = self.get_item(topic, _id)
412 self
.check_conflict_on_del(session
, _id
, item_content
)
416 if self
.multiproject
:
417 filter_q
.update(self
._get
_project
_filter
(session
))
418 if self
.multiproject
and session
["project_id"]:
419 # remove reference from project_read. If not last delete
420 self
.db
.set_one(self
.topic
, filter_q
, update_dict
=None,
421 pull
={"_admin.projects_read": {"$in": session
["project_id"]}})
422 # try to delete if there is not any more reference from projects. Ignore if it is not deleted
423 filter_q
= {'_id': _id
, '_admin.projects_read': [[], ["ANY"]]}
424 v
= self
.db
.del_one(self
.topic
, filter_q
, fail_on_empty
=False)
425 if not v
or not v
["deleted"]:
428 v
= self
.db
.del_one(self
.topic
, filter_q
)
429 self
.delete_extra(session
, _id
, item_content
)
430 self
._send
_msg
("deleted", {"_id": _id
})
433 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
435 Change the content of an item
436 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
437 :param _id: server internal id
438 :param indata: contains the changes to apply
439 :param kwargs: modifies indata
440 :param content: original content of the item
443 indata
= self
._remove
_envelop
(indata
)
445 # Override descriptor with query string kwargs
447 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
449 if indata
and session
.get("set_project"):
450 raise EngineException("Cannot edit content and set to project (query string SET_PROJECT) at same time",
451 HTTPStatus
.UNPROCESSABLE_ENTITY
)
452 indata
= self
._validate
_input
_edit
(indata
, force
=session
["force"])
454 # TODO self._check_edition(session, indata, _id, force)
456 content
= self
.show(session
, _id
)
457 deep_update_rfc7396(content
, indata
)
458 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
459 self
.format_on_edit(content
, indata
)
460 # To allow project addressing by name AS WELL AS _id
461 # self.db.replace(self.topic, _id, content)
462 cid
= content
.get("_id")
463 self
.db
.replace(self
.topic
, cid
if cid
else _id
, content
)
465 indata
.pop("_admin", None)
467 self
._send
_msg
("edit", indata
)
469 except ValidationError
as e
:
470 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)