Code Coverage

Cobertura Coverage Report > osm_nbi >

instance_topics.py

Trend

Classes100%
 
Lines48%
   
Conditionals100%
 

File Coverage summary

NameClassesLinesConditionals
instance_topics.py
100%
1/1
48%
516/1073
100%
0/0

Coverage Breakdown by Class

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