Reformat NBI to standardized format
[osm/NBI.git] / osm_nbi / instance_topics.py
1 # -*- coding: utf-8 -*-
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 # import logging
17 from uuid import uuid4
18 from http import HTTPStatus
19 from time import time
20 from copy import copy, deepcopy
21 from osm_nbi.validation import (
22 validate_input,
23 ValidationError,
24 ns_instantiate,
25 ns_terminate,
26 ns_action,
27 ns_scale,
28 nsi_instantiate,
29 )
30 from osm_nbi.base_topic import (
31 BaseTopic,
32 EngineException,
33 get_iterable,
34 deep_get,
35 increment_ip_mac,
36 )
37 from yaml import safe_dump
38 from osm_common.dbbase import DbException
39 from osm_common.msgbase import MsgException
40 from osm_common.fsbase import FsException
41 from osm_nbi import utils
42 from re import (
43 match,
44 ) # For checking that additional parameter names are valid Jinja2 identifiers
45
46 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
47
48
49 class NsrTopic(BaseTopic):
50 topic = "nsrs"
51 topic_msg = "ns"
52 quota_name = "ns_instances"
53 schema_new = ns_instantiate
54
55 def __init__(self, db, fs, msg, auth):
56 BaseTopic.__init__(self, db, fs, msg, auth)
57
58 def _check_descriptor_dependencies(self, session, descriptor):
59 """
60 Check that the dependent descriptors exist on a new descriptor or edition
61 :param session: client session information
62 :param descriptor: descriptor to be inserted or edit
63 :return: None or raises exception
64 """
65 if not descriptor.get("nsdId"):
66 return
67 nsd_id = descriptor["nsdId"]
68 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
69 raise EngineException(
70 "Descriptor error at nsdId='{}' references a non exist nsd".format(
71 nsd_id
72 ),
73 http_code=HTTPStatus.CONFLICT,
74 )
75
76 @staticmethod
77 def format_on_new(content, project_id=None, make_public=False):
78 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
79 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
80 return None
81
82 def check_conflict_on_del(self, session, _id, db_content):
83 """
84 Check that NSR is not instantiated
85 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
86 :param _id: nsr internal id
87 :param db_content: The database content of the nsr
88 :return: None or raises EngineException with the conflict
89 """
90 if session["force"]:
91 return
92 nsr = db_content
93 if nsr["_admin"].get("nsState") == "INSTANTIATED":
94 raise EngineException(
95 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
96 "Launch 'terminate' operation first; or force deletion".format(_id),
97 http_code=HTTPStatus.CONFLICT,
98 )
99
100 def delete_extra(self, session, _id, db_content, not_send_msg=None):
101 """
102 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
103 Set usageState of pdu, vnfd, nsd
104 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
105 :param _id: server internal id
106 :param db_content: The database content of the descriptor
107 :param not_send_msg: To not send message (False) or store content (list) instead
108 :return: None if ok or raises EngineException with the problem
109 """
110 self.fs.file_delete(_id, ignore_non_exist=True)
111 self.db.del_list("nslcmops", {"nsInstanceId": _id})
112 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
113
114 # set all used pdus as free
115 self.db.set_list(
116 "pdus",
117 {"_admin.usage.nsr_id": _id},
118 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
119 )
120
121 # Set NSD usageState
122 nsr = db_content
123 used_nsd_id = nsr.get("nsd-id")
124 if used_nsd_id:
125 # check if used by another NSR
126 nsrs_list = self.db.get_one(
127 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
128 )
129 if not nsrs_list:
130 self.db.set_one(
131 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
132 )
133
134 # Set VNFD usageState
135 used_vnfd_id_list = nsr.get("vnfd-id")
136 if used_vnfd_id_list:
137 for used_vnfd_id in used_vnfd_id_list:
138 # check if used by another NSR
139 nsrs_list = self.db.get_one(
140 "nsrs",
141 {"vnfd-id": used_vnfd_id},
142 fail_on_empty=False,
143 fail_on_more=False,
144 )
145 if not nsrs_list:
146 self.db.set_one(
147 "vnfds",
148 {"_id": used_vnfd_id},
149 {"_admin.usageState": "NOT_IN_USE"},
150 )
151
152 # delete extra ro_nsrs used for internal RO module
153 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
154
155 @staticmethod
156 def _format_ns_request(ns_request):
157 formated_request = copy(ns_request)
158 formated_request.pop("additionalParamsForNs", None)
159 formated_request.pop("additionalParamsForVnf", None)
160 return formated_request
161
162 @staticmethod
163 def _format_additional_params(
164 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
165 ):
166 """
167 Get and format user additional params for NS or VNF
168 :param ns_request: User instantiation additional parameters
169 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
170 :param descriptor: If not None it check that needed parameters of descriptor are supplied
171 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
172 """
173 additional_params = None
174 other_params = None
175 if not member_vnf_index:
176 additional_params = copy(ns_request.get("additionalParamsForNs"))
177 where_ = "additionalParamsForNs"
178 elif ns_request.get("additionalParamsForVnf"):
179 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
180 member_vnf_index
181 )
182 item = next(
183 (
184 x
185 for x in ns_request["additionalParamsForVnf"]
186 if x["member-vnf-index"] == member_vnf_index
187 ),
188 None,
189 )
190 if item:
191 if not vdu_id and not kdu_name:
192 other_params = item
193 additional_params = copy(item.get("additionalParams")) or {}
194 if vdu_id and item.get("additionalParamsForVdu"):
195 item_vdu = next(
196 (
197 x
198 for x in item["additionalParamsForVdu"]
199 if x["vdu_id"] == vdu_id
200 ),
201 None,
202 )
203 other_params = item_vdu
204 if item_vdu and item_vdu.get("additionalParams"):
205 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
206 additional_params = item_vdu["additionalParams"]
207 if kdu_name:
208 additional_params = {}
209 if item.get("additionalParamsForKdu"):
210 item_kdu = next(
211 (
212 x
213 for x in item["additionalParamsForKdu"]
214 if x["kdu_name"] == kdu_name
215 ),
216 None,
217 )
218 other_params = item_kdu
219 if item_kdu and item_kdu.get("additionalParams"):
220 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
221 kdu_name
222 )
223 additional_params = item_kdu["additionalParams"]
224
225 if additional_params:
226 for k, v in additional_params.items():
227 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
228 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
229 raise EngineException(
230 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
231 "and underscores, and cannot start with a digit".format(
232 where_, k
233 )
234 )
235 # END Check that additional parameter names are valid Jinja2 identifiers
236 if not isinstance(k, str):
237 raise EngineException(
238 "Invalid param at {}:{}. Only string keys are allowed".format(
239 where_, k
240 )
241 )
242 if "." in k or "$" in k:
243 raise EngineException(
244 "Invalid param at {}:{}. Keys must not contain dots or $".format(
245 where_, k
246 )
247 )
248 if isinstance(v, (dict, tuple, list)):
249 additional_params[k] = "!!yaml " + safe_dump(v)
250
251 if descriptor:
252 for df in descriptor.get("df", []):
253 # check that enough parameters are supplied for the initial-config-primitive
254 # TODO: check for cloud-init
255 if member_vnf_index:
256 initial_primitives = []
257 if (
258 "lcm-operations-configuration" in df
259 and "operate-vnf-op-config"
260 in df["lcm-operations-configuration"]
261 ):
262 for config in df["lcm-operations-configuration"][
263 "operate-vnf-op-config"
264 ].get("day1-2", []):
265 for primitive in get_iterable(
266 config.get("initial-config-primitive")
267 ):
268 initial_primitives.append(primitive)
269 else:
270 initial_primitives = deep_get(
271 descriptor, ("ns-configuration", "initial-config-primitive")
272 )
273
274 for initial_primitive in get_iterable(initial_primitives):
275 for param in get_iterable(initial_primitive.get("parameter")):
276 if param["value"].startswith("<") and param["value"].endswith(
277 ">"
278 ):
279 if param["value"] in (
280 "<rw_mgmt_ip>",
281 "<VDU_SCALE_INFO>",
282 "<ns_config_info>",
283 ):
284 continue
285 if (
286 not additional_params
287 or param["value"][1:-1] not in additional_params
288 ):
289 raise EngineException(
290 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
291 "initial-config-primitive[name={}] not supplied".format(
292 param["value"],
293 descriptor["id"],
294 initial_primitive["name"],
295 )
296 )
297
298 return additional_params or None, other_params or None
299
300 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
301 """
302 Creates a new nsr into database. It also creates needed vnfrs
303 :param rollback: list to append the created items at database in case a rollback must be done
304 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
305 :param indata: params to be used for the nsr
306 :param kwargs: used to override the indata descriptor
307 :param headers: http request headers
308 :return: the _id of nsr descriptor created at database. Or an exception of type
309 EngineException, ValidationError, DbException, FsException, MsgException.
310 Note: Exceptions are not captured on purpose. They should be captured at called
311 """
312 try:
313 step = "checking quotas"
314 self.check_quota(session)
315
316 step = "validating input parameters"
317 ns_request = self._remove_envelop(indata)
318 self._update_input_with_kwargs(ns_request, kwargs)
319 ns_request = self._validate_input_new(ns_request, session["force"])
320
321 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
322 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
323 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
324
325 step = "checking nsdOperationalState"
326 self._check_nsd_operational_state(nsd, ns_request)
327
328 step = "filling nsr from input data"
329 nsr_id = str(uuid4())
330 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
331 nsd, ns_request, nsr_id, session
332 )
333
334 # Create VNFRs
335 needed_vnfds = {}
336 # TODO: Change for multiple df support
337 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
338 for vnfp in vnf_profiles:
339 vnfd_id = vnfp.get("vnfd-id")
340 vnf_index = vnfp.get("id")
341 step = (
342 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
343 vnfd_id, vnf_index
344 )
345 )
346 if vnfd_id not in needed_vnfds:
347 vnfd = self._get_vnfd_from_db(vnfd_id, session)
348 needed_vnfds[vnfd_id] = vnfd
349 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
350 else:
351 vnfd = needed_vnfds[vnfd_id]
352
353 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
354 vnfd_id, vnf_index
355 )
356 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
357 nsd,
358 vnfd,
359 vnfd_id,
360 vnf_index,
361 nsr_descriptor,
362 ns_request,
363 ns_k8s_namespace,
364 )
365
366 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
367 vnfd_id, vnf_index
368 )
369 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
370 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
371
372 step = "creating nsr at database"
373 self._add_nsr_to_db(nsr_descriptor, rollback, session)
374
375 step = "creating nsr temporal folder"
376 self.fs.mkdir(nsr_id)
377
378 return nsr_id, None
379 except (
380 ValidationError,
381 EngineException,
382 DbException,
383 MsgException,
384 FsException,
385 ) as e:
386 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
387
388 def _get_nsd_from_db(self, nsd_id, session):
389 _filter = self._get_project_filter(session)
390 _filter["_id"] = nsd_id
391 return self.db.get_one("nsds", _filter)
392
393 def _get_vnfd_from_db(self, vnfd_id, session):
394 _filter = self._get_project_filter(session)
395 _filter["id"] = vnfd_id
396 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
397 vnfd.pop("_admin")
398 return vnfd
399
400 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
401 self.format_on_new(
402 nsr_descriptor, session["project_id"], make_public=session["public"]
403 )
404 self.db.create("nsrs", nsr_descriptor)
405 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
406
407 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
408 self.format_on_new(
409 vnfr_descriptor, session["project_id"], make_public=session["public"]
410 )
411 self.db.create("vnfrs", vnfr_descriptor)
412 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
413
414 def _check_nsd_operational_state(self, nsd, ns_request):
415 if nsd["_admin"]["operationalState"] == "DISABLED":
416 raise EngineException(
417 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
418 "a network service".format(ns_request["nsdId"]),
419 http_code=HTTPStatus.CONFLICT,
420 )
421
422 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
423 additional_params, _ = self._format_additional_params(
424 ns_request, descriptor=nsd
425 )
426 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
427 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
428 if ns_request and ns_request.get("k8s-namespace"):
429 ns_k8s_namespace = ns_request["k8s-namespace"]
430 if additional_params and additional_params.get("k8s-namespace"):
431 ns_k8s_namespace = additional_params["k8s-namespace"]
432
433 return ns_k8s_namespace
434
435 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
436 now = time()
437 additional_params, _ = self._format_additional_params(
438 ns_request, descriptor=nsd
439 )
440
441 nsr_descriptor = {
442 "name": ns_request["nsName"],
443 "name-ref": ns_request["nsName"],
444 "short-name": ns_request["nsName"],
445 "admin-status": "ENABLED",
446 "nsState": "NOT_INSTANTIATED",
447 "currentOperation": "IDLE",
448 "currentOperationID": None,
449 "errorDescription": None,
450 "errorDetail": None,
451 "deploymentStatus": None,
452 "configurationStatus": None,
453 "vcaStatus": None,
454 "nsd": {k: v for k, v in nsd.items()},
455 "datacenter": ns_request["vimAccountId"],
456 "resource-orchestrator": "osmopenmano",
457 "description": ns_request.get("nsDescription", ""),
458 "constituent-vnfr-ref": [],
459 "operational-status": "init", # typedef ns-operational-
460 "config-status": "init", # typedef config-states
461 "detailed-status": "scheduled",
462 "orchestration-progress": {},
463 "create-time": now,
464 "nsd-name-ref": nsd["name"],
465 "operational-events": [], # "id", "timestamp", "description", "event",
466 "nsd-ref": nsd["id"],
467 "nsd-id": nsd["_id"],
468 "vnfd-id": [],
469 "instantiate_params": self._format_ns_request(ns_request),
470 "additionalParamsForNs": additional_params,
471 "ns-instance-config-ref": nsr_id,
472 "id": nsr_id,
473 "_id": nsr_id,
474 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
475 "flavor": [],
476 "image": [],
477 }
478 ns_request["nsr_id"] = nsr_id
479 if ns_request and ns_request.get("config-units"):
480 nsr_descriptor["config-units"] = ns_request["config-units"]
481
482 # Create vld
483 if nsd.get("virtual-link-desc"):
484 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
485 # Fill each vld with vnfd-connection-point-ref data
486 # TODO: Change for multiple df support
487 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
488 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
489 for vnf_profile in vnf_profiles:
490 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
491 for cpd in vlc.get("constituent-cpd-id", ()):
492 all_vld_connection_point_data[
493 vlc.get("virtual-link-profile-id")
494 ].append(
495 {
496 "member-vnf-index-ref": cpd.get(
497 "constituent-base-element-id"
498 ),
499 "vnfd-connection-point-ref": cpd.get(
500 "constituent-cpd-id"
501 ),
502 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
503 }
504 )
505
506 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
507
508 for vdu in vnfd.get("vdu", ()):
509 flavor_data = {}
510 guest_epa = {}
511 # Find this vdu compute and storage descriptors
512 vdu_virtual_compute = {}
513 vdu_virtual_storage = {}
514 for vcd in vnfd.get("virtual-compute-desc", ()):
515 if vcd.get("id") == vdu.get("virtual-compute-desc"):
516 vdu_virtual_compute = vcd
517 for vsd in vnfd.get("virtual-storage-desc", ()):
518 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
519 vdu_virtual_storage = vsd
520 # Get this vdu vcpus, memory and storage info for flavor_data
521 if vdu_virtual_compute.get("virtual-cpu", {}).get(
522 "num-virtual-cpu"
523 ):
524 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
525 "num-virtual-cpu"
526 ]
527 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
528 flavor_data["memory-mb"] = (
529 float(vdu_virtual_compute["virtual-memory"]["size"])
530 * 1024.0
531 )
532 if vdu_virtual_storage.get("size-of-storage"):
533 flavor_data["storage-gb"] = vdu_virtual_storage[
534 "size-of-storage"
535 ]
536 # Get this vdu EPA info for guest_epa
537 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
538 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
539 "cpu-quota"
540 ]
541 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
542 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
543 if vcpu_pinning.get("thread-policy"):
544 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
545 "thread-policy"
546 ]
547 if vcpu_pinning.get("policy"):
548 cpu_policy = (
549 "SHARED"
550 if vcpu_pinning["policy"] == "dynamic"
551 else "DEDICATED"
552 )
553 guest_epa["cpu-pinning-policy"] = cpu_policy
554 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
555 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
556 "mem-quota"
557 ]
558 if vdu_virtual_compute.get("virtual-memory", {}).get(
559 "mempage-size"
560 ):
561 guest_epa["mempage-size"] = vdu_virtual_compute[
562 "virtual-memory"
563 ]["mempage-size"]
564 if vdu_virtual_compute.get("virtual-memory", {}).get(
565 "numa-node-policy"
566 ):
567 guest_epa["numa-node-policy"] = vdu_virtual_compute[
568 "virtual-memory"
569 ]["numa-node-policy"]
570 if vdu_virtual_storage.get("disk-io-quota"):
571 guest_epa["disk-io-quota"] = vdu_virtual_storage[
572 "disk-io-quota"
573 ]
574
575 if guest_epa:
576 flavor_data["guest-epa"] = guest_epa
577
578 flavor_data["name"] = vdu["id"][:56] + "-flv"
579 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
580 nsr_descriptor["flavor"].append(flavor_data)
581
582 sw_image_id = vdu.get("sw-image-desc")
583 if sw_image_id:
584 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
585 self._add_image_to_nsr(nsr_descriptor, image_data)
586
587 # also add alternative images to the list of images
588 for alt_image in vdu.get("alternative-sw-image-desc", ()):
589 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
590 self._add_image_to_nsr(nsr_descriptor, image_data)
591
592 for vld in nsr_vld:
593 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
594 vld.get("id"), []
595 )
596 vld["name"] = vld["id"]
597 nsr_descriptor["vld"] = nsr_vld
598
599 return nsr_descriptor
600
601 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
602 sw_image_desc = utils.find_in_list(
603 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
604 )
605 image_data = {}
606 if sw_image_desc.get("image"):
607 image_data["image"] = sw_image_desc["image"]
608 if sw_image_desc.get("checksum"):
609 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
610 if sw_image_desc.get("vim-type"):
611 image_data["vim-type"] = sw_image_desc["vim-type"]
612 return image_data
613
614 def _add_image_to_nsr(self, nsr_descriptor, image_data):
615 """
616 Adds image to nsr checking first it is not already added
617 """
618 img = next(
619 (
620 f
621 for f in nsr_descriptor["image"]
622 if all(f.get(k) == image_data[k] for k in image_data)
623 ),
624 None,
625 )
626 if not img:
627 image_data["id"] = str(len(nsr_descriptor["image"]))
628 nsr_descriptor["image"].append(image_data)
629
630 def _create_vnfr_descriptor_from_vnfd(
631 self,
632 nsd,
633 vnfd,
634 vnfd_id,
635 vnf_index,
636 nsr_descriptor,
637 ns_request,
638 ns_k8s_namespace,
639 ):
640 vnfr_id = str(uuid4())
641 nsr_id = nsr_descriptor["id"]
642 now = time()
643 additional_params, vnf_params = self._format_additional_params(
644 ns_request, vnf_index, descriptor=vnfd
645 )
646
647 vnfr_descriptor = {
648 "id": vnfr_id,
649 "_id": vnfr_id,
650 "nsr-id-ref": nsr_id,
651 "member-vnf-index-ref": vnf_index,
652 "additionalParamsForVnf": additional_params,
653 "created-time": now,
654 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
655 "vnfd-ref": vnfd_id,
656 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
657 "vim-account-id": None,
658 "vca-id": None,
659 "vdur": [],
660 "connection-point": [],
661 "ip-address": None, # mgmt-interface filled by LCM
662 }
663 vnf_k8s_namespace = ns_k8s_namespace
664 if vnf_params:
665 if vnf_params.get("k8s-namespace"):
666 vnf_k8s_namespace = vnf_params["k8s-namespace"]
667 if vnf_params.get("config-units"):
668 vnfr_descriptor["config-units"] = vnf_params["config-units"]
669
670 # Create vld
671 if vnfd.get("int-virtual-link-desc"):
672 vnfr_descriptor["vld"] = []
673 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
674 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
675
676 for cp in vnfd.get("ext-cpd", ()):
677 vnf_cp = {
678 "name": cp.get("id"),
679 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
680 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
681 "id": cp.get("id"),
682 # "ip-address", "mac-address" # filled by LCM
683 # vim-id # TODO it would be nice having a vim port id
684 }
685 vnfr_descriptor["connection-point"].append(vnf_cp)
686
687 # Create k8s-cluster information
688 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
689 if vnfd.get("k8s-cluster"):
690 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
691 all_k8s_cluster_nets_cpds = {}
692 for cpd in get_iterable(vnfd.get("ext-cpd")):
693 if cpd.get("k8s-cluster-net"):
694 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
695 "id"
696 )
697 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
698 if net.get("id") in all_k8s_cluster_nets_cpds:
699 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
700 net.get("id")
701 ]
702
703 # update kdus
704 for kdu in get_iterable(vnfd.get("kdu")):
705 additional_params, kdu_params = self._format_additional_params(
706 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
707 )
708 kdu_k8s_namespace = vnf_k8s_namespace
709 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
710 if kdu_params and kdu_params.get("k8s-namespace"):
711 kdu_k8s_namespace = kdu_params["k8s-namespace"]
712
713 kdur = {
714 "additionalParams": additional_params,
715 "k8s-namespace": kdu_k8s_namespace,
716 "kdu-name": kdu["name"],
717 # TODO "name": "" Name of the VDU in the VIM
718 "ip-address": None, # mgmt-interface filled by LCM
719 "k8s-cluster": {},
720 }
721 if kdu_params and kdu_params.get("config-units"):
722 kdur["config-units"] = kdu_params["config-units"]
723 if kdu.get("helm-version"):
724 kdur["helm-version"] = kdu["helm-version"]
725 for k8s_type in ("helm-chart", "juju-bundle"):
726 if kdu.get(k8s_type):
727 kdur[k8s_type] = kdu_model or kdu[k8s_type]
728 if not vnfr_descriptor.get("kdur"):
729 vnfr_descriptor["kdur"] = []
730 vnfr_descriptor["kdur"].append(kdur)
731
732 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
733
734 for vdu in vnfd.get("vdu", ()):
735 vdu_mgmt_cp = []
736 try:
737 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
738 "operate-vnf-op-config"
739 ]["day1-2"]
740 vdu_config = utils.find_in_list(
741 configs, lambda config: config["id"] == vdu["id"]
742 )
743 except Exception:
744 vdu_config = None
745
746 try:
747 vdu_instantiation_level = utils.find_in_list(
748 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
749 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
750 )
751 except Exception:
752 vdu_instantiation_level = None
753
754 if vdu_config:
755 external_connection_ee = utils.filter_in_list(
756 vdu_config.get("execution-environment-list", []),
757 lambda ee: "external-connection-point-ref" in ee,
758 )
759 for ee in external_connection_ee:
760 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
761
762 additional_params, vdu_params = self._format_additional_params(
763 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
764 )
765 vdur = {
766 "vdu-id-ref": vdu["id"],
767 # TODO "name": "" Name of the VDU in the VIM
768 "ip-address": None, # mgmt-interface filled by LCM
769 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
770 "internal-connection-point": [],
771 "interfaces": [],
772 "additionalParams": additional_params,
773 "vdu-name": vdu["name"],
774 }
775 if vdu_params and vdu_params.get("config-units"):
776 vdur["config-units"] = vdu_params["config-units"]
777 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
778 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
779 "boot-data-drive"
780 ]
781 if vdu.get("pdu-type"):
782 vdur["pdu-type"] = vdu["pdu-type"]
783 vdur["name"] = vdu["pdu-type"]
784 # TODO volumes: name, volume-id
785 for icp in vdu.get("int-cpd", ()):
786 vdu_icp = {
787 "id": icp["id"],
788 "connection-point-id": icp["id"],
789 "name": icp.get("id"),
790 }
791
792 vdur["internal-connection-point"].append(vdu_icp)
793
794 for iface in icp.get("virtual-network-interface-requirement", ()):
795 iface_fields = ("name", "mac-address")
796 vdu_iface = {
797 x: iface[x] for x in iface_fields if iface.get(x) is not None
798 }
799
800 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
801 if "port-security-enabled" in icp:
802 vdu_iface["port-security-enabled"] = icp[
803 "port-security-enabled"
804 ]
805
806 if "port-security-disable-strategy" in icp:
807 vdu_iface["port-security-disable-strategy"] = icp[
808 "port-security-disable-strategy"
809 ]
810
811 for ext_cp in vnfd.get("ext-cpd", ()):
812 if not ext_cp.get("int-cpd"):
813 continue
814 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
815 continue
816 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
817 vdu_iface["external-connection-point-ref"] = ext_cp.get(
818 "id"
819 )
820
821 if "port-security-enabled" in ext_cp:
822 vdu_iface["port-security-enabled"] = ext_cp[
823 "port-security-enabled"
824 ]
825
826 if "port-security-disable-strategy" in ext_cp:
827 vdu_iface["port-security-disable-strategy"] = ext_cp[
828 "port-security-disable-strategy"
829 ]
830
831 break
832
833 if (
834 vnfd_mgmt_cp
835 and vdu_iface.get("external-connection-point-ref")
836 == vnfd_mgmt_cp
837 ):
838 vdu_iface["mgmt-vnf"] = True
839 vdu_iface["mgmt-interface"] = True
840
841 for ecp in vdu_mgmt_cp:
842 if vdu_iface.get("external-connection-point-ref") == ecp:
843 vdu_iface["mgmt-interface"] = True
844
845 if iface.get("virtual-interface"):
846 vdu_iface.update(deepcopy(iface["virtual-interface"]))
847
848 # look for network where this interface is connected
849 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
850 if iface_ext_cp:
851 # TODO: Change for multiple df support
852 for df in get_iterable(nsd.get("df")):
853 for vnf_profile in get_iterable(df.get("vnf-profile")):
854 for vlc_index, vlc in enumerate(
855 get_iterable(
856 vnf_profile.get("virtual-link-connectivity")
857 )
858 ):
859 for cpd in get_iterable(
860 vlc.get("constituent-cpd-id")
861 ):
862 if (
863 cpd.get("constituent-cpd-id")
864 == iface_ext_cp
865 ):
866 vdu_iface["ns-vld-id"] = vlc.get(
867 "virtual-link-profile-id"
868 )
869 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
870 if vdu_iface.get("type") in (
871 "SR-IOV",
872 "PCI-PASSTHROUGH",
873 ):
874 nsr_descriptor["vld"][vlc_index][
875 "pci-interfaces"
876 ] = True
877 break
878 elif vdu_iface.get("internal-connection-point-ref"):
879 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
880 # TODO: store fixed IP address in the record (if it exists in the ICP)
881 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
882 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
883 ivld_index = utils.find_index_in_list(
884 vnfd.get("int-virtual-link-desc", ()),
885 lambda ivld: ivld["id"]
886 == icp.get("int-virtual-link-desc"),
887 )
888 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
889
890 vdur["interfaces"].append(vdu_iface)
891
892 if vdu.get("sw-image-desc"):
893 sw_image = utils.find_in_list(
894 vnfd.get("sw-image-desc", ()),
895 lambda image: image["id"] == vdu.get("sw-image-desc"),
896 )
897 nsr_sw_image_data = utils.find_in_list(
898 nsr_descriptor["image"],
899 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
900 )
901 vdur["ns-image-id"] = nsr_sw_image_data["id"]
902
903 if vdu.get("alternative-sw-image-desc"):
904 alt_image_ids = []
905 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
906 sw_image = utils.find_in_list(
907 vnfd.get("sw-image-desc", ()),
908 lambda image: image["id"] == alt_image_id,
909 )
910 nsr_sw_image_data = utils.find_in_list(
911 nsr_descriptor["image"],
912 lambda nsr_image: (
913 nsr_image.get("image") == sw_image.get("image")
914 ),
915 )
916 alt_image_ids.append(nsr_sw_image_data["id"])
917 vdur["alt-image-ids"] = alt_image_ids
918
919 flavor_data_name = vdu["id"][:56] + "-flv"
920 nsr_flavor_desc = utils.find_in_list(
921 nsr_descriptor["flavor"],
922 lambda flavor: flavor["name"] == flavor_data_name,
923 )
924
925 if nsr_flavor_desc:
926 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
927
928 if vdu_instantiation_level:
929 count = vdu_instantiation_level.get("number-of-instances")
930 else:
931 count = 1
932
933 for index in range(0, count):
934 vdur = deepcopy(vdur)
935 for iface in vdur["interfaces"]:
936 if iface.get("ip-address"):
937 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
938 if iface.get("mac-address"):
939 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
940
941 vdur["_id"] = str(uuid4())
942 vdur["id"] = vdur["_id"]
943 vdur["count-index"] = index
944 vnfr_descriptor["vdur"].append(vdur)
945
946 return vnfr_descriptor
947
948 def edit(self, session, _id, indata=None, kwargs=None, content=None):
949 raise EngineException(
950 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
951 )
952
953
954 class VnfrTopic(BaseTopic):
955 topic = "vnfrs"
956 topic_msg = None
957
958 def __init__(self, db, fs, msg, auth):
959 BaseTopic.__init__(self, db, fs, msg, auth)
960
961 def delete(self, session, _id, dry_run=False, not_send_msg=None):
962 raise EngineException(
963 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
964 )
965
966 def edit(self, session, _id, indata=None, kwargs=None, content=None):
967 raise EngineException(
968 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
969 )
970
971 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
972 # Not used because vnfrs are created and deleted by NsrTopic class directly
973 raise EngineException(
974 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
975 )
976
977
978 class NsLcmOpTopic(BaseTopic):
979 topic = "nslcmops"
980 topic_msg = "ns"
981 operation_schema = { # mapping between operation and jsonschema to validate
982 "instantiate": ns_instantiate,
983 "action": ns_action,
984 "scale": ns_scale,
985 "terminate": ns_terminate,
986 }
987
988 def __init__(self, db, fs, msg, auth):
989 BaseTopic.__init__(self, db, fs, msg, auth)
990
991 def _check_ns_operation(self, session, nsr, operation, indata):
992 """
993 Check that user has enter right parameters for the operation
994 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
995 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
996 :param indata: descriptor with the parameters of the operation
997 :return: None
998 """
999 if operation == "action":
1000 self._check_action_ns_operation(indata, nsr)
1001 elif operation == "scale":
1002 self._check_scale_ns_operation(indata, nsr)
1003 elif operation == "instantiate":
1004 self._check_instantiate_ns_operation(indata, nsr, session)
1005
1006 def _check_action_ns_operation(self, indata, nsr):
1007 nsd = nsr["nsd"]
1008 # check vnf_member_index
1009 if indata.get("vnf_member_index"):
1010 indata["member_vnf_index"] = indata.pop(
1011 "vnf_member_index"
1012 ) # for backward compatibility
1013 if indata.get("member_vnf_index"):
1014 vnfd = self._get_vnfd_from_vnf_member_index(
1015 indata["member_vnf_index"], nsr["_id"]
1016 )
1017 try:
1018 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1019 "operate-vnf-op-config"
1020 ]["day1-2"]
1021 except Exception:
1022 configs = []
1023
1024 if indata.get("vdu_id"):
1025 self._check_valid_vdu(vnfd, indata["vdu_id"])
1026 descriptor_configuration = utils.find_in_list(
1027 configs, lambda config: config["id"] == indata["vdu_id"]
1028 )
1029 elif indata.get("kdu_name"):
1030 self._check_valid_kdu(vnfd, indata["kdu_name"])
1031 descriptor_configuration = utils.find_in_list(
1032 configs, lambda config: config["id"] == indata.get("kdu_name")
1033 )
1034 else:
1035 descriptor_configuration = utils.find_in_list(
1036 configs, lambda config: config["id"] == vnfd["id"]
1037 )
1038 if descriptor_configuration is not None:
1039 descriptor_configuration = descriptor_configuration.get(
1040 "config-primitive"
1041 )
1042 else: # use a NSD
1043 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1044 "config-primitive"
1045 )
1046
1047 # For k8s allows default primitives without validating the parameters
1048 if indata.get("kdu_name") and indata["primitive"] in (
1049 "upgrade",
1050 "rollback",
1051 "status",
1052 "inspect",
1053 "readme",
1054 ):
1055 # TODO should be checked that rollback only can contains revsision_numbe????
1056 if not indata.get("member_vnf_index"):
1057 raise EngineException(
1058 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1059 indata["primitive"]
1060 )
1061 )
1062 return
1063 # if not, check primitive
1064 for config_primitive in get_iterable(descriptor_configuration):
1065 if indata["primitive"] == config_primitive["name"]:
1066 # check needed primitive_params are provided
1067 if indata.get("primitive_params"):
1068 in_primitive_params_copy = copy(indata["primitive_params"])
1069 else:
1070 in_primitive_params_copy = {}
1071 for paramd in get_iterable(config_primitive.get("parameter")):
1072 if paramd["name"] in in_primitive_params_copy:
1073 del in_primitive_params_copy[paramd["name"]]
1074 elif not paramd.get("default-value"):
1075 raise EngineException(
1076 "Needed parameter {} not provided for primitive '{}'".format(
1077 paramd["name"], indata["primitive"]
1078 )
1079 )
1080 # check no extra primitive params are provided
1081 if in_primitive_params_copy:
1082 raise EngineException(
1083 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1084 list(in_primitive_params_copy.keys()), indata["primitive"]
1085 )
1086 )
1087 break
1088 else:
1089 raise EngineException(
1090 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1091 indata["primitive"]
1092 )
1093 )
1094
1095 def _check_scale_ns_operation(self, indata, nsr):
1096 vnfd = self._get_vnfd_from_vnf_member_index(
1097 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1098 )
1099 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
1100 if (
1101 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1102 == scaling_aspect["id"]
1103 ):
1104 break
1105 else:
1106 raise EngineException(
1107 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1108 "present at vnfd:scaling-aspect".format(
1109 indata["scaleVnfData"]["scaleByStepData"][
1110 "scaling-group-descriptor"
1111 ]
1112 )
1113 )
1114
1115 def _check_instantiate_ns_operation(self, indata, nsr, session):
1116 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
1117 vim_accounts = []
1118 wim_accounts = []
1119 nsd = nsr["nsd"]
1120 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1121 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1122 for in_vnf in get_iterable(indata.get("vnf")):
1123 member_vnf_index = in_vnf["member-vnf-index"]
1124 if vnf_member_index_to_vnfd.get(member_vnf_index):
1125 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
1126 else:
1127 vnfd = self._get_vnfd_from_vnf_member_index(
1128 member_vnf_index, nsr["_id"]
1129 )
1130 vnf_member_index_to_vnfd[
1131 member_vnf_index
1132 ] = vnfd # add to cache, avoiding a later look for
1133 self._check_vnf_instantiation_params(in_vnf, vnfd)
1134 if in_vnf.get("vimAccountId"):
1135 self._check_valid_vim_account(
1136 in_vnf["vimAccountId"], vim_accounts, session
1137 )
1138
1139 for in_vld in get_iterable(indata.get("vld")):
1140 self._check_valid_wim_account(
1141 in_vld.get("wimAccountId"), wim_accounts, session
1142 )
1143 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1144 if in_vld["name"] == vldd["id"]:
1145 break
1146 else:
1147 raise EngineException(
1148 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1149 in_vld["name"]
1150 )
1151 )
1152
1153 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1154 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1155 vnfr = self.db.get_one(
1156 "vnfrs",
1157 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1158 fail_on_empty=False,
1159 )
1160 if not vnfr:
1161 raise EngineException(
1162 "Invalid parameter member_vnf_index='{}' is not one of the "
1163 "nsd:constituent-vnfd".format(member_vnf_index)
1164 )
1165 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1166 if not vnfd:
1167 raise EngineException(
1168 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1169 vnfr["vnfd-id"]
1170 )
1171 )
1172 return vnfd
1173
1174 def _check_valid_vdu(self, vnfd, vdu_id):
1175 for vdud in get_iterable(vnfd.get("vdu")):
1176 if vdud["id"] == vdu_id:
1177 return vdud
1178 else:
1179 raise EngineException(
1180 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1181 vdu_id
1182 )
1183 )
1184
1185 def _check_valid_kdu(self, vnfd, kdu_name):
1186 for kdud in get_iterable(vnfd.get("kdu")):
1187 if kdud["name"] == kdu_name:
1188 return kdud
1189 else:
1190 raise EngineException(
1191 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1192 kdu_name
1193 )
1194 )
1195
1196 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1197 for in_vdu in get_iterable(in_vnf.get("vdu")):
1198 for vdu in get_iterable(vnfd.get("vdu")):
1199 if in_vdu["id"] == vdu["id"]:
1200 for volume in get_iterable(in_vdu.get("volume")):
1201 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1202 if volumed["id"] == volume["name"]:
1203 break
1204 else:
1205 raise EngineException(
1206 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1207 "volume:name='{}' is not present at "
1208 "vnfd:vdu:virtual-storage-desc list".format(
1209 in_vnf["member-vnf-index"],
1210 in_vdu["id"],
1211 volume["id"],
1212 )
1213 )
1214
1215 vdu_if_names = set()
1216 for cpd in get_iterable(vdu.get("int-cpd")):
1217 for iface in get_iterable(
1218 cpd.get("virtual-network-interface-requirement")
1219 ):
1220 vdu_if_names.add(iface.get("name"))
1221
1222 for in_iface in get_iterable(in_vdu["interface"]):
1223 if in_iface["name"] in vdu_if_names:
1224 break
1225 else:
1226 raise EngineException(
1227 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1228 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1229 in_vnf["member-vnf-index"],
1230 in_vdu["id"],
1231 in_iface["name"],
1232 )
1233 )
1234 break
1235
1236 else:
1237 raise EngineException(
1238 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1239 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1240 )
1241
1242 vnfd_ivlds_cpds = {
1243 ivld.get("id"): set()
1244 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1245 }
1246 for vdu in get_iterable(vnfd.get("vdu")):
1247 for cpd in get_iterable(vnfd.get("int-cpd")):
1248 if cpd.get("int-virtual-link-desc"):
1249 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1250
1251 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1252 if in_ivld.get("name") in vnfd_ivlds_cpds:
1253 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1254 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
1255 break
1256 else:
1257 raise EngineException(
1258 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1259 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1260 "vnfd:internal-vld:name/id:internal-connection-point".format(
1261 in_vnf["member-vnf-index"],
1262 in_ivld["name"],
1263 in_icp["id-ref"],
1264 )
1265 )
1266 else:
1267 raise EngineException(
1268 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1269 " is not present at vnfd '{}'".format(
1270 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1271 )
1272 )
1273
1274 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1275 if vim_account in vim_accounts:
1276 return
1277 try:
1278 db_filter = self._get_project_filter(session)
1279 db_filter["_id"] = vim_account
1280 self.db.get_one("vim_accounts", db_filter)
1281 except Exception:
1282 raise EngineException(
1283 "Invalid vimAccountId='{}' not present for the project".format(
1284 vim_account
1285 )
1286 )
1287 vim_accounts.append(vim_account)
1288
1289 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1290 if not isinstance(wim_account, str):
1291 return
1292 if wim_account in wim_accounts:
1293 return
1294 try:
1295 db_filter = self._get_project_filter(session, write=False, show_all=True)
1296 db_filter["_id"] = wim_account
1297 self.db.get_one("wim_accounts", db_filter)
1298 except Exception:
1299 raise EngineException(
1300 "Invalid wimAccountId='{}' not present for the project".format(
1301 wim_account
1302 )
1303 )
1304 wim_accounts.append(wim_account)
1305
1306 def _look_for_pdu(
1307 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1308 ):
1309 """
1310 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1311 (ip_address, ...) information.
1312 Modifies PDU _admin.usageState to 'IN_USE'
1313 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1314 :param rollback: list with the database modifications to rollback if needed
1315 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1316 :param vim_account: vim_account where this vnfr should be deployed
1317 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1318 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1319 of the changed vnfr is needed
1320
1321 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1322 "vim-network-name": used at VIM
1323 "name": interface name
1324 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1325 "ns-vld-id": NSD vld where this interface is connected.
1326 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1327 """
1328
1329 ifaces_forcing_vim_network = []
1330 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1331 if not vdur.get("pdu-type"):
1332 continue
1333 pdu_type = vdur.get("pdu-type")
1334 pdu_filter = self._get_project_filter(session)
1335 pdu_filter["vim_accounts"] = vim_account
1336 pdu_filter["type"] = pdu_type
1337 pdu_filter["_admin.operationalState"] = "ENABLED"
1338 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
1339 # TODO feature 1417: "shared": True,
1340
1341 available_pdus = self.db.get_list("pdus", pdu_filter)
1342 for pdu in available_pdus:
1343 # step 1 check if this pdu contains needed interfaces:
1344 match_interfaces = True
1345 for vdur_interface in vdur["interfaces"]:
1346 for pdu_interface in pdu["interfaces"]:
1347 if pdu_interface["name"] == vdur_interface["name"]:
1348 # TODO feature 1417: match per mgmt type
1349 break
1350 else: # no interface found for name
1351 match_interfaces = False
1352 break
1353 if match_interfaces:
1354 break
1355 else:
1356 raise EngineException(
1357 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1358 "names".format(
1359 pdu_type,
1360 vim_account,
1361 vnfr["member-vnf-index-ref"],
1362 vdur["vdu-id-ref"],
1363 )
1364 )
1365
1366 # step 2. Update pdu
1367 rollback_pdu = {
1368 "_admin.usageState": pdu["_admin"]["usageState"],
1369 "_admin.usage.vnfr_id": None,
1370 "_admin.usage.nsr_id": None,
1371 "_admin.usage.vdur": None,
1372 }
1373 self.db.set_one(
1374 "pdus",
1375 {"_id": pdu["_id"]},
1376 {
1377 "_admin.usageState": "IN_USE",
1378 "_admin.usage": {
1379 "vnfr_id": vnfr["_id"],
1380 "nsr_id": vnfr["nsr-id-ref"],
1381 "vdur": vdur["vdu-id-ref"],
1382 },
1383 },
1384 )
1385 rollback.append(
1386 {
1387 "topic": "pdus",
1388 "_id": pdu["_id"],
1389 "operation": "set",
1390 "content": rollback_pdu,
1391 }
1392 )
1393
1394 # step 3. Fill vnfr info by filling vdur
1395 vdu_text = "vdur.{}".format(vdur_index)
1396 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
1397 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1398 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1399 for pdu_interface in pdu["interfaces"]:
1400 if pdu_interface["name"] == vdur_interface["name"]:
1401 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1402 for k, v in pdu_interface.items():
1403 if k in (
1404 "ip-address",
1405 "mac-address",
1406 ): # TODO: switch-xxxxx must be inserted
1407 vnfr_update[iface_text + ".{}".format(k)] = v
1408 vnfr_update_rollback[
1409 iface_text + ".{}".format(k)
1410 ] = vdur_interface.get(v)
1411 if pdu_interface.get("ip-address"):
1412 if vdur_interface.get(
1413 "mgmt-interface"
1414 ) or vdur_interface.get("mgmt-vnf"):
1415 vnfr_update_rollback[
1416 vdu_text + ".ip-address"
1417 ] = vdur.get("ip-address")
1418 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1419 "ip-address"
1420 ]
1421 if vdur_interface.get("mgmt-vnf"):
1422 vnfr_update_rollback["ip-address"] = vnfr.get(
1423 "ip-address"
1424 )
1425 vnfr_update["ip-address"] = pdu_interface["ip-address"]
1426 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1427 "ip-address"
1428 ]
1429 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1430 "vim-network-id"
1431 ):
1432 ifaces_forcing_vim_network.append(
1433 {
1434 "name": vdur_interface.get("vnf-vld-id")
1435 or vdur_interface.get("ns-vld-id"),
1436 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1437 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1438 }
1439 )
1440 if pdu_interface.get("vim-network-id"):
1441 ifaces_forcing_vim_network[-1][
1442 "vim-network-id"
1443 ] = pdu_interface["vim-network-id"]
1444 if pdu_interface.get("vim-network-name"):
1445 ifaces_forcing_vim_network[-1][
1446 "vim-network-name"
1447 ] = pdu_interface["vim-network-name"]
1448 break
1449
1450 return ifaces_forcing_vim_network
1451
1452 def _look_for_k8scluster(
1453 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1454 ):
1455 """
1456 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1457 Fills vnfr.kdur with the selected k8scluster
1458
1459 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1460 :param rollback: list with the database modifications to rollback if needed
1461 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1462 :param vim_account: vim_account where this vnfr should be deployed
1463 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1464 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1465 of the changed vnfr is needed
1466
1467 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1468 "vim-network-name": used at VIM
1469 "name": interface name
1470 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1471 "ns-vld-id": NSD vld where this interface is connected.
1472 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1473 """
1474
1475 ifaces_forcing_vim_network = []
1476 if not vnfr.get("kdur"):
1477 return ifaces_forcing_vim_network
1478
1479 kdu_filter = self._get_project_filter(session)
1480 kdu_filter["vim_account"] = vim_account
1481 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1482 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1483
1484 k8s_requirements = {} # just for logging
1485 for k8scluster in available_k8sclusters:
1486 if not vnfr.get("k8s-cluster"):
1487 break
1488 # restrict by cni
1489 if vnfr["k8s-cluster"].get("cni"):
1490 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
1491 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1492 k8scluster.get("cni", ())
1493 ):
1494 continue
1495 # restrict by version
1496 if vnfr["k8s-cluster"].get("version"):
1497 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1498 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1499 continue
1500 # restrict by number of networks
1501 if vnfr["k8s-cluster"].get("nets"):
1502 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
1503 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1504 vnfr["k8s-cluster"]["nets"]
1505 ):
1506 continue
1507 break
1508 else:
1509 raise EngineException(
1510 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1511 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1512 )
1513 )
1514
1515 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
1516 # step 3. Fill vnfr info by filling kdur
1517 kdu_text = "kdur.{}.".format(kdur_index)
1518 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1519 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1520
1521 # step 4. Check VIM networks that forces the selected k8s_cluster
1522 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1523 k8scluster_net_list = list(k8scluster.get("nets").keys())
1524 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1525 # get a network from k8s_cluster nets. If name matches use this, if not use other
1526 if kdur_net["id"] in k8scluster_net_list: # name matches
1527 vim_net = k8scluster["nets"][kdur_net["id"]]
1528 k8scluster_net_list.remove(kdur_net["id"])
1529 else:
1530 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1531 k8scluster_net_list.pop(0)
1532 vnfr_update_rollback[
1533 "k8s-cluster.nets.{}.vim_net".format(net_index)
1534 ] = None
1535 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
1536 if vim_net and (
1537 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1538 ):
1539 ifaces_forcing_vim_network.append(
1540 {
1541 "name": kdur_net.get("vnf-vld-id")
1542 or kdur_net.get("ns-vld-id"),
1543 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1544 "ns-vld-id": kdur_net.get("ns-vld-id"),
1545 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1546 }
1547 )
1548 # TODO check that this forcing is not incompatible with other forcing
1549 return ifaces_forcing_vim_network
1550
1551 def _update_vnfrs(self, session, rollback, nsr, indata):
1552 # get vnfr
1553 nsr_id = nsr["_id"]
1554 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1555
1556 for vnfr in vnfrs:
1557 vnfr_update = {}
1558 vnfr_update_rollback = {}
1559 member_vnf_index = vnfr["member-vnf-index-ref"]
1560 # update vim-account-id
1561
1562 vim_account = indata["vimAccountId"]
1563 vca_id = indata.get("vcaId")
1564 # check instantiate parameters
1565 for vnf_inst_params in get_iterable(indata.get("vnf")):
1566 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1567 continue
1568 if vnf_inst_params.get("vimAccountId"):
1569 vim_account = vnf_inst_params.get("vimAccountId")
1570 if vnf_inst_params.get("vcaId"):
1571 vca_id = vnf_inst_params.get("vcaId")
1572
1573 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1574 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1575 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1576 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1577 continue
1578 for iface_inst_param in get_iterable(
1579 vdu_inst_param.get("interface")
1580 ):
1581 iface_index, _ = next(
1582 i
1583 for i in enumerate(vdur["interfaces"])
1584 if i[1]["name"] == iface_inst_param["name"]
1585 )
1586 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1587 vdur_index, iface_index
1588 )
1589 if iface_inst_param.get("ip-address"):
1590 vnfr_update[
1591 vnfr_update_text + ".ip-address"
1592 ] = increment_ip_mac(
1593 iface_inst_param.get("ip-address"),
1594 vdur.get("count-index", 0),
1595 )
1596 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1597 if iface_inst_param.get("mac-address"):
1598 vnfr_update[
1599 vnfr_update_text + ".mac-address"
1600 ] = increment_ip_mac(
1601 iface_inst_param.get("mac-address"),
1602 vdur.get("count-index", 0),
1603 )
1604 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1605 if iface_inst_param.get("floating-ip-required"):
1606 vnfr_update[
1607 vnfr_update_text + ".floating-ip-required"
1608 ] = True
1609 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1610 # TODO update vld with the ip-profile
1611 for ivld_inst_param in get_iterable(
1612 vnf_inst_params.get("internal-vld")
1613 ):
1614 for icp_inst_param in get_iterable(
1615 ivld_inst_param.get("internal-connection-point")
1616 ):
1617 # look for iface
1618 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1619 for iface_index, iface in enumerate(vdur["interfaces"]):
1620 if (
1621 iface.get("internal-connection-point-ref")
1622 == icp_inst_param["id-ref"]
1623 ):
1624 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1625 vdur_index, iface_index
1626 )
1627 if icp_inst_param.get("ip-address"):
1628 vnfr_update[
1629 vnfr_update_text + ".ip-address"
1630 ] = increment_ip_mac(
1631 icp_inst_param.get("ip-address"),
1632 vdur.get("count-index", 0),
1633 )
1634 vnfr_update[
1635 vnfr_update_text + ".fixed-ip"
1636 ] = True
1637 if icp_inst_param.get("mac-address"):
1638 vnfr_update[
1639 vnfr_update_text + ".mac-address"
1640 ] = increment_ip_mac(
1641 icp_inst_param.get("mac-address"),
1642 vdur.get("count-index", 0),
1643 )
1644 vnfr_update[
1645 vnfr_update_text + ".fixed-mac"
1646 ] = True
1647 break
1648 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1649 for vld_inst_param in get_iterable(indata.get("vld")):
1650 for vnfcp_inst_param in get_iterable(
1651 vld_inst_param.get("vnfd-connection-point-ref")
1652 ):
1653 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1654 continue
1655 # look for iface
1656 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1657 for iface_index, iface in enumerate(vdur["interfaces"]):
1658 if (
1659 iface.get("external-connection-point-ref")
1660 == vnfcp_inst_param["vnfd-connection-point-ref"]
1661 ):
1662 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1663 vdur_index, iface_index
1664 )
1665 if vnfcp_inst_param.get("ip-address"):
1666 vnfr_update[
1667 vnfr_update_text + ".ip-address"
1668 ] = increment_ip_mac(
1669 vnfcp_inst_param.get("ip-address"),
1670 vdur.get("count-index", 0),
1671 )
1672 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1673 if vnfcp_inst_param.get("mac-address"):
1674 vnfr_update[
1675 vnfr_update_text + ".mac-address"
1676 ] = increment_ip_mac(
1677 vnfcp_inst_param.get("mac-address"),
1678 vdur.get("count-index", 0),
1679 )
1680 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1681 break
1682
1683 vnfr_update["vim-account-id"] = vim_account
1684 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1685
1686 if vca_id:
1687 vnfr_update["vca-id"] = vca_id
1688 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1689
1690 # get pdu
1691 ifaces_forcing_vim_network = self._look_for_pdu(
1692 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1693 )
1694
1695 # get kdus
1696 ifaces_forcing_vim_network += self._look_for_k8scluster(
1697 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1698 )
1699 # update database vnfr
1700 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1701 rollback.append(
1702 {
1703 "topic": "vnfrs",
1704 "_id": vnfr["_id"],
1705 "operation": "set",
1706 "content": vnfr_update_rollback,
1707 }
1708 )
1709
1710 # Update indada in case pdu forces to use a concrete vim-network-name
1711 # TODO check if user has already insert a vim-network-name and raises an error
1712 if not ifaces_forcing_vim_network:
1713 continue
1714 for iface_info in ifaces_forcing_vim_network:
1715 if iface_info.get("ns-vld-id"):
1716 if "vld" not in indata:
1717 indata["vld"] = []
1718 indata["vld"].append(
1719 {
1720 key: iface_info[key]
1721 for key in ("name", "vim-network-name", "vim-network-id")
1722 if iface_info.get(key)
1723 }
1724 )
1725
1726 elif iface_info.get("vnf-vld-id"):
1727 if "vnf" not in indata:
1728 indata["vnf"] = []
1729 indata["vnf"].append(
1730 {
1731 "member-vnf-index": member_vnf_index,
1732 "internal-vld": [
1733 {
1734 key: iface_info[key]
1735 for key in (
1736 "name",
1737 "vim-network-name",
1738 "vim-network-id",
1739 )
1740 if iface_info.get(key)
1741 }
1742 ],
1743 }
1744 )
1745
1746 @staticmethod
1747 def _create_nslcmop(nsr_id, operation, params):
1748 """
1749 Creates a ns-lcm-opp content to be stored at database.
1750 :param nsr_id: internal id of the instance
1751 :param operation: instantiate, terminate, scale, action, ...
1752 :param params: user parameters for the operation
1753 :return: dictionary following SOL005 format
1754 """
1755 now = time()
1756 _id = str(uuid4())
1757 nslcmop = {
1758 "id": _id,
1759 "_id": _id,
1760 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1761 "queuePosition": None,
1762 "stage": None,
1763 "errorMessage": None,
1764 "detailedStatus": None,
1765 "statusEnteredTime": now,
1766 "nsInstanceId": nsr_id,
1767 "lcmOperationType": operation,
1768 "startTime": now,
1769 "isAutomaticInvocation": False,
1770 "operationParams": params,
1771 "isCancelPending": False,
1772 "links": {
1773 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
1774 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
1775 },
1776 }
1777 return nslcmop
1778
1779 def _get_enabled_vims(self, session):
1780 """
1781 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1782 :param session: current session with user information
1783 """
1784 db_filter = self._get_project_filter(session)
1785 db_filter["_admin.operationalState"] = "ENABLED"
1786 vims = self.db.get_list("vim_accounts", db_filter)
1787 vimAccounts = []
1788 for vim in vims:
1789 vimAccounts.append(vim["_id"])
1790 return vimAccounts
1791
1792 def new(
1793 self,
1794 rollback,
1795 session,
1796 indata=None,
1797 kwargs=None,
1798 headers=None,
1799 slice_object=False,
1800 ):
1801 """
1802 Performs a new operation over a ns
1803 :param rollback: list to append created items at database in case a rollback must to be done
1804 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1805 :param indata: descriptor with the parameters of the operation. It must contains among others
1806 nsInstanceId: _id of the nsr to perform the operation
1807 operation: it can be: instantiate, terminate, action, TODO: update, heal
1808 :param kwargs: used to override the indata descriptor
1809 :param headers: http request headers
1810 :return: id of the nslcmops
1811 """
1812
1813 def check_if_nsr_is_not_slice_member(session, nsr_id):
1814 nsis = None
1815 db_filter = self._get_project_filter(session)
1816 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1817 nsis = self.db.get_one(
1818 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
1819 )
1820 if nsis:
1821 raise EngineException(
1822 "The NS instance {} cannot be terminated because is used by the slice {}".format(
1823 nsr_id, nsis["_id"]
1824 ),
1825 http_code=HTTPStatus.CONFLICT,
1826 )
1827
1828 try:
1829 # Override descriptor with query string kwargs
1830 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
1831 operation = indata["lcmOperationType"]
1832 nsInstanceId = indata["nsInstanceId"]
1833
1834 validate_input(indata, self.operation_schema[operation])
1835 # get ns from nsr_id
1836 _filter = BaseTopic._get_project_filter(session)
1837 _filter["_id"] = nsInstanceId
1838 nsr = self.db.get_one("nsrs", _filter)
1839
1840 # initial checking
1841 if operation == "terminate" and slice_object is False:
1842 check_if_nsr_is_not_slice_member(session, nsr["_id"])
1843 if (
1844 not nsr["_admin"].get("nsState")
1845 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
1846 ):
1847 if operation == "terminate" and indata.get("autoremove"):
1848 # NSR must be deleted
1849 return (
1850 None,
1851 None,
1852 ) # a none in this case is used to indicate not instantiated. It can be removed
1853 if operation != "instantiate":
1854 raise EngineException(
1855 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1856 nsInstanceId, operation
1857 ),
1858 HTTPStatus.CONFLICT,
1859 )
1860 else:
1861 if operation == "instantiate" and not session["force"]:
1862 raise EngineException(
1863 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1864 nsInstanceId, operation
1865 ),
1866 HTTPStatus.CONFLICT,
1867 )
1868 self._check_ns_operation(session, nsr, operation, indata)
1869
1870 if operation == "instantiate":
1871 self._update_vnfrs(session, rollback, nsr, indata)
1872
1873 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
1874 _id = nslcmop_desc["_id"]
1875 self.format_on_new(
1876 nslcmop_desc, session["project_id"], make_public=session["public"]
1877 )
1878 if indata.get("placement-engine"):
1879 # Save valid vim accounts in lcm operation descriptor
1880 nslcmop_desc["operationParams"][
1881 "validVimAccounts"
1882 ] = self._get_enabled_vims(session)
1883 self.db.create("nslcmops", nslcmop_desc)
1884 rollback.append({"topic": "nslcmops", "_id": _id})
1885 if not slice_object:
1886 self.msg.write("ns", operation, nslcmop_desc)
1887 return _id, None
1888 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
1889 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1890 # except DbException as e:
1891 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1892
1893 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1894 raise EngineException(
1895 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1896 )
1897
1898 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1899 raise EngineException(
1900 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1901 )
1902
1903
1904 class NsiTopic(BaseTopic):
1905 topic = "nsis"
1906 topic_msg = "nsi"
1907 quota_name = "slice_instances"
1908
1909 def __init__(self, db, fs, msg, auth):
1910 BaseTopic.__init__(self, db, fs, msg, auth)
1911 self.nsrTopic = NsrTopic(db, fs, msg, auth)
1912
1913 @staticmethod
1914 def _format_ns_request(ns_request):
1915 formated_request = copy(ns_request)
1916 # TODO: Add request params
1917 return formated_request
1918
1919 @staticmethod
1920 def _format_addional_params(slice_request):
1921 """
1922 Get and format user additional params for NS or VNF
1923 :param slice_request: User instantiation additional parameters
1924 :return: a formatted copy of additional params or None if not supplied
1925 """
1926 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1927 if additional_params:
1928 for k, v in additional_params.items():
1929 if not isinstance(k, str):
1930 raise EngineException(
1931 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
1932 k
1933 )
1934 )
1935 if "." in k or "$" in k:
1936 raise EngineException(
1937 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
1938 k
1939 )
1940 )
1941 if isinstance(v, (dict, tuple, list)):
1942 additional_params[k] = "!!yaml " + safe_dump(v)
1943 return additional_params
1944
1945 def _check_descriptor_dependencies(self, session, descriptor):
1946 """
1947 Check that the dependent descriptors exist on a new descriptor or edition
1948 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1949 :param descriptor: descriptor to be inserted or edit
1950 :return: None or raises exception
1951 """
1952 if not descriptor.get("nst-ref"):
1953 return
1954 nstd_id = descriptor["nst-ref"]
1955 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
1956 raise EngineException(
1957 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
1958 nstd_id
1959 ),
1960 http_code=HTTPStatus.CONFLICT,
1961 )
1962
1963 def check_conflict_on_del(self, session, _id, db_content):
1964 """
1965 Check that NSI is not instantiated
1966 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1967 :param _id: nsi internal id
1968 :param db_content: The database content of the _id
1969 :return: None or raises EngineException with the conflict
1970 """
1971 if session["force"]:
1972 return
1973 nsi = db_content
1974 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1975 raise EngineException(
1976 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1977 "Launch 'terminate' operation first; or force deletion".format(_id),
1978 http_code=HTTPStatus.CONFLICT,
1979 )
1980
1981 def delete_extra(self, session, _id, db_content, not_send_msg=None):
1982 """
1983 Deletes associated nsilcmops from database. Deletes associated filesystem.
1984 Set usageState of nst
1985 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1986 :param _id: server internal id
1987 :param db_content: The database content of the descriptor
1988 :param not_send_msg: To not send message (False) or store content (list) instead
1989 :return: None if ok or raises EngineException with the problem
1990 """
1991
1992 # Deleting the nsrs belonging to nsir
1993 nsir = db_content
1994 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1995 nsr_id = nsrs_detailed_item["nsrId"]
1996 if nsrs_detailed_item.get("shared"):
1997 _filter = {
1998 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1999 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2000 "_id.ne": nsir["_id"],
2001 }
2002 nsi = self.db.get_one(
2003 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2004 )
2005 if nsi: # last one using nsr
2006 continue
2007 try:
2008 self.nsrTopic.delete(
2009 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2010 )
2011 except (DbException, EngineException) as e:
2012 if e.http_code == HTTPStatus.NOT_FOUND:
2013 pass
2014 else:
2015 raise
2016
2017 # delete related nsilcmops database entries
2018 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
2019
2020 # Check and set used NST usage state
2021 nsir_admin = nsir.get("_admin")
2022 if nsir_admin and nsir_admin.get("nst-id"):
2023 # check if used by another NSI
2024 nsis_list = self.db.get_one(
2025 "nsis",
2026 {"nst-id": nsir_admin["nst-id"]},
2027 fail_on_empty=False,
2028 fail_on_more=False,
2029 )
2030 if not nsis_list:
2031 self.db.set_one(
2032 "nsts",
2033 {"_id": nsir_admin["nst-id"]},
2034 {"_admin.usageState": "NOT_IN_USE"},
2035 )
2036
2037 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
2038 """
2039 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2040 :param rollback: list to append the created items at database in case a rollback must be done
2041 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2042 :param indata: params to be used for the nsir
2043 :param kwargs: used to override the indata descriptor
2044 :param headers: http request headers
2045 :return: the _id of nsi descriptor created at database
2046 """
2047
2048 try:
2049 step = "checking quotas"
2050 self.check_quota(session)
2051
2052 step = ""
2053 slice_request = self._remove_envelop(indata)
2054 # Override descriptor with query string kwargs
2055 self._update_input_with_kwargs(slice_request, kwargs)
2056 slice_request = self._validate_input_new(slice_request, session["force"])
2057
2058 # look for nstd
2059 step = "getting nstd id='{}' from database".format(
2060 slice_request.get("nstId")
2061 )
2062 _filter = self._get_project_filter(session)
2063 _filter["_id"] = slice_request["nstId"]
2064 nstd = self.db.get_one("nsts", _filter)
2065 # check NST is not disabled
2066 step = "checking NST operationalState"
2067 if nstd["_admin"]["operationalState"] == "DISABLED":
2068 raise EngineException(
2069 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2070 "instance".format(slice_request["nstId"]),
2071 http_code=HTTPStatus.CONFLICT,
2072 )
2073 del _filter["_id"]
2074
2075 # check NSD is not disabled
2076 step = "checking operationalState"
2077 if nstd["_admin"]["operationalState"] == "DISABLED":
2078 raise EngineException(
2079 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2080 "a network slice".format(slice_request["nstId"]),
2081 http_code=HTTPStatus.CONFLICT,
2082 )
2083
2084 nstd.pop("_admin", None)
2085 nstd_id = nstd.pop("_id", None)
2086 nsi_id = str(uuid4())
2087 step = "filling nsi_descriptor with input data"
2088
2089 # Creating the NSIR
2090 nsi_descriptor = {
2091 "id": nsi_id,
2092 "name": slice_request["nsiName"],
2093 "description": slice_request.get("nsiDescription", ""),
2094 "datacenter": slice_request["vimAccountId"],
2095 "nst-ref": nstd["id"],
2096 "instantiation_parameters": slice_request,
2097 "network-slice-template": nstd,
2098 "nsr-ref-list": [],
2099 "vlr-list": [],
2100 "_id": nsi_id,
2101 "additionalParamsForNsi": self._format_addional_params(slice_request),
2102 }
2103
2104 step = "creating nsi at database"
2105 self.format_on_new(
2106 nsi_descriptor, session["project_id"], make_public=session["public"]
2107 )
2108 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2109 nsi_descriptor["_admin"]["netslice-subnet"] = None
2110 nsi_descriptor["_admin"]["deployed"] = {}
2111 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2112 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2113
2114 # Creating netslice-vld for the RO.
2115 step = "creating netslice-vld at database"
2116
2117 # Building the vlds list to be deployed
2118 # From netslice descriptors, creating the initial list
2119 nsi_vlds = []
2120
2121 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2122 # Getting template Instantiation parameters from NST
2123 nsi_vld = deepcopy(netslice_vlds)
2124 nsi_vld["shared-nsrs-list"] = []
2125 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2126 nsi_vlds.append(nsi_vld)
2127
2128 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
2129 # Creating netslice-subnet_record.
2130 needed_nsds = {}
2131 services = []
2132
2133 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2134 for member_ns in nstd["netslice-subnet"]:
2135 nsd_id = member_ns["nsd-ref"]
2136 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
2137 member_ns["nsd-ref"], member_ns["id"]
2138 )
2139 if nsd_id not in needed_nsds:
2140 # Obtain nsd
2141 _filter["id"] = nsd_id
2142 nsd = self.db.get_one(
2143 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2144 )
2145 del _filter["id"]
2146 nsd.pop("_admin")
2147 needed_nsds[nsd_id] = nsd
2148 else:
2149 nsd = needed_nsds[nsd_id]
2150 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2151 services.append(member_ns)
2152
2153 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2154 member_ns["nsd-ref"], member_ns["id"]
2155 )
2156
2157 # creates Network Services records (NSRs)
2158 step = "creating nsrs at database using NsrTopic.new()"
2159 ns_params = slice_request.get("netslice-subnet")
2160 nsrs_list = []
2161 nsi_netslice_subnet = []
2162 for service in services:
2163 # Check if the netslice-subnet is shared and if it is share if the nss exists
2164 _id_nsr = None
2165 indata_ns = {}
2166 # Is the nss shared and instantiated?
2167 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2168 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2169 "nsd-ref"
2170 ]
2171 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
2172 nsi = self.db.get_one(
2173 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2174 )
2175 if nsi and service.get("is-shared-nss"):
2176 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2177 for nsrs_detailed_item in nsrs_detailed_list:
2178 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
2179 if nsrs_detailed_item["nss-id"] == service["id"]:
2180 _id_nsr = nsrs_detailed_item["nsrId"]
2181 break
2182 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2183 if netslice_subnet["nss-id"] == service["id"]:
2184 indata_ns = netslice_subnet
2185 break
2186 else:
2187 indata_ns = {}
2188 if service.get("instantiation-parameters"):
2189 indata_ns = deepcopy(service["instantiation-parameters"])
2190 # del service["instantiation-parameters"]
2191
2192 indata_ns["nsdId"] = service["_id"]
2193 indata_ns["nsName"] = (
2194 slice_request.get("nsiName") + "." + service["id"]
2195 )
2196 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2197 indata_ns["nsDescription"] = service["description"]
2198 if slice_request.get("ssh_keys"):
2199 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
2200
2201 if ns_params:
2202 for ns_param in ns_params:
2203 if ns_param.get("id") == service["id"]:
2204 copy_ns_param = deepcopy(ns_param)
2205 del copy_ns_param["id"]
2206 indata_ns.update(copy_ns_param)
2207 break
2208
2209 # Creates Nsr objects
2210 _id_nsr, _ = self.nsrTopic.new(
2211 rollback, session, indata_ns, kwargs, headers
2212 )
2213 nsrs_item = {
2214 "nsrId": _id_nsr,
2215 "shared": service.get("is-shared-nss"),
2216 "nsd-id": service["nsd-ref"],
2217 "nss-id": service["id"],
2218 "nslcmop_instantiate": None,
2219 }
2220 indata_ns["nss-id"] = service["id"]
2221 nsrs_list.append(nsrs_item)
2222 nsi_netslice_subnet.append(indata_ns)
2223 nsr_ref = {"nsr-ref": _id_nsr}
2224 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
2225
2226 # Adding the nsrs list to the nsi
2227 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
2228 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2229 self.db.set_one(
2230 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2231 )
2232
2233 # Creating the entry in the database
2234 self.db.create("nsis", nsi_descriptor)
2235 rollback.append({"topic": "nsis", "_id": nsi_id})
2236 return nsi_id, None
2237 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2238 self.logger.exception(
2239 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2240 )
2241 raise EngineException("Error {}: {}".format(step, e))
2242 except ValidationError as e:
2243 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2244
2245 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2246 raise EngineException(
2247 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2248 )
2249
2250
2251 class NsiLcmOpTopic(BaseTopic):
2252 topic = "nsilcmops"
2253 topic_msg = "nsi"
2254 operation_schema = { # mapping between operation and jsonschema to validate
2255 "instantiate": nsi_instantiate,
2256 "terminate": None,
2257 }
2258
2259 def __init__(self, db, fs, msg, auth):
2260 BaseTopic.__init__(self, db, fs, msg, auth)
2261 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
2262
2263 def _check_nsi_operation(self, session, nsir, operation, indata):
2264 """
2265 Check that user has enter right parameters for the operation
2266 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2267 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2268 :param indata: descriptor with the parameters of the operation
2269 :return: None
2270 """
2271 nsds = {}
2272 nstd = nsir["network-slice-template"]
2273
2274 def check_valid_netslice_subnet_id(nstId):
2275 # TODO change to vnfR (??)
2276 for netslice_subnet in nstd["netslice-subnet"]:
2277 if nstId == netslice_subnet["id"]:
2278 nsd_id = netslice_subnet["nsd-ref"]
2279 if nsd_id not in nsds:
2280 _filter = self._get_project_filter(session)
2281 _filter["id"] = nsd_id
2282 nsds[nsd_id] = self.db.get_one("nsds", _filter)
2283 return nsds[nsd_id]
2284 else:
2285 raise EngineException(
2286 "Invalid parameter nstId='{}' is not one of the "
2287 "nst:netslice-subnet".format(nstId)
2288 )
2289
2290 if operation == "instantiate":
2291 # check the existance of netslice-subnet items
2292 for in_nst in get_iterable(indata.get("netslice-subnet")):
2293 check_valid_netslice_subnet_id(in_nst["id"])
2294
2295 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2296 now = time()
2297 _id = str(uuid4())
2298 nsilcmop = {
2299 "id": _id,
2300 "_id": _id,
2301 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2302 "statusEnteredTime": now,
2303 "netsliceInstanceId": netsliceInstanceId,
2304 "lcmOperationType": operation,
2305 "startTime": now,
2306 "isAutomaticInvocation": False,
2307 "operationParams": params,
2308 "isCancelPending": False,
2309 "links": {
2310 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
2311 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2312 + netsliceInstanceId,
2313 },
2314 }
2315 return nsilcmop
2316
2317 def add_shared_nsr_2vld(self, nsir, nsr_item):
2318 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2319 if nst_sb_item.get("is-shared-nss"):
2320 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2321 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2322 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
2323 for admin_vld_nss_cp_ref_item in admin_vld_item[
2324 "nss-connection-point-ref"
2325 ]:
2326 if (
2327 admin_subnet_item["nss-id"]
2328 == admin_vld_nss_cp_ref_item["nss-ref"]
2329 ):
2330 if (
2331 not nsr_item["nsrId"]
2332 in admin_vld_item["shared-nsrs-list"]
2333 ):
2334 admin_vld_item["shared-nsrs-list"].append(
2335 nsr_item["nsrId"]
2336 )
2337 break
2338 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2339 self.db.set_one(
2340 "nsis",
2341 {"_id": nsir["_id"]},
2342 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2343 )
2344
2345 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
2346 """
2347 Performs a new operation over a ns
2348 :param rollback: list to append created items at database in case a rollback must to be done
2349 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2350 :param indata: descriptor with the parameters of the operation. It must contains among others
2351 netsliceInstanceId: _id of the nsir to perform the operation
2352 operation: it can be: instantiate, terminate, action, TODO: update, heal
2353 :param kwargs: used to override the indata descriptor
2354 :param headers: http request headers
2355 :return: id of the nslcmops
2356 """
2357 try:
2358 # Override descriptor with query string kwargs
2359 self._update_input_with_kwargs(indata, kwargs)
2360 operation = indata["lcmOperationType"]
2361 netsliceInstanceId = indata["netsliceInstanceId"]
2362 validate_input(indata, self.operation_schema[operation])
2363
2364 # get nsi from netsliceInstanceId
2365 _filter = self._get_project_filter(session)
2366 _filter["_id"] = netsliceInstanceId
2367 nsir = self.db.get_one("nsis", _filter)
2368 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
2369 del _filter["_id"]
2370
2371 # initial checking
2372 if (
2373 not nsir["_admin"].get("nsiState")
2374 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2375 ):
2376 if operation == "terminate" and indata.get("autoremove"):
2377 # NSIR must be deleted
2378 return (
2379 None,
2380 None,
2381 ) # a none in this case is used to indicate not instantiated. It can be removed
2382 if operation != "instantiate":
2383 raise EngineException(
2384 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2385 netsliceInstanceId, operation
2386 ),
2387 HTTPStatus.CONFLICT,
2388 )
2389 else:
2390 if operation == "instantiate" and not session["force"]:
2391 raise EngineException(
2392 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2393 netsliceInstanceId, operation
2394 ),
2395 HTTPStatus.CONFLICT,
2396 )
2397
2398 # Creating all the NS_operation (nslcmop)
2399 # Get service list from db
2400 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2401 nslcmops = []
2402 # nslcmops_item = None
2403 for index, nsr_item in enumerate(nsrs_list):
2404 nsr_id = nsr_item["nsrId"]
2405 if nsr_item.get("shared"):
2406 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2407 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2408 _filter[
2409 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2410 ] = None
2411 _filter["_id.ne"] = netsliceInstanceId
2412 nsi = self.db.get_one(
2413 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2414 )
2415 if operation == "terminate":
2416 _update = {
2417 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2418 index
2419 ): None
2420 }
2421 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2422 if (
2423 nsi
2424 ): # other nsi is using this nsr and it needs this nsr instantiated
2425 continue # do not create nsilcmop
2426 else: # instantiate
2427 # looks the first nsi fulfilling the conditions but not being the current NSIR
2428 if nsi:
2429 nsi_nsr_item = next(
2430 n
2431 for n in nsi["_admin"]["nsrs-detailed-list"]
2432 if n["nsrId"] == nsr_id
2433 and n["shared"]
2434 and n["nslcmop_instantiate"]
2435 )
2436 self.add_shared_nsr_2vld(nsir, nsr_item)
2437 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
2438 _update = {
2439 "_admin.nsrs-detailed-list.{}".format(
2440 index
2441 ): nsi_nsr_item
2442 }
2443 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2444 # continue to not create nslcmop since nsrs is shared and nsrs was created
2445 continue
2446 else:
2447 self.add_shared_nsr_2vld(nsir, nsr_item)
2448
2449 # create operation
2450 try:
2451 indata_ns = {
2452 "lcmOperationType": operation,
2453 "nsInstanceId": nsr_id,
2454 # Including netslice_id in the ns instantiate Operation
2455 "netsliceInstanceId": netsliceInstanceId,
2456 }
2457 if operation == "instantiate":
2458 service = self.db.get_one("nsrs", {"_id": nsr_id})
2459 indata_ns.update(service["instantiate_params"])
2460
2461 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2462 # message via kafka bus
2463 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2464 rollback, session, indata_ns, None, headers, slice_object=True
2465 )
2466 nslcmops.append(nslcmop)
2467 if operation == "instantiate":
2468 _update = {
2469 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2470 index
2471 ): nslcmop
2472 }
2473 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2474 except (DbException, EngineException) as e:
2475 if e.http_code == HTTPStatus.NOT_FOUND:
2476 self.logger.info(
2477 logging_prefix
2478 + "skipping NS={} because not found".format(nsr_id)
2479 )
2480 pass
2481 else:
2482 raise
2483
2484 # Creates nsilcmop
2485 indata["nslcmops_ids"] = nslcmops
2486 self._check_nsi_operation(session, nsir, operation, indata)
2487
2488 nsilcmop_desc = self._create_nsilcmop(
2489 session, netsliceInstanceId, operation, indata
2490 )
2491 self.format_on_new(
2492 nsilcmop_desc, session["project_id"], make_public=session["public"]
2493 )
2494 _id = self.db.create("nsilcmops", nsilcmop_desc)
2495 rollback.append({"topic": "nsilcmops", "_id": _id})
2496 self.msg.write("nsi", operation, nsilcmop_desc)
2497 return _id, None
2498 except ValidationError as e:
2499 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2500
2501 def delete(self, session, _id, dry_run=False, not_send_msg=None):
2502 raise EngineException(
2503 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2504 )
2505
2506 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2507 raise EngineException(
2508 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2509 )