bug 495 check descriptor dependencies at create,delete,edit
[osm/NBI.git] / osm_nbi / engine.py
1 # -*- coding: utf-8 -*-
2
3 from osm_common import dbmongo
4 from osm_common import dbmemory
5 from osm_common import fslocal
6 from osm_common import msglocal
7 from osm_common import msgkafka
8 import tarfile
9 import yaml
10 import json
11 import logging
12 from random import choice as random_choice
13 from uuid import uuid4
14 from hashlib import sha256, md5
15 from osm_common.dbbase import DbException
16 from osm_common.fsbase import FsException
17 from osm_common.msgbase import MsgException
18 from http import HTTPStatus
19 from time import time
20 from copy import deepcopy
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 _deep_update(dict_to_change, dict_reference):
34 """
35 Modifies one dictionary with the information of the other following https://tools.ietf.org/html/rfc7396
36 :param dict_to_change: Ends modified
37 :param dict_reference: reference
38 :return: none
39 """
40 for k in dict_reference:
41 if dict_reference[k] is None: # None->Anything
42 if k in dict_to_change:
43 del dict_to_change[k]
44 elif not isinstance(dict_reference[k], dict): # NotDict->Anything
45 dict_to_change[k] = dict_reference[k]
46 elif k not in dict_to_change: # Dict->Empty
47 dict_to_change[k] = deepcopy(dict_reference[k])
48 _deep_update(dict_to_change[k], dict_reference[k])
49 elif isinstance(dict_to_change[k], dict): # Dict->Dict
50 _deep_update(dict_to_change[k], dict_reference[k])
51 else: # Dict->NotDict
52 dict_to_change[k] = deepcopy(dict_reference[k])
53 _deep_update(dict_to_change[k], dict_reference[k])
54
55
56 class Engine(object):
57
58 def __init__(self):
59 self.tokens = {}
60 self.db = None
61 self.fs = None
62 self.msg = None
63 self.config = None
64 self.logger = logging.getLogger("nbi.engine")
65
66 def start(self, config):
67 """
68 Connect to database, filesystem storage, and messaging
69 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
70 :return: None
71 """
72 self.config = config
73 try:
74 if not self.db:
75 if config["database"]["driver"] == "mongo":
76 self.db = dbmongo.DbMongo()
77 self.db.db_connect(config["database"])
78 elif config["database"]["driver"] == "memory":
79 self.db = dbmemory.DbMemory()
80 self.db.db_connect(config["database"])
81 else:
82 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
83 config["database"]["driver"]))
84 if not self.fs:
85 if config["storage"]["driver"] == "local":
86 self.fs = fslocal.FsLocal()
87 self.fs.fs_connect(config["storage"])
88 else:
89 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
90 config["storage"]["driver"]))
91 if not self.msg:
92 if config["message"]["driver"] == "local":
93 self.msg = msglocal.MsgLocal()
94 self.msg.connect(config["message"])
95 elif config["message"]["driver"] == "kafka":
96 self.msg = msgkafka.MsgKafka()
97 self.msg.connect(config["message"])
98 else:
99 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
100 config["storage"]["driver"]))
101 except (DbException, FsException, MsgException) as e:
102 raise EngineException(str(e), http_code=e.http_code)
103
104 def stop(self):
105 try:
106 if self.db:
107 self.db.db_disconnect()
108 if self.fs:
109 self.fs.fs_disconnect()
110 if self.fs:
111 self.fs.fs_disconnect()
112 except (DbException, FsException, MsgException) as e:
113 raise EngineException(str(e), http_code=e.http_code)
114
115 def authorize(self, token):
116 try:
117 if not token:
118 raise EngineException("Needed a token or Authorization http header",
119 http_code=HTTPStatus.UNAUTHORIZED)
120 if token not in self.tokens:
121 raise EngineException("Invalid token or Authorization http header",
122 http_code=HTTPStatus.UNAUTHORIZED)
123 session = self.tokens[token]
124 now = time()
125 if session["expires"] < now:
126 del self.tokens[token]
127 raise EngineException("Expired Token or Authorization http header",
128 http_code=HTTPStatus.UNAUTHORIZED)
129 return session
130 except EngineException:
131 if self.config["global"].get("test.user_not_authorized"):
132 return {"id": "fake-token-id-for-test",
133 "project_id": self.config["global"].get("test.project_not_authorized", "admin"),
134 "username": self.config["global"]["test.user_not_authorized"]}
135 else:
136 raise
137
138 def new_token(self, session, indata, remote):
139 now = time()
140 user_content = None
141
142 # Try using username/password
143 if indata.get("username"):
144 user_rows = self.db.get_list("users", {"username": indata.get("username")})
145 user_content = None
146 if user_rows:
147 user_content = user_rows[0]
148 salt = user_content["_admin"]["salt"]
149 shadow_password = sha256(indata.get("password", "").encode('utf-8') + salt.encode('utf-8')).hexdigest()
150 if shadow_password != user_content["password"]:
151 user_content = None
152 if not user_content:
153 raise EngineException("Invalid username/password", http_code=HTTPStatus.UNAUTHORIZED)
154 elif session:
155 user_rows = self.db.get_list("users", {"username": session["username"]})
156 if user_rows:
157 user_content = user_rows[0]
158 else:
159 raise EngineException("Invalid token", http_code=HTTPStatus.UNAUTHORIZED)
160 else:
161 raise EngineException("Provide credentials: username/password or Authorization Bearer token",
162 http_code=HTTPStatus.UNAUTHORIZED)
163
164 token_id = ''.join(random_choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
165 for _ in range(0, 32))
166 if indata.get("project_id"):
167 project_id = indata.get("project_id")
168 if project_id not in user_content["projects"]:
169 raise EngineException("project {} not allowed for this user".format(project_id),
170 http_code=HTTPStatus.UNAUTHORIZED)
171 else:
172 project_id = user_content["projects"][0]
173 if project_id == "admin":
174 session_admin = True
175 else:
176 project = self.db.get_one("projects", {"_id": project_id})
177 session_admin = project.get("admin", False)
178 new_session = {"issued_at": now, "expires": now+3600,
179 "_id": token_id, "id": token_id, "project_id": project_id, "username": user_content["username"],
180 "remote_port": remote.port, "admin": session_admin}
181 if remote.name:
182 new_session["remote_host"] = remote.name
183 elif remote.ip:
184 new_session["remote_host"] = remote.ip
185
186 self.tokens[token_id] = new_session
187 return deepcopy(new_session)
188
189 def get_token_list(self, session):
190 token_list = []
191 for token_id, token_value in self.tokens.items():
192 if token_value["username"] == session["username"]:
193 token_list.append(deepcopy(token_value))
194 return token_list
195
196 def get_token(self, session, token_id):
197 token_value = self.tokens.get(token_id)
198 if not token_value:
199 raise EngineException("token not found", http_code=HTTPStatus.NOT_FOUND)
200 if token_value["username"] != session["username"] and not session["admin"]:
201 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
202 return token_value
203
204 def del_token(self, token_id):
205 try:
206 del self.tokens[token_id]
207 return "token '{}' deleted".format(token_id)
208 except KeyError:
209 raise EngineException("Token '{}' not found".format(token_id), http_code=HTTPStatus.NOT_FOUND)
210
211 @staticmethod
212 def _remove_envelop(item, indata=None):
213 """
214 Obtain the useful data removing the envelop. It goes throw the vnfd or nsd catalog and returns the
215 vnfd or nsd content
216 :param item: can be vnfds, nsds, users, projects, userDefinedData (initial content of a vnfds, nsds
217 :param indata: Content to be inspected
218 :return: the useful part of indata
219 """
220 clean_indata = indata
221 if not indata:
222 return {}
223 if item == "vnfds":
224 if clean_indata.get('vnfd:vnfd-catalog'):
225 clean_indata = clean_indata['vnfd:vnfd-catalog']
226 elif clean_indata.get('vnfd-catalog'):
227 clean_indata = clean_indata['vnfd-catalog']
228 if clean_indata.get('vnfd'):
229 if not isinstance(clean_indata['vnfd'], list) or len(clean_indata['vnfd']) != 1:
230 raise EngineException("'vnfd' must be a list only one element")
231 clean_indata = clean_indata['vnfd'][0]
232 elif item == "nsds":
233 if clean_indata.get('nsd:nsd-catalog'):
234 clean_indata = clean_indata['nsd:nsd-catalog']
235 elif clean_indata.get('nsd-catalog'):
236 clean_indata = clean_indata['nsd-catalog']
237 if clean_indata.get('nsd'):
238 if not isinstance(clean_indata['nsd'], list) or len(clean_indata['nsd']) != 1:
239 raise EngineException("'nsd' must be a list only one element")
240 clean_indata = clean_indata['nsd'][0]
241 elif item == "userDefinedData":
242 if "userDefinedData" in indata:
243 clean_indata = clean_indata['userDefinedData']
244 return clean_indata
245
246 def _check_dependencies_on_descriptor(self, session, item, descriptor_id):
247 """
248 Check that the descriptor to be deleded is not a dependency of others
249 :param session: client session information
250 :param item: can be vnfds, nsds
251 :param descriptor_id: id of descriptor to be deleted
252 :return: None or raises exception
253 """
254 if item == "vnfds":
255 _filter = {"constituent-vnfd.ANYINDEX.vnfd-id-ref": descriptor_id}
256 if self.get_item_list(session, "nsds", _filter):
257 raise EngineException("There are nsd that depends on this VNFD", http_code=HTTPStatus.CONFLICT)
258 elif item == "nsds":
259 _filter = {"nsdId": descriptor_id}
260 if self.get_item_list(session, "nsrs", _filter):
261 raise EngineException("There are nsr that depends on this NSD", http_code=HTTPStatus.CONFLICT)
262
263 def _check_descriptor_dependencies(self, session, item, descriptor):
264 """
265 Check that the dependent descriptors exist on a new descriptor or edition
266 :param session: client session information
267 :param item: can be nsds, nsrs
268 :param descriptor: descriptor to be inserted or edit
269 :return: None or raises exception
270 """
271 if item == "nsds":
272 if not descriptor.get("constituent-vnfd"):
273 return
274 for vnf in descriptor["constituent-vnfd"]:
275 vnfd_id = vnf["vnfd-id-ref"]
276 if not self.get_item_list(session, "vnfds", {"id": vnfd_id}):
277 raise EngineException("Descriptor error at 'constituent-vnfd':'vnfd-id-ref'='{}' references a non "
278 "existing vnfd".format(vnfd_id), http_code=HTTPStatus.CONFLICT)
279 elif item == "nsrs":
280 if not descriptor.get("nsdId"):
281 return
282 nsd_id = descriptor["nsdId"]
283 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
284 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
285 http_code=HTTPStatus.CONFLICT)
286
287 def _validate_new_data(self, session, item, indata, id=None, force=False):
288 if item == "users":
289 if not indata.get("username"):
290 raise EngineException("missing 'username'", HTTPStatus.UNPROCESSABLE_ENTITY)
291 if not indata.get("password"):
292 raise EngineException("missing 'password'", HTTPStatus.UNPROCESSABLE_ENTITY)
293 if not indata.get("projects"):
294 raise EngineException("missing 'projects'", HTTPStatus.UNPROCESSABLE_ENTITY)
295 # check username not exists
296 if self.db.get_one(item, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
297 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
298 elif item == "projects":
299 if not indata.get("name"):
300 raise EngineException("missing 'name'")
301 # check name not exists
302 if self.db.get_one(item, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
303 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
304 elif item in ("vnfds", "nsds"):
305 filter = {"id": indata["id"]}
306 if id:
307 filter["_id.neq"] = id
308 # TODO add admin to filter, validate rights
309 self._add_read_filter(session, item, filter)
310 if self.db.get_one(item, filter, fail_on_empty=False):
311 raise EngineException("{} with id '{}' already exists for this tenant".format(item[:-1], indata["id"]),
312 HTTPStatus.CONFLICT)
313
314 # TODO validate with pyangbind
315 if item == "nsds" and not force:
316 self._check_descriptor_dependencies(session, "nsds", indata)
317 elif item == "userDefinedData":
318 # TODO validate userDefinedData is a keypair values
319 pass
320
321 elif item == "nsrs":
322 pass
323 elif item == "vim_accounts" or item == "sdns":
324 if self.db.get_one(item, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
325 raise EngineException("name '{}' already exists for {}".format(indata["name"], item),
326 HTTPStatus.CONFLICT)
327
328 def _format_new_data(self, session, item, indata):
329 now = time()
330 if not "_admin" in indata:
331 indata["_admin"] = {}
332 indata["_admin"]["created"] = now
333 indata["_admin"]["modified"] = now
334 if item == "users":
335 indata["_id"] = indata["username"]
336 salt = uuid4().hex
337 indata["_admin"]["salt"] = salt
338 indata["password"] = sha256(indata["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
339 elif item == "projects":
340 indata["_id"] = indata["name"]
341 else:
342 if not indata.get("_id"):
343 indata["_id"] = str(uuid4())
344 if item in ("vnfds", "nsds", "nsrs", "vnfrs"):
345 if not indata["_admin"].get("projects_read"):
346 indata["_admin"]["projects_read"] = [session["project_id"]]
347 if not indata["_admin"].get("projects_write"):
348 indata["_admin"]["projects_write"] = [session["project_id"]]
349 if item in ("vnfds", "nsds"):
350 indata["_admin"]["onboardingState"] = "CREATED"
351 indata["_admin"]["operationalState"] = "DISABLED"
352 indata["_admin"]["usageSate"] = "NOT_IN_USE"
353 if item == "nsrs":
354 indata["_admin"]["nsState"] = "NOT_INSTANTIATED"
355 if item in ("vim_accounts", "sdns"):
356 indata["_admin"]["operationalState"] = "PROCESSING"
357
358 def upload_content(self, session, item, _id, indata, kwargs, headers):
359 """
360 Used for receiving content by chunks (with a transaction_id header and/or gzip file. It will store and extract)
361 :param session: session
362 :param item: can be nsds or vnfds
363 :param _id : the nsd,vnfd is already created, this is the id
364 :param indata: http body request
365 :param kwargs: user query string to override parameters. NOT USED
366 :param headers: http request headers
367 :return: True package has is completely uploaded or False if partial content has been uplodaed.
368 Raise exception on error
369 """
370 # Check that _id exists and it is valid
371 current_desc = self.get_item(session, item, _id)
372
373 content_range_text = headers.get("Content-Range")
374 expected_md5 = headers.get("Content-File-MD5")
375 compressed = None
376 content_type = headers.get("Content-Type")
377 if content_type and "application/gzip" in content_type or "application/x-gzip" in content_type or \
378 "application/zip" in content_type:
379 compressed = "gzip"
380 filename = headers.get("Content-Filename")
381 if not filename:
382 filename = "package.tar.gz" if compressed else "package"
383 # TODO change to Content-Disposition filename https://tools.ietf.org/html/rfc6266
384 file_pkg = None
385 error_text = ""
386 try:
387 if content_range_text:
388 content_range = content_range_text.replace("-", " ").replace("/", " ").split()
389 if content_range[0] != "bytes": # TODO check x<y not negative < total....
390 raise IndexError()
391 start = int(content_range[1])
392 end = int(content_range[2]) + 1
393 total = int(content_range[3])
394 else:
395 start = 0
396
397 if start:
398 if not self.fs.file_exists(_id, 'dir'):
399 raise EngineException("invalid Transaction-Id header", HTTPStatus.NOT_FOUND)
400 else:
401 self.fs.file_delete(_id, ignore_non_exist=True)
402 self.fs.mkdir(_id)
403
404 storage = self.fs.get_params()
405 storage["folder"] = _id
406
407 file_path = (_id, filename)
408 if self.fs.file_exists(file_path, 'file'):
409 file_size = self.fs.file_size(file_path)
410 else:
411 file_size = 0
412 if file_size != start:
413 raise EngineException("invalid Content-Range start sequence, expected '{}' but received '{}'".format(
414 file_size, start), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
415 file_pkg = self.fs.file_open(file_path, 'a+b')
416 if isinstance(indata, dict):
417 indata_text = yaml.safe_dump(indata, indent=4, default_flow_style=False)
418 file_pkg.write(indata_text.encode(encoding="utf-8"))
419 else:
420 indata_len = 0
421 while True:
422 indata_text = indata.read(4096)
423 indata_len += len(indata_text)
424 if not indata_text:
425 break
426 file_pkg.write(indata_text)
427 if content_range_text:
428 if indata_len != end-start:
429 raise EngineException("Mismatch between Content-Range header {}-{} and body length of {}".format(
430 start, end-1, indata_len), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
431 if end != total:
432 # TODO update to UPLOADING
433 return False
434
435 # PACKAGE UPLOADED
436 if expected_md5:
437 file_pkg.seek(0, 0)
438 file_md5 = md5()
439 chunk_data = file_pkg.read(1024)
440 while chunk_data:
441 file_md5.update(chunk_data)
442 chunk_data = file_pkg.read(1024)
443 if expected_md5 != file_md5.hexdigest():
444 raise EngineException("Error, MD5 mismatch", HTTPStatus.CONFLICT)
445 file_pkg.seek(0, 0)
446 if compressed == "gzip":
447 tar = tarfile.open(mode='r', fileobj=file_pkg)
448 descriptor_file_name = None
449 for tarinfo in tar:
450 tarname = tarinfo.name
451 tarname_path = tarname.split("/")
452 if not tarname_path[0] or ".." in tarname_path: # if start with "/" means absolute path
453 raise EngineException("Absolute path or '..' are not allowed for package descriptor tar.gz")
454 if len(tarname_path) == 1 and not tarinfo.isdir():
455 raise EngineException("All files must be inside a dir for package descriptor tar.gz")
456 if tarname.endswith(".yaml") or tarname.endswith(".json") or tarname.endswith(".yml"):
457 storage["pkg-dir"] = tarname_path[0]
458 if len(tarname_path) == 2:
459 if descriptor_file_name:
460 raise EngineException("Found more than one descriptor file at package descriptor tar.gz")
461 descriptor_file_name = tarname
462 if not descriptor_file_name:
463 raise EngineException("Not found any descriptor file at package descriptor tar.gz")
464 storage["descriptor"] = descriptor_file_name
465 storage["zipfile"] = filename
466 self.fs.file_extract(tar, _id)
467 with self.fs.file_open((_id, descriptor_file_name), "r") as descriptor_file:
468 content = descriptor_file.read()
469 else:
470 content = file_pkg.read()
471 storage["descriptor"] = descriptor_file_name = filename
472
473 if descriptor_file_name.endswith(".json"):
474 error_text = "Invalid json format "
475 indata = json.load(content)
476 else:
477 error_text = "Invalid yaml format "
478 indata = yaml.load(content)
479
480 current_desc["_admin"]["storage"] = storage
481 current_desc["_admin"]["onboardingState"] = "ONBOARDED"
482 current_desc["_admin"]["operationalState"] = "ENABLED"
483
484 self._edit_item(session, item, _id, current_desc, indata, kwargs)
485 # TODO if descriptor has changed because kwargs update content and remove cached zip
486 # TODO if zip is not present creates one
487 return True
488
489 except EngineException:
490 raise
491 except IndexError:
492 raise EngineException("invalid Content-Range header format. Expected 'bytes start-end/total'",
493 HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
494 except IOError as e:
495 raise EngineException("invalid upload transaction sequence: '{}'".format(e), HTTPStatus.BAD_REQUEST)
496 except tarfile.ReadError as e:
497 raise EngineException("invalid file content {}".format(e), HTTPStatus.BAD_REQUEST)
498 except (ValueError, yaml.YAMLError) as e:
499 raise EngineException(error_text + str(e))
500 finally:
501 if file_pkg:
502 file_pkg.close()
503
504 def new_nsr(self, session, ns_request):
505 """
506 Creates a new nsr into database. It also creates needed vnfrs
507 :param session: contains the used login username and working project
508 :param ns_request: params to be used for the nsr
509 :return: the _id of nsr descriptor stored at database
510 """
511 rollback = []
512 step = ""
513 try:
514 # look for nsr
515 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
516 nsd = self.get_item(session, "nsds", ns_request["nsdId"])
517 nsr_id = str(uuid4())
518 now = time()
519 step = "filling nsr from input data"
520 nsr_descriptor = {
521 "name": ns_request["nsName"],
522 "name-ref": ns_request["nsName"],
523 "short-name": ns_request["nsName"],
524 "admin-status": "ENABLED",
525 "nsd": nsd,
526 "datacenter": ns_request["vimAccountId"],
527 "resource-orchestrator": "osmopenmano",
528 "description": ns_request.get("nsDescription", ""),
529 "constituent-vnfr-ref": [],
530
531 "operational-status": "init", # typedef ns-operational-
532 "config-status": "init", # typedef config-states
533 "detailed-status": "scheduled",
534
535 "orchestration-progress": {}, # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
536
537 "crete-time": now,
538 "nsd-name-ref": nsd["name"],
539 "operational-events": [], # "id", "timestamp", "description", "event",
540 "nsd-ref": nsd["id"],
541 "instantiate_params": ns_request,
542 "ns-instance-config-ref": nsr_id,
543 "id": nsr_id,
544 "_id": nsr_id,
545 # "input-parameter": xpath, value,
546 "ssh-authorized-key": ns_request.get("key-pair-ref"),
547 }
548 ns_request["nsr_id"] = nsr_id
549
550 # Create VNFR
551 needed_vnfds = {}
552 for member_vnf in nsd["constituent-vnfd"]:
553 vnfd_id = member_vnf["vnfd-id-ref"]
554 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
555 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
556 if vnfd_id not in needed_vnfds:
557 # Obtain vnfd
558 vnf_filter = {"id": vnfd_id}
559 self._add_read_filter(session, "vnfds", vnf_filter)
560 vnfd = self.db.get_one("vnfds", vnf_filter)
561 vnfd.pop("_admin")
562 needed_vnfds[vnfd_id] = vnfd
563 else:
564 vnfd = needed_vnfds[vnfd_id]
565 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
566 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
567 vnfr_id = str(uuid4())
568 vnfr_descriptor = {
569 "id": vnfr_id,
570 "_id": vnfr_id,
571 "nsr-id-ref": nsr_id,
572 "member-vnf-index-ref": member_vnf["member-vnf-index"],
573 "created-time": now,
574 # "vnfd": vnfd, # at OSM model. TODO can it be removed in the future to avoid data duplication?
575 "vnfd-ref": vnfd_id,
576 "vnfd-id": vnfr_id, # not at OSM model, but useful
577 "vim-account-id": None,
578 "vdur": [],
579 "connection-point": [],
580 "ip-address": None, # mgmt-interface filled by LCM
581 }
582 for cp in vnfd.get("connection-point", ()):
583 vnf_cp = {
584 "name": cp["name"],
585 "connection-point-id": cp.get("id"),
586 "id": cp.get("id"),
587 # "ip-address", "mac-address" # filled by LCM
588 # vim-id # TODO it would be nice having a vim port id
589 }
590 vnfr_descriptor["connection-point"].append(vnf_cp)
591 for vdu in vnfd["vdu"]:
592 vdur_id = str(uuid4())
593 vdur = {
594 "id": vdur_id,
595 "vdu-id-ref": vdu["id"],
596 "ip-address": None, # mgmt-interface filled by LCM
597 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
598 "internal-connection-point": [],
599 }
600 # TODO volumes: name, volume-id
601 for icp in vdu.get("internal-connection-point", ()):
602 vdu_icp = {
603 "id": icp["id"],
604 "connection-point-id": icp["id"],
605 "name": icp.get("name"),
606 # "ip-address", "mac-address" # filled by LCM
607 # vim-id # TODO it would be nice having a vim port id
608 }
609 vdur["internal-connection-point"].append(vdu_icp)
610 vnfr_descriptor["vdur"].append(vdur)
611
612 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
613 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
614 self._format_new_data(session, "vnfrs", vnfr_descriptor)
615 self.db.create("vnfrs", vnfr_descriptor)
616 rollback.append({"session": session, "item": "vnfrs", "_id": vnfr_id, "force": True})
617 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
618
619 step = "creating nsr at database"
620 self._format_new_data(session, "nsrs", nsr_descriptor)
621 self.db.create("nsrs", nsr_descriptor)
622 return nsr_id
623 except Exception as e:
624 raise EngineException("Error {}: {}".format(step, e))
625 for rollback_item in rollback:
626 try:
627 self.engine.del_item(**rollback)
628 except Exception as e2:
629 self.logger.error("Rollback Exception {}: {}".format(rollback, e2))
630
631 @staticmethod
632 def _update_descriptor(desc, kwargs):
633 """
634 Update descriptor with the kwargs
635 :param kwargs:
636 :return:
637 """
638 if not kwargs:
639 return
640 try:
641 for k, v in kwargs.items():
642 update_content = content
643 kitem_old = None
644 klist = k.split(".")
645 for kitem in klist:
646 if kitem_old is not None:
647 update_content = update_content[kitem_old]
648 if isinstance(update_content, dict):
649 kitem_old = kitem
650 elif isinstance(update_content, list):
651 kitem_old = int(kitem)
652 else:
653 raise EngineException(
654 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
655 update_content[kitem_old] = v
656 except KeyError:
657 raise EngineException(
658 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
659 except ValueError:
660 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
661 k, kitem))
662 except IndexError:
663 raise EngineException(
664 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
665
666 def new_item(self, session, item, indata={}, kwargs=None, headers={}, force=False):
667 """
668 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
669 that must be completed with a call to method upload_content
670 :param session: contains the used login username and working project
671 :param item: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
672 :param indata: data to be inserted
673 :param kwargs: used to override the indata descriptor
674 :param headers: http request headers
675 :param force: If True avoid some dependence checks
676 :return: _id: identity of the inserted data.
677 """
678
679 try:
680 item_envelop = item
681 if item in ("nsds", "vnfds"):
682 item_envelop = "userDefinedData"
683 content = self._remove_envelop(item_envelop, indata)
684
685 # Override descriptor with query string kwargs
686 self._update_descriptor(content, kwargs)
687 if not indata and item not in ("nsds", "vnfds"):
688 raise EngineException("Empty payload")
689
690 validate_input(content, item, new=True)
691
692 if item == "nsrs":
693 # in this case the input descriptor is not the data to be stored
694 return self.new_nsr(session, ns_request=content)
695
696 self._validate_new_data(session, item_envelop, content, force)
697 if item in ("nsds", "vnfds"):
698 content = {"_admin": {"userDefinedData": content}}
699 self._format_new_data(session, item, content)
700 _id = self.db.create(item, content)
701
702 if item == "vim_accounts":
703 msg_data = self.db.get_one(item, {"_id": _id})
704 msg_data.pop("_admin", None)
705 self.msg.write("vim_account", "create", msg_data)
706 elif item == "sdns":
707 msg_data = self.db.get_one(item, {"_id": _id})
708 msg_data.pop("_admin", None)
709 self.msg.write("sdn", "create", msg_data)
710 return _id
711 except ValidationError as e:
712 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
713
714 def new_nslcmop(self, session, nsInstanceId, action, params):
715 now = time()
716 _id = str(uuid4())
717 nslcmop = {
718 "id": _id,
719 "_id": _id,
720 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
721 "statusEnteredTime": now,
722 "nsInstanceId": nsInstanceId,
723 "lcmOperationType": action,
724 "startTime": now,
725 "isAutomaticInvocation": False,
726 "operationParams": params,
727 "isCancelPending": False,
728 "links": {
729 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
730 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsInstanceId,
731 }
732 }
733 return nslcmop
734
735 def ns_action(self, session, nsInstanceId, action, indata, kwargs=None):
736 """
737 Performs a new action over a ns
738 :param session: contains the used login username and working project
739 :param nsInstanceId: _id of the nsr to perform the action
740 :param action: it can be: instantiate, terminate, action, TODO: update, heal
741 :param indata: descriptor with the parameters of the action
742 :param kwargs: used to override the indata descriptor
743 :return: id of the nslcmops
744 """
745 try:
746 # Override descriptor with query string kwargs
747 self._update_descriptor(indata, kwargs)
748 validate_input(indata, "ns_" + action, new=True)
749 # get ns from nsr_id
750 nsr = self.get_item(session, "nsrs", nsInstanceId)
751 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
752 if action == "terminate" and indata.get("autoremove"):
753 # NSR must be deleted
754 return self.del_item(session, "nsrs", nsInstanceId)
755 if action != "instantiate":
756 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
757 nsInstanceId, action), HTTPStatus.CONFLICT)
758 else:
759 if action == "instantiate" and not indata.get("force"):
760 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
761 nsInstanceId, action), HTTPStatus.CONFLICT)
762 indata["nsInstanceId"] = nsInstanceId
763 # TODO
764 nslcmop = self.new_nslcmop(session, nsInstanceId, action, indata)
765 self._format_new_data(session, "nslcmops", nslcmop)
766 _id = self.db.create("nslcmops", nslcmop)
767 indata["_id"] = _id
768 self.msg.write("ns", action, nslcmop)
769 return _id
770 except ValidationError as e:
771 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
772 # except DbException as e:
773 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
774
775 def _add_read_filter(self, session, item, filter):
776 if session["project_id"] == "admin": # allows all
777 return filter
778 if item == "users":
779 filter["username"] = session["username"]
780 elif item in ("vnfds", "nsds", "nsrs"):
781 filter["_admin.projects_read.cont"] = ["ANY", session["project_id"]]
782
783 def _add_delete_filter(self, session, item, filter):
784 if session["project_id"] != "admin" and item in ("users", "projects"):
785 raise EngineException("Only admin users can perform this task", http_code=HTTPStatus.FORBIDDEN)
786 if item == "users":
787 if filter.get("_id") == session["username"] or filter.get("username") == session["username"]:
788 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
789 elif item == "project":
790 if filter.get("_id") == session["project_id"]:
791 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
792 elif item in ("vnfds", "nsds") and session["project_id"] != "admin":
793 filter["_admin.projects_write.cont"] = ["ANY", session["project_id"]]
794
795 def get_file(self, session, item, _id, path=None, accept_header=None):
796 """
797 Return the file content of a vnfd or nsd
798 :param session: contains the used login username and working project
799 :param item: it can be vnfds or nsds
800 :param _id: Identity of the vnfd, ndsd
801 :param path: artifact path or "$DESCRIPTOR" or None
802 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
803 :return: opened file or raises an exception
804 """
805 accept_text = accept_zip = False
806 if accept_header:
807 if 'text/plain' in accept_header or '*/*' in accept_header:
808 accept_text = True
809 if 'application/zip' in accept_header or '*/*' in accept_header:
810 accept_zip = True
811 if not accept_text and not accept_zip:
812 raise EngineException("provide request header 'Accept' with 'application/zip' or 'text/plain'",
813 http_code=HTTPStatus.NOT_ACCEPTABLE)
814
815 content = self.get_item(session, item, _id)
816 if content["_admin"]["onboardingState"] != "ONBOARDED":
817 raise EngineException("Cannot get content because this resource is not at 'ONBOARDED' state. "
818 "onboardingState is {}".format(content["_admin"]["onboardingState"]),
819 http_code=HTTPStatus.CONFLICT)
820 storage = content["_admin"]["storage"]
821 if path is not None and path != "$DESCRIPTOR": # artifacts
822 if not storage.get('pkg-dir'):
823 raise EngineException("Packages does not contains artifacts", http_code=HTTPStatus.BAD_REQUEST)
824 if self.fs.file_exists((storage['folder'], storage['pkg-dir'], *path), 'dir'):
825 folder_content = self.fs.dir_ls((storage['folder'], storage['pkg-dir'], *path))
826 return folder_content, "text/plain"
827 # TODO manage folders in http
828 else:
829 return self.fs.file_open((storage['folder'], storage['pkg-dir'], *path), "rb"), \
830 "application/octet-stream"
831
832 # pkgtype accept ZIP TEXT -> result
833 # manyfiles yes X -> zip
834 # no yes -> error
835 # onefile yes no -> zip
836 # X yes -> text
837
838 if accept_text and (not storage.get('pkg-dir') or path == "$DESCRIPTOR"):
839 return self.fs.file_open((storage['folder'], storage['descriptor']), "r"), "text/plain"
840 elif storage.get('pkg-dir') and not accept_zip:
841 raise EngineException("Packages that contains several files need to be retrieved with 'application/zip'"
842 "Accept header", http_code=HTTPStatus.NOT_ACCEPTABLE)
843 else:
844 if not storage.get('zipfile'):
845 # TODO generate zipfile if not present
846 raise EngineException("Only allowed 'text/plain' Accept header for this descriptor. To be solved in future versions"
847 "", http_code=HTTPStatus.NOT_ACCEPTABLE)
848 return self.fs.file_open((storage['folder'], storage['zipfile']), "rb"), "application/zip"
849
850 def get_item_list(self, session, item, filter={}):
851 """
852 Get a list of items
853 :param session: contains the used login username and working project
854 :param item: it can be: users, projects, vnfds, nsds, ...
855 :param filter: filter of data to be applied
856 :return: The list, it can be empty if no one match the filter.
857 """
858 # TODO add admin to filter, validate rights
859 # TODO transform data for SOL005 URL requests. Transform filtering
860 # TODO implement "field-type" query string SOL005
861
862 self._add_read_filter(session, item, filter)
863 return self.db.get_list(item, filter)
864
865 def get_item(self, session, item, _id):
866 """
867 Get complete information on an items
868 :param session: contains the used login username and working project
869 :param item: it can be: users, projects, vnfds, nsds,
870 :param _id: server id of the item
871 :return: dictionary, raise exception if not found.
872 """
873 database_item = item
874 filter = {"_id": _id}
875 # TODO add admin to filter, validate rights
876 # TODO transform data for SOL005 URL requests
877 self._add_read_filter(session, item, filter)
878 return self.db.get_one(item, filter)
879
880 def del_item_list(self, session, item, filter={}):
881 """
882 Delete a list of items
883 :param session: contains the used login username and working project
884 :param item: it can be: users, projects, vnfds, nsds, ...
885 :param filter: filter of data to be applied
886 :return: The deleted list, it can be empty if no one match the filter.
887 """
888 # TODO add admin to filter, validate rights
889 self._add_read_filter(session, item, filter)
890 return self.db.del_list(item, filter)
891
892 def del_item(self, session, item, _id, force=False):
893 """
894 Delete item by its internal id
895 :param session: contains the used login username and working project
896 :param item: it can be: users, projects, vnfds, nsds, ...
897 :param _id: server id of the item
898 :param force: indicates if deletion must be forced in case of conflict
899 :return: dictionary with deleted item _id. It raises exception if not found.
900 """
901 # TODO add admin to filter, validate rights
902 # data = self.get_item(item, _id)
903 filter = {"_id": _id}
904 self._add_delete_filter(session, item, filter)
905 if item in ("vnfds", "nsds") and not force:
906 descriptor = self.get_item(session, item, _id)
907 descriptor_id = descriptor["id"]
908 self._check_dependencies_on_descriptor(session, item, descriptor_id)
909
910 if item == "nsrs":
911 nsr = self.db.get_one(item, filter)
912 if nsr["_admin"]["nsState"] == "INSTANTIATED" and not force:
913 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
914 "Launch 'terminate' action first; or force deletion".format(_id),
915 http_code=HTTPStatus.CONFLICT)
916 v = self.db.del_one(item, {"_id": _id})
917 self.db.del_list("nslcmops", {"nsInstanceId": _id})
918 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
919 self.msg.write("ns", "deleted", {"_id": _id})
920 return v
921 if item in ("vim_accounts", "sdns"):
922 desc = self.db.get_one(item, filter)
923 desc["_admin"]["to_delete"] = True
924 self.db.replace(item, _id, desc) # TODO change to set_one
925 if item == "vim_accounts":
926 self.msg.write("vim_account", "delete", {"_id": _id})
927 elif item == "sdns":
928 self.msg.write("sdn", "delete", {"_id": _id})
929 return {"deleted": 1} # TODO indicate an offline operation to return 202 ACCEPTED
930
931 v = self.db.del_one(item, filter)
932 self.fs.file_delete(_id, ignore_non_exist=True)
933 return v
934
935 def prune(self):
936 """
937 Prune database not needed content
938 :return: None
939 """
940 return self.db.del_list("nsrs", {"_admin.to_delete": True})
941
942 def create_admin(self):
943 """
944 Creates a new user admin/admin into database if database is empty. Useful for initialization
945 :return: _id identity of the inserted data, or None
946 """
947 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
948 if users:
949 return None
950 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
951 indata = {"username": "admin", "password": "admin", "projects": ["admin"]}
952 fake_session = {"project_id": "admin", "username": "admin"}
953 self._format_new_data(fake_session, "users", indata)
954 _id = self.db.create("users", indata)
955 return _id
956
957 def init_db(self, target_version='1.0'):
958 """
959 Init database if empty. If not empty it checks that database version is ok.
960 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
961 :return: None if ok, exception if error or if the version is different.
962 """
963 version = self.db.get_one("version", fail_on_empty=False, fail_on_more=False)
964 if not version:
965 # create user admin
966 self.create_admin()
967 # create database version
968 version_data = {
969 "_id": '1.0', # version text
970 "version": 1000, # version number
971 "date": "2018-04-12", # version date
972 "description": "initial design", # changes in this version
973 'status': 'ENABLED' # ENABLED, DISABLED (migration in process), ERROR,
974 }
975 self.db.create("version", version_data)
976 elif version["_id"] != target_version:
977 # TODO implement migration process
978 raise EngineException("Wrong database version '{}'. Expected '{}'".format(
979 version["_id"], target_version), HTTPStatus.INTERNAL_SERVER_ERROR)
980 elif version["status"] != 'ENABLED':
981 raise EngineException("Wrong database status '{}'".format(
982 version["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
983 return
984
985 def _edit_item(self, session, item, id, content, indata={}, kwargs=None, force=False):
986 if indata:
987 indata = self._remove_envelop(item, indata)
988
989 # Override descriptor with query string kwargs
990 if kwargs:
991 try:
992 for k, v in kwargs.items():
993 update_content = indata
994 kitem_old = None
995 klist = k.split(".")
996 for kitem in klist:
997 if kitem_old is not None:
998 update_content = update_content[kitem_old]
999 if isinstance(update_content, dict):
1000 kitem_old = kitem
1001 elif isinstance(update_content, list):
1002 kitem_old = int(kitem)
1003 else:
1004 raise EngineException(
1005 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
1006 update_content[kitem_old] = v
1007 except KeyError:
1008 raise EngineException(
1009 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
1010 except ValueError:
1011 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
1012 k, kitem))
1013 except IndexError:
1014 raise EngineException(
1015 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
1016 try:
1017 validate_input(content, item, new=False)
1018 except ValidationError as e:
1019 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1020
1021 _deep_update(content, indata)
1022 self._validate_new_data(session, item, content, id, force)
1023 # self._format_new_data(session, item, content)
1024 self.db.replace(item, id, content)
1025 if item in ("vim_accounts", "sdns"):
1026 indata.pop("_admin", None)
1027 indata["_id"] = id
1028 if item == "vim_accounts":
1029 self.msg.write("vim_account", "edit", indata)
1030 elif item == "sdns":
1031 self.msg.write("sdn", "edit", indata)
1032 return id
1033
1034 def edit_item(self, session, item, _id, indata={}, kwargs=None, force=False):
1035 """
1036 Update an existing entry at database
1037 :param session: contains the used login username and working project
1038 :param item: it can be: users, projects, vnfds, nsds, ...
1039 :param _id: identifier to be updated
1040 :param indata: data to be inserted
1041 :param kwargs: used to override the indata descriptor
1042 :param force: If True avoid some dependence checks
1043 :return: dictionary, raise exception if not found.
1044 """
1045
1046 content = self.get_item(session, item, _id)
1047 return self._edit_item(session, item, _id, content, indata, kwargs, force)
1048