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