Merge branch 'netslice'
[osm/NBI.git] / osm_nbi / instance_topics.py
1 # -*- coding: utf-8 -*-
2
3 # import logging
4 from uuid import uuid4
5 from http import HTTPStatus
6 from time import time
7 from copy import copy, deepcopy
8 from validation import validate_input, ValidationError, ns_instantiate, ns_action, ns_scale, nsi_instantiate
9 from base_topic import BaseTopic, EngineException, get_iterable
10 from descriptor_topics import DescriptorTopic
11
12 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
13
14
15 class NsrTopic(BaseTopic):
16 topic = "nsrs"
17 topic_msg = "ns"
18
19 def __init__(self, db, fs, msg):
20 BaseTopic.__init__(self, db, fs, msg)
21
22 def _check_descriptor_dependencies(self, session, descriptor):
23 """
24 Check that the dependent descriptors exist on a new descriptor or edition
25 :param session: client session information
26 :param descriptor: descriptor to be inserted or edit
27 :return: None or raises exception
28 """
29 if not descriptor.get("nsdId"):
30 return
31 nsd_id = descriptor["nsdId"]
32 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
33 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
34 http_code=HTTPStatus.CONFLICT)
35
36 @staticmethod
37 def format_on_new(content, project_id=None, make_public=False):
38 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
39 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
40
41 def check_conflict_on_del(self, session, _id, force=False):
42 if force:
43 return
44 nsr = self.db.get_one("nsrs", {"_id": _id})
45 if nsr["_admin"].get("nsState") == "INSTANTIATED":
46 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
47 "Launch 'terminate' operation first; or force deletion".format(_id),
48 http_code=HTTPStatus.CONFLICT)
49
50 def delete(self, session, _id, force=False, dry_run=False):
51 """
52 Delete item by its internal _id
53 :param session: contains the used login username, working project, and admin rights
54 :param _id: server internal id
55 :param force: indicates if deletion must be forced in case of conflict
56 :param dry_run: make checking but do not delete
57 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
58 """
59 # TODO add admin to filter, validate rights
60 BaseTopic.delete(self, session, _id, force, dry_run=True)
61 if dry_run:
62 return
63
64 v = self.db.del_one("nsrs", {"_id": _id})
65 self.db.del_list("nslcmops", {"nsInstanceId": _id})
66 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
67 # set all used pdus as free
68 self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
69 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
70 self._send_msg("deleted", {"_id": _id})
71 return v
72
73 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
74 """
75 Creates a new nsr into database. It also creates needed vnfrs
76 :param rollback: list to append the created items at database in case a rollback must be done
77 :param session: contains the used login username and working project
78 :param indata: params to be used for the nsr
79 :param kwargs: used to override the indata descriptor
80 :param headers: http request headers
81 :param force: If True avoid some dependence checks
82 :param make_public: Make the created item public to all projects
83 :return: the _id of nsr descriptor created at database
84 """
85
86 try:
87 ns_request = self._remove_envelop(indata)
88 # Override descriptor with query string kwargs
89 self._update_input_with_kwargs(ns_request, kwargs)
90 self._validate_input_new(ns_request, force)
91
92 step = ""
93 # look for nsr
94 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
95 _filter = {"_id": ns_request["nsdId"]}
96 _filter.update(BaseTopic._get_project_filter(session, write=False, show_all=True))
97 nsd = self.db.get_one("nsds", _filter)
98
99 nsr_id = str(uuid4())
100 now = time()
101 step = "filling nsr from input data"
102 nsr_descriptor = {
103 "name": ns_request["nsName"],
104 "name-ref": ns_request["nsName"],
105 "short-name": ns_request["nsName"],
106 "admin-status": "ENABLED",
107 "nsd": nsd,
108 "datacenter": ns_request["vimAccountId"],
109 "resource-orchestrator": "osmopenmano",
110 "description": ns_request.get("nsDescription", ""),
111 "constituent-vnfr-ref": [],
112
113 "operational-status": "init", # typedef ns-operational-
114 "config-status": "init", # typedef config-states
115 "detailed-status": "scheduled",
116
117 "orchestration-progress": {},
118 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
119
120 "crete-time": now,
121 "nsd-name-ref": nsd["name"],
122 "operational-events": [], # "id", "timestamp", "description", "event",
123 "nsd-ref": nsd["id"],
124 "instantiate_params": ns_request,
125 "ns-instance-config-ref": nsr_id,
126 "id": nsr_id,
127 "_id": nsr_id,
128 # "input-parameter": xpath, value,
129 "ssh-authorized-key": ns_request.get("key-pair-ref"), # TODO remove
130 }
131 ns_request["nsr_id"] = nsr_id
132 # Create vld
133 if nsd.get("vld"):
134 nsr_descriptor["vld"] = []
135 for nsd_vld in nsd.get("vld"):
136 nsr_descriptor["vld"].append(
137 {key: nsd_vld[key] for key in ("id", "vim-network-name") if key in nsd_vld})
138
139 # Create VNFR
140 needed_vnfds = {}
141 for member_vnf in nsd.get("constituent-vnfd", ()):
142 vnfd_id = member_vnf["vnfd-id-ref"]
143 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
144 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
145 if vnfd_id not in needed_vnfds:
146 # Obtain vnfd
147 vnfd = DescriptorTopic.get_one_by_id(self.db, session, "vnfds", vnfd_id)
148 vnfd.pop("_admin")
149 needed_vnfds[vnfd_id] = vnfd
150 else:
151 vnfd = needed_vnfds[vnfd_id]
152 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
153 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
154 vnfr_id = str(uuid4())
155 vnfr_descriptor = {
156 "id": vnfr_id,
157 "_id": vnfr_id,
158 "nsr-id-ref": nsr_id,
159 "member-vnf-index-ref": member_vnf["member-vnf-index"],
160 "created-time": now,
161 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
162 "vnfd-ref": vnfd_id,
163 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
164 "vim-account-id": None,
165 "vdur": [],
166 "connection-point": [],
167 "ip-address": None, # mgmt-interface filled by LCM
168 }
169
170 # Create vld
171 if vnfd.get("internal-vld"):
172 vnfr_descriptor["vld"] = []
173 for vnfd_vld in vnfd.get("internal-vld"):
174 vnfr_descriptor["vld"].append(
175 {key: vnfd_vld[key] for key in ("id", "vim-network-name") if key in vnfd_vld})
176
177 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
178 for cp in vnfd.get("connection-point", ()):
179 vnf_cp = {
180 "name": cp["name"],
181 "connection-point-id": cp.get("id"),
182 "id": cp.get("id"),
183 # "ip-address", "mac-address" # filled by LCM
184 # vim-id # TODO it would be nice having a vim port id
185 }
186 vnfr_descriptor["connection-point"].append(vnf_cp)
187 for vdu in vnfd.get("vdu", ()):
188 vdur = {
189 "vdu-id-ref": vdu["id"],
190 # TODO "name": "" Name of the VDU in the VIM
191 "ip-address": None, # mgmt-interface filled by LCM
192 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
193 "internal-connection-point": [],
194 "interfaces": [],
195 }
196 if vdu.get("pdu-type"):
197 vdur["pdu-type"] = vdu["pdu-type"]
198 # TODO volumes: name, volume-id
199 for icp in vdu.get("internal-connection-point", ()):
200 vdu_icp = {
201 "id": icp["id"],
202 "connection-point-id": icp["id"],
203 "name": icp.get("name"),
204 # "ip-address", "mac-address" # filled by LCM
205 # vim-id # TODO it would be nice having a vim port id
206 }
207 vdur["internal-connection-point"].append(vdu_icp)
208 for iface in vdu.get("interface", ()):
209 vdu_iface = {
210 "name": iface.get("name"),
211 # "ip-address", "mac-address" # filled by LCM
212 # vim-id # TODO it would be nice having a vim port id
213 }
214 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
215 vdu_iface["mgmt-vnf"] = True
216 if iface.get("mgmt-interface"):
217 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
218
219 # look for network where this interface is connected
220 if iface.get("external-connection-point-ref"):
221 for nsd_vld in get_iterable(nsd.get("vld")):
222 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
223 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
224 iface["external-connection-point-ref"] and \
225 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
226 vdu_iface["ns-vld-id"] = nsd_vld["id"]
227 break
228 else:
229 continue
230 break
231 elif iface.get("internal-connection-point-ref"):
232 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
233 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
234 if vnfd_ivld_icp.get("id-ref") == iface["internal-connection-point-ref"]:
235 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
236 break
237 else:
238 continue
239 break
240
241 vdur["interfaces"].append(vdu_iface)
242 count = vdu.get("count", 1)
243 if count is None:
244 count = 1
245 count = int(count) # TODO remove when descriptor serialized with payngbind
246 for index in range(0, count):
247 if index:
248 vdur = deepcopy(vdur)
249 vdur["_id"] = str(uuid4())
250 vdur["count-index"] = index
251 vnfr_descriptor["vdur"].append(vdur)
252
253 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
254 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
255
256 # add at database
257 BaseTopic.format_on_new(vnfr_descriptor, session["project_id"], make_public=make_public)
258 self.db.create("vnfrs", vnfr_descriptor)
259 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
260 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
261
262 step = "creating nsr at database"
263 self.format_on_new(nsr_descriptor, session["project_id"], make_public=make_public)
264 self.db.create("nsrs", nsr_descriptor)
265 rollback.append({"topic": "nsrs", "_id": nsr_id})
266 return nsr_id
267 except Exception as e:
268 self.logger.exception("Exception {} at NsrTopic.new()".format(e), exc_info=True)
269 raise EngineException("Error {}: {}".format(step, e))
270 except ValidationError as e:
271 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
272
273 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
274 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
275
276
277 class VnfrTopic(BaseTopic):
278 topic = "vnfrs"
279 topic_msg = None
280
281 def __init__(self, db, fs, msg):
282 BaseTopic.__init__(self, db, fs, msg)
283
284 def delete(self, session, _id, force=False, dry_run=False):
285 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
286
287 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
288 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
289
290 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
291 # Not used because vnfrs are created and deleted by NsrTopic class directly
292 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
293
294
295 class NsLcmOpTopic(BaseTopic):
296 topic = "nslcmops"
297 topic_msg = "ns"
298 operation_schema = { # mapping between operation and jsonschema to validate
299 "instantiate": ns_instantiate,
300 "action": ns_action,
301 "scale": ns_scale,
302 "terminate": None,
303 }
304
305 def __init__(self, db, fs, msg):
306 BaseTopic.__init__(self, db, fs, msg)
307
308 def _check_ns_operation(self, session, nsr, operation, indata):
309 """
310 Check that user has enter right parameters for the operation
311 :param session:
312 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
313 :param indata: descriptor with the parameters of the operation
314 :return: None
315 """
316 vnfds = {}
317 vim_accounts = []
318 nsd = nsr["nsd"]
319
320 def check_valid_vnf_member_index(member_vnf_index):
321 # TODO change to vnfR
322 for vnf in nsd["constituent-vnfd"]:
323 if member_vnf_index == vnf["member-vnf-index"]:
324 vnfd_id = vnf["vnfd-id-ref"]
325 if vnfd_id not in vnfds:
326 vnfds[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
327 return vnfds[vnfd_id]
328 else:
329 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
330 "nsd:constituent-vnfd".format(member_vnf_index))
331
332 def _check_vnf_instantiation_params(in_vnfd, vnfd):
333
334 for in_vdu in get_iterable(in_vnfd.get("vdu")):
335 for vdu in get_iterable(vnfd.get("vdu")):
336 if in_vdu["id"] == vdu["id"]:
337 for volume in get_iterable(in_vdu.get("volume")):
338 for volumed in get_iterable(vdu.get("volumes")):
339 if volumed["name"] == volume["name"]:
340 break
341 else:
342 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
343 "volume:name='{}' is not present at vnfd:vdu:volumes list".
344 format(in_vnf["member-vnf-index"], in_vdu["id"],
345 volume["name"]))
346 for in_iface in get_iterable(in_vdu["interface"]):
347 for iface in get_iterable(vdu.get("interface")):
348 if in_iface["name"] == iface["name"]:
349 break
350 else:
351 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
352 "interface[name='{}'] is not present at vnfd:vdu:interface"
353 .format(in_vnf["member-vnf-index"], in_vdu["id"],
354 in_iface["name"]))
355 break
356 else:
357 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
358 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
359
360 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
361 for ivld in get_iterable(vnfd.get("internal-vld")):
362 if in_ivld["name"] == ivld["name"] or in_ivld["name"] == ivld["id"]:
363 for in_icp in get_iterable(in_ivld["internal-connection-point"]):
364 for icp in ivld["internal-connection-point"]:
365 if in_icp["id-ref"] == icp["id-ref"]:
366 break
367 else:
368 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
369 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
370 "vnfd:internal-vld:name/id:internal-connection-point"
371 .format(in_vnf["member-vnf-index"], in_ivld["name"],
372 in_icp["id-ref"], vnfd["id"]))
373 break
374 else:
375 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
376 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
377 in_ivld["name"], vnfd["id"]))
378
379 def check_valid_vim_account(vim_account):
380 if vim_account in vim_accounts:
381 return
382 try:
383 db_filter = self._get_project_filter(session, write=False, show_all=True)
384 db_filter["_id"] = vim_account
385 self.db.get_one("vim_accounts", db_filter)
386 except Exception:
387 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
388 vim_accounts.append(vim_account)
389
390 if operation == "action":
391 # check vnf_member_index
392 if indata.get("vnf_member_index"):
393 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
394 if not indata.get("member_vnf_index"):
395 raise EngineException("Missing 'member_vnf_index' parameter")
396 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
397 # check primitive
398 for config_primitive in get_iterable(vnfd.get("vnf-configuration", {}).get("config-primitive")):
399 if indata["primitive"] == config_primitive["name"]:
400 # check needed primitive_params are provided
401 if indata.get("primitive_params"):
402 in_primitive_params_copy = copy(indata["primitive_params"])
403 else:
404 in_primitive_params_copy = {}
405 for paramd in get_iterable(config_primitive.get("parameter")):
406 if paramd["name"] in in_primitive_params_copy:
407 del in_primitive_params_copy[paramd["name"]]
408 elif not paramd.get("default-value"):
409 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
410 paramd["name"], indata["primitive"]))
411 # check no extra primitive params are provided
412 if in_primitive_params_copy:
413 raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
414 list(in_primitive_params_copy.keys()), indata["primitive"]))
415 break
416 else:
417 raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata["primitive"]))
418 if operation == "scale":
419 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
420 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
421 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
422 break
423 else:
424 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
425 "present at vnfd:scaling-group-descriptor".format(
426 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
427 if operation == "instantiate":
428 # check vim_account
429 check_valid_vim_account(indata["vimAccountId"])
430 for in_vnf in get_iterable(indata.get("vnf")):
431 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
432 _check_vnf_instantiation_params(in_vnf, vnfd)
433 if in_vnf.get("vimAccountId"):
434 check_valid_vim_account(in_vnf["vimAccountId"])
435
436 for in_vld in get_iterable(indata.get("vld")):
437 for vldd in get_iterable(nsd.get("vld")):
438 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
439 break
440 else:
441 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
442 in_vld["name"]))
443
444 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
445 """
446 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
447 (ip_address, ...) information.
448 Modifies PDU _admin.usageState to 'IN_USE'
449
450 :param session: client session information
451 :param rollback: list with the database modifications to rollback if needed
452 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
453 :param vim_account: vim_account where this vnfr should be deployed
454 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
455 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
456 of the changed vnfr is needed
457
458 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
459 "vim-network-name": used at VIM
460 "name": interface name
461 "vnf-vld-id": internal VNFD vld where this interface is connected, or
462 "ns-vld-id": NSD vld where this interface is connected.
463 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
464 """
465
466 ifaces_forcing_vim_network = []
467 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
468 if not vdur.get("pdu-type"):
469 continue
470 pdu_type = vdur.get("pdu-type")
471 pdu_filter = self._get_project_filter(session, write=True, show_all=True)
472 pdu_filter["vim_accounts"] = vim_account
473 pdu_filter["type"] = pdu_type
474 pdu_filter["_admin.operationalState"] = "ENABLED"
475 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
476 # TODO feature 1417: "shared": True,
477
478 available_pdus = self.db.get_list("pdus", pdu_filter)
479 for pdu in available_pdus:
480 # step 1 check if this pdu contains needed interfaces:
481 match_interfaces = True
482 for vdur_interface in vdur["interfaces"]:
483 for pdu_interface in pdu["interfaces"]:
484 if pdu_interface["name"] == vdur_interface["name"]:
485 # TODO feature 1417: match per mgmt type
486 break
487 else: # no interface found for name
488 match_interfaces = False
489 break
490 if match_interfaces:
491 break
492 else:
493 raise EngineException(
494 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
495 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
496
497 # step 2. Update pdu
498 rollback_pdu = {
499 "_admin.usageState": pdu["_admin"]["usageState"],
500 "_admin.usage.vnfr_id": None,
501 "_admin.usage.nsr_id": None,
502 "_admin.usage.vdur": None,
503 }
504 self.db.set_one("pdus", {"_id": pdu["_id"]},
505 {"_admin.usageState": "IN_USE",
506 "_admin.usage.vnfr_id": vnfr["_id"],
507 "_admin.usage.nsr_id": vnfr["nsr-id-ref"],
508 "_admin.usage.vdur": vdur["vdu-id-ref"]}
509 )
510 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
511
512 # step 3. Fill vnfr info by filling vdur
513 vdu_text = "vdur.{}".format(vdur_index)
514 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
515 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
516 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
517 for pdu_interface in pdu["interfaces"]:
518 if pdu_interface["name"] == vdur_interface["name"]:
519 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
520 for k, v in pdu_interface.items():
521 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
522 vnfr_update[iface_text + ".{}".format(k)] = v
523 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
524 if pdu_interface.get("ip-address"):
525 if vdur_interface.get("mgmt-interface"):
526 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
527 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
528 if vdur_interface.get("mgmt-vnf"):
529 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
530 vnfr_update["ip-address"] = pdu_interface["ip-address"]
531 if pdu_interface.get("vim-network-name"): # or pdu_interface.get("vim-network-id"):
532 ifaces_forcing_vim_network.append({
533 # "vim-network-id": pdu_interface.get("vim-network-id"),
534 "vim-network-name": pdu_interface.get("vim-network-name"),
535 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
536 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
537 "ns-vld-id": vdur_interface.get("ns-vld-id")})
538 break
539
540 return ifaces_forcing_vim_network
541
542 def _update_vnfrs(self, session, rollback, nsr, indata):
543 vnfrs = None
544 # get vnfr
545 nsr_id = nsr["_id"]
546 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
547
548 for vnfr in vnfrs:
549 vnfr_update = {}
550 vnfr_update_rollback = {}
551 member_vnf_index = vnfr["member-vnf-index-ref"]
552 # update vim-account-id
553
554 vim_account = indata["vimAccountId"]
555 # check instantiate parameters
556 for vnf_inst_params in get_iterable(indata.get("vnf")):
557 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
558 continue
559 if vnf_inst_params.get("vimAccountId"):
560 vim_account = vnf_inst_params.get("vimAccountId")
561
562 vnfr_update["vim-account-id"] = vim_account
563 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
564
565 # get pdu
566 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
567 vnfr_update_rollback)
568
569 # updata database vnfr
570 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
571 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
572
573 # Update indada in case pdu forces to use a concrete vim-network-name
574 # TODO check if user has already insert a vim-network-name and raises an error
575 if not ifaces_forcing_vim_network:
576 continue
577 for iface_info in ifaces_forcing_vim_network:
578 if iface_info.get("ns-vld-id"):
579 if "vld" not in indata:
580 indata["vld"] = []
581 indata["vld"].append({key: iface_info[key] for key in
582 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
583
584 elif iface_info.get("vnf-vld-id"):
585 if "vnf" not in indata:
586 indata["vnf"] = []
587 indata["vnf"].append({
588 "member-vnf-index": member_vnf_index,
589 "internal-vld": [{key: iface_info[key] for key in
590 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
591 })
592
593 @staticmethod
594 def _create_nslcmop(nsr_id, operation, params):
595 """
596 Creates a ns-lcm-opp content to be stored at database.
597 :param nsr_id: internal id of the instance
598 :param operation: instantiate, terminate, scale, action, ...
599 :param params: user parameters for the operation
600 :return: dictionary following SOL005 format
601 """
602 now = time()
603 _id = str(uuid4())
604 nslcmop = {
605 "id": _id,
606 "_id": _id,
607 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
608 "statusEnteredTime": now,
609 "nsInstanceId": nsr_id,
610 "lcmOperationType": operation,
611 "startTime": now,
612 "isAutomaticInvocation": False,
613 "operationParams": params,
614 "isCancelPending": False,
615 "links": {
616 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
617 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
618 }
619 }
620 return nslcmop
621
622 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False,
623 slice_object=False):
624 """
625 Performs a new operation over a ns
626 :param rollback: list to append created items at database in case a rollback must to be done
627 :param session: contains the used login username and working project
628 :param indata: descriptor with the parameters of the operation. It must contains among others
629 nsInstanceId: _id of the nsr to perform the operation
630 operation: it can be: instantiate, terminate, action, TODO: update, heal
631 :param kwargs: used to override the indata descriptor
632 :param headers: http request headers
633 :param force: If True avoid some dependence checks
634 :param make_public: Make the created item public to all projects
635 :return: id of the nslcmops
636 """
637 try:
638 # Override descriptor with query string kwargs
639 self._update_input_with_kwargs(indata, kwargs)
640 operation = indata["lcmOperationType"]
641 nsInstanceId = indata["nsInstanceId"]
642
643 validate_input(indata, self.operation_schema[operation])
644 # get ns from nsr_id
645 _filter = BaseTopic._get_project_filter(session, write=True, show_all=False)
646 _filter["_id"] = nsInstanceId
647 nsr = self.db.get_one("nsrs", _filter)
648
649 # initial checking
650 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
651 if operation == "terminate" and indata.get("autoremove"):
652 # NSR must be deleted
653 return self.delete(session, nsInstanceId)
654 if operation != "instantiate":
655 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
656 nsInstanceId, operation), HTTPStatus.CONFLICT)
657 else:
658 if operation == "instantiate" and not indata.get("force"):
659 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
660 nsInstanceId, operation), HTTPStatus.CONFLICT)
661 self._check_ns_operation(session, nsr, operation, indata)
662
663 if operation == "instantiate":
664 self._update_vnfrs(session, rollback, nsr, indata)
665
666 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
667 self.format_on_new(nslcmop_desc, session["project_id"], make_public=make_public)
668 _id = self.db.create("nslcmops", nslcmop_desc)
669 rollback.append({"topic": "nslcmops", "_id": _id})
670 if not slice_object:
671 self.msg.write("ns", operation, nslcmop_desc)
672 return _id
673 except ValidationError as e:
674 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
675 # except DbException as e:
676 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
677
678 def delete(self, session, _id, force=False, dry_run=False):
679 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
680
681 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
682 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
683
684
685 class NsiTopic(BaseTopic):
686 topic = "nsis"
687 topic_msg = "nsi"
688
689 def __init__(self, db, fs, msg):
690 BaseTopic.__init__(self, db, fs, msg)
691
692 def _check_descriptor_dependencies(self, session, descriptor):
693 """
694 Check that the dependent descriptors exist on a new descriptor or edition
695 :param session: client session information
696 :param descriptor: descriptor to be inserted or edit
697 :return: None or raises exception
698 """
699 if not descriptor.get("nst-ref"):
700 return
701 nstd_id = descriptor["nst-ref"]
702 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
703 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
704 http_code=HTTPStatus.CONFLICT)
705
706 @staticmethod
707 def format_on_new(content, project_id=None, make_public=False):
708 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
709
710 def check_conflict_on_del(self, session, _id, force=False):
711 if force:
712 return
713 nsi = self.db.get_one("nsis", {"_id": _id})
714 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
715 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
716 "Launch 'terminate' operation first; or force deletion".format(_id),
717 http_code=HTTPStatus.CONFLICT)
718
719 def delete(self, session, _id, force=False, dry_run=False):
720 """
721 Delete item by its internal _id
722 :param session: contains the used login username, working project, and admin rights
723 :param _id: server internal id
724 :param force: indicates if deletion must be forced in case of conflict
725 :param dry_run: make checking but do not delete
726 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
727 """
728 # TODO add admin to filter, validate rights
729 BaseTopic.delete(self, session, _id, force, dry_run=True)
730 if dry_run:
731 return
732
733 # deletes NetSlice instance object
734 v = self.db.del_one("nsis", {"_id": _id})
735
736 # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
737 _filter = {"netsliceInstanceId": _id}
738 self.db.del_list("nsilcmops", _filter)
739
740 _filter = {"operationParams.netsliceInstanceId": _id}
741 nslcmops_list = self.db.get_list("nslcmops", _filter)
742
743 for id_item in nslcmops_list:
744 _filter = {"_id": id_item}
745 nslcmop = self.db.get_one("nslcmops", _filter)
746 nsr_id = nslcmop["operationParams"]["nsr_id"]
747 NsrTopic.delete(self, session, nsr_id, force=False, dry_run=False)
748 self._send_msg("deleted", {"_id": _id})
749 return v
750
751 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
752 """
753 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
754 :param rollback: list to append the created items at database in case a rollback must be done
755 :param session: contains the used login username and working project
756 :param indata: params to be used for the nsir
757 :param kwargs: used to override the indata descriptor
758 :param headers: http request headers
759 :param force: If True avoid some dependence checks
760 :param make_public: Make the created item public to all projects
761 :return: the _id of nsi descriptor created at database
762 """
763
764 try:
765 slice_request = self._remove_envelop(indata)
766 # Override descriptor with query string kwargs
767 self._update_input_with_kwargs(slice_request, kwargs)
768 self._validate_input_new(slice_request, force)
769
770 step = ""
771 # look for nstd
772 self.logger.info(str(slice_request))
773 step = "getting nstd id='{}' from database".format(slice_request.get("nstdId"))
774 _filter = {"id": slice_request["nstdId"]}
775 _filter.update(BaseTopic._get_project_filter(session, write=False, show_all=True))
776 nstd = self.db.get_one("nsts", _filter)
777 nstd.pop("_admin", None)
778 nstd.pop("_id", None)
779 nsi_id = str(uuid4())
780 step = "filling nsi_descriptor with input data"
781
782 # "instantiation-parameters.netslice-subnet": []
783 # TODO: Equal as template for now
784 nsi_descriptor = {
785 "id": nsi_id,
786 "nst-ref": nstd["id"],
787 "instantiation-parameters": {
788 "netslice-subnet": []
789 },
790 "network-slice-template": nstd,
791 "_id": nsi_id,
792 }
793
794 # Creating netslice-subnet_record.
795 needed_nsds = {}
796 services = []
797 for member_ns in nstd["netslice-subnet"]:
798 nsd_id = member_ns["nsd-ref"]
799 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
800 member_ns["nsd-ref"], member_ns["id"])
801 if nsd_id not in needed_nsds:
802 # Obtain nsd
803 nsd = DescriptorTopic.get_one_by_id(self.db, session, "nsds", nsd_id)
804 nsd.pop("_admin")
805 needed_nsds[nsd_id] = nsd
806 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
807 services.append(member_ns)
808 else:
809 nsd = needed_nsds[nsd_id]
810 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
811 services.append(member_ns)
812
813 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
814 member_ns["nsd-ref"], member_ns["id"])
815
816 step = "creating nsi at database"
817 self.format_on_new(nsi_descriptor, session["project_id"], make_public=make_public)
818 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
819
820 # creates Network Services records (NSRs)
821 step = "creating nsrs at database using NsrTopic.new()"
822 nsrs_list = []
823 for service in services:
824 indata_ns = {}
825 indata_ns["nsdId"] = service["_id"]
826 indata_ns["nsName"] = service["name"]
827 indata_ns["vimAccountId"] = indata.get("vimAccountId")
828 indata_ns["nsDescription"] = service["description"]
829 indata_ns["key-pair-ref"] = None
830 # NsrTopic(rollback, session, indata_ns, kwargs, headers, force)
831 _id_nsr = NsrTopic.new(self, rollback, session, indata_ns, kwargs, headers, force)
832 nsrs_item = {"nsrId": _id_nsr}
833 nsrs_list.append(nsrs_item)
834
835 # Adding the nsrs list to the nsi
836 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
837 # Creating the entry in the database
838 self.db.create("nsis", nsi_descriptor)
839 rollback.append({"topic": "nsis", "_id": nsi_id})
840 return nsi_id
841 except Exception as e:
842 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
843 raise EngineException("Error {}: {}".format(step, e))
844 except ValidationError as e:
845 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
846
847 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
848 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
849
850
851 class NsiLcmOpTopic(BaseTopic):
852 topic = "nsilcmops"
853 topic_msg = "nsi"
854 operation_schema = { # mapping between operation and jsonschema to validate
855 "instantiate": nsi_instantiate,
856 "terminate": None
857 }
858
859 def __init__(self, db, fs, msg):
860 BaseTopic.__init__(self, db, fs, msg)
861
862 def _check_nsi_operation(self, session, nsir, operation, indata):
863 """
864 Check that user has enter right parameters for the operation
865 :param session:
866 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
867 :param indata: descriptor with the parameters of the operation
868 :return: None
869 """
870 nsds = {}
871 nstd = nsir["network-slice-template"]
872
873 def check_valid_netslice_subnet_id(nsId):
874 # TODO change to vnfR (??)
875 for ns in nstd["netslice-subnet"]:
876 if nsId == ns["id"]:
877 nsd_id = ns["nsd-ref"]
878 if nsd_id not in nsds:
879 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
880 return nsds[nsd_id]
881 else:
882 raise EngineException("Invalid parameter nsId='{}' is not one of the "
883 "nst:netslice-subnet".format(nsId))
884 if operation == "instantiate":
885 # check the existance of netslice-subnet items
886 for in_nst in get_iterable(indata.get("netslice-subnet")):
887 nstd = check_valid_netslice_subnet_id(in_nst["nsdId"])
888
889 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
890 now = time()
891 _id = str(uuid4())
892 nsilcmop = {
893 "id": _id,
894 "_id": _id,
895 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
896 "statusEnteredTime": now,
897 "netsliceInstanceId": netsliceInstanceId,
898 "lcmOperationType": operation,
899 "startTime": now,
900 "isAutomaticInvocation": False,
901 "operationParams": params,
902 "isCancelPending": False,
903 "links": {
904 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
905 "nsInstance": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
906 }
907 }
908 return nsilcmop
909
910 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
911 """
912 Performs a new operation over a ns
913 :param rollback: list to append created items at database in case a rollback must to be done
914 :param session: contains the used login username and working project
915 :param indata: descriptor with the parameters of the operation. It must contains among others
916 nsiInstanceId: _id of the nsir to perform the operation
917 operation: it can be: instantiate, terminate, action, TODO: update, heal
918 :param kwargs: used to override the indata descriptor
919 :param headers: http request headers
920 :param force: If True avoid some dependence checks
921 :param make_public: Make the created item public to all projects
922 :return: id of the nslcmops
923 """
924 try:
925 # Override descriptor with query string kwargs
926 self._update_input_with_kwargs(indata, kwargs)
927 operation = indata["lcmOperationType"]
928 nsiInstanceId = indata["nsiInstanceId"]
929 validate_input(indata, self.operation_schema[operation])
930
931 # get nsi from nsiInstanceId
932 _filter = BaseTopic._get_project_filter(session, write=True, show_all=False)
933 _filter["_id"] = nsiInstanceId
934 nsir = self.db.get_one("nsis", _filter)
935
936 # initial checking
937 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
938 if operation == "terminate" and indata.get("autoremove"):
939 # NSIR must be deleted
940 return self.delete(session, nsiInstanceId)
941 if operation != "instantiate":
942 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
943 nsiInstanceId, operation), HTTPStatus.CONFLICT)
944 else:
945 if operation == "instantiate" and not indata.get("force"):
946 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
947 format(nsiInstanceId, operation), HTTPStatus.CONFLICT)
948
949 # Creating all the NS_operation (nslcmop)
950 # Get service list from db
951 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
952 nslcmops = []
953 for nsr_item in nsrs_list:
954 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
955 indata_ns = {}
956 indata_ns = service["instantiate_params"]
957 indata_ns["lcmOperationType"] = operation
958 indata_ns["nsInstanceId"] = service["_id"]
959 # Including netslice_id in the ns instantiate Operation
960 indata_ns["netsliceInstanceId"] = nsiInstanceId
961 del indata_ns["key-pair-ref"]
962 nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg)
963 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
964 # message via kafka bus
965 nslcmop = nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers, force, slice_object=True)
966 nslcmops.append(nslcmop)
967
968 # Creates nsilcmop
969 indata["nslcmops_ids"] = nslcmops
970 self._check_nsi_operation(session, nsir, operation, indata)
971 nsilcmop_desc = self._create_nsilcmop(session, nsiInstanceId, operation, indata)
972 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=make_public)
973 _id = self.db.create("nsilcmops", nsilcmop_desc)
974 rollback.append({"topic": "nsilcmops", "_id": _id})
975 self.msg.write("nsi", operation, nsilcmop_desc)
976 return _id
977 except ValidationError as e:
978 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
979 # except DbException as e:
980 # raise EngineException("Cannot get nsi_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
981
982 def delete(self, session, _id, force=False, dry_run=False):
983 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
984
985 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
986 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)