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