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