Code Coverage

Cobertura Coverage Report > osm_nbi >

instance_topics.py

Trend

File Coverage summary

NameClassesLinesConditionals
instance_topics.py
100%
1/1
49%
658/1344
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
instance_topics.py
49%
658/1344
N/A

Source

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