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