Gerrit id-7270 Enhancing NBI to define APIs for metric collection
[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
59 # Alternative ID Fields for some Topics
60 alt_id_field = {
61 "projects": "name",
62 "users": "username"
63 }
64
65 def __init__(self, db, fs, msg):
66 self.db = db
67 self.fs = fs
68 self.msg = msg
69 self.logger = logging.getLogger("nbi.engine")
70
71 @staticmethod
72 def id_field(topic, value):
73 "Returns ID Field for given topic and field value"
74 if topic in ["projects", "users"] and not is_valid_uuid(value):
75 return BaseTopic.alt_id_field[topic]
76 else:
77 return "_id"
78
79 @staticmethod
80 def _remove_envelop(indata=None):
81 if not indata:
82 return {}
83 return indata
84
85 def _validate_input_new(self, input, force=False):
86 """
87 Validates input user content for a new entry. It uses jsonschema. Some overrides will use pyangbind
88 :param input: user input content for the new topic
89 :param force: may be used for being more tolerant
90 :return: The same input content, or a changed version of it.
91 """
92 if self.schema_new:
93 validate_input(input, self.schema_new)
94 return input
95
96 def _validate_input_edit(self, input, force=False):
97 """
98 Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
99 :param input: user input content for the new topic
100 :param force: may be used for being more tolerant
101 :return: The same input content, or a changed version of it.
102 """
103 if self.schema_edit:
104 validate_input(input, self.schema_edit)
105 return input
106
107 @staticmethod
108 def _get_project_filter(session, write=False, show_all=True):
109 """
110 Generates a filter dictionary for querying database, so that only allowed items for this project can be
111 addressed. Only propietary or public can be used. Allowed projects are at _admin.project_read/write. If it is
112 not present or contains ANY mean public.
113 :param session: contains "username", if user is "admin" and the working "project_id"
114 :param write: if operation is for reading (False) or writing (True)
115 :param show_all: if True it will show public or
116 :return:
117 """
118 if write:
119 k = "_admin.projects_write.cont"
120 else:
121 k = "_admin.projects_read.cont"
122 if not show_all:
123 return {k: session["project_id"]}
124 elif session["admin"]: # and show_all: # allows all
125 return {}
126 else:
127 return {k: ["ANY", session["project_id"], None]}
128
129 def check_conflict_on_new(self, session, indata, force=False):
130 """
131 Check that the data to be inserted is valid
132 :param session: contains "username", if user is "admin" and the working "project_id"
133 :param indata: data to be inserted
134 :param force: boolean. With force it is more tolerant
135 :return: None or raises EngineException
136 """
137 pass
138
139 def check_conflict_on_edit(self, session, final_content, edit_content, _id, force=False):
140 """
141 Check that the data to be edited/uploaded is valid
142 :param session: contains "username", if user is "admin" and the working "project_id"
143 :param final_content: data once modified
144 :param edit_content: incremental data that contains the modifications to apply
145 :param _id: internal _id
146 :param force: boolean. With force it is more tolerant
147 :return: None or raises EngineException
148 """
149 pass
150
151 def check_unique_name(self, session, name, _id=None):
152 """
153 Check that the name is unique for this project
154 :param session: contains "username", if user is "admin" and the working "project_id"
155 :param name: name to be checked
156 :param _id: If not None, ignore this entry that are going to change
157 :return: None or raises EngineException
158 """
159 _filter = self._get_project_filter(session, write=False, show_all=False)
160 _filter["name"] = name
161 if _id:
162 _filter["_id.neq"] = _id
163 if self.db.get_one(self.topic, _filter, fail_on_empty=False, fail_on_more=False):
164 raise EngineException("name '{}' already exists for {}".format(name, self.topic), HTTPStatus.CONFLICT)
165
166 @staticmethod
167 def format_on_new(content, project_id=None, make_public=False):
168 """
169 Modifies content descriptor to include _admin
170 :param content: descriptor to be modified
171 :param project_id: if included, it add project read/write permissions
172 :param make_public: if included it is generated as public for reading.
173 :return: None, but content is modified
174 """
175 now = time()
176 if "_admin" not in content:
177 content["_admin"] = {}
178 if not content["_admin"].get("created"):
179 content["_admin"]["created"] = now
180 content["_admin"]["modified"] = now
181 if not content.get("_id"):
182 content["_id"] = str(uuid4())
183 if project_id:
184 if not content["_admin"].get("projects_read"):
185 content["_admin"]["projects_read"] = [project_id]
186 if make_public:
187 content["_admin"]["projects_read"].append("ANY")
188 if not content["_admin"].get("projects_write"):
189 content["_admin"]["projects_write"] = [project_id]
190
191 @staticmethod
192 def format_on_edit(final_content, edit_content):
193 if final_content.get("_admin"):
194 now = time()
195 final_content["_admin"]["modified"] = now
196
197 def _send_msg(self, action, content):
198 if self.topic_msg:
199 content.pop("_admin", None)
200 self.msg.write(self.topic_msg, action, content)
201
202 def check_conflict_on_del(self, session, _id, force=False):
203 """
204 Check if deletion can be done because of dependencies if it is not force. To override
205 :param session: contains "username", if user is "admin" and the working "project_id"
206 :param _id: itnernal _id
207 :param force: Avoid this checking
208 :return: None if ok or raises EngineException with the conflict
209 """
210 pass
211
212 @staticmethod
213 def _update_input_with_kwargs(desc, kwargs):
214 """
215 Update descriptor with the kwargs. It contains dot separated keys
216 :param desc: dictionary to be updated
217 :param kwargs: plain dictionary to be used for updating.
218 :return: None, 'desc' is modified. It raises EngineException.
219 """
220 if not kwargs:
221 return
222 try:
223 for k, v in kwargs.items():
224 update_content = desc
225 kitem_old = None
226 klist = k.split(".")
227 for kitem in klist:
228 if kitem_old is not None:
229 update_content = update_content[kitem_old]
230 if isinstance(update_content, dict):
231 kitem_old = kitem
232 elif isinstance(update_content, list):
233 kitem_old = int(kitem)
234 else:
235 raise EngineException(
236 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
237 update_content[kitem_old] = v
238 except KeyError:
239 raise EngineException(
240 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
241 except ValueError:
242 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
243 k, kitem))
244 except IndexError:
245 raise EngineException(
246 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
247
248 def show(self, session, _id):
249 """
250 Get complete information on an topic
251 :param session: contains the used login username and working project
252 :param _id: server internal id
253 :return: dictionary, raise exception if not found.
254 """
255 filter_db = self._get_project_filter(session, write=False, show_all=True)
256 # To allow project&user addressing by name AS WELL AS _id
257 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
258 return self.db.get_one(self.topic, filter_db)
259 # TODO transform data for SOL005 URL requests
260 # TODO remove _admin if not admin
261
262 def get_file(self, session, _id, path=None, accept_header=None):
263 """
264 Only implemented for descriptor topics. Return the file content of a descriptor
265 :param session: contains the used login username and working project
266 :param _id: Identity of the item to get content
267 :param path: artifact path or "$DESCRIPTOR" or None
268 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
269 :return: opened file or raises an exception
270 """
271 raise EngineException("Method get_file not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
272
273 def list(self, session, filter_q=None):
274 """
275 Get a list of the topic that matches a filter
276 :param session: contains the used login username and working project
277 :param filter_q: filter of data to be applied
278 :return: The list, it can be empty if no one match the filter.
279 """
280 if not filter_q:
281 filter_q = {}
282
283 filter_q.update(self._get_project_filter(session, write=False, show_all=True))
284
285 # TODO transform data for SOL005 URL requests. Transform filtering
286 # TODO implement "field-type" query string SOL005
287 return self.db.get_list(self.topic, filter_q)
288
289 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
290 """
291 Creates a new entry into database.
292 :param rollback: list to append created items at database in case a rollback may to be done
293 :param session: contains the used login username and working project
294 :param indata: data to be inserted
295 :param kwargs: used to override the indata descriptor
296 :param headers: http request headers
297 :param force: If True avoid some dependence checks
298 :param make_public: Make the created item public to all projects
299 :return: _id: identity of the inserted data.
300 """
301 try:
302 content = self._remove_envelop(indata)
303
304 # Override descriptor with query string kwargs
305 self._update_input_with_kwargs(content, kwargs)
306 content = self._validate_input_new(content, force=force)
307 self.check_conflict_on_new(session, content, force=force)
308 self.format_on_new(content, project_id=session["project_id"], make_public=make_public)
309 _id = self.db.create(self.topic, content)
310 rollback.append({"topic": self.topic, "_id": _id})
311 self._send_msg("create", content)
312 return _id
313 except ValidationError as e:
314 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
315
316 def upload_content(self, session, _id, indata, kwargs, headers, force=False):
317 """
318 Only implemented for descriptor topics. Used for receiving content by chunks (with a transaction_id header
319 and/or gzip file. It will store and extract)
320 :param session: session
321 :param _id : the database id of entry to be updated
322 :param indata: http body request
323 :param kwargs: user query string to override parameters. NOT USED
324 :param headers: http request headers
325 :param force: to be more tolerant with validation
326 :return: True package has is completely uploaded or False if partial content has been uplodaed.
327 Raise exception on error
328 """
329 raise EngineException("Method upload_content not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
330
331 def delete_list(self, session, filter_q=None):
332 """
333 Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API
334 :param session: contains the used login username and working project
335 :param filter_q: filter of data to be applied
336 :return: The deleted list, it can be empty if no one match the filter.
337 """
338 # TODO add admin to filter, validate rights
339 if not filter_q:
340 filter_q = {}
341 filter_q.update(self._get_project_filter(session, write=True, show_all=True))
342 return self.db.del_list(self.topic, filter_q)
343
344 def delete(self, session, _id, force=False, dry_run=False):
345 """
346 Delete item by its internal _id
347 :param session: contains the used login username, working project, and admin rights
348 :param _id: server internal id
349 :param force: indicates if deletion must be forced in case of conflict
350 :param dry_run: make checking but do not delete
351 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
352 """
353 # TODO add admin to filter, validate rights
354 # data = self.get_item(topic, _id)
355 self.check_conflict_on_del(session, _id, force)
356 filter_q = self._get_project_filter(session, write=True, show_all=True)
357 # To allow project addressing by name AS WELL AS _id
358 filter_q[BaseTopic.id_field(self.topic, _id)] = _id
359 if not dry_run:
360 v = self.db.del_one(self.topic, filter_q)
361 self._send_msg("deleted", {"_id": _id})
362 return v
363 return None
364
365 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
366 indata = self._remove_envelop(indata)
367
368 # Override descriptor with query string kwargs
369 if kwargs:
370 self._update_input_with_kwargs(indata, kwargs)
371 try:
372 indata = self._validate_input_edit(indata, force=force)
373
374 # TODO self._check_edition(session, indata, _id, force)
375 if not content:
376 content = self.show(session, _id)
377 deep_update_rfc7396(content, indata)
378 self.check_conflict_on_edit(session, content, indata, _id=_id, force=force)
379 self.format_on_edit(content, indata)
380 # To allow project addressing by name AS WELL AS _id
381 # self.db.replace(self.topic, _id, content)
382 cid = content.get("_id")
383 self.db.replace(self.topic, cid if cid else _id, content)
384
385 indata.pop("_admin", None)
386 indata["_id"] = _id
387 self._send_msg("edit", indata)
388 return id
389 except ValidationError as e:
390 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)