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 uuid
import uuid4
13 from hashlib
import sha256
, md5
14 from osm_common
.dbbase
import DbException
, deep_update
15 from osm_common
.fsbase
import FsException
16 from osm_common
.msgbase
import MsgException
17 from http
import HTTPStatus
20 from validation
import validate_input
, ValidationError
22 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
25 class EngineException(Exception):
27 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
28 self
.http_code
= http_code
29 Exception.__init
__(self
, message
)
32 def get_iterable(input):
34 Returns an iterable, in case input is None it just returns an empty tuple
51 self
.logger
= logging
.getLogger("nbi.engine")
53 def start(self
, config
):
55 Connect to database, filesystem storage, and messaging
56 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
62 if config
["database"]["driver"] == "mongo":
63 self
.db
= dbmongo
.DbMongo()
64 self
.db
.db_connect(config
["database"])
65 elif config
["database"]["driver"] == "memory":
66 self
.db
= dbmemory
.DbMemory()
67 self
.db
.db_connect(config
["database"])
69 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
70 config
["database"]["driver"]))
72 if config
["storage"]["driver"] == "local":
73 self
.fs
= fslocal
.FsLocal()
74 self
.fs
.fs_connect(config
["storage"])
76 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
77 config
["storage"]["driver"]))
79 if config
["message"]["driver"] == "local":
80 self
.msg
= msglocal
.MsgLocal()
81 self
.msg
.connect(config
["message"])
82 elif config
["message"]["driver"] == "kafka":
83 self
.msg
= msgkafka
.MsgKafka()
84 self
.msg
.connect(config
["message"])
86 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
87 config
["storage"]["driver"]))
88 except (DbException
, FsException
, MsgException
) as e
:
89 raise EngineException(str(e
), http_code
=e
.http_code
)
94 self
.db
.db_disconnect()
96 self
.fs
.fs_disconnect()
98 self
.fs
.fs_disconnect()
99 except (DbException
, FsException
, MsgException
) as e
:
100 raise EngineException(str(e
), http_code
=e
.http_code
)
103 def _remove_envelop(item
, indata
=None):
105 Obtain the useful data removing the envelop. It goes throw the vnfd or nsd catalog and returns the
107 :param item: can be vnfds, nsds, users, projects, userDefinedData (initial content of a vnfds, nsds
108 :param indata: Content to be inspected
109 :return: the useful part of indata
111 clean_indata
= indata
115 if clean_indata
.get('vnfd:vnfd-catalog'):
116 clean_indata
= clean_indata
['vnfd:vnfd-catalog']
117 elif clean_indata
.get('vnfd-catalog'):
118 clean_indata
= clean_indata
['vnfd-catalog']
119 if clean_indata
.get('vnfd'):
120 if not isinstance(clean_indata
['vnfd'], list) or len(clean_indata
['vnfd']) != 1:
121 raise EngineException("'vnfd' must be a list only one element")
122 clean_indata
= clean_indata
['vnfd'][0]
124 if clean_indata
.get('nsd:nsd-catalog'):
125 clean_indata
= clean_indata
['nsd:nsd-catalog']
126 elif clean_indata
.get('nsd-catalog'):
127 clean_indata
= clean_indata
['nsd-catalog']
128 if clean_indata
.get('nsd'):
129 if not isinstance(clean_indata
['nsd'], list) or len(clean_indata
['nsd']) != 1:
130 raise EngineException("'nsd' must be a list only one element")
131 clean_indata
= clean_indata
['nsd'][0]
132 elif item
== "userDefinedData":
133 if "userDefinedData" in indata
:
134 clean_indata
= clean_indata
['userDefinedData']
137 def _check_project_dependencies(self
, project_id
):
139 Check if a project can be deleted
144 # TODO Is it needed to check descriptors _admin.project_read/project_write??
145 _filter
= {"projects": project_id
}
146 if self
.db
.get_list("users", _filter
):
147 raise EngineException("There are users that uses this project", http_code
=HTTPStatus
.CONFLICT
)
149 def _check_dependencies_on_descriptor(self
, session
, item
, descriptor_id
, _id
):
151 Check that the descriptor to be deleded is not a dependency of others
152 :param session: client session information
153 :param item: can be vnfds, nsds
154 :param descriptor_id: id (provided by client) of descriptor to be deleted
155 :param _id: internal id of descriptor to be deleted
156 :return: None or raises exception
159 _filter
= {"constituent-vnfd.ANYINDEX.vnfd-id-ref": descriptor_id
}
160 if self
.get_item_list(session
, "nsds", _filter
):
161 raise EngineException("There are nsd that depends on this VNFD", http_code
=HTTPStatus
.CONFLICT
)
162 if self
.get_item_list(session
, "vnfrs", {"vnfd-id": _id
}):
163 raise EngineException("There are vnfr that depends on this VNFD", http_code
=HTTPStatus
.CONFLICT
)
165 _filter
= {"nsdId": _id
}
166 if self
.get_item_list(session
, "nsrs", _filter
):
167 raise EngineException("There are nsr that depends on this NSD", http_code
=HTTPStatus
.CONFLICT
)
169 def _check_descriptor_dependencies(self
, session
, item
, descriptor
):
171 Check that the dependent descriptors exist on a new descriptor or edition
172 :param session: client session information
173 :param item: can be nsds, nsrs
174 :param descriptor: descriptor to be inserted or edit
175 :return: None or raises exception
178 if not descriptor
.get("constituent-vnfd"):
180 for vnf
in descriptor
["constituent-vnfd"]:
181 vnfd_id
= vnf
["vnfd-id-ref"]
182 if not self
.get_item_list(session
, "vnfds", {"id": vnfd_id
}):
183 raise EngineException("Descriptor error at 'constituent-vnfd':'vnfd-id-ref'='{}' references a non "
184 "existing vnfd".format(vnfd_id
), http_code
=HTTPStatus
.CONFLICT
)
186 if not descriptor
.get("nsdId"):
188 nsd_id
= descriptor
["nsdId"]
189 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
190 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
191 http_code
=HTTPStatus
.CONFLICT
)
193 def _check_edition(self
, session
, item
, indata
, id, force
=False):
195 if indata
.get("projects"):
196 if not session
["admin"]:
197 raise EngineException("Needed admin privileges to edit user projects", HTTPStatus
.UNAUTHORIZED
)
198 if indata
.get("password"):
199 # regenerate salt and encrypt password
201 indata
["_admin"] = {"salt": salt
}
202 indata
["password"] = sha256(indata
["password"].encode('utf-8') + salt
.encode('utf-8')).hexdigest()
204 def _validate_new_data(self
, session
, item
, indata
, id=None, force
=False):
206 # check username not exists
207 if not id and self
.db
.get_one(item
, {"username": indata
.get("username")}, fail_on_empty
=False,
209 raise EngineException("username '{}' exists".format(indata
["username"]), HTTPStatus
.CONFLICT
)
212 for p
in indata
["projects"]:
215 if not self
.db
.get_one("projects", {"_id": p
}, fail_on_empty
=False, fail_on_more
=False):
216 raise EngineException("project '{}' does not exists".format(p
), HTTPStatus
.CONFLICT
)
217 elif item
== "projects":
218 if not indata
.get("name"):
219 raise EngineException("missing 'name'")
220 # check name not exists
221 if not id and self
.db
.get_one(item
, {"name": indata
.get("name")}, fail_on_empty
=False, fail_on_more
=False):
222 raise EngineException("name '{}' exists".format(indata
["name"]), HTTPStatus
.CONFLICT
)
223 elif item
in ("vnfds", "nsds"):
224 filter = {"id": indata
["id"]}
226 filter["_id.neq"] = id
227 # TODO add admin to filter, validate rights
228 self
._add
_read
_filter
(session
, item
, filter)
229 if self
.db
.get_one(item
, filter, fail_on_empty
=False):
230 raise EngineException("{} with id '{}' already exists for this tenant".format(item
[:-1], indata
["id"]),
232 # TODO validate with pyangbind. Load and dumps to convert data types
234 # transform constituent-vnfd:member-vnf-index to string
235 if indata
.get("constituent-vnfd"):
236 for constituent_vnfd
in indata
["constituent-vnfd"]:
237 if "member-vnf-index" in constituent_vnfd
:
238 constituent_vnfd
["member-vnf-index"] = str(constituent_vnfd
["member-vnf-index"])
240 if item
== "nsds" and not force
:
241 self
._check
_descriptor
_dependencies
(session
, "nsds", indata
)
242 elif item
== "userDefinedData":
243 # TODO validate userDefinedData is a keypair values
248 elif item
== "vim_accounts" or item
== "sdns":
249 filter = {"name": indata
.get("name")}
251 filter["_id.neq"] = id
252 if self
.db
.get_one(item
, filter, fail_on_empty
=False, fail_on_more
=False):
253 raise EngineException("name '{}' already exists for {}".format(indata
["name"], item
),
256 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
258 Check that user has enter right parameters for the operation
260 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
261 :param indata: descriptor with the parameters of the operation
268 def check_valid_vnf_member_index(member_vnf_index
):
269 for vnf
in nsd
["constituent-vnfd"]:
270 if member_vnf_index
== vnf
["member-vnf-index"]:
271 vnfd_id
= vnf
["vnfd-id-ref"]
272 if vnfd_id
not in vnfds
:
273 vnfds
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
274 return vnfds
[vnfd_id
]
276 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
277 "nsd:constituent-vnfd".format(member_vnf_index
))
279 def check_valid_vim_account(vim_account
):
280 if vim_account
in vim_accounts
:
283 self
.db
.get_one("vim_accounts", {"_id": vim_account
})
285 raise EngineException("Invalid vimAccountId='{}' not present".format(vim_account
))
286 vim_accounts
.append(vim_account
)
288 if operation
== "action":
289 # check vnf_member_index
290 if indata
.get("vnf_member_index"):
291 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
292 if not indata
.get("member_vnf_index"):
293 raise EngineException("Missing 'member_vnf_index' parameter")
294 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
296 for config_primitive
in get_iterable(vnfd
.get("vnf-configuration", {}).get("config-primitive")):
297 if indata
["primitive"] == config_primitive
["name"]:
298 # check needed primitive_params are provided
299 if indata
.get("primitive_params"):
300 in_primitive_params_copy
= copy(indata
["primitive_params"])
302 in_primitive_params_copy
= {}
303 for paramd
in get_iterable(config_primitive
.get("parameter")):
304 if paramd
["name"] in in_primitive_params_copy
:
305 del in_primitive_params_copy
[paramd
["name"]]
306 elif not paramd
.get("default-value"):
307 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
308 paramd
["name"], indata
["primitive"]))
309 # check no extra primitive params are provided
310 if in_primitive_params_copy
:
311 raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
312 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
315 raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata
["primitive"]))
316 if operation
== "scale":
317 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
318 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
319 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
322 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
323 "present at vnfd:scaling-group-descriptor".format(
324 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
325 if operation
== "instantiate":
327 check_valid_vim_account(indata
["vimAccountId"])
328 for in_vnf
in get_iterable(indata
.get("vnf")):
329 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
330 if in_vnf
.get("vimAccountId"):
331 check_valid_vim_account(in_vnf
["vimAccountId"])
332 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
333 for vdud
in get_iterable(vnfd
.get("vdu")):
334 if vdud
["id"] == in_vdu
["id"]:
335 for volume
in get_iterable(in_vdu
.get("volume")):
336 for volumed
in get_iterable(vdud
.get("volumes")):
337 if volumed
["name"] == volume
["name"]:
340 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
341 "volume:name='{}' is not present at vnfd:vdu:volumes list".
342 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
346 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu:id='{}' is not "
347 "present at vnfd".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
349 for in_internal_vld
in get_iterable(in_vnf
.get("internal-vld")):
350 for internal_vldd
in get_iterable(vnfd
.get("internal-vld")):
351 if in_internal_vld
["name"] == internal_vldd
["name"] or \
352 in_internal_vld
["name"] == internal_vldd
["id"]:
355 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
356 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
357 in_internal_vld
["name"],
359 for in_vld
in get_iterable(indata
.get("vld")):
360 for vldd
in get_iterable(nsd
.get("vld")):
361 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
364 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
367 def _format_new_data(self
, session
, item
, indata
):
369 if "_admin" not in indata
:
370 indata
["_admin"] = {}
371 indata
["_admin"]["created"] = now
372 indata
["_admin"]["modified"] = now
374 indata
["_id"] = indata
["username"]
376 indata
["_admin"]["salt"] = salt
377 indata
["password"] = sha256(indata
["password"].encode('utf-8') + salt
.encode('utf-8')).hexdigest()
378 elif item
== "projects":
379 indata
["_id"] = indata
["name"]
381 if not indata
.get("_id"):
382 indata
["_id"] = str(uuid4())
383 if item
in ("vnfds", "nsds", "nsrs", "vnfrs"):
384 if not indata
["_admin"].get("projects_read"):
385 indata
["_admin"]["projects_read"] = [session
["project_id"]]
386 if not indata
["_admin"].get("projects_write"):
387 indata
["_admin"]["projects_write"] = [session
["project_id"]]
388 if item
in ("vnfds", "nsds"):
389 indata
["_admin"]["onboardingState"] = "CREATED"
390 indata
["_admin"]["operationalState"] = "DISABLED"
391 indata
["_admin"]["usageSate"] = "NOT_IN_USE"
393 indata
["_admin"]["nsState"] = "NOT_INSTANTIATED"
394 if item
in ("vim_accounts", "sdns"):
395 indata
["_admin"]["operationalState"] = "PROCESSING"
397 def upload_content(self
, session
, item
, _id
, indata
, kwargs
, headers
):
399 Used for receiving content by chunks (with a transaction_id header and/or gzip file. It will store and extract)
400 :param session: session
401 :param item: can be nsds or vnfds
402 :param _id : the nsd,vnfd is already created, this is the id
403 :param indata: http body request
404 :param kwargs: user query string to override parameters. NOT USED
405 :param headers: http request headers
406 :return: True package has is completely uploaded or False if partial content has been uplodaed.
407 Raise exception on error
409 # Check that _id exists and it is valid
410 current_desc
= self
.get_item(session
, item
, _id
)
412 content_range_text
= headers
.get("Content-Range")
413 expected_md5
= headers
.get("Content-File-MD5")
415 content_type
= headers
.get("Content-Type")
416 if content_type
and "application/gzip" in content_type
or "application/x-gzip" in content_type
or \
417 "application/zip" in content_type
:
419 filename
= headers
.get("Content-Filename")
421 filename
= "package.tar.gz" if compressed
else "package"
422 # TODO change to Content-Disposition filename https://tools.ietf.org/html/rfc6266
426 if content_range_text
:
427 content_range
= content_range_text
.replace("-", " ").replace("/", " ").split()
428 if content_range
[0] != "bytes": # TODO check x<y not negative < total....
430 start
= int(content_range
[1])
431 end
= int(content_range
[2]) + 1
432 total
= int(content_range
[3])
437 if not self
.fs
.file_exists(_id
, 'dir'):
438 raise EngineException("invalid Transaction-Id header", HTTPStatus
.NOT_FOUND
)
440 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
443 storage
= self
.fs
.get_params()
444 storage
["folder"] = _id
446 file_path
= (_id
, filename
)
447 if self
.fs
.file_exists(file_path
, 'file'):
448 file_size
= self
.fs
.file_size(file_path
)
451 if file_size
!= start
:
452 raise EngineException("invalid Content-Range start sequence, expected '{}' but received '{}'".format(
453 file_size
, start
), HTTPStatus
.REQUESTED_RANGE_NOT_SATISFIABLE
)
454 file_pkg
= self
.fs
.file_open(file_path
, 'a+b')
455 if isinstance(indata
, dict):
456 indata_text
= yaml
.safe_dump(indata
, indent
=4, default_flow_style
=False)
457 file_pkg
.write(indata_text
.encode(encoding
="utf-8"))
461 indata_text
= indata
.read(4096)
462 indata_len
+= len(indata_text
)
465 file_pkg
.write(indata_text
)
466 if content_range_text
:
467 if indata_len
!= end
-start
:
468 raise EngineException("Mismatch between Content-Range header {}-{} and body length of {}".format(
469 start
, end
-1, indata_len
), HTTPStatus
.REQUESTED_RANGE_NOT_SATISFIABLE
)
471 # TODO update to UPLOADING
478 chunk_data
= file_pkg
.read(1024)
480 file_md5
.update(chunk_data
)
481 chunk_data
= file_pkg
.read(1024)
482 if expected_md5
!= file_md5
.hexdigest():
483 raise EngineException("Error, MD5 mismatch", HTTPStatus
.CONFLICT
)
485 if compressed
== "gzip":
486 tar
= tarfile
.open(mode
='r', fileobj
=file_pkg
)
487 descriptor_file_name
= None
489 tarname
= tarinfo
.name
490 tarname_path
= tarname
.split("/")
491 if not tarname_path
[0] or ".." in tarname_path
: # if start with "/" means absolute path
492 raise EngineException("Absolute path or '..' are not allowed for package descriptor tar.gz")
493 if len(tarname_path
) == 1 and not tarinfo
.isdir():
494 raise EngineException("All files must be inside a dir for package descriptor tar.gz")
495 if tarname
.endswith(".yaml") or tarname
.endswith(".json") or tarname
.endswith(".yml"):
496 storage
["pkg-dir"] = tarname_path
[0]
497 if len(tarname_path
) == 2:
498 if descriptor_file_name
:
499 raise EngineException(
500 "Found more than one descriptor file at package descriptor tar.gz")
501 descriptor_file_name
= tarname
502 if not descriptor_file_name
:
503 raise EngineException("Not found any descriptor file at package descriptor tar.gz")
504 storage
["descriptor"] = descriptor_file_name
505 storage
["zipfile"] = filename
506 self
.fs
.file_extract(tar
, _id
)
507 with self
.fs
.file_open((_id
, descriptor_file_name
), "r") as descriptor_file
:
508 content
= descriptor_file
.read()
510 content
= file_pkg
.read()
511 storage
["descriptor"] = descriptor_file_name
= filename
513 if descriptor_file_name
.endswith(".json"):
514 error_text
= "Invalid json format "
515 indata
= json
.load(content
)
517 error_text
= "Invalid yaml format "
518 indata
= yaml
.load(content
)
520 current_desc
["_admin"]["storage"] = storage
521 current_desc
["_admin"]["onboardingState"] = "ONBOARDED"
522 current_desc
["_admin"]["operationalState"] = "ENABLED"
524 self
._edit
_item
(session
, item
, _id
, current_desc
, indata
, kwargs
)
525 # TODO if descriptor has changed because kwargs update content and remove cached zip
526 # TODO if zip is not present creates one
529 except EngineException
:
532 raise EngineException("invalid Content-Range header format. Expected 'bytes start-end/total'",
533 HTTPStatus
.REQUESTED_RANGE_NOT_SATISFIABLE
)
535 raise EngineException("invalid upload transaction sequence: '{}'".format(e
), HTTPStatus
.BAD_REQUEST
)
536 except tarfile
.ReadError
as e
:
537 raise EngineException("invalid file content {}".format(e
), HTTPStatus
.BAD_REQUEST
)
538 except (ValueError, yaml
.YAMLError
) as e
:
539 raise EngineException(error_text
+ str(e
))
544 def new_nsr(self
, rollback
, session
, ns_request
):
546 Creates a new nsr into database. It also creates needed vnfrs
547 :param rollback: list where this method appends created items at database in case a rollback may to be done
548 :param session: contains the used login username and working project
549 :param ns_request: params to be used for the nsr
550 :return: the _id of nsr descriptor stored at database
552 rollback_index
= len(rollback
)
556 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
557 nsd
= self
.get_item(session
, "nsds", ns_request
["nsdId"])
558 nsr_id
= str(uuid4())
560 step
= "filling nsr from input data"
562 "name": ns_request
["nsName"],
563 "name-ref": ns_request
["nsName"],
564 "short-name": ns_request
["nsName"],
565 "admin-status": "ENABLED",
567 "datacenter": ns_request
["vimAccountId"],
568 "resource-orchestrator": "osmopenmano",
569 "description": ns_request
.get("nsDescription", ""),
570 "constituent-vnfr-ref": [],
572 "operational-status": "init", # typedef ns-operational-
573 "config-status": "init", # typedef config-states
574 "detailed-status": "scheduled",
576 "orchestration-progress": {},
577 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
580 "nsd-name-ref": nsd
["name"],
581 "operational-events": [], # "id", "timestamp", "description", "event",
582 "nsd-ref": nsd
["id"],
584 "instantiate_params": ns_request
,
585 "ns-instance-config-ref": nsr_id
,
588 # "input-parameter": xpath, value,
589 "ssh-authorized-key": ns_request
.get("key-pair-ref"),
591 ns_request
["nsr_id"] = nsr_id
595 for member_vnf
in nsd
["constituent-vnfd"]:
596 vnfd_id
= member_vnf
["vnfd-id-ref"]
597 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
598 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
599 if vnfd_id
not in needed_vnfds
:
601 vnf_filter
= {"id": vnfd_id
}
602 self
._add
_read
_filter
(session
, "vnfds", vnf_filter
)
603 vnfd
= self
.db
.get_one("vnfds", vnf_filter
)
605 needed_vnfds
[vnfd_id
] = vnfd
607 vnfd
= needed_vnfds
[vnfd_id
]
608 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
609 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
610 vnfr_id
= str(uuid4())
614 "nsr-id-ref": nsr_id
,
615 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
617 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
619 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
620 "vim-account-id": None,
622 "connection-point": [],
623 "ip-address": None, # mgmt-interface filled by LCM
625 for cp
in vnfd
.get("connection-point", ()):
628 "connection-point-id": cp
.get("id"),
630 # "ip-address", "mac-address" # filled by LCM
631 # vim-id # TODO it would be nice having a vim port id
633 vnfr_descriptor
["connection-point"].append(vnf_cp
)
634 for vdu
in vnfd
["vdu"]:
635 vdur_id
= str(uuid4())
638 "vdu-id-ref": vdu
["id"],
639 # TODO "name": "" Name of the VDU in the VIM
640 "ip-address": None, # mgmt-interface filled by LCM
641 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
642 "internal-connection-point": [],
645 # TODO volumes: name, volume-id
646 for icp
in vdu
.get("internal-connection-point", ()):
649 "connection-point-id": icp
["id"],
650 "name": icp
.get("name"),
651 # "ip-address", "mac-address" # filled by LCM
652 # vim-id # TODO it would be nice having a vim port id
654 vdur
["internal-connection-point"].append(vdu_icp
)
655 for iface
in vdu
.get("interface", ()):
657 "name": iface
.get("name"),
658 # "ip-address", "mac-address" # filled by LCM
659 # vim-id # TODO it would be nice having a vim port id
661 vdur
["interfaces"].append(vdu_iface
)
662 vnfr_descriptor
["vdur"].append(vdur
)
664 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
665 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
666 self
._format
_new
_data
(session
, "vnfrs", vnfr_descriptor
)
667 self
.db
.create("vnfrs", vnfr_descriptor
)
668 rollback
.insert(0, {"item": "vnfrs", "_id": vnfr_id
})
669 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
671 step
= "creating nsr at database"
672 self
._format
_new
_data
(session
, "nsrs", nsr_descriptor
)
673 self
.db
.create("nsrs", nsr_descriptor
)
674 rollback
.insert(rollback_index
, {"item": "nsrs", "_id": nsr_id
})
676 except Exception as e
:
677 raise EngineException("Error {}: {}".format(step
, e
))
680 def _update_descriptor(desc
, kwargs
):
682 Update descriptor with the kwargs. It contains dot separated keys
683 :param desc: dictionary to be updated
684 :param kwargs: plain dictionary to be used for updating.
690 for k
, v
in kwargs
.items():
691 update_content
= desc
695 if kitem_old
is not None:
696 update_content
= update_content
[kitem_old
]
697 if isinstance(update_content
, dict):
699 elif isinstance(update_content
, list):
700 kitem_old
= int(kitem
)
702 raise EngineException(
703 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k
, kitem
))
704 update_content
[kitem_old
] = v
706 raise EngineException(
707 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k
, kitem_old
))
709 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
712 raise EngineException(
713 "Invalid query string '{}'. Index '{}' out of range".format(k
, kitem_old
))
715 def new_item(self
, rollback
, session
, item
, indata
={}, kwargs
=None, headers
={}, force
=False):
717 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
718 that must be completed with a call to method upload_content
719 :param rollback: list where this method appends created items at database in case a rollback may to be done
720 :param session: contains the used login username and working project
721 :param item: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
722 :param indata: data to be inserted
723 :param kwargs: used to override the indata descriptor
724 :param headers: http request headers
725 :param force: If True avoid some dependence checks
726 :return: _id: identity of the inserted data.
729 if not session
["admin"] and item
in ("users", "projects"):
730 raise EngineException("Needed admin privileges to perform this operation", HTTPStatus
.UNAUTHORIZED
)
734 if item
in ("nsds", "vnfds"):
735 item_envelop
= "userDefinedData"
736 content
= self
._remove
_envelop
(item_envelop
, indata
)
738 # Override descriptor with query string kwargs
739 self
._update
_descriptor
(content
, kwargs
)
740 if not content
and item
not in ("nsds", "vnfds"):
741 raise EngineException("Empty payload")
743 validate_input(content
, item
, new
=True)
746 # in this case the input descriptor is not the data to be stored
747 return self
.new_nsr(rollback
, session
, ns_request
=content
)
749 self
._validate
_new
_data
(session
, item_envelop
, content
, force
=force
)
750 if item
in ("nsds", "vnfds"):
751 content
= {"_admin": {"userDefinedData": content
}}
752 self
._format
_new
_data
(session
, item
, content
)
753 _id
= self
.db
.create(item
, content
)
754 rollback
.insert(0, {"item": item
, "_id": _id
})
756 if item
== "vim_accounts":
757 msg_data
= self
.db
.get_one(item
, {"_id": _id
})
758 msg_data
.pop("_admin", None)
759 self
.msg
.write("vim_account", "create", msg_data
)
761 msg_data
= self
.db
.get_one(item
, {"_id": _id
})
762 msg_data
.pop("_admin", None)
763 self
.msg
.write("sdn", "create", msg_data
)
765 except ValidationError
as e
:
766 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
768 def new_nslcmop(self
, session
, nsInstanceId
, operation
, params
):
774 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
775 "statusEnteredTime": now
,
776 "nsInstanceId": nsInstanceId
,
777 "lcmOperationType": operation
,
779 "isAutomaticInvocation": False,
780 "operationParams": params
,
781 "isCancelPending": False,
783 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
784 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsInstanceId
,
789 def ns_operation(self
, rollback
, session
, nsInstanceId
, operation
, indata
, kwargs
=None):
791 Performs a new operation over a ns
792 :param rollback: list where this method appends created items at database in case a rollback may to be done
793 :param session: contains the used login username and working project
794 :param nsInstanceId: _id of the nsr to perform the operation
795 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
796 :param indata: descriptor with the parameters of the operation
797 :param kwargs: used to override the indata descriptor
798 :return: id of the nslcmops
801 # Override descriptor with query string kwargs
802 self
._update
_descriptor
(indata
, kwargs
)
803 validate_input(indata
, "ns_" + operation
, new
=True)
805 nsr
= self
.get_item(session
, "nsrs", nsInstanceId
)
806 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
807 if operation
== "terminate" and indata
.get("autoremove"):
808 # NSR must be deleted
809 return self
.del_item(session
, "nsrs", nsInstanceId
)
810 if operation
!= "instantiate":
811 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
812 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
814 if operation
== "instantiate" and not indata
.get("force"):
815 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
816 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
817 indata
["nsInstanceId"] = nsInstanceId
818 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
819 nslcmop
= self
.new_nslcmop(session
, nsInstanceId
, operation
, indata
)
820 self
._format
_new
_data
(session
, "nslcmops", nslcmop
)
821 _id
= self
.db
.create("nslcmops", nslcmop
)
822 rollback
.insert(0, {"item": "nslcmops", "_id": _id
})
824 self
.msg
.write("ns", operation
, nslcmop
)
826 except ValidationError
as e
:
827 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
828 # except DbException as e:
829 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
831 def _add_read_filter(self
, session
, item
, filter):
832 if session
["admin"]: # allows all
835 filter["username"] = session
["username"]
836 elif item
in ("vnfds", "nsds", "nsrs", "vnfrs"):
837 filter["_admin.projects_read.cont"] = ["ANY", session
["project_id"]]
839 def _add_delete_filter(self
, session
, item
, filter):
840 if not session
["admin"] and item
in ("users", "projects"):
841 raise EngineException("Only admin users can perform this task", http_code
=HTTPStatus
.FORBIDDEN
)
843 if filter.get("_id") == session
["username"] or filter.get("username") == session
["username"]:
844 raise EngineException("You cannot delete your own user", http_code
=HTTPStatus
.CONFLICT
)
845 elif item
== "project":
846 if filter.get("_id") == session
["project_id"]:
847 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
848 elif item
in ("vnfds", "nsds") and not session
["admin"]:
849 filter["_admin.projects_write.cont"] = ["ANY", session
["project_id"]]
851 def get_file(self
, session
, item
, _id
, path
=None, accept_header
=None):
853 Return the file content of a vnfd or nsd
854 :param session: contains the used login username and working project
855 :param item: it can be vnfds or nsds
856 :param _id: Identity of the vnfd, ndsd
857 :param path: artifact path or "$DESCRIPTOR" or None
858 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
859 :return: opened file or raises an exception
861 accept_text
= accept_zip
= False
863 if 'text/plain' in accept_header
or '*/*' in accept_header
:
865 if 'application/zip' in accept_header
or '*/*' in accept_header
:
867 if not accept_text
and not accept_zip
:
868 raise EngineException("provide request header 'Accept' with 'application/zip' or 'text/plain'",
869 http_code
=HTTPStatus
.NOT_ACCEPTABLE
)
871 content
= self
.get_item(session
, item
, _id
)
872 if content
["_admin"]["onboardingState"] != "ONBOARDED":
873 raise EngineException("Cannot get content because this resource is not at 'ONBOARDED' state. "
874 "onboardingState is {}".format(content
["_admin"]["onboardingState"]),
875 http_code
=HTTPStatus
.CONFLICT
)
876 storage
= content
["_admin"]["storage"]
877 if path
is not None and path
!= "$DESCRIPTOR": # artifacts
878 if not storage
.get('pkg-dir'):
879 raise EngineException("Packages does not contains artifacts", http_code
=HTTPStatus
.BAD_REQUEST
)
880 if self
.fs
.file_exists((storage
['folder'], storage
['pkg-dir'], *path
), 'dir'):
881 folder_content
= self
.fs
.dir_ls((storage
['folder'], storage
['pkg-dir'], *path
))
882 return folder_content
, "text/plain"
883 # TODO manage folders in http
885 return self
.fs
.file_open((storage
['folder'], storage
['pkg-dir'], *path
), "rb"),\
886 "application/octet-stream"
888 # pkgtype accept ZIP TEXT -> result
889 # manyfiles yes X -> zip
891 # onefile yes no -> zip
894 if accept_text
and (not storage
.get('pkg-dir') or path
== "$DESCRIPTOR"):
895 return self
.fs
.file_open((storage
['folder'], storage
['descriptor']), "r"), "text/plain"
896 elif storage
.get('pkg-dir') and not accept_zip
:
897 raise EngineException("Packages that contains several files need to be retrieved with 'application/zip'"
898 "Accept header", http_code
=HTTPStatus
.NOT_ACCEPTABLE
)
900 if not storage
.get('zipfile'):
901 # TODO generate zipfile if not present
902 raise EngineException("Only allowed 'text/plain' Accept header for this descriptor. To be solved in "
903 "future versions", http_code
=HTTPStatus
.NOT_ACCEPTABLE
)
904 return self
.fs
.file_open((storage
['folder'], storage
['zipfile']), "rb"), "application/zip"
906 def get_item_list(self
, session
, item
, filter={}):
909 :param session: contains the used login username and working project
910 :param item: it can be: users, projects, vnfds, nsds, ...
911 :param filter: filter of data to be applied
912 :return: The list, it can be empty if no one match the filter.
914 # TODO add admin to filter, validate rights
915 # TODO transform data for SOL005 URL requests. Transform filtering
916 # TODO implement "field-type" query string SOL005
918 self
._add
_read
_filter
(session
, item
, filter)
919 return self
.db
.get_list(item
, filter)
921 def get_item(self
, session
, item
, _id
):
923 Get complete information on an items
924 :param session: contains the used login username and working project
925 :param item: it can be: users, projects, vnfds, nsds,
926 :param _id: server id of the item
927 :return: dictionary, raise exception if not found.
929 filter = {"_id": _id
}
930 # TODO add admin to filter, validate rights
931 # TODO transform data for SOL005 URL requests
932 self
._add
_read
_filter
(session
, item
, filter)
933 return self
.db
.get_one(item
, filter)
935 def del_item_list(self
, session
, item
, filter={}):
937 Delete a list of items
938 :param session: contains the used login username and working project
939 :param item: it can be: users, projects, vnfds, nsds, ...
940 :param filter: filter of data to be applied
941 :return: The deleted list, it can be empty if no one match the filter.
943 # TODO add admin to filter, validate rights
944 self
._add
_read
_filter
(session
, item
, filter)
945 return self
.db
.del_list(item
, filter)
947 def del_item(self
, session
, item
, _id
, force
=False):
949 Delete item by its internal id
950 :param session: contains the used login username and working project
951 :param item: it can be: users, projects, vnfds, nsds, ...
952 :param _id: server id of the item
953 :param force: indicates if deletion must be forced in case of conflict
954 :return: dictionary with deleted item _id. It raises exception if not found.
956 # TODO add admin to filter, validate rights
957 # data = self.get_item(item, _id)
958 filter = {"_id": _id
}
959 self
._add
_delete
_filter
(session
, item
, filter)
960 if item
in ("vnfds", "nsds") and not force
:
961 descriptor
= self
.get_item(session
, item
, _id
)
962 descriptor_id
= descriptor
.get("id")
964 self
._check
_dependencies
_on
_descriptor
(session
, item
, descriptor_id
, _id
)
965 elif item
== "projects":
967 self
._check
_project
_dependencies
(_id
)
970 nsr
= self
.db
.get_one(item
, filter)
971 if nsr
["_admin"].get("nsState") == "INSTANTIATED" and not force
:
972 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
973 "Launch 'terminate' operation first; or force deletion".format(_id
),
974 http_code
=HTTPStatus
.CONFLICT
)
975 v
= self
.db
.del_one(item
, {"_id": _id
})
976 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
977 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
978 self
.msg
.write("ns", "deleted", {"_id": _id
})
980 if item
in ("vim_accounts", "sdns") and not force
:
981 self
.db
.set_one(item
, {"_id": _id
}, {"_admin.to_delete": True}) # TODO change status
982 if item
== "vim_accounts":
983 self
.msg
.write("vim_account", "delete", {"_id": _id
})
985 self
.msg
.write("sdn", "delete", {"_id": _id
})
986 return {"deleted": 1} # TODO indicate an offline operation to return 202 ACCEPTED
988 v
= self
.db
.del_one(item
, filter)
989 if item
in ("vnfds", "nsds"):
990 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
991 if item
in ("vim_accounts", "sdns", "vnfds", "nsds"):
992 self
.msg
.write(item
[:-1], "deleted", {"_id": _id
})
997 Prune database not needed content
1000 return self
.db
.del_list("nsrs", {"_admin.to_delete": True})
1002 def create_admin(self
):
1004 Creates a new user admin/admin into database if database is empty. Useful for initialization
1005 :return: _id identity of the inserted data, or None
1007 users
= self
.db
.get_one("users", fail_on_empty
=False, fail_on_more
=False)
1010 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
1011 indata
= {"username": "admin", "password": "admin", "projects": ["admin"]}
1012 fake_session
= {"project_id": "admin", "username": "admin"}
1013 self
._format
_new
_data
(fake_session
, "users", indata
)
1014 _id
= self
.db
.create("users", indata
)
1017 def init_db(self
, target_version
='1.0'):
1019 Init database if empty. If not empty it checks that database version is ok.
1020 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
1021 :return: None if ok, exception if error or if the version is different.
1023 version
= self
.db
.get_one("version", fail_on_empty
=False, fail_on_more
=False)
1027 # create database version
1029 "_id": '1.0', # version text
1030 "version": 1000, # version number
1031 "date": "2018-04-12", # version date
1032 "description": "initial design", # changes in this version
1033 'status': 'ENABLED' # ENABLED, DISABLED (migration in process), ERROR,
1035 self
.db
.create("version", version_data
)
1036 elif version
["_id"] != target_version
:
1037 # TODO implement migration process
1038 raise EngineException("Wrong database version '{}'. Expected '{}'".format(
1039 version
["_id"], target_version
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
1040 elif version
["status"] != 'ENABLED':
1041 raise EngineException("Wrong database status '{}'".format(
1042 version
["status"]), HTTPStatus
.INTERNAL_SERVER_ERROR
)
1045 def _edit_item(self
, session
, item
, id, content
, indata
={}, kwargs
=None, force
=False):
1047 indata
= self
._remove
_envelop
(item
, indata
)
1049 # Override descriptor with query string kwargs
1052 for k
, v
in kwargs
.items():
1053 update_content
= indata
1055 klist
= k
.split(".")
1057 if kitem_old
is not None:
1058 update_content
= update_content
[kitem_old
]
1059 if isinstance(update_content
, dict):
1061 elif isinstance(update_content
, list):
1062 kitem_old
= int(kitem
)
1064 raise EngineException(
1065 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k
, kitem
))
1066 update_content
[kitem_old
] = v
1068 raise EngineException(
1069 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k
, kitem_old
))
1071 raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
1074 raise EngineException(
1075 "Invalid query string '{}'. Index '{}' out of range".format(k
, kitem_old
))
1077 validate_input(indata
, item
, new
=False)
1078 except ValidationError
as e
:
1079 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1081 self
._check
_edition
(session
, item
, indata
, id, force
)
1082 deep_update(content
, indata
)
1083 self
._validate
_new
_data
(session
, item
, content
, id=id, force
=force
)
1084 # self._format_new_data(session, item, content)
1085 self
.db
.replace(item
, id, content
)
1086 if item
in ("vim_accounts", "sdns"):
1087 indata
.pop("_admin", None)
1089 if item
== "vim_accounts":
1090 self
.msg
.write("vim_account", "edit", indata
)
1091 elif item
== "sdns":
1092 self
.msg
.write("sdn", "edit", indata
)
1095 def edit_item(self
, session
, item
, _id
, indata
={}, kwargs
=None, force
=False):
1097 Update an existing entry at database
1098 :param session: contains the used login username and working project
1099 :param item: it can be: users, projects, vnfds, nsds, ...
1100 :param _id: identifier to be updated
1101 :param indata: data to be inserted
1102 :param kwargs: used to override the indata descriptor
1103 :param force: If True avoid some dependence checks
1104 :return: dictionary, raise exception if not found.
1106 if not session
["admin"] and item
== "projects":
1107 raise EngineException("Needed admin privileges to perform this operation", HTTPStatus
.UNAUTHORIZED
)
1109 content
= self
.get_item(session
, item
, _id
)
1110 return self
._edit
_item
(session
, item
, _id
, content
, indata
, kwargs
, force
)