Code Coverage

Cobertura Coverage Report > osm_nbi >

instance_topics.py

Trend

File Coverage summary

NameClassesLinesConditionals
instance_topics.py
100%
1/1
51%
652/1289
100%
0/0

Coverage Breakdown by Class

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