1 # -*- coding: utf-8 -*-
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
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
20 from copy
import deepcopy
21 from validation
import validate_input
, ValidationError
23 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
26 class EngineException(Exception):
28 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
29 self
.http_code
= http_code
30 Exception.__init
__(self
, message
)
33 def _deep_update(dict_to_change
, dict_reference
):
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
40 for k
in dict_reference
:
41 if dict_reference
[k
] is None: # None->Anything
42 if k
in dict_to_change
:
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
])
52 dict_to_change
[k
] = deepcopy(dict_reference
[k
])
53 _deep_update(dict_to_change
[k
], dict_reference
[k
])
64 self
.logger
= logging
.getLogger("nbi.engine")
66 def start(self
, config
):
68 Connect to database, filesystem storage, and messaging
69 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
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"])
82 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
83 config
["database"]["driver"]))
85 if config
["storage"]["driver"] == "local":
86 self
.fs
= fslocal
.FsLocal()
87 self
.fs
.fs_connect(config
["storage"])
89 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
90 config
["storage"]["driver"]))
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"])
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
)
107 self
.db
.db_disconnect()
109 self
.fs
.fs_disconnect()
111 self
.fs
.fs_disconnect()
112 except (DbException
, FsException
, MsgException
) as e
:
113 raise EngineException(str(e
), http_code
=e
.http_code
)
115 def authorize(self
, 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
]
125 if session
["expires"] < now
:
126 del self
.tokens
[token
]
127 raise EngineException("Expired Token or Authorization http header",
128 http_code
=HTTPStatus
.UNAUTHORIZED
)
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"]}
138 def new_token(self
, session
, indata
, remote
):
142 # Try using username/password
143 if indata
.get("username"):
144 user_rows
= self
.db
.get_list("users", {"username": indata
.get("username")})
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"]:
153 raise EngineException("Invalid username/password", http_code
=HTTPStatus
.UNAUTHORIZED
)
155 user_rows
= self
.db
.get_list("users", {"username": session
["username"]})
157 user_content
= user_rows
[0]
159 raise EngineException("Invalid token", http_code
=HTTPStatus
.UNAUTHORIZED
)
161 raise EngineException("Provide credentials: username/password or Authorization Bearer token",
162 http_code
=HTTPStatus
.UNAUTHORIZED
)
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
)
172 project_id
= user_content
["projects"][0]
173 if project_id
== "admin":
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
}
182 new_session
["remote_host"] = remote
.name
184 new_session
["remote_host"] = remote
.ip
186 self
.tokens
[token_id
] = new_session
187 return deepcopy(new_session
)
189 def get_token_list(self
, session
):
191 for token_id
, token_value
in self
.tokens
.items():
192 if token_value
["username"] == session
["username"]:
193 token_list
.append(deepcopy(token_value
))
196 def get_token(self
, session
, token_id
):
197 token_value
= self
.tokens
.get(token_id
)
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
)
204 def del_token(self
, token_id
):
206 del self
.tokens
[token_id
]
207 return "token '{}' deleted".format(token_id
)
209 raise EngineException("Token '{}' not found".format(token_id
), http_code
=HTTPStatus
.NOT_FOUND
)
212 def _remove_envelop(item
, indata
=None):
214 Obtain the useful data removing the envelop. It goes throw the vnfd or nsd catalog and returns the
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
220 clean_indata
= indata
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]
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']
246 def _check_dependencies_on_descriptor(self
, session
, item
, descriptor_id
):
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
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
)
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
)
263 def _check_descriptor_dependencies(self
, session
, item
, descriptor
):
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
272 if not descriptor
.get("constituent-vnfd"):
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
)
280 if not descriptor
.get("nsdId"):
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
)
287 def _validate_new_data(self
, session
, item
, indata
, id=None, force
=False):
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"]}
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"]),
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
323 elif item
== "vim_accounts" or item
== "sdns":
324 if self
.db
.get_one(item
, {"name": indata
.get("name")}, fail_on_empty
=False, fail_on_more
=False):
325 raise EngineException("name '{}' already exists for {}".format(indata
["name"], item
),
328 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
330 Check that user has enter right parameters for the operation
332 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
333 :param indata: descriptor with the parameters of the operation
336 if operation
== "action":
337 if indata
.get("vnf_member_index"):
338 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
339 for vnf
in nsr
["nsd"]["constituent-vnfd"]:
340 if indata
["member_vnf_index"] == vnf
["member-vnf-index"]:
341 # TODO get vnfd, check primitives
344 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the nsd "
345 "constituent-vnfd".format(indata
["member_vnf_index"]))
347 def _format_new_data(self
, session
, item
, indata
):
349 if not "_admin" in indata
:
350 indata
["_admin"] = {}
351 indata
["_admin"]["created"] = now
352 indata
["_admin"]["modified"] = now
354 indata
["_id"] = indata
["username"]
356 indata
["_admin"]["salt"] = salt
357 indata
["password"] = sha256(indata
["password"].encode('utf-8') + salt
.encode('utf-8')).hexdigest()
358 elif item
== "projects":
359 indata
["_id"] = indata
["name"]
361 if not indata
.get("_id"):
362 indata
["_id"] = str(uuid4())
363 if item
in ("vnfds", "nsds", "nsrs", "vnfrs"):
364 if not indata
["_admin"].get("projects_read"):
365 indata
["_admin"]["projects_read"] = [session
["project_id"]]
366 if not indata
["_admin"].get("projects_write"):
367 indata
["_admin"]["projects_write"] = [session
["project_id"]]
368 if item
in ("vnfds", "nsds"):
369 indata
["_admin"]["onboardingState"] = "CREATED"
370 indata
["_admin"]["operationalState"] = "DISABLED"
371 indata
["_admin"]["usageSate"] = "NOT_IN_USE"
373 indata
["_admin"]["nsState"] = "NOT_INSTANTIATED"
374 if item
in ("vim_accounts", "sdns"):
375 indata
["_admin"]["operationalState"] = "PROCESSING"
377 def upload_content(self
, session
, item
, _id
, indata
, kwargs
, headers
):
379 Used for receiving content by chunks (with a transaction_id header and/or gzip file. It will store and extract)
380 :param session: session
381 :param item: can be nsds or vnfds
382 :param _id : the nsd,vnfd is already created, this is the id
383 :param indata: http body request
384 :param kwargs: user query string to override parameters. NOT USED
385 :param headers: http request headers
386 :return: True package has is completely uploaded or False if partial content has been uplodaed.
387 Raise exception on error
389 # Check that _id exists and it is valid
390 current_desc
= self
.get_item(session
, item
, _id
)
392 content_range_text
= headers
.get("Content-Range")
393 expected_md5
= headers
.get("Content-File-MD5")
395 content_type
= headers
.get("Content-Type")
396 if content_type
and "application/gzip" in content_type
or "application/x-gzip" in content_type
or \
397 "application/zip" in content_type
:
399 filename
= headers
.get("Content-Filename")
401 filename
= "package.tar.gz" if compressed
else "package"
402 # TODO change to Content-Disposition filename https://tools.ietf.org/html/rfc6266
406 if content_range_text
:
407 content_range
= content_range_text
.replace("-", " ").replace("/", " ").split()
408 if content_range
[0] != "bytes": # TODO check x<y not negative < total....
410 start
= int(content_range
[1])
411 end
= int(content_range
[2]) + 1
412 total
= int(content_range
[3])
417 if not self
.fs
.file_exists(_id
, 'dir'):
418 raise EngineException("invalid Transaction-Id header", HTTPStatus
.NOT_FOUND
)
420 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
423 storage
= self
.fs
.get_params()
424 storage
["folder"] = _id
426 file_path
= (_id
, filename
)
427 if self
.fs
.file_exists(file_path
, 'file'):
428 file_size
= self
.fs
.file_size(file_path
)
431 if file_size
!= start
:
432 raise EngineException("invalid Content-Range start sequence, expected '{}' but received '{}'".format(
433 file_size
, start
), HTTPStatus
.REQUESTED_RANGE_NOT_SATISFIABLE
)
434 file_pkg
= self
.fs
.file_open(file_path
, 'a+b')
435 if isinstance(indata
, dict):
436 indata_text
= yaml
.safe_dump(indata
, indent
=4, default_flow_style
=False)
437 file_pkg
.write(indata_text
.encode(encoding
="utf-8"))
441 indata_text
= indata
.read(4096)
442 indata_len
+= len(indata_text
)
445 file_pkg
.write(indata_text
)
446 if content_range_text
:
447 if indata_len
!= end
-start
:
448 raise EngineException("Mismatch between Content-Range header {}-{} and body length of {}".format(
449 start
, end
-1, indata_len
), HTTPStatus
.REQUESTED_RANGE_NOT_SATISFIABLE
)
451 # TODO update to UPLOADING
458 chunk_data
= file_pkg
.read(1024)
460 file_md5
.update(chunk_data
)
461 chunk_data
= file_pkg
.read(1024)
462 if expected_md5
!= file_md5
.hexdigest():
463 raise EngineException("Error, MD5 mismatch", HTTPStatus
.CONFLICT
)
465 if compressed
== "gzip":
466 tar
= tarfile
.open(mode
='r', fileobj
=file_pkg
)
467 descriptor_file_name
= None
469 tarname
= tarinfo
.name
470 tarname_path
= tarname
.split("/")
471 if not tarname_path
[0] or ".." in tarname_path
: # if start with "/" means absolute path
472 raise EngineException("Absolute path or '..' are not allowed for package descriptor tar.gz")
473 if len(tarname_path
) == 1 and not tarinfo
.isdir():
474 raise EngineException("All files must be inside a dir for package descriptor tar.gz")
475 if tarname
.endswith(".yaml") or tarname
.endswith(".json") or tarname
.endswith(".yml"):
476 storage
["pkg-dir"] = tarname_path
[0]
477 if len(tarname_path
) == 2:
478 if descriptor_file_name
:
479 raise EngineException("Found more than one descriptor file at package descriptor tar.gz")
480 descriptor_file_name
= tarname
481 if not descriptor_file_name
:
482 raise EngineException("Not found any descriptor file at package descriptor tar.gz")
483 storage
["descriptor"] = descriptor_file_name
484 storage
["zipfile"] = filename
485 self
.fs
.file_extract(tar
, _id
)
486 with self
.fs
.file_open((_id
, descriptor_file_name
), "r") as descriptor_file
:
487 content
= descriptor_file
.read()
489 content
= file_pkg
.read()
490 storage
["descriptor"] = descriptor_file_name
= filename
492 if descriptor_file_name
.endswith(".json"):
493 error_text
= "Invalid json format "
494 indata
= json
.load(content
)
496 error_text
= "Invalid yaml format "
497 indata
= yaml
.load(content
)
499 current_desc
["_admin"]["storage"] = storage
500 current_desc
["_admin"]["onboardingState"] = "ONBOARDED"
501 current_desc
["_admin"]["operationalState"] = "ENABLED"
503 self
._edit
_item
(session
, item
, _id
, current_desc
, indata
, kwargs
)
504 # TODO if descriptor has changed because kwargs update content and remove cached zip
505 # TODO if zip is not present creates one
508 except EngineException
:
511 raise EngineException("invalid Content-Range header format. Expected 'bytes start-end/total'",
512 HTTPStatus
.REQUESTED_RANGE_NOT_SATISFIABLE
)
514 raise EngineException("invalid upload transaction sequence: '{}'".format(e
), HTTPStatus
.BAD_REQUEST
)
515 except tarfile
.ReadError
as e
:
516 raise EngineException("invalid file content {}".format(e
), HTTPStatus
.BAD_REQUEST
)
517 except (ValueError, yaml
.YAMLError
) as e
:
518 raise EngineException(error_text
+ str(e
))
523 def new_nsr(self
, session
, ns_request
):
525 Creates a new nsr into database. It also creates needed vnfrs
526 :param session: contains the used login username and working project
527 :param ns_request: params to be used for the nsr
528 :return: the _id of nsr descriptor stored at database
534 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
535 nsd
= self
.get_item(session
, "nsds", ns_request
["nsdId"])
536 nsr_id
= str(uuid4())
538 step
= "filling nsr from input data"
540 "name": ns_request
["nsName"],
541 "name-ref": ns_request
["nsName"],
542 "short-name": ns_request
["nsName"],
543 "admin-status": "ENABLED",
545 "datacenter": ns_request
["vimAccountId"],
546 "resource-orchestrator": "osmopenmano",
547 "description": ns_request
.get("nsDescription", ""),
548 "constituent-vnfr-ref": [],
550 "operational-status": "init", # typedef ns-operational-
551 "config-status": "init", # typedef config-states
552 "detailed-status": "scheduled",
554 "orchestration-progress": {}, # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
557 "nsd-name-ref": nsd
["name"],
558 "operational-events": [], # "id", "timestamp", "description", "event",
559 "nsd-ref": nsd
["id"],
560 "instantiate_params": ns_request
,
561 "ns-instance-config-ref": nsr_id
,
564 # "input-parameter": xpath, value,
565 "ssh-authorized-key": ns_request
.get("key-pair-ref"),
567 ns_request
["nsr_id"] = nsr_id
571 for member_vnf
in nsd
["constituent-vnfd"]:
572 vnfd_id
= member_vnf
["vnfd-id-ref"]
573 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
574 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
575 if vnfd_id
not in needed_vnfds
:
577 vnf_filter
= {"id": vnfd_id
}
578 self
._add
_read
_filter
(session
, "vnfds", vnf_filter
)
579 vnfd
= self
.db
.get_one("vnfds", vnf_filter
)
581 needed_vnfds
[vnfd_id
] = vnfd
583 vnfd
= needed_vnfds
[vnfd_id
]
584 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
585 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
586 vnfr_id
= str(uuid4())
590 "nsr-id-ref": nsr_id
,
591 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
593 # "vnfd": vnfd, # at OSM model. TODO can it be removed in the future to avoid data duplication?
595 "vnfd-id": vnfr_id
, # not at OSM model, but useful
596 "vim-account-id": None,
598 "connection-point": [],
599 "ip-address": None, # mgmt-interface filled by LCM
601 for cp
in vnfd
.get("connection-point", ()):
604 "connection-point-id": cp
.get("id"),
606 # "ip-address", "mac-address" # filled by LCM
607 # vim-id # TODO it would be nice having a vim port id
609 vnfr_descriptor
["connection-point"].append(vnf_cp
)
610 for vdu
in vnfd
["vdu"]:
611 vdur_id
= str(uuid4())
614 "vdu-id-ref": vdu
["id"],
615 "ip-address": None, # mgmt-interface filled by LCM
616 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
617 "internal-connection-point": [],
619 # TODO volumes: name, volume-id
620 for icp
in vdu
.get("internal-connection-point", ()):
623 "connection-point-id": icp
["id"],
624 "name": icp
.get("name"),
625 # "ip-address", "mac-address" # filled by LCM
626 # vim-id # TODO it would be nice having a vim port id
628 vdur
["internal-connection-point"].append(vdu_icp
)
629 vnfr_descriptor
["vdur"].append(vdur
)
631 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
632 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
633 self
._format
_new
_data
(session
, "vnfrs", vnfr_descriptor
)
634 self
.db
.create("vnfrs", vnfr_descriptor
)
635 rollback
.append({"session": session
, "item": "vnfrs", "_id": vnfr_id
, "force": True})
636 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
638 step
= "creating nsr at database"
639 self
._format
_new
_data
(session
, "nsrs", nsr_descriptor
)
640 self
.db
.create("nsrs", nsr_descriptor
)
642 except Exception as e
:
643 raise EngineException("Error {}: {}".format(step
, e
))
644 for rollback_item
in rollback
:
646 self
.engine
.del_item(**rollback
)
647 except Exception as e2
:
648 self
.logger
.error("Rollback Exception {}: {}".format(rollback
, e2
))
651 def _update_descriptor(desc
, kwargs
):
653 Update descriptor with the kwargs
660 for k
, v
in kwargs
.items():
661 update_content
= content
665 if kitem_old
is not None:
666 update_content
= update_content
[kitem_old
]
667 if isinstance(update_content
, dict):
669 elif isinstance(update_content
, list):
670 kitem_old
= int(kitem
)
672 raise EngineException(
673 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k
, kitem
))
674 update_content
[kitem_old
] = v
676 raise EngineException(
677 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k
, kitem_old
))
679 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
682 raise EngineException(
683 "Invalid query string '{}'. Index '{}' out of range".format(k
, kitem_old
))
685 def new_item(self
, session
, item
, indata
={}, kwargs
=None, headers
={}, force
=False):
687 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
688 that must be completed with a call to method upload_content
689 :param session: contains the used login username and working project
690 :param item: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
691 :param indata: data to be inserted
692 :param kwargs: used to override the indata descriptor
693 :param headers: http request headers
694 :param force: If True avoid some dependence checks
695 :return: _id: identity of the inserted data.
700 if item
in ("nsds", "vnfds"):
701 item_envelop
= "userDefinedData"
702 content
= self
._remove
_envelop
(item_envelop
, indata
)
704 # Override descriptor with query string kwargs
705 self
._update
_descriptor
(content
, kwargs
)
706 if not indata
and item
not in ("nsds", "vnfds"):
707 raise EngineException("Empty payload")
709 validate_input(content
, item
, new
=True)
712 # in this case the input descriptor is not the data to be stored
713 return self
.new_nsr(session
, ns_request
=content
)
715 self
._validate
_new
_data
(session
, item_envelop
, content
, force
)
716 if item
in ("nsds", "vnfds"):
717 content
= {"_admin": {"userDefinedData": content
}}
718 self
._format
_new
_data
(session
, item
, content
)
719 _id
= self
.db
.create(item
, content
)
721 if item
== "vim_accounts":
722 msg_data
= self
.db
.get_one(item
, {"_id": _id
})
723 msg_data
.pop("_admin", None)
724 self
.msg
.write("vim_account", "create", msg_data
)
726 msg_data
= self
.db
.get_one(item
, {"_id": _id
})
727 msg_data
.pop("_admin", None)
728 self
.msg
.write("sdn", "create", msg_data
)
730 except ValidationError
as e
:
731 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
733 def new_nslcmop(self
, session
, nsInstanceId
, operation
, params
):
739 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
740 "statusEnteredTime": now
,
741 "nsInstanceId": nsInstanceId
,
742 "lcmOperationType": operation
,
744 "isAutomaticInvocation": False,
745 "operationParams": params
,
746 "isCancelPending": False,
748 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
749 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsInstanceId
,
754 def ns_operation(self
, session
, nsInstanceId
, operation
, indata
, kwargs
=None):
756 Performs a new operation over a ns
757 :param session: contains the used login username and working project
758 :param nsInstanceId: _id of the nsr to perform the operation
759 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
760 :param indata: descriptor with the parameters of the operation
761 :param kwargs: used to override the indata descriptor
762 :return: id of the nslcmops
765 # Override descriptor with query string kwargs
766 self
._update
_descriptor
(indata
, kwargs
)
767 validate_input(indata
, "ns_" + operation
, new
=True)
769 nsr
= self
.get_item(session
, "nsrs", nsInstanceId
)
770 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
771 if operation
== "terminate" and indata
.get("autoremove"):
772 # NSR must be deleted
773 return self
.del_item(session
, "nsrs", nsInstanceId
)
774 if operation
!= "instantiate":
775 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
776 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
778 if operation
== "instantiate" and not indata
.get("force"):
779 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
780 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
781 indata
["nsInstanceId"] = nsInstanceId
782 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
783 nslcmop
= self
.new_nslcmop(session
, nsInstanceId
, operation
, indata
)
784 self
._format
_new
_data
(session
, "nslcmops", nslcmop
)
785 _id
= self
.db
.create("nslcmops", nslcmop
)
787 self
.msg
.write("ns", operation
, nslcmop
)
789 except ValidationError
as e
:
790 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
791 # except DbException as e:
792 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
794 def _add_read_filter(self
, session
, item
, filter):
795 if session
["project_id"] == "admin": # allows all
798 filter["username"] = session
["username"]
799 elif item
in ("vnfds", "nsds", "nsrs"):
800 filter["_admin.projects_read.cont"] = ["ANY", session
["project_id"]]
802 def _add_delete_filter(self
, session
, item
, filter):
803 if session
["project_id"] != "admin" and item
in ("users", "projects"):
804 raise EngineException("Only admin users can perform this task", http_code
=HTTPStatus
.FORBIDDEN
)
806 if filter.get("_id") == session
["username"] or filter.get("username") == session
["username"]:
807 raise EngineException("You cannot delete your own user", http_code
=HTTPStatus
.CONFLICT
)
808 elif item
== "project":
809 if filter.get("_id") == session
["project_id"]:
810 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
811 elif item
in ("vnfds", "nsds") and session
["project_id"] != "admin":
812 filter["_admin.projects_write.cont"] = ["ANY", session
["project_id"]]
814 def get_file(self
, session
, item
, _id
, path
=None, accept_header
=None):
816 Return the file content of a vnfd or nsd
817 :param session: contains the used login username and working project
818 :param item: it can be vnfds or nsds
819 :param _id: Identity of the vnfd, ndsd
820 :param path: artifact path or "$DESCRIPTOR" or None
821 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
822 :return: opened file or raises an exception
824 accept_text
= accept_zip
= False
826 if 'text/plain' in accept_header
or '*/*' in accept_header
:
828 if 'application/zip' in accept_header
or '*/*' in accept_header
:
830 if not accept_text
and not accept_zip
:
831 raise EngineException("provide request header 'Accept' with 'application/zip' or 'text/plain'",
832 http_code
=HTTPStatus
.NOT_ACCEPTABLE
)
834 content
= self
.get_item(session
, item
, _id
)
835 if content
["_admin"]["onboardingState"] != "ONBOARDED":
836 raise EngineException("Cannot get content because this resource is not at 'ONBOARDED' state. "
837 "onboardingState is {}".format(content
["_admin"]["onboardingState"]),
838 http_code
=HTTPStatus
.CONFLICT
)
839 storage
= content
["_admin"]["storage"]
840 if path
is not None and path
!= "$DESCRIPTOR": # artifacts
841 if not storage
.get('pkg-dir'):
842 raise EngineException("Packages does not contains artifacts", http_code
=HTTPStatus
.BAD_REQUEST
)
843 if self
.fs
.file_exists((storage
['folder'], storage
['pkg-dir'], *path
), 'dir'):
844 folder_content
= self
.fs
.dir_ls((storage
['folder'], storage
['pkg-dir'], *path
))
845 return folder_content
, "text/plain"
846 # TODO manage folders in http
848 return self
.fs
.file_open((storage
['folder'], storage
['pkg-dir'], *path
), "rb"), \
849 "application/octet-stream"
851 # pkgtype accept ZIP TEXT -> result
852 # manyfiles yes X -> zip
854 # onefile yes no -> zip
857 if accept_text
and (not storage
.get('pkg-dir') or path
== "$DESCRIPTOR"):
858 return self
.fs
.file_open((storage
['folder'], storage
['descriptor']), "r"), "text/plain"
859 elif storage
.get('pkg-dir') and not accept_zip
:
860 raise EngineException("Packages that contains several files need to be retrieved with 'application/zip'"
861 "Accept header", http_code
=HTTPStatus
.NOT_ACCEPTABLE
)
863 if not storage
.get('zipfile'):
864 # TODO generate zipfile if not present
865 raise EngineException("Only allowed 'text/plain' Accept header for this descriptor. To be solved in future versions"
866 "", http_code
=HTTPStatus
.NOT_ACCEPTABLE
)
867 return self
.fs
.file_open((storage
['folder'], storage
['zipfile']), "rb"), "application/zip"
869 def get_item_list(self
, session
, item
, filter={}):
872 :param session: contains the used login username and working project
873 :param item: it can be: users, projects, vnfds, nsds, ...
874 :param filter: filter of data to be applied
875 :return: The list, it can be empty if no one match the filter.
877 # TODO add admin to filter, validate rights
878 # TODO transform data for SOL005 URL requests. Transform filtering
879 # TODO implement "field-type" query string SOL005
881 self
._add
_read
_filter
(session
, item
, filter)
882 return self
.db
.get_list(item
, filter)
884 def get_item(self
, session
, item
, _id
):
886 Get complete information on an items
887 :param session: contains the used login username and working project
888 :param item: it can be: users, projects, vnfds, nsds,
889 :param _id: server id of the item
890 :return: dictionary, raise exception if not found.
893 filter = {"_id": _id
}
894 # TODO add admin to filter, validate rights
895 # TODO transform data for SOL005 URL requests
896 self
._add
_read
_filter
(session
, item
, filter)
897 return self
.db
.get_one(item
, filter)
899 def del_item_list(self
, session
, item
, filter={}):
901 Delete a list of items
902 :param session: contains the used login username and working project
903 :param item: it can be: users, projects, vnfds, nsds, ...
904 :param filter: filter of data to be applied
905 :return: The deleted list, it can be empty if no one match the filter.
907 # TODO add admin to filter, validate rights
908 self
._add
_read
_filter
(session
, item
, filter)
909 return self
.db
.del_list(item
, filter)
911 def del_item(self
, session
, item
, _id
, force
=False):
913 Delete item by its internal id
914 :param session: contains the used login username and working project
915 :param item: it can be: users, projects, vnfds, nsds, ...
916 :param _id: server id of the item
917 :param force: indicates if deletion must be forced in case of conflict
918 :return: dictionary with deleted item _id. It raises exception if not found.
920 # TODO add admin to filter, validate rights
921 # data = self.get_item(item, _id)
922 filter = {"_id": _id
}
923 self
._add
_delete
_filter
(session
, item
, filter)
924 if item
in ("vnfds", "nsds") and not force
:
925 descriptor
= self
.get_item(session
, item
, _id
)
926 descriptor_id
= descriptor
["id"]
927 self
._check
_dependencies
_on
_descriptor
(session
, item
, descriptor_id
)
930 nsr
= self
.db
.get_one(item
, filter)
931 if nsr
["_admin"]["nsState"] == "INSTANTIATED" and not force
:
932 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
933 "Launch 'terminate' operation first; or force deletion".format(_id
),
934 http_code
=HTTPStatus
.CONFLICT
)
935 v
= self
.db
.del_one(item
, {"_id": _id
})
936 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
937 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
938 self
.msg
.write("ns", "deleted", {"_id": _id
})
940 if item
in ("vim_accounts", "sdns"):
941 desc
= self
.db
.get_one(item
, filter)
942 desc
["_admin"]["to_delete"] = True
943 self
.db
.replace(item
, _id
, desc
) # TODO change to set_one
944 if item
== "vim_accounts":
945 self
.msg
.write("vim_account", "delete", {"_id": _id
})
947 self
.msg
.write("sdn", "delete", {"_id": _id
})
948 return {"deleted": 1} # TODO indicate an offline operation to return 202 ACCEPTED
950 v
= self
.db
.del_one(item
, filter)
951 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
956 Prune database not needed content
959 return self
.db
.del_list("nsrs", {"_admin.to_delete": True})
961 def create_admin(self
):
963 Creates a new user admin/admin into database if database is empty. Useful for initialization
964 :return: _id identity of the inserted data, or None
966 users
= self
.db
.get_one("users", fail_on_empty
=False, fail_on_more
=False)
969 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
970 indata
= {"username": "admin", "password": "admin", "projects": ["admin"]}
971 fake_session
= {"project_id": "admin", "username": "admin"}
972 self
._format
_new
_data
(fake_session
, "users", indata
)
973 _id
= self
.db
.create("users", indata
)
976 def init_db(self
, target_version
='1.0'):
978 Init database if empty. If not empty it checks that database version is ok.
979 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
980 :return: None if ok, exception if error or if the version is different.
982 version
= self
.db
.get_one("version", fail_on_empty
=False, fail_on_more
=False)
986 # create database version
988 "_id": '1.0', # version text
989 "version": 1000, # version number
990 "date": "2018-04-12", # version date
991 "description": "initial design", # changes in this version
992 'status': 'ENABLED' # ENABLED, DISABLED (migration in process), ERROR,
994 self
.db
.create("version", version_data
)
995 elif version
["_id"] != target_version
:
996 # TODO implement migration process
997 raise EngineException("Wrong database version '{}'. Expected '{}'".format(
998 version
["_id"], target_version
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
999 elif version
["status"] != 'ENABLED':
1000 raise EngineException("Wrong database status '{}'".format(
1001 version
["status"]), HTTPStatus
.INTERNAL_SERVER_ERROR
)
1004 def _edit_item(self
, session
, item
, id, content
, indata
={}, kwargs
=None, force
=False):
1006 indata
= self
._remove
_envelop
(item
, indata
)
1008 # Override descriptor with query string kwargs
1011 for k
, v
in kwargs
.items():
1012 update_content
= indata
1014 klist
= k
.split(".")
1016 if kitem_old
is not None:
1017 update_content
= update_content
[kitem_old
]
1018 if isinstance(update_content
, dict):
1020 elif isinstance(update_content
, list):
1021 kitem_old
= int(kitem
)
1023 raise EngineException(
1024 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k
, kitem
))
1025 update_content
[kitem_old
] = v
1027 raise EngineException(
1028 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k
, kitem_old
))
1030 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
1033 raise EngineException(
1034 "Invalid query string '{}'. Index '{}' out of range".format(k
, kitem_old
))
1036 validate_input(content
, item
, new
=False)
1037 except ValidationError
as e
:
1038 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1040 _deep_update(content
, indata
)
1041 self
._validate
_new
_data
(session
, item
, content
, id, force
)
1042 # self._format_new_data(session, item, content)
1043 self
.db
.replace(item
, id, content
)
1044 if item
in ("vim_accounts", "sdns"):
1045 indata
.pop("_admin", None)
1047 if item
== "vim_accounts":
1048 self
.msg
.write("vim_account", "edit", indata
)
1049 elif item
== "sdns":
1050 self
.msg
.write("sdn", "edit", indata
)
1053 def edit_item(self
, session
, item
, _id
, indata
={}, kwargs
=None, force
=False):
1055 Update an existing entry at database
1056 :param session: contains the used login username and working project
1057 :param item: it can be: users, projects, vnfds, nsds, ...
1058 :param _id: identifier to be updated
1059 :param indata: data to be inserted
1060 :param kwargs: used to override the indata descriptor
1061 :param force: If True avoid some dependence checks
1062 :return: dictionary, raise exception if not found.
1065 content
= self
.get_item(session
, item
, _id
)
1066 return self
._edit
_item
(session
, item
, _id
, content
, indata
, kwargs
, force
)