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