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