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