219becf8fde9b54376c7d5453e3d20687bd04e44
[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 filter = {"name": indata.get("name")}
325 if id:
326 filter["_id.neq"] = id
327 if self.db.get_one(item, filter, fail_on_empty=False, fail_on_more=False):
328 raise EngineException("name '{}' already exists for {}".format(indata["name"], item),
329 HTTPStatus.CONFLICT)
330
331 def _check_ns_operation(self, session, nsr, operation, indata):
332 """
333 Check that user has enter right parameters for the operation
334 :param session:
335 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
336 :param indata: descriptor with the parameters of the operation
337 :return: None
338 """
339 if operation == "action":
340 if indata.get("vnf_member_index"):
341 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
342 for vnf in nsr["nsd"]["constituent-vnfd"]:
343 if indata["member_vnf_index"] == vnf["member-vnf-index"]:
344 # TODO get vnfd, check primitives
345 break
346 else:
347 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the nsd "
348 "constituent-vnfd".format(indata["member_vnf_index"]))
349
350 def _format_new_data(self, session, item, indata):
351 now = time()
352 if "_admin" not in indata:
353 indata["_admin"] = {}
354 indata["_admin"]["created"] = now
355 indata["_admin"]["modified"] = now
356 if item == "users":
357 indata["_id"] = indata["username"]
358 salt = uuid4().hex
359 indata["_admin"]["salt"] = salt
360 indata["password"] = sha256(indata["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
361 elif item == "projects":
362 indata["_id"] = indata["name"]
363 else:
364 if not indata.get("_id"):
365 indata["_id"] = str(uuid4())
366 if item in ("vnfds", "nsds", "nsrs", "vnfrs"):
367 if not indata["_admin"].get("projects_read"):
368 indata["_admin"]["projects_read"] = [session["project_id"]]
369 if not indata["_admin"].get("projects_write"):
370 indata["_admin"]["projects_write"] = [session["project_id"]]
371 if item in ("vnfds", "nsds"):
372 indata["_admin"]["onboardingState"] = "CREATED"
373 indata["_admin"]["operationalState"] = "DISABLED"
374 indata["_admin"]["usageSate"] = "NOT_IN_USE"
375 if item == "nsrs":
376 indata["_admin"]["nsState"] = "NOT_INSTANTIATED"
377 if item in ("vim_accounts", "sdns"):
378 indata["_admin"]["operationalState"] = "PROCESSING"
379
380 def upload_content(self, session, item, _id, indata, kwargs, headers):
381 """
382 Used for receiving content by chunks (with a transaction_id header and/or gzip file. It will store and extract)
383 :param session: session
384 :param item: can be nsds or vnfds
385 :param _id : the nsd,vnfd is already created, this is the id
386 :param indata: http body request
387 :param kwargs: user query string to override parameters. NOT USED
388 :param headers: http request headers
389 :return: True package has is completely uploaded or False if partial content has been uplodaed.
390 Raise exception on error
391 """
392 # Check that _id exists and it is valid
393 current_desc = self.get_item(session, item, _id)
394
395 content_range_text = headers.get("Content-Range")
396 expected_md5 = headers.get("Content-File-MD5")
397 compressed = None
398 content_type = headers.get("Content-Type")
399 if content_type and "application/gzip" in content_type or "application/x-gzip" in content_type or \
400 "application/zip" in content_type:
401 compressed = "gzip"
402 filename = headers.get("Content-Filename")
403 if not filename:
404 filename = "package.tar.gz" if compressed else "package"
405 # TODO change to Content-Disposition filename https://tools.ietf.org/html/rfc6266
406 file_pkg = None
407 error_text = ""
408 try:
409 if content_range_text:
410 content_range = content_range_text.replace("-", " ").replace("/", " ").split()
411 if content_range[0] != "bytes": # TODO check x<y not negative < total....
412 raise IndexError()
413 start = int(content_range[1])
414 end = int(content_range[2]) + 1
415 total = int(content_range[3])
416 else:
417 start = 0
418
419 if start:
420 if not self.fs.file_exists(_id, 'dir'):
421 raise EngineException("invalid Transaction-Id header", HTTPStatus.NOT_FOUND)
422 else:
423 self.fs.file_delete(_id, ignore_non_exist=True)
424 self.fs.mkdir(_id)
425
426 storage = self.fs.get_params()
427 storage["folder"] = _id
428
429 file_path = (_id, filename)
430 if self.fs.file_exists(file_path, 'file'):
431 file_size = self.fs.file_size(file_path)
432 else:
433 file_size = 0
434 if file_size != start:
435 raise EngineException("invalid Content-Range start sequence, expected '{}' but received '{}'".format(
436 file_size, start), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
437 file_pkg = self.fs.file_open(file_path, 'a+b')
438 if isinstance(indata, dict):
439 indata_text = yaml.safe_dump(indata, indent=4, default_flow_style=False)
440 file_pkg.write(indata_text.encode(encoding="utf-8"))
441 else:
442 indata_len = 0
443 while True:
444 indata_text = indata.read(4096)
445 indata_len += len(indata_text)
446 if not indata_text:
447 break
448 file_pkg.write(indata_text)
449 if content_range_text:
450 if indata_len != end-start:
451 raise EngineException("Mismatch between Content-Range header {}-{} and body length of {}".format(
452 start, end-1, indata_len), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
453 if end != total:
454 # TODO update to UPLOADING
455 return False
456
457 # PACKAGE UPLOADED
458 if expected_md5:
459 file_pkg.seek(0, 0)
460 file_md5 = md5()
461 chunk_data = file_pkg.read(1024)
462 while chunk_data:
463 file_md5.update(chunk_data)
464 chunk_data = file_pkg.read(1024)
465 if expected_md5 != file_md5.hexdigest():
466 raise EngineException("Error, MD5 mismatch", HTTPStatus.CONFLICT)
467 file_pkg.seek(0, 0)
468 if compressed == "gzip":
469 tar = tarfile.open(mode='r', fileobj=file_pkg)
470 descriptor_file_name = None
471 for tarinfo in tar:
472 tarname = tarinfo.name
473 tarname_path = tarname.split("/")
474 if not tarname_path[0] or ".." in tarname_path: # if start with "/" means absolute path
475 raise EngineException("Absolute path or '..' are not allowed for package descriptor tar.gz")
476 if len(tarname_path) == 1 and not tarinfo.isdir():
477 raise EngineException("All files must be inside a dir for package descriptor tar.gz")
478 if tarname.endswith(".yaml") or tarname.endswith(".json") or tarname.endswith(".yml"):
479 storage["pkg-dir"] = tarname_path[0]
480 if len(tarname_path) == 2:
481 if descriptor_file_name:
482 raise EngineException(
483 "Found more than one descriptor file at package descriptor tar.gz")
484 descriptor_file_name = tarname
485 if not descriptor_file_name:
486 raise EngineException("Not found any descriptor file at package descriptor tar.gz")
487 storage["descriptor"] = descriptor_file_name
488 storage["zipfile"] = filename
489 self.fs.file_extract(tar, _id)
490 with self.fs.file_open((_id, descriptor_file_name), "r") as descriptor_file:
491 content = descriptor_file.read()
492 else:
493 content = file_pkg.read()
494 storage["descriptor"] = descriptor_file_name = filename
495
496 if descriptor_file_name.endswith(".json"):
497 error_text = "Invalid json format "
498 indata = json.load(content)
499 else:
500 error_text = "Invalid yaml format "
501 indata = yaml.load(content)
502
503 current_desc["_admin"]["storage"] = storage
504 current_desc["_admin"]["onboardingState"] = "ONBOARDED"
505 current_desc["_admin"]["operationalState"] = "ENABLED"
506
507 self._edit_item(session, item, _id, current_desc, indata, kwargs)
508 # TODO if descriptor has changed because kwargs update content and remove cached zip
509 # TODO if zip is not present creates one
510 return True
511
512 except EngineException:
513 raise
514 except IndexError:
515 raise EngineException("invalid Content-Range header format. Expected 'bytes start-end/total'",
516 HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
517 except IOError as e:
518 raise EngineException("invalid upload transaction sequence: '{}'".format(e), HTTPStatus.BAD_REQUEST)
519 except tarfile.ReadError as e:
520 raise EngineException("invalid file content {}".format(e), HTTPStatus.BAD_REQUEST)
521 except (ValueError, yaml.YAMLError) as e:
522 raise EngineException(error_text + str(e))
523 finally:
524 if file_pkg:
525 file_pkg.close()
526
527 def new_nsr(self, session, ns_request):
528 """
529 Creates a new nsr into database. It also creates needed vnfrs
530 :param session: contains the used login username and working project
531 :param ns_request: params to be used for the nsr
532 :return: the _id of nsr descriptor stored at database
533 """
534 rollback = []
535 step = ""
536 try:
537 # look for nsr
538 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
539 nsd = self.get_item(session, "nsds", ns_request["nsdId"])
540 nsr_id = str(uuid4())
541 now = time()
542 step = "filling nsr from input data"
543 nsr_descriptor = {
544 "name": ns_request["nsName"],
545 "name-ref": ns_request["nsName"],
546 "short-name": ns_request["nsName"],
547 "admin-status": "ENABLED",
548 "nsd": nsd,
549 "datacenter": ns_request["vimAccountId"],
550 "resource-orchestrator": "osmopenmano",
551 "description": ns_request.get("nsDescription", ""),
552 "constituent-vnfr-ref": [],
553
554 "operational-status": "init", # typedef ns-operational-
555 "config-status": "init", # typedef config-states
556 "detailed-status": "scheduled",
557
558 "orchestration-progress": {},
559 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
560
561 "crete-time": now,
562 "nsd-name-ref": nsd["name"],
563 "operational-events": [], # "id", "timestamp", "description", "event",
564 "nsd-ref": nsd["id"],
565 "instantiate_params": ns_request,
566 "ns-instance-config-ref": nsr_id,
567 "id": nsr_id,
568 "_id": nsr_id,
569 # "input-parameter": xpath, value,
570 "ssh-authorized-key": ns_request.get("key-pair-ref"),
571 }
572 ns_request["nsr_id"] = nsr_id
573
574 # Create VNFR
575 needed_vnfds = {}
576 for member_vnf in nsd["constituent-vnfd"]:
577 vnfd_id = member_vnf["vnfd-id-ref"]
578 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
579 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
580 if vnfd_id not in needed_vnfds:
581 # Obtain vnfd
582 vnf_filter = {"id": vnfd_id}
583 self._add_read_filter(session, "vnfds", vnf_filter)
584 vnfd = self.db.get_one("vnfds", vnf_filter)
585 vnfd.pop("_admin")
586 needed_vnfds[vnfd_id] = vnfd
587 else:
588 vnfd = needed_vnfds[vnfd_id]
589 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
590 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
591 vnfr_id = str(uuid4())
592 vnfr_descriptor = {
593 "id": vnfr_id,
594 "_id": vnfr_id,
595 "nsr-id-ref": nsr_id,
596 "member-vnf-index-ref": member_vnf["member-vnf-index"],
597 "created-time": now,
598 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
599 "vnfd-ref": vnfd_id,
600 "vnfd-id": vnfr_id, # not at OSM model, but useful
601 "vim-account-id": None,
602 "vdur": [],
603 "connection-point": [],
604 "ip-address": None, # mgmt-interface filled by LCM
605 }
606 for cp in vnfd.get("connection-point", ()):
607 vnf_cp = {
608 "name": cp["name"],
609 "connection-point-id": cp.get("id"),
610 "id": cp.get("id"),
611 # "ip-address", "mac-address" # filled by LCM
612 # vim-id # TODO it would be nice having a vim port id
613 }
614 vnfr_descriptor["connection-point"].append(vnf_cp)
615 for vdu in vnfd["vdu"]:
616 vdur_id = str(uuid4())
617 vdur = {
618 "id": vdur_id,
619 "vdu-id-ref": vdu["id"],
620 "ip-address": None, # mgmt-interface filled by LCM
621 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
622 "internal-connection-point": [],
623 }
624 # TODO volumes: name, volume-id
625 for icp in vdu.get("internal-connection-point", ()):
626 vdu_icp = {
627 "id": icp["id"],
628 "connection-point-id": icp["id"],
629 "name": icp.get("name"),
630 # "ip-address", "mac-address" # filled by LCM
631 # vim-id # TODO it would be nice having a vim port id
632 }
633 vdur["internal-connection-point"].append(vdu_icp)
634 vnfr_descriptor["vdur"].append(vdur)
635
636 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
637 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
638 self._format_new_data(session, "vnfrs", vnfr_descriptor)
639 self.db.create("vnfrs", vnfr_descriptor)
640 rollback.append({"session": session, "item": "vnfrs", "_id": vnfr_id, "force": True})
641 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
642
643 step = "creating nsr at database"
644 self._format_new_data(session, "nsrs", nsr_descriptor)
645 self.db.create("nsrs", nsr_descriptor)
646 return nsr_id
647 except Exception as e:
648 raise EngineException("Error {}: {}".format(step, e))
649 for rollback_item in rollback:
650 try:
651 self.engine.del_item(**rollback)
652 except Exception as e2:
653 self.logger.error("Rollback Exception {}: {}".format(rollback, e2))
654
655 @staticmethod
656 def _update_descriptor(desc, kwargs):
657 """
658 Update descriptor with the kwargs. It contains dot separated keys
659 :param desc: dictionary to be updated
660 :param kwargs: plain dictionary to be used for updating.
661 :return:
662 """
663 if not kwargs:
664 return
665 try:
666 for k, v in kwargs.items():
667 update_content = desc
668 kitem_old = None
669 klist = k.split(".")
670 for kitem in klist:
671 if kitem_old is not None:
672 update_content = update_content[kitem_old]
673 if isinstance(update_content, dict):
674 kitem_old = kitem
675 elif isinstance(update_content, list):
676 kitem_old = int(kitem)
677 else:
678 raise EngineException(
679 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
680 update_content[kitem_old] = v
681 except KeyError:
682 raise EngineException(
683 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
684 except ValueError:
685 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
686 k, kitem))
687 except IndexError:
688 raise EngineException(
689 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
690
691 def new_item(self, session, item, indata={}, kwargs=None, headers={}, force=False):
692 """
693 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
694 that must be completed with a call to method upload_content
695 :param session: contains the used login username and working project
696 :param item: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
697 :param indata: data to be inserted
698 :param kwargs: used to override the indata descriptor
699 :param headers: http request headers
700 :param force: If True avoid some dependence checks
701 :return: _id: identity of the inserted data.
702 """
703
704 try:
705 item_envelop = item
706 if item in ("nsds", "vnfds"):
707 item_envelop = "userDefinedData"
708 content = self._remove_envelop(item_envelop, indata)
709
710 # Override descriptor with query string kwargs
711 self._update_descriptor(content, kwargs)
712 if not indata and item not in ("nsds", "vnfds"):
713 raise EngineException("Empty payload")
714
715 validate_input(content, item, new=True)
716
717 if item == "nsrs":
718 # in this case the input descriptor is not the data to be stored
719 return self.new_nsr(session, ns_request=content)
720
721 self._validate_new_data(session, item_envelop, content, force)
722 if item in ("nsds", "vnfds"):
723 content = {"_admin": {"userDefinedData": content}}
724 self._format_new_data(session, item, content)
725 _id = self.db.create(item, content)
726
727 if item == "vim_accounts":
728 msg_data = self.db.get_one(item, {"_id": _id})
729 msg_data.pop("_admin", None)
730 self.msg.write("vim_account", "create", msg_data)
731 elif item == "sdns":
732 msg_data = self.db.get_one(item, {"_id": _id})
733 msg_data.pop("_admin", None)
734 self.msg.write("sdn", "create", msg_data)
735 return _id
736 except ValidationError as e:
737 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
738
739 def new_nslcmop(self, session, nsInstanceId, operation, params):
740 now = time()
741 _id = str(uuid4())
742 nslcmop = {
743 "id": _id,
744 "_id": _id,
745 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
746 "statusEnteredTime": now,
747 "nsInstanceId": nsInstanceId,
748 "lcmOperationType": operation,
749 "startTime": now,
750 "isAutomaticInvocation": False,
751 "operationParams": params,
752 "isCancelPending": False,
753 "links": {
754 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
755 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsInstanceId,
756 }
757 }
758 return nslcmop
759
760 def ns_operation(self, session, nsInstanceId, operation, indata, kwargs=None):
761 """
762 Performs a new operation over a ns
763 :param session: contains the used login username and working project
764 :param nsInstanceId: _id of the nsr to perform the operation
765 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
766 :param indata: descriptor with the parameters of the operation
767 :param kwargs: used to override the indata descriptor
768 :return: id of the nslcmops
769 """
770 try:
771 # Override descriptor with query string kwargs
772 self._update_descriptor(indata, kwargs)
773 validate_input(indata, "ns_" + operation, new=True)
774 # get ns from nsr_id
775 nsr = self.get_item(session, "nsrs", nsInstanceId)
776 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
777 if operation == "terminate" and indata.get("autoremove"):
778 # NSR must be deleted
779 return self.del_item(session, "nsrs", nsInstanceId)
780 if operation != "instantiate":
781 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
782 nsInstanceId, operation), HTTPStatus.CONFLICT)
783 else:
784 if operation == "instantiate" and not indata.get("force"):
785 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
786 nsInstanceId, operation), HTTPStatus.CONFLICT)
787 indata["nsInstanceId"] = nsInstanceId
788 self._check_ns_operation(session, nsr, operation, indata)
789 nslcmop = self.new_nslcmop(session, nsInstanceId, operation, indata)
790 self._format_new_data(session, "nslcmops", nslcmop)
791 _id = self.db.create("nslcmops", nslcmop)
792 indata["_id"] = _id
793 self.msg.write("ns", operation, nslcmop)
794 return _id
795 except ValidationError as e:
796 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
797 # except DbException as e:
798 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
799
800 def _add_read_filter(self, session, item, filter):
801 if session["project_id"] == "admin": # allows all
802 return filter
803 if item == "users":
804 filter["username"] = session["username"]
805 elif item in ("vnfds", "nsds", "nsrs"):
806 filter["_admin.projects_read.cont"] = ["ANY", session["project_id"]]
807
808 def _add_delete_filter(self, session, item, filter):
809 if session["project_id"] != "admin" and item in ("users", "projects"):
810 raise EngineException("Only admin users can perform this task", http_code=HTTPStatus.FORBIDDEN)
811 if item == "users":
812 if filter.get("_id") == session["username"] or filter.get("username") == session["username"]:
813 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
814 elif item == "project":
815 if filter.get("_id") == session["project_id"]:
816 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
817 elif item in ("vnfds", "nsds") and session["project_id"] != "admin":
818 filter["_admin.projects_write.cont"] = ["ANY", session["project_id"]]
819
820 def get_file(self, session, item, _id, path=None, accept_header=None):
821 """
822 Return the file content of a vnfd or nsd
823 :param session: contains the used login username and working project
824 :param item: it can be vnfds or nsds
825 :param _id: Identity of the vnfd, ndsd
826 :param path: artifact path or "$DESCRIPTOR" or None
827 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
828 :return: opened file or raises an exception
829 """
830 accept_text = accept_zip = False
831 if accept_header:
832 if 'text/plain' in accept_header or '*/*' in accept_header:
833 accept_text = True
834 if 'application/zip' in accept_header or '*/*' in accept_header:
835 accept_zip = True
836 if not accept_text and not accept_zip:
837 raise EngineException("provide request header 'Accept' with 'application/zip' or 'text/plain'",
838 http_code=HTTPStatus.NOT_ACCEPTABLE)
839
840 content = self.get_item(session, item, _id)
841 if content["_admin"]["onboardingState"] != "ONBOARDED":
842 raise EngineException("Cannot get content because this resource is not at 'ONBOARDED' state. "
843 "onboardingState is {}".format(content["_admin"]["onboardingState"]),
844 http_code=HTTPStatus.CONFLICT)
845 storage = content["_admin"]["storage"]
846 if path is not None and path != "$DESCRIPTOR": # artifacts
847 if not storage.get('pkg-dir'):
848 raise EngineException("Packages does not contains artifacts", http_code=HTTPStatus.BAD_REQUEST)
849 if self.fs.file_exists((storage['folder'], storage['pkg-dir'], *path), 'dir'):
850 folder_content = self.fs.dir_ls((storage['folder'], storage['pkg-dir'], *path))
851 return folder_content, "text/plain"
852 # TODO manage folders in http
853 else:
854 return self.fs.file_open((storage['folder'], storage['pkg-dir'], *path), "rb"), \
855 "application/octet-stream"
856
857 # pkgtype accept ZIP TEXT -> result
858 # manyfiles yes X -> zip
859 # no yes -> error
860 # onefile yes no -> zip
861 # X yes -> text
862
863 if accept_text and (not storage.get('pkg-dir') or path == "$DESCRIPTOR"):
864 return self.fs.file_open((storage['folder'], storage['descriptor']), "r"), "text/plain"
865 elif storage.get('pkg-dir') and not accept_zip:
866 raise EngineException("Packages that contains several files need to be retrieved with 'application/zip'"
867 "Accept header", http_code=HTTPStatus.NOT_ACCEPTABLE)
868 else:
869 if not storage.get('zipfile'):
870 # TODO generate zipfile if not present
871 raise EngineException("Only allowed 'text/plain' Accept header for this descriptor. To be solved in "
872 "future versions", http_code=HTTPStatus.NOT_ACCEPTABLE)
873 return self.fs.file_open((storage['folder'], storage['zipfile']), "rb"), "application/zip"
874
875 def get_item_list(self, session, item, filter={}):
876 """
877 Get a list of items
878 :param session: contains the used login username and working project
879 :param item: it can be: users, projects, vnfds, nsds, ...
880 :param filter: filter of data to be applied
881 :return: The list, it can be empty if no one match the filter.
882 """
883 # TODO add admin to filter, validate rights
884 # TODO transform data for SOL005 URL requests. Transform filtering
885 # TODO implement "field-type" query string SOL005
886
887 self._add_read_filter(session, item, filter)
888 return self.db.get_list(item, filter)
889
890 def get_item(self, session, item, _id):
891 """
892 Get complete information on an items
893 :param session: contains the used login username and working project
894 :param item: it can be: users, projects, vnfds, nsds,
895 :param _id: server id of the item
896 :return: dictionary, raise exception if not found.
897 """
898 filter = {"_id": _id}
899 # TODO add admin to filter, validate rights
900 # TODO transform data for SOL005 URL requests
901 self._add_read_filter(session, item, filter)
902 return self.db.get_one(item, filter)
903
904 def del_item_list(self, session, item, filter={}):
905 """
906 Delete a list of items
907 :param session: contains the used login username and working project
908 :param item: it can be: users, projects, vnfds, nsds, ...
909 :param filter: filter of data to be applied
910 :return: The deleted list, it can be empty if no one match the filter.
911 """
912 # TODO add admin to filter, validate rights
913 self._add_read_filter(session, item, filter)
914 return self.db.del_list(item, filter)
915
916 def del_item(self, session, item, _id, force=False):
917 """
918 Delete item by its internal id
919 :param session: contains the used login username and working project
920 :param item: it can be: users, projects, vnfds, nsds, ...
921 :param _id: server id of the item
922 :param force: indicates if deletion must be forced in case of conflict
923 :return: dictionary with deleted item _id. It raises exception if not found.
924 """
925 # TODO add admin to filter, validate rights
926 # data = self.get_item(item, _id)
927 filter = {"_id": _id}
928 self._add_delete_filter(session, item, filter)
929 if item in ("vnfds", "nsds") and not force:
930 descriptor = self.get_item(session, item, _id)
931 descriptor_id = descriptor["id"]
932 self._check_dependencies_on_descriptor(session, item, descriptor_id)
933
934 if item == "nsrs":
935 nsr = self.db.get_one(item, filter)
936 if nsr["_admin"]["nsState"] == "INSTANTIATED" and not force:
937 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
938 "Launch 'terminate' operation first; or force deletion".format(_id),
939 http_code=HTTPStatus.CONFLICT)
940 v = self.db.del_one(item, {"_id": _id})
941 self.db.del_list("nslcmops", {"nsInstanceId": _id})
942 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
943 self.msg.write("ns", "deleted", {"_id": _id})
944 return v
945 if item in ("vim_accounts", "sdns"):
946 desc = self.db.get_one(item, filter)
947 desc["_admin"]["to_delete"] = True
948 self.db.replace(item, _id, desc) # TODO change to set_one
949 if item == "vim_accounts":
950 self.msg.write("vim_account", "delete", {"_id": _id})
951 elif item == "sdns":
952 self.msg.write("sdn", "delete", {"_id": _id})
953 return {"deleted": 1} # TODO indicate an offline operation to return 202 ACCEPTED
954
955 v = self.db.del_one(item, filter)
956 self.fs.file_delete(_id, ignore_non_exist=True)
957 return v
958
959 def prune(self):
960 """
961 Prune database not needed content
962 :return: None
963 """
964 return self.db.del_list("nsrs", {"_admin.to_delete": True})
965
966 def create_admin(self):
967 """
968 Creates a new user admin/admin into database if database is empty. Useful for initialization
969 :return: _id identity of the inserted data, or None
970 """
971 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
972 if users:
973 return None
974 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
975 indata = {"username": "admin", "password": "admin", "projects": ["admin"]}
976 fake_session = {"project_id": "admin", "username": "admin"}
977 self._format_new_data(fake_session, "users", indata)
978 _id = self.db.create("users", indata)
979 return _id
980
981 def init_db(self, target_version='1.0'):
982 """
983 Init database if empty. If not empty it checks that database version is ok.
984 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
985 :return: None if ok, exception if error or if the version is different.
986 """
987 version = self.db.get_one("version", fail_on_empty=False, fail_on_more=False)
988 if not version:
989 # create user admin
990 self.create_admin()
991 # create database version
992 version_data = {
993 "_id": '1.0', # version text
994 "version": 1000, # version number
995 "date": "2018-04-12", # version date
996 "description": "initial design", # changes in this version
997 'status': 'ENABLED' # ENABLED, DISABLED (migration in process), ERROR,
998 }
999 self.db.create("version", version_data)
1000 elif version["_id"] != target_version:
1001 # TODO implement migration process
1002 raise EngineException("Wrong database version '{}'. Expected '{}'".format(
1003 version["_id"], target_version), HTTPStatus.INTERNAL_SERVER_ERROR)
1004 elif version["status"] != 'ENABLED':
1005 raise EngineException("Wrong database status '{}'".format(
1006 version["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
1007 return
1008
1009 def _edit_item(self, session, item, id, content, indata={}, kwargs=None, force=False):
1010 if indata:
1011 indata = self._remove_envelop(item, indata)
1012
1013 # Override descriptor with query string kwargs
1014 if kwargs:
1015 try:
1016 for k, v in kwargs.items():
1017 update_content = indata
1018 kitem_old = None
1019 klist = k.split(".")
1020 for kitem in klist:
1021 if kitem_old is not None:
1022 update_content = update_content[kitem_old]
1023 if isinstance(update_content, dict):
1024 kitem_old = kitem
1025 elif isinstance(update_content, list):
1026 kitem_old = int(kitem)
1027 else:
1028 raise EngineException(
1029 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
1030 update_content[kitem_old] = v
1031 except KeyError:
1032 raise EngineException(
1033 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
1034 except ValueError:
1035 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
1036 k, kitem))
1037 except IndexError:
1038 raise EngineException(
1039 "Invalid query string '{}'. Index '{}' out of range".format(k, kitem_old))
1040 try:
1041 validate_input(indata, item, new=False)
1042 except ValidationError as e:
1043 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1044
1045 _deep_update(content, indata)
1046 self._validate_new_data(session, item, content, id, force)
1047 # self._format_new_data(session, item, content)
1048 self.db.replace(item, id, content)
1049 if item in ("vim_accounts", "sdns"):
1050 indata.pop("_admin", None)
1051 indata["_id"] = id
1052 if item == "vim_accounts":
1053 self.msg.write("vim_account", "edit", indata)
1054 elif item == "sdns":
1055 self.msg.write("sdn", "edit", indata)
1056 return id
1057
1058 def edit_item(self, session, item, _id, indata={}, kwargs=None, force=False):
1059 """
1060 Update an existing entry at database
1061 :param session: contains the used login username and working project
1062 :param item: it can be: users, projects, vnfds, nsds, ...
1063 :param _id: identifier to be updated
1064 :param indata: data to be inserted
1065 :param kwargs: used to override the indata descriptor
1066 :param force: If True avoid some dependence checks
1067 :return: dictionary, raise exception if not found.
1068 """
1069
1070 content = self.get_item(session, item, _id)
1071 return self._edit_item(session, item, _id, content, indata, kwargs, force)