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