Fixing user ids when listing
[osm/NBI.git] / osm_nbi / base_topic.py
1 # -*- coding: utf-8 -*-
2
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
16 import logging
17 from uuid import uuid4
18 from http import HTTPStatus
19 from time import time
20 from osm_common.dbbase import deep_update_rfc7396
21 from validation import validate_input, ValidationError, is_valid_uuid
22
23 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
24
25
26 class EngineException(Exception):
27
28 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
29 self.http_code = http_code
30 Exception.__init__(self, message)
31
32
33 def get_iterable(input_var):
34 """
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
38 """
39 if input_var is None:
40 return ()
41 return input_var
42
43
44 def versiontuple(v):
45 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
46 filled = []
47 for point in v.split("."):
48 filled.append(point.zfill(8))
49 return tuple(filled)
50
51
52 class BaseTopic:
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
59
60 # Alternative ID Fields for some Topics
61 alt_id_field = {
62 "projects": "name",
63 "users": "username"
64 }
65
66 def __init__(self, db, fs, msg):
67 self.db = db
68 self.fs = fs
69 self.msg = msg
70 self.logger = logging.getLogger("nbi.engine")
71
72 @staticmethod
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]
77 else:
78 return "_id"
79
80 @staticmethod
81 def _remove_envelop(indata=None):
82 if not indata:
83 return {}
84 return indata
85
86 def _validate_input_new(self, input, force=False):
87 """
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.
92 """
93 if self.schema_new:
94 validate_input(input, self.schema_new)
95 return input
96
97 def _validate_input_edit(self, input, force=False):
98 """
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.
103 """
104 if self.schema_edit:
105 validate_input(input, self.schema_edit)
106 return input
107
108 @staticmethod
109 def _get_project_filter(session):
110 """
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
117 force: True or False
118 public: True, False or None
119 method: "list", "show", "write", "delete"
120 admin: True or False
121 :return: dictionary with project filter
122 """
123 p_filter = {}
124 project_filter_n = []
125 project_filter = list(session["project_id"])
126
127 if session["method"] not in ("list", "delete"):
128 if project_filter:
129 project_filter.append("ANY")
130 elif session["public"] is not None:
131 if session["public"]:
132 project_filter.append("ANY")
133 else:
134 project_filter_n.append("ANY")
135
136 if session.get("PROJECT.ne"):
137 project_filter_n.append(session["PROJECT.ne"])
138
139 if project_filter:
140 if session["method"] in ("list", "show", "delete") or session.get("set_project"):
141 p_filter["_admin.projects_read.cont"] = project_filter
142 else:
143 p_filter["_admin.projects_write.cont"] = project_filter
144 if project_filter_n:
145 if session["method"] in ("list", "show", "delete") or session.get("set_project"):
146 p_filter["_admin.projects_read.ncont"] = project_filter_n
147 else:
148 p_filter["_admin.projects_write.ncont"] = project_filter_n
149
150 return p_filter
151
152 def check_conflict_on_new(self, session, indata):
153 """
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
158 """
159 pass
160
161 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
162 """
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
169 """
170 if not self.multiproject:
171 return
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")
179
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)
185
186 def check_unique_name(self, session, name, _id=None):
187 """
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
193 """
194 _filter = self._get_project_filter(session)
195 _filter["name"] = name
196 if _id:
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)
200
201 @staticmethod
202 def format_on_new(content, project_id=None, make_public=False):
203 """
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
209 """
210 now = time()
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)
221 if make_public:
222 content["_admin"]["projects_read"].append("ANY")
223 if not content["_admin"].get("projects_write"):
224 content["_admin"]["projects_write"] = list(project_id)
225
226 @staticmethod
227 def format_on_edit(final_content, edit_content):
228 if final_content.get("_admin"):
229 now = time()
230 final_content["_admin"]["modified"] = now
231
232 def _send_msg(self, action, content):
233 if self.topic_msg:
234 content.pop("_admin", None)
235 self.msg.write(self.topic_msg, action, content)
236
237 def check_conflict_on_del(self, session, _id, db_content):
238 """
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
244 """
245 pass
246
247 @staticmethod
248 def _update_input_with_kwargs(desc, kwargs):
249 """
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.
254 """
255 if not kwargs:
256 return
257 try:
258 for k, v in kwargs.items():
259 update_content = desc
260 kitem_old = None
261 klist = k.split(".")
262 for kitem in klist:
263 if kitem_old is not None:
264 update_content = update_content[kitem_old]
265 if isinstance(update_content, dict):
266 kitem_old = kitem
267 elif isinstance(update_content, list):
268 kitem_old = int(kitem)
269 else:
270 raise EngineException(
271 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
272 update_content[kitem_old] = v
273 except KeyError:
274 raise EngineException(
275 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
276 except ValueError:
277 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
278 k, kitem))
279 except IndexError:
280 raise EngineException(
281 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
282
283 def show(self, session, _id):
284 """
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.
289 """
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
296
297 def get_file(self, session, _id, path=None, accept_header=None):
298 """
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
305 """
306 raise EngineException("Method get_file not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
307
308 def list(self, session, filter_q=None):
309 """
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.
314 """
315 if not filter_q:
316 filter_q = {}
317
318 filter_q.update(self._get_project_filter(session))
319
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)
323
324 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
325 """
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.
333 """
334 try:
335 content = self._remove_envelop(indata)
336
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)
345 return _id
346 except ValidationError as e:
347 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
348
349 def upload_content(self, session, _id, indata, kwargs, headers):
350 """
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
360 """
361 raise EngineException("Method upload_content not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
362
363 def delete_list(self, session, filter_q=None):
364 """
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.
369 """
370 # TODO add admin to filter, validate rights
371 if not filter_q:
372 filter_q = {}
373 filter_q.update(self._get_project_filter(session))
374 return self.db.del_list(self.topic, filter_q)
375
376 def delete_extra(self, session, _id, db_content):
377 """
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
385 """
386 pass
387
388 def delete(self, session, _id, dry_run=False):
389 """
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, ...
395 """
396
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)
400
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)
404 if dry_run:
405 return None
406
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"]:
416 return v
417 else:
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})
421 return v
422
423 def edit(self, session, _id, indata=None, kwargs=None, content=None):
424 """
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
431 :return:
432 """
433 indata = self._remove_envelop(indata)
434
435 # Override descriptor with query string kwargs
436 if kwargs:
437 self._update_input_with_kwargs(indata, kwargs)
438 try:
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"])
443
444 # TODO self._check_edition(session, indata, _id, force)
445 if not content:
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)
454
455 indata.pop("_admin", None)
456 indata["_id"] = _id
457 self._send_msg("edit", indata)
458 return _id
459 except ValidationError as e:
460 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)