blob: aa3e51cf63ac21721393dd502fb755147bd8c5bd [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# 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
tiernob24258a2018-10-04 18:39:49 +020016# import logging
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +010017import json
tiernob24258a2018-10-04 18:39:49 +020018from uuid import uuid4
19from http import HTTPStatus
20from time import time
tiernocc103432018-10-19 14:10:35 +020021from copy import copy, deepcopy
garciadeblas4568a372021-03-24 09:19:48 +010022from osm_nbi.validation import (
23 validate_input,
24 ValidationError,
25 ns_instantiate,
26 ns_terminate,
27 ns_action,
28 ns_scale,
aticig544a2ae2022-04-05 09:00:17 +030029 ns_update,
garciadeblas0964edf2022-02-11 00:43:44 +010030 ns_heal,
garciadeblas4568a372021-03-24 09:19:48 +010031 nsi_instantiate,
elumalai8e3806c2022-04-28 17:26:24 +053032 ns_migrate,
Gabriel Cuba84a60df2023-10-30 14:01:54 -050033 nslcmop_cancel,
garciadeblas4568a372021-03-24 09:19:48 +010034)
35from osm_nbi.base_topic import (
36 BaseTopic,
37 EngineException,
38 get_iterable,
39 deep_get,
40 increment_ip_mac,
aticig2b5e1232022-08-10 17:30:12 +030041 update_descriptor_usage_state,
garciadeblas4568a372021-03-24 09:19:48 +010042)
tiernobee085c2018-12-12 17:03:04 +000043from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010044from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000045from osm_common.msgbase import MsgException
46from osm_common.fsbase import FsException
garciaale7cbd03c2020-11-27 10:38:35 -030047from osm_nbi import utils
garciadeblas4568a372021-03-24 09:19:48 +010048from re import (
49 match,
50) # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020051
52__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
53
54
55class NsrTopic(BaseTopic):
56 topic = "nsrs"
57 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000058 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000059 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020060
delacruzramo32bab472019-09-13 12:24:22 +020061 def __init__(self, db, fs, msg, auth):
62 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020063
tiernob24258a2018-10-04 18:39:49 +020064 @staticmethod
65 def format_on_new(content, project_id=None, make_public=False):
66 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
67 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000068 return None
tiernob24258a2018-10-04 18:39:49 +020069
tiernob4844ab2019-05-23 08:42:12 +000070 def check_conflict_on_del(self, session, _id, db_content):
71 """
72 Check that NSR is not instantiated
73 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
74 :param _id: nsr internal id
75 :param db_content: The database content of the nsr
76 :return: None or raises EngineException with the conflict
77 """
tierno65ca36d2019-02-12 19:27:52 +010078 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020079 return
tiernob4844ab2019-05-23 08:42:12 +000080 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020081 if nsr["_admin"].get("nsState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +010082 raise EngineException(
83 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
84 "Launch 'terminate' operation first; or force deletion".format(_id),
85 http_code=HTTPStatus.CONFLICT,
86 )
tiernob24258a2018-10-04 18:39:49 +020087
tiernobee3bad2019-12-05 12:26:01 +000088 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +000089 """
90 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
91 Set usageState of pdu, vnfd, nsd
92 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
93 :param _id: server internal id
94 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +000095 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +000096 :return: None if ok or raises EngineException with the problem
97 """
tiernobee085c2018-12-12 17:03:04 +000098 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +020099 self.db.del_list("nslcmops", {"nsInstanceId": _id})
100 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +0000101
tiernob24258a2018-10-04 18:39:49 +0200102 # set all used pdus as free
garciadeblas4568a372021-03-24 09:19:48 +0100103 self.db.set_list(
104 "pdus",
105 {"_admin.usage.nsr_id": _id},
106 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
107 )
tiernob24258a2018-10-04 18:39:49 +0200108
tiernob4844ab2019-05-23 08:42:12 +0000109 # Set NSD usageState
110 nsr = db_content
111 used_nsd_id = nsr.get("nsd-id")
112 if used_nsd_id:
113 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100114 nsrs_list = self.db.get_one(
115 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
116 )
tiernob4844ab2019-05-23 08:42:12 +0000117 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100118 self.db.set_one(
119 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
120 )
tiernob4844ab2019-05-23 08:42:12 +0000121
kayal2001f71c2e82024-06-25 15:26:24 +0530122 # Set NS CONFIG TEMPLATE usageState
123 if nsr.get("instantiate_params", {}).get("nsConfigTemplateId"):
124 nsconfigtemplate_id = nsr.get("instantiate_params", {}).get(
125 "nsConfigTemplateId"
126 )
127 nsconfigtemplate_list = self.db.get_one(
128 "nsrs",
129 {"instantiate_params.nsConfigTemplateId": nsconfigtemplate_id},
130 fail_on_empty=False,
131 fail_on_more=False,
132 )
133 if not nsconfigtemplate_list:
134 self.db.set_one(
135 "ns_config_template",
136 {"_id": nsconfigtemplate_id},
137 {"_admin.usageState": "NOT_IN_USE"},
138 )
139
tiernob4844ab2019-05-23 08:42:12 +0000140 # 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
garciadeblas4568a372021-03-24 09:19:48 +0100145 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 )
tiernob4844ab2019-05-23 08:42:12 +0000151 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100152 self.db.set_one(
153 "vnfds",
154 {"_id": used_vnfd_id},
155 {"_admin.usageState": "NOT_IN_USE"},
156 )
tiernob4844ab2019-05-23 08:42:12 +0000157
tiernof0441ea2020-05-26 15:39:18 +0000158 # 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
tiernobee085c2018-12-12 17:03:04 +0000161 @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
garciadeblas4568a372021-03-24 09:19:48 +0100169 def _format_additional_params(
170 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
171 ):
tiernobee085c2018-12-12 17:03:04 +0000172 """
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100173 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
tiernobee085c2018-12-12 17:03:04 +0000177 :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
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100179 :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
tiernobee085c2018-12-12 17:03:04 +0000181 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000182 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000183 """
184 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000185 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000186 if not member_vnf_index:
187 additional_params = copy(ns_request.get("additionalParamsForNs"))
188 where_ = "additionalParamsForNs"
189 elif ns_request.get("additionalParamsForVnf"):
garciadeblas4568a372021-03-24 09:19:48 +0100190 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 )
tierno714954e2019-11-29 13:43:26 +0000201 if item:
tierno54db2e42020-04-06 15:29:42 +0000202 if not vdu_id and not kdu_name:
203 other_params = item
tierno714954e2019-11-29 13:43:26 +0000204 additional_params = copy(item.get("additionalParams")) or {}
205 if vdu_id and item.get("additionalParamsForVdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100206 item_vdu = next(
207 (
208 x
209 for x in item["additionalParamsForVdu"]
210 if x["vdu_id"] == vdu_id
211 ),
212 None,
213 )
tiernobce98f02020-04-17 11:27:47 +0000214 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000215 if item_vdu and item_vdu.get("additionalParams"):
216 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000217 additional_params = item_vdu["additionalParams"]
218 if kdu_name:
219 additional_params = {}
220 if item.get("additionalParamsForKdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100221 item_kdu = next(
222 (
223 x
224 for x in item["additionalParamsForKdu"]
225 if x["kdu_name"] == kdu_name
226 ),
227 None,
228 )
tiernobce98f02020-04-17 11:27:47 +0000229 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000230 if item_kdu and item_kdu.get("additionalParams"):
garciadeblas4568a372021-03-24 09:19:48 +0100231 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
232 kdu_name
233 )
tiernob091dc12019-12-02 15:53:25 +0000234 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000235
tiernobee085c2018-12-12 17:03:04 +0000236 if additional_params:
237 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000238 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
garciadeblas4568a372021-03-24 09:19:48 +0100239 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 )
delacruzramo36ffe552019-05-03 14:52:37 +0200246 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000247 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +0100248 raise EngineException(
249 "Invalid param at {}:{}. Only string keys are allowed".format(
250 where_, k
251 )
252 )
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100253 if "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +0100254 raise EngineException(
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100255 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
garciadeblas4568a372021-03-24 09:19:48 +0100256 where_, k
257 )
258 )
tiernobee085c2018-12-12 17:03:04 +0000259 if isinstance(v, (dict, tuple, list)):
260 additional_params[k] = "!!yaml " + safe_dump(v)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100261 if kdu_name:
262 additional_params = json.dumps(additional_params)
tiernobee085c2018-12-12 17:03:04 +0000263
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100264 # 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
tiernobee085c2018-12-12 17:03:04 +0000267 if descriptor:
bravof41a52052021-02-17 18:08:01 -0300268 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:
garciaale7cbd03c2020-11-27 10:38:35 -0300272 initial_primitives = []
garciadeblas4568a372021-03-24 09:19:48 +0100273 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", []):
garciadeblasf2af4a12023-01-24 16:56:54 +0100281 # Verify the target object (VNF|NS|VDU|KDU) where we need to populate
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100282 # 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)
bravof41a52052021-02-17 18:08:01 -0300288 else:
garciadeblas4568a372021-03-24 09:19:48 +0100289 initial_primitives = deep_get(
290 descriptor, ("ns-configuration", "initial-config-primitive")
291 )
tiernobee085c2018-12-12 17:03:04 +0000292
bravof41a52052021-02-17 18:08:01 -0300293 for initial_primitive in get_iterable(initial_primitives):
294 for param in get_iterable(initial_primitive.get("parameter")):
garciadeblas4568a372021-03-24 09:19:48 +0100295 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>",
garciadeblasf2af4a12023-01-24 16:56:54 +0100302 "<OSM>",
garciadeblas4568a372021-03-24 09:19:48 +0100303 ):
bravof41a52052021-02-17 18:08:01 -0300304 continue
garciadeblas4568a372021-03-24 09:19:48 +0100305 if (
306 not additional_params
307 or param["value"][1:-1] not in additional_params
308 ):
309 raise EngineException(
310 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
311 "initial-config-primitive[name={}] not supplied".format(
312 param["value"],
313 descriptor["id"],
314 initial_primitive["name"],
315 )
316 )
tierno714954e2019-11-29 13:43:26 +0000317
tierno54db2e42020-04-06 15:29:42 +0000318 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000319
tierno65ca36d2019-02-12 19:27:52 +0100320 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200321 """
322 Creates a new nsr into database. It also creates needed vnfrs
323 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100324 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200325 :param indata: params to be used for the nsr
326 :param kwargs: used to override the indata descriptor
327 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000328 :return: the _id of nsr descriptor created at database. Or an exception of type
329 EngineException, ValidationError, DbException, FsException, MsgException.
330 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200331 """
garciadeblasf2af4a12023-01-24 16:56:54 +0100332 step = "checking quotas" # first step must be defined outside try
tiernob24258a2018-10-04 18:39:49 +0200333 try:
delacruzramo32bab472019-09-13 12:24:22 +0200334 self.check_quota(session)
335
tierno99d4b172019-07-02 09:28:40 +0000336 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200337 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200338 self._update_input_with_kwargs(ns_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -0300339 ns_request = self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200340
tiernob24258a2018-10-04 18:39:49 +0200341 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale7cbd03c2020-11-27 10:38:35 -0300342 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
343 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200344
kayal2001f71c2e82024-06-25 15:26:24 +0530345 # Uploading the instantiation parameters to ns_request from ns config template
346 if ns_request.get("nsConfigTemplateId"):
347 step = "getting ns_config_template is='{}' from database".format(
348 ns_request.get("nsConfigTemplateId")
349 )
350 ns_config_template_db = self._get_nsConfigTemplate_from_db(
351 ns_request.get("nsConfigTemplateId"), session
352 )
353 ns_config_params = ns_config_template_db.get("config")
354 for key, value in ns_config_params.items():
355 if key == "vnf":
356 ns_request["vnf"] = ns_config_params.get("vnf")
357 elif key == "additionalParamsForVnf":
358 ns_request["additionalParamsForVnf"] = ns_config_params.get(
359 "additionalParamsForVnf"
360 )
361 elif key == "additionalParamsForNs":
362 ns_request["additionalParamsForNs"] = ns_config_params.get(
363 "additionalParamsForNs"
364 )
365 elif key == "vld":
366 ns_request["vld"] = ns_config_params.get("vld")
367 step = "checking ns_config_templateOperationalState"
368 self._check_ns_config_template_operational_state(
369 ns_config_template_db, ns_request
370 )
371
372 step = "Updating NSCONFIG TEMPLATE usageState"
373 update_descriptor_usage_state(
374 ns_config_template_db, "ns_config_template", self.db
375 )
376
kayal2001b16cf252024-11-28 10:47:32 +0530377 elif ns_request.get("vnf"):
378 vnf_data = ns_request.get("vnf")
379 for vnf in vnf_data:
garciadeblas5e8a4182025-06-24 15:36:38 +0200380 for vdu in vnf.get("vdu", []):
kayal2001b16cf252024-11-28 10:47:32 +0530381 if vdu.get("vim-flavor-name") and vdu.get("vim-flavor-id"):
382 raise EngineException(
383 "Instantiation parameters vim-flavor-name and vim-flavor-id are mutually exclusive"
384 )
385
Frank Bryden3c64ab62020-07-21 14:25:32 +0000386 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300387 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000388
tiernob24258a2018-10-04 18:39:49 +0200389 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300390 nsr_id = str(uuid4())
garciadeblas4568a372021-03-24 09:19:48 +0100391 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
392 nsd, ns_request, nsr_id, session
393 )
tierno54db2e42020-04-06 15:29:42 +0000394
garciaale7cbd03c2020-11-27 10:38:35 -0300395 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200396 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300397 # TODO: Change for multiple df support
K Sai Kiranbb006022021-05-20 11:09:49 +0530398 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
garciaale7cbd03c2020-11-27 10:38:35 -0300399 for vnfp in vnf_profiles:
400 vnfd_id = vnfp.get("vnfd-id")
401 vnf_index = vnfp.get("id")
garciadeblas4568a372021-03-24 09:19:48 +0100402 step = (
403 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
404 vnfd_id, vnf_index
405 )
406 )
tiernob24258a2018-10-04 18:39:49 +0200407 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300408 vnfd = self._get_vnfd_from_db(vnfd_id, session)
beierlmcee2ebf2022-03-29 17:42:48 -0400409 if "revision" in vnfd["_admin"]:
410 vnfd["revision"] = vnfd["_admin"]["revision"]
411 vnfd.pop("_admin")
tiernob24258a2018-10-04 18:39:49 +0200412 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000413 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200414 else:
415 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100416
garciadeblas4568a372021-03-24 09:19:48 +0100417 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
418 vnfd_id, vnf_index
419 )
420 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
421 nsd,
422 vnfd,
423 vnfd_id,
424 vnf_index,
425 nsr_descriptor,
426 ns_request,
427 ns_k8s_namespace,
428 )
tierno36ec8602018-11-02 17:27:11 +0100429
garciadeblas4568a372021-03-24 09:19:48 +0100430 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
431 vnfd_id, vnf_index
432 )
garciaale7cbd03c2020-11-27 10:38:35 -0300433 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
434 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
aticig2b5e1232022-08-10 17:30:12 +0300435 step = "Updating VNFD usageState"
436 update_descriptor_usage_state(vnfd, "vnfds", self.db)
tiernob24258a2018-10-04 18:39:49 +0200437
438 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300439 self._add_nsr_to_db(nsr_descriptor, rollback, session)
aticig2b5e1232022-08-10 17:30:12 +0300440 step = "Updating NSD usageState"
441 update_descriptor_usage_state(nsd, "nsds", self.db)
tiernobee085c2018-12-12 17:03:04 +0000442
443 step = "creating nsr temporal folder"
444 self.fs.mkdir(nsr_id)
445
tiernobdebce92019-07-01 15:36:49 +0000446 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100447 except (
448 ValidationError,
449 EngineException,
450 DbException,
451 MsgException,
452 FsException,
453 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000454 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200455
garciaale7cbd03c2020-11-27 10:38:35 -0300456 def _get_nsd_from_db(self, nsd_id, session):
457 _filter = self._get_project_filter(session)
458 _filter["_id"] = nsd_id
459 return self.db.get_one("nsds", _filter)
460
kayal2001f71c2e82024-06-25 15:26:24 +0530461 def _get_nsConfigTemplate_from_db(self, nsConfigTemplate_id, session):
462 _filter = self._get_project_filter(session)
463 _filter["_id"] = nsConfigTemplate_id
464 ns_config_template_db = self.db.get_one(
465 "ns_config_template", _filter, fail_on_empty=False
466 )
467 return ns_config_template_db
468
garciaale7cbd03c2020-11-27 10:38:35 -0300469 def _get_vnfd_from_db(self, vnfd_id, session):
470 _filter = self._get_project_filter(session)
471 _filter["id"] = vnfd_id
472 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
garciaale7cbd03c2020-11-27 10:38:35 -0300473 return vnfd
474
475 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100476 self.format_on_new(
477 nsr_descriptor, session["project_id"], make_public=session["public"]
478 )
garciaale7cbd03c2020-11-27 10:38:35 -0300479 self.db.create("nsrs", nsr_descriptor)
480 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
481
482 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100483 self.format_on_new(
484 vnfr_descriptor, session["project_id"], make_public=session["public"]
485 )
garciaale7cbd03c2020-11-27 10:38:35 -0300486 self.db.create("vnfrs", vnfr_descriptor)
487 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
488
489 def _check_nsd_operational_state(self, nsd, ns_request):
490 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100491 raise EngineException(
492 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
493 "a network service".format(ns_request["nsdId"]),
494 http_code=HTTPStatus.CONFLICT,
495 )
garciaale7cbd03c2020-11-27 10:38:35 -0300496
kayal2001f71c2e82024-06-25 15:26:24 +0530497 def _check_ns_config_template_operational_state(
498 self, ns_config_template_db, ns_request
499 ):
500 if ns_config_template_db["_admin"]["operationalState"] == "DISABLED":
501 raise EngineException(
502 "ns_config_template with id '{}' is DISABLED, and thus cannot be used to create "
503 "a network service".format(ns_request["nsConfigTemplateId"]),
504 http_code=HTTPStatus.CONFLICT,
505 )
506
garciaale7cbd03c2020-11-27 10:38:35 -0300507 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100508 additional_params, _ = self._format_additional_params(
509 ns_request, descriptor=nsd
510 )
garciaale7cbd03c2020-11-27 10:38:35 -0300511 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
512 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
513 if ns_request and ns_request.get("k8s-namespace"):
514 ns_k8s_namespace = ns_request["k8s-namespace"]
515 if additional_params and additional_params.get("k8s-namespace"):
516 ns_k8s_namespace = additional_params["k8s-namespace"]
517
518 return ns_k8s_namespace
519
vegall18101ea2023-03-06 13:49:21 +0000520 def _add_shared_volumes_to_nsr(
521 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
522 ):
523 svsd = []
524 for vsd in vnfd.get("virtual-storage-desc", ()):
525 if vsd.get("vdu-storage-requirements"):
526 if (
527 vsd.get("vdu-storage-requirements")[0].get("key") == "multiattach"
528 and vsd.get("vdu-storage-requirements")[0].get("value") == "True"
529 ):
vegallf976a3a2023-06-02 21:25:32 +0000530 # Avoid setting the volume name multiple times
531 if not match(f"shared-.*-{vnfd['id']}", vsd["id"]):
vegall18101ea2023-03-06 13:49:21 +0000532 vsd["id"] = f"shared-{vsd['id']}-{vnfd['id']}"
533 svsd.append(vsd)
534 if svsd:
535 nsr_descriptor["shared-volumes"] = svsd
536
garciadeblasf2af4a12023-01-24 16:56:54 +0100537 def _add_flavor_to_nsr(
538 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
539 ):
elumalai6c5ea6b2022-04-25 22:27:59 +0530540 flavor_data = {}
541 guest_epa = {}
542 # Find this vdu compute and storage descriptors
543 vdu_virtual_compute = {}
544 vdu_virtual_storage = {}
545 for vcd in vnfd.get("virtual-compute-desc", ()):
546 if vcd.get("id") == vdu.get("virtual-compute-desc"):
547 vdu_virtual_compute = vcd
548 for vsd in vnfd.get("virtual-storage-desc", ()):
549 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
550 vdu_virtual_storage = vsd
551 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblasf2af4a12023-01-24 16:56:54 +0100552 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
elumalai6c5ea6b2022-04-25 22:27:59 +0530553 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
554 "num-virtual-cpu"
555 ]
556 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
557 flavor_data["memory-mb"] = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100558 float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
elumalai6c5ea6b2022-04-25 22:27:59 +0530559 )
560 if vdu_virtual_storage.get("size-of-storage"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100561 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530562 # Get this vdu EPA info for guest_epa
563 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100564 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530565 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
566 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
567 if vcpu_pinning.get("thread-policy"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100568 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530569 if vcpu_pinning.get("policy"):
570 cpu_policy = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100571 "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
elumalai6c5ea6b2022-04-25 22:27:59 +0530572 )
573 guest_epa["cpu-pinning-policy"] = cpu_policy
574 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100575 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
576 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
577 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"][
578 "mempage-size"
elumalai6c5ea6b2022-04-25 22:27:59 +0530579 ]
garciadeblasf2af4a12023-01-24 16:56:54 +0100580 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
581 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"][
582 "numa-node-policy"
583 ]
elumalai6c5ea6b2022-04-25 22:27:59 +0530584 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100585 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530586
587 if guest_epa:
588 flavor_data["guest-epa"] = guest_epa
589
elumalai99078a92022-07-05 17:53:59 +0530590 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +0100591 flavor_data["name"] = (
592 vdu["id"][:56] + "-" + member_vnf_index + "-" + str(revision) + "-flv"
593 )
elumalai6c5ea6b2022-04-25 22:27:59 +0530594 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
595 nsr_descriptor["flavor"].append(flavor_data)
596
bravofe76b8822021-02-26 16:57:52 -0300597 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300598 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100599 additional_params, _ = self._format_additional_params(
600 ns_request, descriptor=nsd
601 )
garciaale7cbd03c2020-11-27 10:38:35 -0300602
603 nsr_descriptor = {
604 "name": ns_request["nsName"],
605 "name-ref": ns_request["nsName"],
606 "short-name": ns_request["nsName"],
607 "admin-status": "ENABLED",
608 "nsState": "NOT_INSTANTIATED",
609 "currentOperation": "IDLE",
610 "currentOperationID": None,
611 "errorDescription": None,
612 "errorDetail": None,
613 "deploymentStatus": None,
614 "configurationStatus": None,
615 "vcaStatus": None,
616 "nsd": {k: v for k, v in nsd.items()},
617 "datacenter": ns_request["vimAccountId"],
618 "resource-orchestrator": "osmopenmano",
619 "description": ns_request.get("nsDescription", ""),
620 "constituent-vnfr-ref": [],
621 "operational-status": "init", # typedef ns-operational-
622 "config-status": "init", # typedef config-states
623 "detailed-status": "scheduled",
624 "orchestration-progress": {},
625 "create-time": now,
626 "nsd-name-ref": nsd["name"],
627 "operational-events": [], # "id", "timestamp", "description", "event",
628 "nsd-ref": nsd["id"],
629 "nsd-id": nsd["_id"],
630 "vnfd-id": [],
631 "instantiate_params": self._format_ns_request(ns_request),
632 "additionalParamsForNs": additional_params,
633 "ns-instance-config-ref": nsr_id,
634 "id": nsr_id,
635 "_id": nsr_id,
636 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
637 "flavor": [],
638 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100639 "affinity-or-anti-affinity-group": [],
vegall18101ea2023-03-06 13:49:21 +0000640 "shared-volumes": [],
selvi.j828f3f22023-05-16 05:43:48 +0000641 "vnffgd": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300642 }
beierlmbc5a5242022-05-17 21:25:29 -0400643 if "revision" in nsd["_admin"]:
644 nsr_descriptor["revision"] = nsd["_admin"]["revision"]
645
garciaale7cbd03c2020-11-27 10:38:35 -0300646 ns_request["nsr_id"] = nsr_id
647 if ns_request and ns_request.get("config-units"):
648 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300649 # Create vld
650 if nsd.get("virtual-link-desc"):
651 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
652 # Fill each vld with vnfd-connection-point-ref data
653 # TODO: Change for multiple df support
654 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
655 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
656 for vnf_profile in vnf_profiles:
657 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
658 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100659 all_vld_connection_point_data[
660 vlc.get("virtual-link-profile-id")
661 ].append(
662 {
663 "member-vnf-index-ref": cpd.get(
664 "constituent-base-element-id"
665 ),
666 "vnfd-connection-point-ref": cpd.get(
667 "constituent-cpd-id"
668 ),
669 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
670 }
671 )
garciaale7cbd03c2020-11-27 10:38:35 -0300672
bravofe76b8822021-02-26 16:57:52 -0300673 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400674 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300675
676 for vdu in vnfd.get("vdu", ()):
elumalai99078a92022-07-05 17:53:59 +0530677 member_vnf_index = vnf_profile.get("id")
678 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor, member_vnf_index)
vegall18101ea2023-03-06 13:49:21 +0000679 self._add_shared_volumes_to_nsr(
680 vdu, vnfd, nsr_descriptor, member_vnf_index
681 )
garciaale7cbd03c2020-11-27 10:38:35 -0300682 sw_image_id = vdu.get("sw-image-desc")
683 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000684 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
685 self._add_image_to_nsr(nsr_descriptor, image_data)
686
687 # also add alternative images to the list of images
688 for alt_image in vdu.get("alternative-sw-image-desc", ()):
689 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
690 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300691
Alexis Romero03fb5842022-03-11 15:53:40 +0100692 # Add Affinity or Anti-affinity group information to NSR
693 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200694 affinity_group_prefix_name = "{}-{}".format(
695 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
696 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100697
698 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200699 affinity_group_data = {}
700 for affinity_group in vdu_profile.get(
701 "affinity-or-anti-affinity-group", ()
702 ):
703 affinity_group_data = (
704 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
705 vnfd, affinity_group["id"]
706 )
707 )
708 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
709 self._add_affinity_or_anti_affinity_group_to_nsr(
710 nsr_descriptor,
711 affinity_group_data,
712 affinity_group_prefix_name,
713 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100714
garciaale7cbd03c2020-11-27 10:38:35 -0300715 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100716 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
717 vld.get("id"), []
718 )
garciaale7cbd03c2020-11-27 10:38:35 -0300719 vld["name"] = vld["id"]
720 nsr_descriptor["vld"] = nsr_vld
selvi.j828f3f22023-05-16 05:43:48 +0000721 if nsd.get("vnffgd"):
722 vnffgd = nsd.get("vnffgd")
723 for vnffg in vnffgd:
724 info = {}
725 for k, v in vnffg.items():
726 if k == "id":
727 info.update({k: v})
728 if k == "nfpd":
729 info.update({k: v})
730 nsr_descriptor["vnffgd"].append(info)
731
garciaale7cbd03c2020-11-27 10:38:35 -0300732 return nsr_descriptor
733
Alexis Romeroee31f532022-04-26 19:10:21 +0200734 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
735 self, vnfd, affinity_group_id
736 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100737 """
738 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
739 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200740 affinity_group = utils.find_in_list(
741 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
742 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100743 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200744 affinity_group_data = {}
745 if affinity_group:
746 if affinity_group.get("id"):
747 affinity_group_data["ag-id"] = affinity_group["id"]
748 if affinity_group.get("type"):
749 affinity_group_data["type"] = affinity_group["type"]
750 if affinity_group.get("scope"):
751 affinity_group_data["scope"] = affinity_group["scope"]
752 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100753
Alexis Romeroee31f532022-04-26 19:10:21 +0200754 def _add_affinity_or_anti_affinity_group_to_nsr(
755 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
756 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100757 """
758 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
759 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200760 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100761 (
762 f
763 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200764 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100765 ),
766 None,
767 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200768 if not affinity_group:
769 affinity_group_data["id"] = str(
770 len(nsr_descriptor["affinity-or-anti-affinity-group"])
771 )
772 affinity_group_data["name"] = "{}-{}".format(
773 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
774 )
775 nsr_descriptor["affinity-or-anti-affinity-group"].append(
776 affinity_group_data
777 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100778
lloretgalleg28c13b62021-02-08 11:48:48 +0000779 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100780 sw_image_desc = utils.find_in_list(
781 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
782 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000783 image_data = {}
784 if sw_image_desc.get("image"):
785 image_data["image"] = sw_image_desc["image"]
786 if sw_image_desc.get("checksum"):
787 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
788 if sw_image_desc.get("vim-type"):
789 image_data["vim-type"] = sw_image_desc["vim-type"]
790 return image_data
791
792 def _add_image_to_nsr(self, nsr_descriptor, image_data):
793 """
794 Adds image to nsr checking first it is not already added
795 """
garciadeblas4568a372021-03-24 09:19:48 +0100796 img = next(
797 (
798 f
799 for f in nsr_descriptor["image"]
800 if all(f.get(k) == image_data[k] for k in image_data)
801 ),
802 None,
803 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000804 if not img:
805 image_data["id"] = str(len(nsr_descriptor["image"]))
806 nsr_descriptor["image"].append(image_data)
807
garciadeblas4568a372021-03-24 09:19:48 +0100808 def _create_vnfr_descriptor_from_vnfd(
809 self,
810 nsd,
811 vnfd,
812 vnfd_id,
813 vnf_index,
814 nsr_descriptor,
815 ns_request,
816 ns_k8s_namespace,
elumalai99078a92022-07-05 17:53:59 +0530817 revision=None,
garciadeblas4568a372021-03-24 09:19:48 +0100818 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300819 vnfr_id = str(uuid4())
820 nsr_id = nsr_descriptor["id"]
821 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100822 additional_params, vnf_params = self._format_additional_params(
823 ns_request, vnf_index, descriptor=vnfd
824 )
garciaale7cbd03c2020-11-27 10:38:35 -0300825
826 vnfr_descriptor = {
827 "id": vnfr_id,
828 "_id": vnfr_id,
829 "nsr-id-ref": nsr_id,
830 "member-vnf-index-ref": vnf_index,
831 "additionalParamsForVnf": additional_params,
832 "created-time": now,
833 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
834 "vnfd-ref": vnfd_id,
835 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
836 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200837 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300838 "vdur": [],
839 "connection-point": [],
840 "ip-address": None, # mgmt-interface filled by LCM
841 }
beierlmcee2ebf2022-03-29 17:42:48 -0400842
843 # Revision backwards compatility. Only specify the revision in the record if
844 # the original VNFD has a revision.
845 if "revision" in vnfd:
846 vnfr_descriptor["revision"] = vnfd["revision"]
847
garciaale7cbd03c2020-11-27 10:38:35 -0300848 vnf_k8s_namespace = ns_k8s_namespace
849 if vnf_params:
850 if vnf_params.get("k8s-namespace"):
851 vnf_k8s_namespace = vnf_params["k8s-namespace"]
852 if vnf_params.get("config-units"):
853 vnfr_descriptor["config-units"] = vnf_params["config-units"]
854
855 # Create vld
856 if vnfd.get("int-virtual-link-desc"):
857 vnfr_descriptor["vld"] = []
858 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
859 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
860
861 for cp in vnfd.get("ext-cpd", ()):
862 vnf_cp = {
863 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100864 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
865 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300866 "id": cp.get("id"),
867 # "ip-address", "mac-address" # filled by LCM
868 # vim-id # TODO it would be nice having a vim port id
869 }
870 vnfr_descriptor["connection-point"].append(vnf_cp)
871
872 # Create k8s-cluster information
873 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
874 if vnfd.get("k8s-cluster"):
875 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
876 all_k8s_cluster_nets_cpds = {}
877 for cpd in get_iterable(vnfd.get("ext-cpd")):
878 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100879 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
880 "id"
881 )
garciaale7cbd03c2020-11-27 10:38:35 -0300882 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
883 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100884 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
885 net.get("id")
886 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300887
888 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300889 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100890 additional_params, kdu_params = self._format_additional_params(
891 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
892 )
garciaale7cbd03c2020-11-27 10:38:35 -0300893 kdu_k8s_namespace = vnf_k8s_namespace
894 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
895 if kdu_params and kdu_params.get("k8s-namespace"):
896 kdu_k8s_namespace = kdu_params["k8s-namespace"]
897
romeromonserbfebfc02021-05-28 10:51:35 +0200898 kdu_deployment_name = ""
899 if kdu_params and kdu_params.get("kdu-deployment-name"):
900 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
901
garciaale7cbd03c2020-11-27 10:38:35 -0300902 kdur = {
903 "additionalParams": additional_params,
904 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200905 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000906 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300907 # TODO "name": "" Name of the VDU in the VIM
908 "ip-address": None, # mgmt-interface filled by LCM
909 "k8s-cluster": {},
910 }
911 if kdu_params and kdu_params.get("config-units"):
912 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000913 if kdu.get("helm-version"):
914 kdur["helm-version"] = kdu["helm-version"]
915 for k8s_type in ("helm-chart", "juju-bundle"):
916 if kdu.get(k8s_type):
917 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300918 if not vnfr_descriptor.get("kdur"):
919 vnfr_descriptor["kdur"] = []
920 vnfr_descriptor["kdur"].append(kdur)
921
922 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300923
garciaale7cbd03c2020-11-27 10:38:35 -0300924 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300925 vdu_mgmt_cp = []
926 try:
garciadeblas4568a372021-03-24 09:19:48 +0100927 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
928 "operate-vnf-op-config"
929 ]["day1-2"]
930 vdu_config = utils.find_in_list(
931 configs, lambda config: config["id"] == vdu["id"]
932 )
bravoff3c39552021-02-24 17:22:24 -0300933 except Exception:
934 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400935
936 try:
937 vdu_instantiation_level = utils.find_in_list(
938 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100939 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400940 )
941 except Exception:
942 vdu_instantiation_level = None
943
bravoff3c39552021-02-24 17:22:24 -0300944 if vdu_config:
945 external_connection_ee = utils.filter_in_list(
946 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100947 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300948 )
949 for ee in external_connection_ee:
950 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
951
garciaale7cbd03c2020-11-27 10:38:35 -0300952 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100953 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
954 )
bravof65e22e52021-11-10 17:58:58 -0300955
956 try:
957 vdu_virtual_storage_descriptors = utils.filter_in_list(
958 vnfd.get("virtual-storage-desc", []),
garciadeblasf2af4a12023-01-24 16:56:54 +0100959 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"],
bravof65e22e52021-11-10 17:58:58 -0300960 )
961 except Exception:
962 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300963 vdur = {
964 "vdu-id-ref": vdu["id"],
965 # TODO "name": "" Name of the VDU in the VIM
966 "ip-address": None, # mgmt-interface filled by LCM
967 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
968 "internal-connection-point": [],
969 "interfaces": [],
970 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100971 "vdu-name": vdu["name"],
garciadeblasf2af4a12023-01-24 16:56:54 +0100972 "virtual-storages": vdu_virtual_storage_descriptors,
garciaale7cbd03c2020-11-27 10:38:35 -0300973 }
974 if vdu_params and vdu_params.get("config-units"):
975 vdur["config-units"] = vdu_params["config-units"]
976 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100977 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
978 "boot-data-drive"
979 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300980 if vdu.get("pdu-type"):
981 vdur["pdu-type"] = vdu["pdu-type"]
982 vdur["name"] = vdu["pdu-type"]
983 # TODO volumes: name, volume-id
984 for icp in vdu.get("int-cpd", ()):
985 vdu_icp = {
986 "id": icp["id"],
987 "connection-point-id": icp["id"],
988 "name": icp.get("id"),
989 }
bravof35766442021-02-04 14:58:04 -0300990
garciaale7cbd03c2020-11-27 10:38:35 -0300991 vdur["internal-connection-point"].append(vdu_icp)
992
993 for iface in icp.get("virtual-network-interface-requirement", ()):
aticigc9c03392022-06-16 01:39:44 +0300994 # Name, mac-address and interface position is taken from VNFD
995 # and included into VNFR. By this way RO can process this information
996 # while creating the VDU.
Gulsum Atici9af2a472023-03-28 17:50:48 +0300997 iface_fields = ("name", "mac-address", "position", "ip-address")
garciadeblas4568a372021-03-24 09:19:48 +0100998 vdu_iface = {
999 x: iface[x] for x in iface_fields if iface.get(x) is not None
1000 }
garciaale7cbd03c2020-11-27 10:38:35 -03001001
1002 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +01001003 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +01001004 vdu_iface["port-security-enabled"] = icp[
1005 "port-security-enabled"
1006 ]
sousaedu003844e2021-03-02 00:19:15 +01001007
1008 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +01001009 vdu_iface["port-security-disable-strategy"] = icp[
1010 "port-security-disable-strategy"
1011 ]
sousaedu003844e2021-03-02 00:19:15 +01001012
garciaale7cbd03c2020-11-27 10:38:35 -03001013 for ext_cp in vnfd.get("ext-cpd", ()):
1014 if not ext_cp.get("int-cpd"):
1015 continue
1016 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
1017 continue
1018 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +01001019 vdu_iface["external-connection-point-ref"] = ext_cp.get(
1020 "id"
1021 )
sousaedu003844e2021-03-02 00:19:15 +01001022
1023 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +01001024 vdu_iface["port-security-enabled"] = ext_cp[
1025 "port-security-enabled"
1026 ]
sousaedu003844e2021-03-02 00:19:15 +01001027
1028 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +01001029 vdu_iface["port-security-disable-strategy"] = ext_cp[
1030 "port-security-disable-strategy"
1031 ]
sousaedu003844e2021-03-02 00:19:15 +01001032
garciaale7cbd03c2020-11-27 10:38:35 -03001033 break
1034
garciadeblas4568a372021-03-24 09:19:48 +01001035 if (
1036 vnfd_mgmt_cp
1037 and vdu_iface.get("external-connection-point-ref")
1038 == vnfd_mgmt_cp
1039 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001040 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -03001041 vdu_iface["mgmt-interface"] = True
1042
1043 for ecp in vdu_mgmt_cp:
1044 if vdu_iface.get("external-connection-point-ref") == ecp:
1045 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001046
1047 if iface.get("virtual-interface"):
1048 vdu_iface.update(deepcopy(iface["virtual-interface"]))
1049
1050 # look for network where this interface is connected
1051 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
1052 if iface_ext_cp:
1053 # TODO: Change for multiple df support
1054 for df in get_iterable(nsd.get("df")):
1055 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +01001056 for vlc_index, vlc in enumerate(
1057 get_iterable(
1058 vnf_profile.get("virtual-link-connectivity")
1059 )
1060 ):
1061 for cpd in get_iterable(
1062 vlc.get("constituent-cpd-id")
1063 ):
1064 if (
1065 cpd.get("constituent-cpd-id")
1066 == iface_ext_cp
Pedro Escaleira4606e4a2023-05-31 14:32:17 +01001067 ) and vnf_profile.get("id") == vnf_index:
garciadeblas4568a372021-03-24 09:19:48 +01001068 vdu_iface["ns-vld-id"] = vlc.get(
1069 "virtual-link-profile-id"
1070 )
garciadeblas61c95912021-02-12 11:23:50 +00001071 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +01001072 if vdu_iface.get("type") in (
1073 "SR-IOV",
1074 "PCI-PASSTHROUGH",
1075 ):
1076 nsr_descriptor["vld"][vlc_index][
1077 "pci-interfaces"
1078 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001079 break
1080 elif vdu_iface.get("internal-connection-point-ref"):
1081 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +00001082 # TODO: store fixed IP address in the record (if it exists in the ICP)
1083 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
1084 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +01001085 ivld_index = utils.find_index_in_list(
1086 vnfd.get("int-virtual-link-desc", ()),
1087 lambda ivld: ivld["id"]
1088 == icp.get("int-virtual-link-desc"),
1089 )
garciadeblas61c95912021-02-12 11:23:50 +00001090 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001091
1092 vdur["interfaces"].append(vdu_iface)
1093
1094 if vdu.get("sw-image-desc"):
1095 sw_image = utils.find_in_list(
1096 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001097 lambda image: image["id"] == vdu.get("sw-image-desc"),
1098 )
garciaale7cbd03c2020-11-27 10:38:35 -03001099 nsr_sw_image_data = utils.find_in_list(
1100 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001101 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -03001102 )
1103 vdur["ns-image-id"] = nsr_sw_image_data["id"]
1104
lloretgalleg28c13b62021-02-08 11:48:48 +00001105 if vdu.get("alternative-sw-image-desc"):
1106 alt_image_ids = []
1107 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1108 sw_image = utils.find_in_list(
1109 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001110 lambda image: image["id"] == alt_image_id,
1111 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001112 nsr_sw_image_data = utils.find_in_list(
1113 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001114 lambda nsr_image: (
1115 nsr_image.get("image") == sw_image.get("image")
1116 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001117 )
1118 alt_image_ids.append(nsr_sw_image_data["id"])
1119 vdur["alt-image-ids"] = alt_image_ids
1120
elumalai99078a92022-07-05 17:53:59 +05301121 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +01001122 flavor_data_name = (
1123 vdu["id"][:56] + "-" + vnf_index + "-" + str(revision) + "-flv"
1124 )
garciaale7cbd03c2020-11-27 10:38:35 -03001125 nsr_flavor_desc = utils.find_in_list(
1126 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001127 lambda flavor: flavor["name"] == flavor_data_name,
1128 )
garciaale7cbd03c2020-11-27 10:38:35 -03001129
1130 if nsr_flavor_desc:
1131 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1132
vegall18101ea2023-03-06 13:49:21 +00001133 # Adding Shared Volume information to vdur
1134 if vdur.get("virtual-storages"):
1135 nsr_sv = []
1136 for vsd in vdur["virtual-storages"]:
1137 if vsd.get("vdu-storage-requirements"):
1138 if (
1139 vsd["vdu-storage-requirements"][0].get("key")
1140 == "multiattach"
1141 and vsd["vdu-storage-requirements"][0].get("value")
1142 == "True"
1143 ):
1144 nsr_sv.append(vsd["id"])
1145 if nsr_sv:
1146 vdur["shared-volumes-id"] = nsr_sv
1147
Alexis Romero03fb5842022-03-11 15:53:40 +01001148 # Adding Affinity groups information to vdur
1149 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001150 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001151 vnfd.get("df")[0]["vdu-profile"],
1152 lambda a_vdu: a_vdu["id"] == vdu["id"],
1153 )
1154 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001155 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001156
Alexis Romeroee31f532022-04-26 19:10:21 +02001157 if vdu_profile_affinity_group:
1158 affinity_group_ids = []
1159 for affinity_group in vdu_profile_affinity_group.get(
1160 "affinity-or-anti-affinity-group", ()
1161 ):
1162 vdu_affinity_group = utils.find_in_list(
1163 vdu_profile_affinity_group.get(
1164 "affinity-or-anti-affinity-group", ()
1165 ),
1166 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001167 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001168 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001169 nsr_descriptor["affinity-or-anti-affinity-group"],
1170 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001171 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1172 and nsr_ag.get("member-vnf-index")
1173 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001174 ),
1175 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001176 # Update Affinity Group VIM name if VDU instantiation parameter is present
1177 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1178 vnf_params_affinity_group = utils.find_in_list(
1179 vnf_params["affinity-or-anti-affinity-group"],
1180 lambda vnfp_ag: (
1181 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1182 ),
1183 )
1184 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1185 nsr_affinity_group[
1186 "vim-affinity-group-id"
1187 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1188 affinity_group_ids.append(nsr_affinity_group["id"])
1189 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001190
bravof4ca51522021-04-22 10:03:02 -04001191 if vdu_instantiation_level:
1192 count = vdu_instantiation_level.get("number-of-instances")
1193 else:
1194 count = 1
1195
garciaale7cbd03c2020-11-27 10:38:35 -03001196 for index in range(0, count):
1197 vdur = deepcopy(vdur)
1198 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001199 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001200 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001201 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001202 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1203
1204 vdur["_id"] = str(uuid4())
1205 vdur["id"] = vdur["_id"]
1206 vdur["count-index"] = index
1207 vnfr_descriptor["vdur"].append(vdur)
garciaale7cbd03c2020-11-27 10:38:35 -03001208 return vnfr_descriptor
1209
K Sai Kiran57589552021-01-27 21:38:34 +05301210 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1211 """
1212 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1213 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1214 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1215 :param ns_instance_content: ns instance content
1216 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1217 :return: None
1218 """
garciadeblasf2af4a12023-01-24 16:56:54 +01001219 time_now, time_delta = (
1220 time(),
1221 time() - ns_instance_content["_admin"]["modified"],
1222 )
1223 force_refresh = (
1224 isinstance(filter_q, dict) and filter_q.get("vcaStatusRefresh") == "true"
1225 )
K Sai Kiran57589552021-01-27 21:38:34 +05301226 threshold_reached = time_delta > 120
1227 if force_refresh or threshold_reached:
1228 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1229 ns_instance_content["_admin"]["modified"] = time_now
1230 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1231 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
garciadeblasf2af4a12023-01-24 16:56:54 +01001232 self.format_on_new(
1233 nslcmop_desc, session["project_id"], make_public=session["public"]
1234 )
K Sai Kiran57589552021-01-27 21:38:34 +05301235 nslcmop_desc["_admin"].pop("nsState")
1236 self.msg.write("ns", operation, nslcmop_desc)
1237 return
1238
1239 def show(self, session, _id, filter_q=None, api_req=False):
1240 """
1241 Get complete information on an ns instance.
1242 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1243 :param _id: string, ns instance id
1244 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1245 :param api_req: True if this call is serving an external API request. False if serving internal request.
1246 :return: dictionary, raise exception if not found.
1247 """
1248 ns_instance_content = super().show(session, _id, api_req)
1249 self.vca_status_refresh(session, ns_instance_content, filter_q)
1250 return ns_instance_content
1251
tierno65ca36d2019-02-12 19:27:52 +01001252 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001253 raise EngineException(
1254 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1255 )
tiernob24258a2018-10-04 18:39:49 +02001256
1257
1258class VnfrTopic(BaseTopic):
1259 topic = "vnfrs"
1260 topic_msg = None
1261
delacruzramo32bab472019-09-13 12:24:22 +02001262 def __init__(self, db, fs, msg, auth):
1263 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001264
tiernobee3bad2019-12-05 12:26:01 +00001265 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001266 raise EngineException(
1267 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1268 )
tiernob24258a2018-10-04 18:39:49 +02001269
tierno65ca36d2019-02-12 19:27:52 +01001270 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001271 raise EngineException(
1272 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1273 )
tiernob24258a2018-10-04 18:39:49 +02001274
tierno65ca36d2019-02-12 19:27:52 +01001275 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001276 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001277 raise EngineException(
1278 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1279 )
tiernob24258a2018-10-04 18:39:49 +02001280
1281
1282class NsLcmOpTopic(BaseTopic):
1283 topic = "nslcmops"
1284 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001285 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001286 "instantiate": ns_instantiate,
1287 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001288 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001289 "scale": ns_scale,
garciadeblas0964edf2022-02-11 00:43:44 +01001290 "heal": ns_heal,
tierno1c38f2f2020-03-24 11:51:39 +00001291 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301292 "migrate": ns_migrate,
Gabriel Cuba84a60df2023-10-30 14:01:54 -05001293 "cancel": nslcmop_cancel,
tiernob24258a2018-10-04 18:39:49 +02001294 }
1295
delacruzramo32bab472019-09-13 12:24:22 +02001296 def __init__(self, db, fs, msg, auth):
1297 BaseTopic.__init__(self, db, fs, msg, auth)
elumalai6c5ea6b2022-04-25 22:27:59 +05301298 self.nsrtopic = NsrTopic(db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001299
tiernob24258a2018-10-04 18:39:49 +02001300 def _check_ns_operation(self, session, nsr, operation, indata):
1301 """
1302 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001303 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
garciadeblas0964edf2022-02-11 00:43:44 +01001304 :param operation: it can be: instantiate, terminate, action, update, heal
tiernob24258a2018-10-04 18:39:49 +02001305 :param indata: descriptor with the parameters of the operation
1306 :return: None
1307 """
garciaale7cbd03c2020-11-27 10:38:35 -03001308 if operation == "action":
1309 self._check_action_ns_operation(indata, nsr)
1310 elif operation == "scale":
1311 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001312 elif operation == "update":
1313 self._check_update_ns_operation(indata, nsr)
garciadeblas0964edf2022-02-11 00:43:44 +01001314 elif operation == "heal":
1315 self._check_heal_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001316 elif operation == "instantiate":
1317 self._check_instantiate_ns_operation(indata, nsr, session)
1318
1319 def _check_action_ns_operation(self, indata, nsr):
1320 nsd = nsr["nsd"]
1321 # check vnf_member_index
1322 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001323 indata["member_vnf_index"] = indata.pop(
1324 "vnf_member_index"
1325 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001326 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001327 vnfd = self._get_vnfd_from_vnf_member_index(
1328 indata["member_vnf_index"], nsr["_id"]
1329 )
bravof41a52052021-02-17 18:08:01 -03001330 try:
garciadeblas4568a372021-03-24 09:19:48 +01001331 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1332 "operate-vnf-op-config"
1333 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001334 except Exception:
1335 configs = []
1336
garciaale7cbd03c2020-11-27 10:38:35 -03001337 if indata.get("vdu_id"):
1338 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001339 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001340 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001341 )
garciaale7cbd03c2020-11-27 10:38:35 -03001342 elif indata.get("kdu_name"):
1343 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001344 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001345 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001346 )
garciaale7cbd03c2020-11-27 10:38:35 -03001347 else:
bravof41a52052021-02-17 18:08:01 -03001348 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001349 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001350 )
1351 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001352 descriptor_configuration = descriptor_configuration.get(
1353 "config-primitive"
1354 )
garciaale7cbd03c2020-11-27 10:38:35 -03001355 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001356 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1357 "config-primitive"
1358 )
garciaale7cbd03c2020-11-27 10:38:35 -03001359
1360 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001361 if indata.get("kdu_name") and indata["primitive"] in (
1362 "upgrade",
1363 "rollback",
1364 "status",
1365 "inspect",
1366 "readme",
1367 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001368 # TODO should be checked that rollback only can contains revsision_numbe????
1369 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001370 raise EngineException(
1371 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1372 indata["primitive"]
1373 )
1374 )
garciaale7cbd03c2020-11-27 10:38:35 -03001375 return
1376 # if not, check primitive
1377 for config_primitive in get_iterable(descriptor_configuration):
1378 if indata["primitive"] == config_primitive["name"]:
1379 # check needed primitive_params are provided
1380 if indata.get("primitive_params"):
1381 in_primitive_params_copy = copy(indata["primitive_params"])
1382 else:
1383 in_primitive_params_copy = {}
1384 for paramd in get_iterable(config_primitive.get("parameter")):
1385 if paramd["name"] in in_primitive_params_copy:
1386 del in_primitive_params_copy[paramd["name"]]
1387 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001388 raise EngineException(
1389 "Needed parameter {} not provided for primitive '{}'".format(
1390 paramd["name"], indata["primitive"]
1391 )
1392 )
garciaale7cbd03c2020-11-27 10:38:35 -03001393 # check no extra primitive params are provided
1394 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001395 raise EngineException(
1396 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1397 list(in_primitive_params_copy.keys()), indata["primitive"]
1398 )
1399 )
garciaale7cbd03c2020-11-27 10:38:35 -03001400 break
1401 else:
garciadeblas4568a372021-03-24 09:19:48 +01001402 raise EngineException(
1403 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1404 indata["primitive"]
1405 )
1406 )
garciaale7cbd03c2020-11-27 10:38:35 -03001407
aticig544a2ae2022-04-05 09:00:17 +03001408 def _check_update_ns_operation(self, indata, nsr) -> None:
1409 """Validates the ns-update request according to updateType
1410
1411 If updateType is CHANGE_VNFPKG:
1412 - it checks the vnfInstanceId, whether it's available under ns instance
1413 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1414 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301415 If updateType is REMOVE_VNF:
1416 - it checks if the vnfInstanceId is available in the ns instance
1417 - Otherwise exception will be raised.
jegancd7d9f02024-05-16 07:07:27 +00001418 If updateType is OPERATE_VNF
1419 - it checks if the vdu-id is persent in the descriptor or not
1420 - it checks if the changeStateTo is either start, stop or rebuild
1421 If updateType is VERTICAL_SCALE
1422 - it checks if the vdu-id is persent in the descriptor or not
aticig544a2ae2022-04-05 09:00:17 +03001423
1424 Args:
1425 indata: includes updateType such as CHANGE_VNFPKG,
1426 nsr: network service record
1427
1428 Raises:
1429 EngineException:
1430 a meaningful error if given update parameters are not proper such as
1431 "Error in validating ns-update request: <ID> does not match
1432 with the vnfd-id of vnfinstance
1433 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1434
1435 """
1436 try:
1437 if indata["updateType"] == "CHANGE_VNFPKG":
1438 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1439 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1440 ns_instance_id = indata["nsInstanceId"]
1441 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1442
1443 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
aticig544a2ae2022-04-05 09:00:17 +03001444 raise EngineException(
1445 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1446 f"belong to NS {ns_instance_id}",
1447 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1448 )
1449
1450 # Getting vnfrs through the ns_instance_id
1451 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1452 constituent_vnfd_id = next(
1453 (
1454 vnfr["vnfd-id"]
1455 for vnfr in vnfrs
1456 if vnfr["id"] == vnf_instance_id
1457 ),
1458 None,
1459 )
1460
1461 # Check the given vnfd-id belongs to given vnf instance
1462 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
aticig544a2ae2022-04-05 09:00:17 +03001463 raise EngineException(
1464 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1465 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1466 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1467 )
1468
1469 # Validating the ns update timeout
1470 if (
1471 indata.get("timeout_ns_update")
1472 and indata["timeout_ns_update"] < 300
1473 ):
1474 raise EngineException(
1475 "Error in validating ns-update request: {} second is not enough "
1476 "to upgrade the VNF instance: {}".format(
1477 indata["timeout_ns_update"], vnf_instance_id
1478 ),
1479 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1480 )
elumalai6380e7c2022-04-28 00:15:59 +05301481 elif indata["updateType"] == "REMOVE_VNF":
1482 vnf_instance_id = indata["removeVnfInstanceId"]
1483 ns_instance_id = indata["nsInstanceId"]
1484 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1485 raise EngineException(
1486 "Invalid VNF Instance Id. '{}' is not "
1487 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1488 )
jegancd7d9f02024-05-16 07:07:27 +00001489 elif indata["updateType"] == "OPERATE_VNF":
1490 if indata.get("operateVnfData"):
1491 if indata["operateVnfData"]["changeStateTo"] not in (
1492 "start",
1493 "stop",
1494 "rebuild",
Isabel Lloretee15f2e2025-04-25 10:52:04 +02001495 "console",
jegancd7d9f02024-05-16 07:07:27 +00001496 ):
1497 raise EngineException(
Isabel Lloretee15f2e2025-04-25 10:52:04 +02001498 f"The operate type should be either start, stop, console or rebuild not {indata['operateVnfData']['changeStateTo']}",
jegancd7d9f02024-05-16 07:07:27 +00001499 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1500 )
1501 if indata["operateVnfData"].get("additionalParam"):
1502 vdu_id = indata["operateVnfData"]["additionalParam"]["vdu_id"]
1503 vnfinstance_id = indata["operateVnfData"]["vnfInstanceId"]
1504 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1505 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1506 vnfd = self._get_vnfd_from_vnf_member_index(
1507 vnfd_member_vnf_index, nsr["_id"]
1508 )
1509 self._check_valid_vdu(vnfd, vdu_id)
1510 elif indata["updateType"] == "VERTICAL_SCALE":
1511 if indata.get("verticalScaleVnf"):
1512 vdu_id = indata["verticalScaleVnf"]["vduId"]
1513 vnfinstance_id = indata["verticalScaleVnf"]["vnfInstanceId"]
1514 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1515 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1516 vnfd = self._get_vnfd_from_vnf_member_index(
1517 vnfd_member_vnf_index, nsr["_id"]
1518 )
1519 self._check_valid_vdu(vnfd, vdu_id)
aticig544a2ae2022-04-05 09:00:17 +03001520
1521 except (
1522 DbException,
1523 AttributeError,
1524 IndexError,
1525 KeyError,
1526 ValueError,
1527 ) as e:
1528 raise type(e)(
1529 "Ns update request could not be processed with error: {}.".format(e)
1530 )
1531
garciaale7cbd03c2020-11-27 10:38:35 -03001532 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001533 vnfd = self._get_vnfd_from_vnf_member_index(
1534 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1535 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001536 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001537 if (
1538 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1539 == scaling_aspect["id"]
1540 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001541 break
1542 else:
garciadeblas4568a372021-03-24 09:19:48 +01001543 raise EngineException(
1544 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1545 "present at vnfd:scaling-aspect".format(
1546 indata["scaleVnfData"]["scaleByStepData"][
1547 "scaling-group-descriptor"
1548 ]
1549 )
1550 )
garciaale7cbd03c2020-11-27 10:38:35 -03001551
garciadeblas0964edf2022-02-11 00:43:44 +01001552 def _check_heal_ns_operation(self, indata, nsr):
jegan0b273342023-11-13 05:01:53 +00001553 try:
1554 for data in indata.get("healVnfData"):
1555 vnf_id = data.get("vnfInstanceId")
1556 vnf = self.db.get_one("vnfrs", {"_id": vnf_id})
1557 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1558 vnfd = self._get_vnfd_from_vnf_member_index(
1559 vnfd_member_vnf_index, nsr["_id"]
1560 )
1561 if data.get("additionalParams"):
1562 vdu_id = data["additionalParams"].get("vdu")
1563 if vdu_id:
1564 for index in range(len(vdu_id)):
1565 vdu = vdu_id[index].get("vdu-id")
1566 self._check_valid_vdu(vnfd, vdu)
1567 except (DbException, AttributeError, IndexError, KeyError, ValueError) as e:
1568 raise type(e)(
1569 "Ns healing request could not be processed with error: {}.".format(e)
1570 )
garciadeblas0964edf2022-02-11 00:43:44 +01001571
garciaale7cbd03c2020-11-27 10:38:35 -03001572 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001573 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001574 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001575 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001576 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001577 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1578 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1579 for in_vnf in get_iterable(indata.get("vnf")):
1580 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001581 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001582 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001583 else:
garciadeblas4568a372021-03-24 09:19:48 +01001584 vnfd = self._get_vnfd_from_vnf_member_index(
1585 member_vnf_index, nsr["_id"]
1586 )
1587 vnf_member_index_to_vnfd[
1588 member_vnf_index
1589 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001590 self._check_vnf_instantiation_params(in_vnf, vnfd)
1591 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001592 self._check_valid_vim_account(
1593 in_vnf["vimAccountId"], vim_accounts, session
1594 )
tierno260dd6f2019-09-02 10:48:56 +00001595
garciaale7cbd03c2020-11-27 10:38:35 -03001596 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001597 self._check_valid_wim_account(
1598 in_vld.get("wimAccountId"), wim_accounts, session
1599 )
garciaale7cbd03c2020-11-27 10:38:35 -03001600 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1601 if in_vld["name"] == vldd["id"]:
1602 break
tierno9cb7d672019-10-30 12:13:48 +00001603 else:
garciadeblas4568a372021-03-24 09:19:48 +01001604 raise EngineException(
1605 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1606 in_vld["name"]
1607 )
1608 )
tierno9cb7d672019-10-30 12:13:48 +00001609
garciaale7cbd03c2020-11-27 10:38:35 -03001610 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1611 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001612 vnfr = self.db.get_one(
1613 "vnfrs",
1614 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1615 fail_on_empty=False,
1616 )
garciaale7cbd03c2020-11-27 10:38:35 -03001617 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001618 raise EngineException(
1619 "Invalid parameter member_vnf_index='{}' is not one of the "
1620 "nsd:constituent-vnfd".format(member_vnf_index)
1621 )
beierlmcee2ebf2022-03-29 17:42:48 -04001622
garciadeblasf2af4a12023-01-24 16:56:54 +01001623 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
beierlmcee2ebf2022-03-29 17:42:48 -04001624 if "revision" in vnfr:
1625 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
garciadeblasf2af4a12023-01-24 16:56:54 +01001626 vnfd = self.db.get_one(
1627 "vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False
1628 )
beierlmcee2ebf2022-03-29 17:42:48 -04001629 else:
garciadeblasf2af4a12023-01-24 16:56:54 +01001630 vnfd = self.db.get_one(
1631 "vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False
1632 )
beierlmcee2ebf2022-03-29 17:42:48 -04001633
garciaale7cbd03c2020-11-27 10:38:35 -03001634 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001635 raise EngineException(
1636 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1637 vnfr["vnfd-id"]
1638 )
1639 )
garciaale7cbd03c2020-11-27 10:38:35 -03001640 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001641
garciaale7cbd03c2020-11-27 10:38:35 -03001642 def _check_valid_vdu(self, vnfd, vdu_id):
1643 for vdud in get_iterable(vnfd.get("vdu")):
1644 if vdud["id"] == vdu_id:
1645 return vdud
1646 else:
garciadeblas4568a372021-03-24 09:19:48 +01001647 raise EngineException(
1648 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1649 vdu_id
1650 )
1651 )
garciaale7cbd03c2020-11-27 10:38:35 -03001652
1653 def _check_valid_kdu(self, vnfd, kdu_name):
1654 for kdud in get_iterable(vnfd.get("kdu")):
1655 if kdud["name"] == kdu_name:
1656 return kdud
1657 else:
garciadeblas4568a372021-03-24 09:19:48 +01001658 raise EngineException(
1659 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1660 kdu_name
1661 )
1662 )
garciaale7cbd03c2020-11-27 10:38:35 -03001663
1664 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1665 for in_vdu in get_iterable(in_vnf.get("vdu")):
1666 for vdu in get_iterable(vnfd.get("vdu")):
1667 if in_vdu["id"] == vdu["id"]:
1668 for volume in get_iterable(in_vdu.get("volume")):
1669 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
aticigd7753fc2022-05-18 18:55:23 +03001670 if volumed == volume["name"]:
garciaale7cbd03c2020-11-27 10:38:35 -03001671 break
1672 else:
garciadeblas4568a372021-03-24 09:19:48 +01001673 raise EngineException(
1674 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1675 "volume:name='{}' is not present at "
1676 "vnfd:vdu:virtual-storage-desc list".format(
1677 in_vnf["member-vnf-index"],
1678 in_vdu["id"],
1679 volume["id"],
1680 )
1681 )
garciaale7cbd03c2020-11-27 10:38:35 -03001682
1683 vdu_if_names = set()
1684 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001685 for iface in get_iterable(
1686 cpd.get("virtual-network-interface-requirement")
1687 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001688 vdu_if_names.add(iface.get("name"))
1689
aticigd7753fc2022-05-18 18:55:23 +03001690 for in_iface in get_iterable(in_vdu.get("interface")):
garciaale7cbd03c2020-11-27 10:38:35 -03001691 if in_iface["name"] in vdu_if_names:
1692 break
1693 else:
garciadeblas4568a372021-03-24 09:19:48 +01001694 raise EngineException(
1695 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1696 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1697 in_vnf["member-vnf-index"],
1698 in_vdu["id"],
1699 in_iface["name"],
1700 )
1701 )
garciaale7cbd03c2020-11-27 10:38:35 -03001702 break
1703
1704 else:
garciadeblas4568a372021-03-24 09:19:48 +01001705 raise EngineException(
1706 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1707 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1708 )
garciaale7cbd03c2020-11-27 10:38:35 -03001709
garciadeblas4568a372021-03-24 09:19:48 +01001710 vnfd_ivlds_cpds = {
1711 ivld.get("id"): set()
1712 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1713 }
Gulsum Atici9af2a472023-03-28 17:50:48 +03001714 for vdu in vnfd.get("vdu", {}):
1715 for cpd in vdu.get("int-cpd", {}):
garciaale7cbd03c2020-11-27 10:38:35 -03001716 if cpd.get("int-virtual-link-desc"):
1717 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1718
1719 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1720 if in_ivld.get("name") in vnfd_ivlds_cpds:
1721 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1722 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001723 break
tiernob24258a2018-10-04 18:39:49 +02001724 else:
garciadeblas4568a372021-03-24 09:19:48 +01001725 raise EngineException(
1726 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1727 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1728 "vnfd:internal-vld:name/id:internal-connection-point".format(
1729 in_vnf["member-vnf-index"],
1730 in_ivld["name"],
1731 in_icp["id-ref"],
1732 )
1733 )
tiernob24258a2018-10-04 18:39:49 +02001734 else:
garciadeblas4568a372021-03-24 09:19:48 +01001735 raise EngineException(
1736 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1737 " is not present at vnfd '{}'".format(
1738 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1739 )
1740 )
tiernob24258a2018-10-04 18:39:49 +02001741
garciaale7cbd03c2020-11-27 10:38:35 -03001742 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1743 if vim_account in vim_accounts:
1744 return
1745 try:
1746 db_filter = self._get_project_filter(session)
1747 db_filter["_id"] = vim_account
1748 self.db.get_one("vim_accounts", db_filter)
1749 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001750 raise EngineException(
1751 "Invalid vimAccountId='{}' not present for the project".format(
1752 vim_account
1753 )
1754 )
garciaale7cbd03c2020-11-27 10:38:35 -03001755 vim_accounts.append(vim_account)
1756
David Garcia98de2982021-10-13 17:14:01 +02001757 def _get_vim_account(self, vim_id: str, session):
1758 try:
1759 db_filter = self._get_project_filter(session)
1760 db_filter["_id"] = vim_id
1761 return self.db.get_one("vim_accounts", db_filter)
1762 except Exception:
1763 raise EngineException(
garciadeblasf2af4a12023-01-24 16:56:54 +01001764 "Invalid vimAccountId='{}' not present for the project".format(vim_id)
David Garcia98de2982021-10-13 17:14:01 +02001765 )
1766
garciaale7cbd03c2020-11-27 10:38:35 -03001767 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1768 if not isinstance(wim_account, str):
1769 return
1770 if wim_account in wim_accounts:
1771 return
1772 try:
gifrerenom44f5ec12022-03-07 16:57:25 +00001773 db_filter = self._get_project_filter(session)
garciaale7cbd03c2020-11-27 10:38:35 -03001774 db_filter["_id"] = wim_account
1775 self.db.get_one("wim_accounts", db_filter)
1776 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001777 raise EngineException(
1778 "Invalid wimAccountId='{}' not present for the project".format(
1779 wim_account
1780 )
1781 )
garciaale7cbd03c2020-11-27 10:38:35 -03001782 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001783
garciadeblas4568a372021-03-24 09:19:48 +01001784 def _look_for_pdu(
1785 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1786 ):
tiernocc103432018-10-19 14:10:35 +02001787 """
tierno36ec8602018-11-02 17:27:11 +01001788 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1789 (ip_address, ...) information.
1790 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001791 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001792 :param rollback: list with the database modifications to rollback if needed
1793 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1794 :param vim_account: vim_account where this vnfr should be deployed
1795 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1796 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1797 of the changed vnfr is needed
1798
1799 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1800 "vim-network-name": used at VIM
1801 "name": interface name
1802 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1803 "ns-vld-id": NSD vld where this interface is connected.
1804 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
tiernocc103432018-10-19 14:10:35 +02001805 """
tierno36ec8602018-11-02 17:27:11 +01001806
1807 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001808 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1809 if not vdur.get("pdu-type"):
1810 continue
1811 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001812 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001813 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001814 pdu_filter["type"] = pdu_type
1815 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001816 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001817 # TODO feature 1417: "shared": True,
1818
1819 available_pdus = self.db.get_list("pdus", pdu_filter)
1820 for pdu in available_pdus:
1821 # step 1 check if this pdu contains needed interfaces:
1822 match_interfaces = True
1823 for vdur_interface in vdur["interfaces"]:
1824 for pdu_interface in pdu["interfaces"]:
1825 if pdu_interface["name"] == vdur_interface["name"]:
1826 # TODO feature 1417: match per mgmt type
1827 break
1828 else: # no interface found for name
1829 match_interfaces = False
1830 break
1831 if match_interfaces:
1832 break
1833 else:
1834 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001835 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001836 "names".format(
1837 pdu_type,
1838 vim_account,
1839 vnfr["member-vnf-index-ref"],
1840 vdur["vdu-id-ref"],
1841 )
1842 )
tiernocc103432018-10-19 14:10:35 +02001843
1844 # step 2. Update pdu
1845 rollback_pdu = {
1846 "_admin.usageState": pdu["_admin"]["usageState"],
1847 "_admin.usage.vnfr_id": None,
1848 "_admin.usage.nsr_id": None,
1849 "_admin.usage.vdur": None,
1850 }
garciadeblas4568a372021-03-24 09:19:48 +01001851 self.db.set_one(
1852 "pdus",
1853 {"_id": pdu["_id"]},
1854 {
1855 "_admin.usageState": "IN_USE",
1856 "_admin.usage": {
1857 "vnfr_id": vnfr["_id"],
1858 "nsr_id": vnfr["nsr-id-ref"],
1859 "vdur": vdur["vdu-id-ref"],
1860 },
1861 },
1862 )
1863 rollback.append(
1864 {
1865 "topic": "pdus",
1866 "_id": pdu["_id"],
1867 "operation": "set",
1868 "content": rollback_pdu,
1869 }
1870 )
tiernocc103432018-10-19 14:10:35 +02001871
1872 # step 3. Fill vnfr info by filling vdur
1873 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001874 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001875 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1876 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1877 for pdu_interface in pdu["interfaces"]:
1878 if pdu_interface["name"] == vdur_interface["name"]:
1879 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1880 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001881 if k in (
1882 "ip-address",
1883 "mac-address",
1884 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001885 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001886 vnfr_update_rollback[
1887 iface_text + ".{}".format(k)
1888 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001889 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001890 if vdur_interface.get(
1891 "mgmt-interface"
1892 ) or vdur_interface.get("mgmt-vnf"):
1893 vnfr_update_rollback[
1894 vdu_text + ".ip-address"
1895 ] = vdur.get("ip-address")
1896 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1897 "ip-address"
1898 ]
tierno36ec8602018-11-02 17:27:11 +01001899 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001900 vnfr_update_rollback["ip-address"] = vnfr.get(
1901 "ip-address"
1902 )
tierno36ec8602018-11-02 17:27:11 +01001903 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001904 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1905 "ip-address"
1906 ]
1907 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1908 "vim-network-id"
1909 ):
1910 ifaces_forcing_vim_network.append(
1911 {
1912 "name": vdur_interface.get("vnf-vld-id")
1913 or vdur_interface.get("ns-vld-id"),
1914 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1915 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1916 }
1917 )
gcalvino17d5b732018-12-17 16:26:21 +01001918 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001919 ifaces_forcing_vim_network[-1][
1920 "vim-network-id"
1921 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001922 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001923 ifaces_forcing_vim_network[-1][
1924 "vim-network-name"
1925 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001926 break
1927
tierno36ec8602018-11-02 17:27:11 +01001928 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001929
garciadeblas4568a372021-03-24 09:19:48 +01001930 def _look_for_k8scluster(
1931 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1932 ):
tierno9cb7d672019-10-30 12:13:48 +00001933 """
1934 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1935 Fills vnfr.kdur with the selected k8scluster
1936
1937 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1938 :param rollback: list with the database modifications to rollback if needed
1939 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1940 :param vim_account: vim_account where this vnfr should be deployed
1941 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1942 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1943 of the changed vnfr is needed
1944
1945 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1946 "vim-network-name": used at VIM
1947 "name": interface name
1948 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1949 "ns-vld-id": NSD vld where this interface is connected.
1950 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1951 """
1952
1953 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001954 if not vnfr.get("kdur"):
1955 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001956
tiernoc67b0e92019-11-05 12:45:29 +00001957 kdu_filter = self._get_project_filter(session)
1958 kdu_filter["vim_account"] = vim_account
1959 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1960 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1961
1962 k8s_requirements = {} # just for logging
1963 for k8scluster in available_k8sclusters:
1964 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001965 break
tiernoc67b0e92019-11-05 12:45:29 +00001966 # restrict by cni
1967 if vnfr["k8s-cluster"].get("cni"):
1968 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001969 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1970 k8scluster.get("cni", ())
1971 ):
tiernoc67b0e92019-11-05 12:45:29 +00001972 continue
1973 # restrict by version
1974 if vnfr["k8s-cluster"].get("version"):
1975 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1976 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1977 continue
1978 # restrict by number of networks
1979 if vnfr["k8s-cluster"].get("nets"):
1980 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001981 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1982 vnfr["k8s-cluster"]["nets"]
1983 ):
tiernoc67b0e92019-11-05 12:45:29 +00001984 continue
1985 break
1986 else:
garciadeblas4568a372021-03-24 09:19:48 +01001987 raise EngineException(
1988 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1989 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1990 )
1991 )
tierno9cb7d672019-10-30 12:13:48 +00001992
tiernoc67b0e92019-11-05 12:45:29 +00001993 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001994 # step 3. Fill vnfr info by filling kdur
1995 kdu_text = "kdur.{}.".format(kdur_index)
1996 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1997 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1998
tiernoc67b0e92019-11-05 12:45:29 +00001999 # step 4. Check VIM networks that forces the selected k8s_cluster
2000 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
2001 k8scluster_net_list = list(k8scluster.get("nets").keys())
2002 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
2003 # get a network from k8s_cluster nets. If name matches use this, if not use other
2004 if kdur_net["id"] in k8scluster_net_list: # name matches
2005 vim_net = k8scluster["nets"][kdur_net["id"]]
2006 k8scluster_net_list.remove(kdur_net["id"])
2007 else:
2008 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
2009 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01002010 vnfr_update_rollback[
2011 "k8s-cluster.nets.{}.vim_net".format(net_index)
2012 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00002013 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01002014 if vim_net and (
2015 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
2016 ):
2017 ifaces_forcing_vim_network.append(
2018 {
2019 "name": kdur_net.get("vnf-vld-id")
2020 or kdur_net.get("ns-vld-id"),
2021 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
2022 "ns-vld-id": kdur_net.get("ns-vld-id"),
2023 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
2024 }
2025 )
tiernoc67b0e92019-11-05 12:45:29 +00002026 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00002027 return ifaces_forcing_vim_network
2028
Gulsum Aticie395aa42021-11-10 20:59:06 +03002029 def _update_vnfrs_from_nsd(self, nsr):
garciadeblasf2af4a12023-01-24 16:56:54 +01002030 step = "Getting vnf_profiles from nsd" # first step must be defined outside try
Gulsum Aticie395aa42021-11-10 20:59:06 +03002031 try:
2032 nsr_id = nsr["_id"]
2033 nsd = nsr["nsd"]
2034
Gulsum Aticie395aa42021-11-10 20:59:06 +03002035 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
2036 vld_fixed_ip_connection_point_data = {}
2037
2038 step = "Getting ip-address info from vnf_profile if it exists"
2039 for vnfp in vnf_profiles:
2040 # Checking ip-address info from nsd.vnf_profile and storing
2041 for vlc in vnfp.get("virtual-link-connectivity", ()):
2042 for cpd in vlc.get("constituent-cpd-id", ()):
2043 if cpd.get("ip-address"):
2044 step = "Storing ip-address info"
garciadeblasf2af4a12023-01-24 16:56:54 +01002045 vld_fixed_ip_connection_point_data.update(
2046 {
2047 vlc.get("virtual-link-profile-id")
2048 + "."
2049 + cpd.get("constituent-base-element-id"): {
2050 "vnfd-connection-point-ref": cpd.get(
2051 "constituent-cpd-id"
2052 ),
2053 "ip-address": cpd.get("ip-address"),
2054 }
2055 }
2056 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002057
2058 # Inserting ip address to vnfr
2059 if len(vld_fixed_ip_connection_point_data) > 0:
2060 step = "Getting vnfrs"
2061 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2062 for item in vld_fixed_ip_connection_point_data.keys():
2063 step = "Filtering vnfrs"
garciadeblasf2af4a12023-01-24 16:56:54 +01002064 vnfr = next(
2065 filter(
2066 lambda vnfr: vnfr["member-vnf-index-ref"]
2067 == item.split(".")[1],
2068 vnfrs,
2069 ),
2070 None,
2071 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002072 if vnfr:
2073 vnfr_update = {}
2074 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2075 for iface_index, iface in enumerate(vdur["interfaces"]):
2076 step = "Looking for matched interface"
2077 if (
garciadeblasf2af4a12023-01-24 16:56:54 +01002078 iface.get("external-connection-point-ref")
2079 == vld_fixed_ip_connection_point_data[item].get(
2080 "vnfd-connection-point-ref"
2081 )
2082 and iface.get("ns-vld-id") == item.split(".")[0]
Gulsum Aticie395aa42021-11-10 20:59:06 +03002083 ):
2084 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2085 vdur_index, iface_index
2086 )
2087 step = "Storing info in order to update vnfr"
2088 vnfr_update[
2089 vnfr_update_text + ".ip-address"
garciadeblasf2af4a12023-01-24 16:56:54 +01002090 ] = increment_ip_mac(
2091 vld_fixed_ip_connection_point_data[item].get(
2092 "ip-address"
2093 ),
2094 vdur.get("count-index", 0),
2095 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002096 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
2097
2098 step = "updating vnfr at database"
2099 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
2100 except (
garciadeblasf2af4a12023-01-24 16:56:54 +01002101 ValidationError,
2102 EngineException,
2103 DbException,
2104 MsgException,
2105 FsException,
Gulsum Aticie395aa42021-11-10 20:59:06 +03002106 ) as e:
2107 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
2108
tiernocc103432018-10-19 14:10:35 +02002109 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02002110 # get vnfr
2111 nsr_id = nsr["_id"]
2112 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2113
2114 for vnfr in vnfrs:
2115 vnfr_update = {}
2116 vnfr_update_rollback = {}
2117 member_vnf_index = vnfr["member-vnf-index-ref"]
2118 # update vim-account-id
2119
2120 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02002121 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002122 # check instantiate parameters
2123 for vnf_inst_params in get_iterable(indata.get("vnf")):
2124 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
2125 continue
2126 if vnf_inst_params.get("vimAccountId"):
2127 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02002128 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002129
tiernocddb07d2020-10-06 08:28:00 +00002130 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
2131 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
2132 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2133 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
2134 continue
garciadeblas4568a372021-03-24 09:19:48 +01002135 for iface_inst_param in get_iterable(
2136 vdu_inst_param.get("interface")
2137 ):
2138 iface_index, _ = next(
2139 i
2140 for i in enumerate(vdur["interfaces"])
2141 if i[1]["name"] == iface_inst_param["name"]
2142 )
2143 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2144 vdur_index, iface_index
2145 )
tiernocddb07d2020-10-06 08:28:00 +00002146 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002147 vnfr_update[
2148 vnfr_update_text + ".ip-address"
2149 ] = increment_ip_mac(
2150 iface_inst_param.get("ip-address"),
2151 vdur.get("count-index", 0),
2152 )
tierno1bd9d952020-11-13 15:56:51 +00002153 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002154 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002155 vnfr_update[
2156 vnfr_update_text + ".mac-address"
2157 ] = increment_ip_mac(
2158 iface_inst_param.get("mac-address"),
2159 vdur.get("count-index", 0),
2160 )
tierno1bd9d952020-11-13 15:56:51 +00002161 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03002162 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01002163 vnfr_update[
2164 vnfr_update_text + ".floating-ip-required"
2165 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002166 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2167 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01002168 for ivld_inst_param in get_iterable(
2169 vnf_inst_params.get("internal-vld")
2170 ):
2171 for icp_inst_param in get_iterable(
2172 ivld_inst_param.get("internal-connection-point")
2173 ):
tiernocddb07d2020-10-06 08:28:00 +00002174 # look for iface
2175 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2176 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002177 if (
2178 iface.get("internal-connection-point-ref")
2179 == icp_inst_param["id-ref"]
2180 ):
2181 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2182 vdur_index, iface_index
2183 )
tiernocddb07d2020-10-06 08:28:00 +00002184 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002185 vnfr_update[
2186 vnfr_update_text + ".ip-address"
2187 ] = increment_ip_mac(
2188 icp_inst_param.get("ip-address"),
2189 vdur.get("count-index", 0),
2190 )
2191 vnfr_update[
2192 vnfr_update_text + ".fixed-ip"
2193 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002194 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002195 vnfr_update[
2196 vnfr_update_text + ".mac-address"
2197 ] = increment_ip_mac(
2198 icp_inst_param.get("mac-address"),
2199 vdur.get("count-index", 0),
2200 )
2201 vnfr_update[
2202 vnfr_update_text + ".fixed-mac"
2203 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002204 break
2205 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2206 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01002207 for vnfcp_inst_param in get_iterable(
2208 vld_inst_param.get("vnfd-connection-point-ref")
2209 ):
tiernocddb07d2020-10-06 08:28:00 +00002210 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2211 continue
2212 # look for iface
2213 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2214 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002215 if (
2216 iface.get("external-connection-point-ref")
2217 == vnfcp_inst_param["vnfd-connection-point-ref"]
2218 ):
2219 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2220 vdur_index, iface_index
2221 )
tiernocddb07d2020-10-06 08:28:00 +00002222 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002223 vnfr_update[
2224 vnfr_update_text + ".ip-address"
2225 ] = increment_ip_mac(
2226 vnfcp_inst_param.get("ip-address"),
2227 vdur.get("count-index", 0),
2228 )
tierno1bd9d952020-11-13 15:56:51 +00002229 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002230 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002231 vnfr_update[
2232 vnfr_update_text + ".mac-address"
2233 ] = increment_ip_mac(
2234 vnfcp_inst_param.get("mac-address"),
2235 vdur.get("count-index", 0),
2236 )
tierno1bd9d952020-11-13 15:56:51 +00002237 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002238 break
2239
tiernocc103432018-10-19 14:10:35 +02002240 vnfr_update["vim-account-id"] = vim_account
2241 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2242
David Garciaecb41322021-03-31 19:10:46 +02002243 if vca_id:
2244 vnfr_update["vca-id"] = vca_id
2245 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2246
tiernocc103432018-10-19 14:10:35 +02002247 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002248 ifaces_forcing_vim_network = self._look_for_pdu(
2249 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2250 )
tiernocc103432018-10-19 14:10:35 +02002251
tierno9cb7d672019-10-30 12:13:48 +00002252 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002253 ifaces_forcing_vim_network += self._look_for_k8scluster(
2254 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2255 )
tierno9cb7d672019-10-30 12:13:48 +00002256 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002257 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002258 rollback.append(
2259 {
2260 "topic": "vnfrs",
2261 "_id": vnfr["_id"],
2262 "operation": "set",
2263 "content": vnfr_update_rollback,
2264 }
2265 )
tierno36ec8602018-11-02 17:27:11 +01002266
2267 # Update indada in case pdu forces to use a concrete vim-network-name
2268 # TODO check if user has already insert a vim-network-name and raises an error
2269 if not ifaces_forcing_vim_network:
2270 continue
2271 for iface_info in ifaces_forcing_vim_network:
2272 if iface_info.get("ns-vld-id"):
2273 if "vld" not in indata:
2274 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002275 indata["vld"].append(
2276 {
2277 key: iface_info[key]
2278 for key in ("name", "vim-network-name", "vim-network-id")
2279 if iface_info.get(key)
2280 }
2281 )
tierno36ec8602018-11-02 17:27:11 +01002282
2283 elif iface_info.get("vnf-vld-id"):
2284 if "vnf" not in indata:
2285 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002286 indata["vnf"].append(
2287 {
2288 "member-vnf-index": member_vnf_index,
2289 "internal-vld": [
2290 {
2291 key: iface_info[key]
2292 for key in (
2293 "name",
2294 "vim-network-name",
2295 "vim-network-id",
2296 )
2297 if iface_info.get(key)
2298 }
2299 ],
2300 }
2301 )
tierno36ec8602018-11-02 17:27:11 +01002302
2303 @staticmethod
2304 def _create_nslcmop(nsr_id, operation, params):
2305 """
2306 Creates a ns-lcm-opp content to be stored at database.
2307 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002308 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002309 :param params: user parameters for the operation
2310 :return: dictionary following SOL005 format
2311 """
tiernob24258a2018-10-04 18:39:49 +02002312 now = time()
2313 _id = str(uuid4())
2314 nslcmop = {
2315 "id": _id,
2316 "_id": _id,
2317 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002318 "queuePosition": None,
2319 "stage": None,
2320 "errorMessage": None,
2321 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002322 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002323 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002324 "lcmOperationType": operation,
2325 "startTime": now,
2326 "isAutomaticInvocation": False,
2327 "operationParams": params,
2328 "isCancelPending": False,
2329 "links": {
2330 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002331 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002332 },
tiernob24258a2018-10-04 18:39:49 +02002333 }
2334 return nslcmop
2335
magnussonlf318b302020-01-20 18:38:18 +01002336 def _get_enabled_vims(self, session):
2337 """
2338 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2339 :param session: current session with user information
2340 """
2341 db_filter = self._get_project_filter(session)
2342 db_filter["_admin.operationalState"] = "ENABLED"
2343 vims = self.db.get_list("vim_accounts", db_filter)
2344 vimAccounts = []
2345 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002346 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002347 return vimAccounts
2348
garciadeblas4568a372021-03-24 09:19:48 +01002349 def new(
2350 self,
2351 rollback,
2352 session,
2353 indata=None,
2354 kwargs=None,
2355 headers=None,
2356 slice_object=False,
2357 ):
tiernob24258a2018-10-04 18:39:49 +02002358 """
2359 Performs a new operation over a ns
2360 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002361 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002362 :param indata: descriptor with the parameters of the operation. It must contains among others
2363 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002364 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002365 :param kwargs: used to override the indata descriptor
2366 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002367 :return: id of the nslcmops
2368 """
garciadeblas4568a372021-03-24 09:19:48 +01002369
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002370 def check_if_nsr_is_not_slice_member(session, nsr_id):
2371 nsis = None
2372 db_filter = self._get_project_filter(session)
2373 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002374 nsis = self.db.get_one(
2375 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2376 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002377 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002378 raise EngineException(
2379 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2380 nsr_id, nsis["_id"]
2381 ),
2382 http_code=HTTPStatus.CONFLICT,
2383 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002384
tiernob24258a2018-10-04 18:39:49 +02002385 try:
2386 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002387 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002388 operation = indata["lcmOperationType"]
2389 nsInstanceId = indata["nsInstanceId"]
2390
2391 validate_input(indata, self.operation_schema[operation])
2392 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002393 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002394 _filter["_id"] = nsInstanceId
2395 nsr = self.db.get_one("nsrs", _filter)
2396
2397 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002398 if operation == "terminate" and slice_object is False:
2399 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002400 if (
2401 not nsr["_admin"].get("nsState")
2402 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2403 ):
tiernob24258a2018-10-04 18:39:49 +02002404 if operation == "terminate" and indata.get("autoremove"):
2405 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002406 return (
2407 None,
2408 None,
garciadeblasf53612b2024-07-12 14:44:37 +02002409 None,
garciadeblas4568a372021-03-24 09:19:48 +01002410 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002411 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002412 raise EngineException(
2413 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2414 nsInstanceId, operation
2415 ),
2416 HTTPStatus.CONFLICT,
2417 )
tiernob24258a2018-10-04 18:39:49 +02002418 else:
tierno65ca36d2019-02-12 19:27:52 +01002419 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002420 raise EngineException(
2421 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2422 nsInstanceId, operation
2423 ),
2424 HTTPStatus.CONFLICT,
2425 )
tiernob24258a2018-10-04 18:39:49 +02002426 self._check_ns_operation(session, nsr, operation, indata)
garciadeblasf2af4a12023-01-24 16:56:54 +01002427 if indata.get("primitive_params"):
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002428 indata["primitive_params"] = json.dumps(indata["primitive_params"])
garciadeblasf2af4a12023-01-24 16:56:54 +01002429 elif indata.get("additionalParamsForVnf"):
2430 indata["additionalParamsForVnf"] = json.dumps(
2431 indata["additionalParamsForVnf"]
2432 )
tierno36ec8602018-11-02 17:27:11 +01002433
tiernocc103432018-10-19 14:10:35 +02002434 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002435 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002436 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302437 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2438 nsr_update = {}
2439 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2440 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2441 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2442 ns_request = nsr["instantiate_params"]
garciadeblasf2af4a12023-01-24 16:56:54 +01002443 vnfr = self.db.get_one(
2444 "vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]}
2445 )
elumalai8bf978e2022-05-26 15:32:06 +05302446 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2447 vnfr_vnfd_revision = vnfr.get("revision", 1)
2448 if latest_vnfd_revision != vnfr_vnfd_revision:
2449 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
garciadeblasf2af4a12023-01-24 16:56:54 +01002450 old_db_vnfd = self.db.get_one(
2451 "vnfds_revisions", {"_id": old_vnfd_id}
2452 )
elumalai8bf978e2022-05-26 15:32:06 +05302453 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2454 new_sw_version = vnfd.get("software-version", "1.0")
2455 if new_sw_version != old_sw_version:
2456 vnf_index = vnfr["member-vnf-index-ref"]
jegan3b558c72024-11-04 12:20:19 +00002457 for vdu in vnfd.get("vdu", []):
vegall18101ea2023-03-06 13:49:21 +00002458 self.nsrtopic._add_shared_volumes_to_nsr(
2459 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2460 )
garciadeblasf2af4a12023-01-24 16:56:54 +01002461 self.nsrtopic._add_flavor_to_nsr(
2462 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2463 )
elumalai8bf978e2022-05-26 15:32:06 +05302464 sw_image_id = vdu.get("sw-image-desc")
2465 if sw_image_id:
garciadeblasf2af4a12023-01-24 16:56:54 +01002466 image_data = self.nsrtopic._get_image_data_from_vnfd(
2467 vnfd, sw_image_id
2468 )
elumalai8bf978e2022-05-26 15:32:06 +05302469 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2470 for alt_image in vdu.get("alternative-sw-image-desc", ()):
garciadeblasf2af4a12023-01-24 16:56:54 +01002471 image_data = self.nsrtopic._get_image_data_from_vnfd(
2472 vnfd, alt_image
2473 )
elumalai8bf978e2022-05-26 15:32:06 +05302474 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2475 nsr_update["image"] = nsr["image"]
2476 nsr_update["flavor"] = nsr["flavor"]
vegall18101ea2023-03-06 13:49:21 +00002477 nsr_update["shared-volumes"] = nsr["shared-volumes"]
elumalai8bf978e2022-05-26 15:32:06 +05302478 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
garciadeblasf2af4a12023-01-24 16:56:54 +01002479 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(
2480 nsd, ns_request, session
2481 )
2482 vnfr_descriptor = (
2483 self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2484 nsd,
2485 vnfd,
2486 vnfd_id,
2487 vnf_index,
2488 nsr,
2489 ns_request,
2490 ns_k8s_namespace,
2491 latest_vnfd_revision,
2492 )
elumalai8bf978e2022-05-26 15:32:06 +05302493 )
elumalaia3366932023-11-14 15:06:38 +05302494 self._update_vnfrs_from_nsd(nsr)
2495 vnfr_new = self.db.get_one(
2496 "vnfrs",
2497 {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]},
2498 )
2499 fixed_ip_dict = {}
2500 for vdu_record in vnfr_new.get("vdur"):
2501 if vdu_record.get("count-index") == 0:
2502 for interface in vdu_record.get("interfaces"):
2503 if (
2504 interface.get("external-connection-point-ref")
2505 and interface.get("fixed-ip") is True
2506 ):
2507 fixed_ip_dict[
2508 vdu_record.get("vdu-id-ref")
2509 ] = interface.get("ip-address")
2510 for new_vdu in vnfr_descriptor.get("vdur"):
2511 if fixed_ip_dict.get(new_vdu.get("vdu-id-ref")):
2512 for new_interface in new_vdu.get("interfaces"):
2513 if new_interface.get(
2514 "external-connection-point-ref"
2515 ):
2516 new_interface["ip-address"] = fixed_ip_dict.get(
2517 new_vdu.get("vdu-id-ref")
2518 )
2519 new_interface["fixed-ip"] = True
elumalai8bf978e2022-05-26 15:32:06 +05302520 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002521 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002522 _id = nslcmop_desc["_id"]
garciadeblasf53612b2024-07-12 14:44:37 +02002523 nsName = nsr.get("name")
garciadeblas4568a372021-03-24 09:19:48 +01002524 self.format_on_new(
2525 nslcmop_desc, session["project_id"], make_public=session["public"]
2526 )
magnussonlf318b302020-01-20 18:38:18 +01002527 if indata.get("placement-engine"):
2528 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002529 nslcmop_desc["operationParams"][
2530 "validVimAccounts"
2531 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002532 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002533 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002534 if not slice_object:
2535 self.msg.write("ns", operation, nslcmop_desc)
garciadeblasf53612b2024-07-12 14:44:37 +02002536 return _id, nsName, None
tiernobdebce92019-07-01 15:36:49 +00002537 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002538 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2539 # except DbException as e:
2540 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2541
Gabriel Cuba84a60df2023-10-30 14:01:54 -05002542 def cancel(self, rollback, session, indata=None, kwargs=None, headers=None):
2543 validate_input(indata, self.operation_schema["cancel"])
2544 # Override descriptor with query string kwargs
2545 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
2546 nsLcmOpOccId = indata["nsLcmOpOccId"]
2547 cancelMode = indata["cancelMode"]
2548 # get nslcmop from nsLcmOpOccId
2549 _filter = BaseTopic._get_project_filter(session)
2550 _filter["_id"] = nsLcmOpOccId
2551 nslcmop = self.db.get_one("nslcmops", _filter)
2552 # Fail is this is not an ongoing nslcmop
2553 if nslcmop.get("operationState") not in [
2554 "STARTING",
2555 "PROCESSING",
2556 "ROLLING_BACK",
2557 ]:
2558 raise EngineException(
2559 "Operation is not in STARTING, PROCESSING or ROLLING_BACK state",
2560 http_code=HTTPStatus.CONFLICT,
2561 )
2562 nsInstanceId = nslcmop["nsInstanceId"]
2563 update_dict = {
2564 "isCancelPending": True,
2565 "cancelMode": cancelMode,
2566 }
2567 self.db.set_one(
2568 "nslcmops", q_filter=_filter, update_dict=update_dict, fail_on_empty=False
2569 )
2570 data = {
2571 "_id": nsLcmOpOccId,
2572 "nsInstanceId": nsInstanceId,
2573 "cancelMode": cancelMode,
2574 }
2575 self.msg.write("nslcmops", "cancel", data)
2576
tiernobee3bad2019-12-05 12:26:01 +00002577 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002578 raise EngineException(
2579 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2580 )
tiernob24258a2018-10-04 18:39:49 +02002581
tierno65ca36d2019-02-12 19:27:52 +01002582 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002583 raise EngineException(
2584 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2585 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002586
2587
2588class NsiTopic(BaseTopic):
2589 topic = "nsis"
2590 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002591 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002592
delacruzramo32bab472019-09-13 12:24:22 +02002593 def __init__(self, db, fs, msg, auth):
2594 BaseTopic.__init__(self, db, fs, msg, auth)
2595 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002596
Felipe Vicensc37b3842019-01-12 12:24:42 +01002597 @staticmethod
2598 def _format_ns_request(ns_request):
2599 formated_request = copy(ns_request)
2600 # TODO: Add request params
2601 return formated_request
2602
2603 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002604 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002605 """
2606 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002607 :param slice_request: User instantiation additional parameters
2608 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002609 """
tiernofd160572019-01-21 10:41:37 +00002610 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2611 if additional_params:
2612 for k, v in additional_params.items():
2613 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002614 raise EngineException(
2615 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2616 k
2617 )
2618 )
tiernofd160572019-01-21 10:41:37 +00002619 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002620 raise EngineException(
2621 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2622 k
2623 )
2624 )
tiernofd160572019-01-21 10:41:37 +00002625 if isinstance(v, (dict, tuple, list)):
2626 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002627 return additional_params
2628
tiernob4844ab2019-05-23 08:42:12 +00002629 def check_conflict_on_del(self, session, _id, db_content):
2630 """
2631 Check that NSI is not instantiated
2632 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2633 :param _id: nsi internal id
2634 :param db_content: The database content of the _id
2635 :return: None or raises EngineException with the conflict
2636 """
tierno65ca36d2019-02-12 19:27:52 +01002637 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002638 return
tiernob4844ab2019-05-23 08:42:12 +00002639 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002640 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002641 raise EngineException(
2642 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2643 "Launch 'terminate' operation first; or force deletion".format(_id),
2644 http_code=HTTPStatus.CONFLICT,
2645 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002646
tiernobee3bad2019-12-05 12:26:01 +00002647 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002648 """
tiernob4844ab2019-05-23 08:42:12 +00002649 Deletes associated nsilcmops from database. Deletes associated filesystem.
2650 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002651 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002652 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002653 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002654 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002655 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002656 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002657
Felipe Vicens09e65422019-01-22 15:06:46 +01002658 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002659 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002660 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2661 nsr_id = nsrs_detailed_item["nsrId"]
2662 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002663 _filter = {
2664 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2665 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2666 "_id.ne": nsir["_id"],
2667 }
2668 nsi = self.db.get_one(
2669 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2670 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002671 if nsi: # last one using nsr
2672 continue
2673 try:
garciadeblas4568a372021-03-24 09:19:48 +01002674 self.nsrTopic.delete(
2675 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2676 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002677 except (DbException, EngineException) as e:
2678 if e.http_code == HTTPStatus.NOT_FOUND:
2679 pass
2680 else:
2681 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002682
tiernob4844ab2019-05-23 08:42:12 +00002683 # delete related nsilcmops database entries
2684 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002685
tiernob4844ab2019-05-23 08:42:12 +00002686 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002687 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002688 if nsir_admin and nsir_admin.get("nst-id"):
2689 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002690 nsis_list = self.db.get_one(
2691 "nsis",
2692 {"nst-id": nsir_admin["nst-id"]},
2693 fail_on_empty=False,
2694 fail_on_more=False,
2695 )
tiernob4844ab2019-05-23 08:42:12 +00002696 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002697 self.db.set_one(
2698 "nsts",
2699 {"_id": nsir_admin["nst-id"]},
2700 {"_admin.usageState": "NOT_IN_USE"},
2701 )
tiernob4844ab2019-05-23 08:42:12 +00002702
tierno65ca36d2019-02-12 19:27:52 +01002703 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002704 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002705 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002706 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002707 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002708 :param indata: params to be used for the nsir
2709 :param kwargs: used to override the indata descriptor
2710 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002711 :return: the _id of nsi descriptor created at database
2712 """
2713
garciadeblasf2af4a12023-01-24 16:56:54 +01002714 step = "checking quotas" # first step must be defined outside try
Felipe Vicensb57758d2018-10-16 16:00:20 +02002715 try:
delacruzramo32bab472019-09-13 12:24:22 +02002716 self.check_quota(session)
2717
tierno99d4b172019-07-02 09:28:40 +00002718 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002719 slice_request = self._remove_envelop(indata)
2720 # Override descriptor with query string kwargs
2721 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002722 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002723
Felipe Vicensb57758d2018-10-16 16:00:20 +02002724 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002725 step = "getting nstd id='{}' from database".format(
2726 slice_request.get("nstId")
2727 )
tiernob4844ab2019-05-23 08:42:12 +00002728 _filter = self._get_project_filter(session)
2729 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002730 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002731 # check NST is not disabled
2732 step = "checking NST operationalState"
2733 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002734 raise EngineException(
2735 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2736 "instance".format(slice_request["nstId"]),
2737 http_code=HTTPStatus.CONFLICT,
2738 )
tiernob4844ab2019-05-23 08:42:12 +00002739 del _filter["_id"]
2740
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002741 # check NSD is not disabled
2742 step = "checking operationalState"
2743 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002744 raise EngineException(
2745 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2746 "a network slice".format(slice_request["nstId"]),
2747 http_code=HTTPStatus.CONFLICT,
2748 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002749
Felipe Vicens07f31722018-10-29 15:16:44 +01002750 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002751 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002752 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002753 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002754
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002755 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002756 nsi_descriptor = {
2757 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002758 "name": slice_request["nsiName"],
2759 "description": slice_request.get("nsiDescription", ""),
2760 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002761 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002762 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002763 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002764 "nsr-ref-list": [],
2765 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002766 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002767 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002768 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002769
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002770 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002771 self.format_on_new(
2772 nsi_descriptor, session["project_id"], make_public=session["public"]
2773 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002774 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2775 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002776 nsi_descriptor["_admin"]["deployed"] = {}
2777 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2778 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2779
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002780 # Creating netslice-vld for the RO.
2781 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002782
2783 # Building the vlds list to be deployed
2784 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002785 nsi_vlds = []
2786
2787 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2788 # Getting template Instantiation parameters from NST
2789 nsi_vld = deepcopy(netslice_vlds)
2790 nsi_vld["shared-nsrs-list"] = []
2791 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2792 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002793
2794 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002795 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002796 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002797 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002798
Felipe Vicens09e65422019-01-22 15:06:46 +01002799 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002800 for member_ns in nstd["netslice-subnet"]:
2801 nsd_id = member_ns["nsd-ref"]
2802 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002803 member_ns["nsd-ref"], member_ns["id"]
2804 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002805 if nsd_id not in needed_nsds:
2806 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002807 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002808 nsd = self.db.get_one(
2809 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2810 )
tiernob4844ab2019-05-23 08:42:12 +00002811 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002812 nsd.pop("_admin")
2813 needed_nsds[nsd_id] = nsd
2814 else:
2815 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002816 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2817 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002818
Felipe Vicensb57758d2018-10-16 16:00:20 +02002819 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002820 member_ns["nsd-ref"], member_ns["id"]
2821 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002822
Felipe Vicens07f31722018-10-29 15:16:44 +01002823 # creates Network Services records (NSRs)
2824 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002825 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002826 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002827 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002828 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002829 # Check if the netslice-subnet is shared and if it is share if the nss exists
2830 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002831 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002832 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002833 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002834 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2835 "nsd-ref"
2836 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002837 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002838 nsi = self.db.get_one(
2839 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2840 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002841 if nsi and service.get("is-shared-nss"):
2842 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2843 for nsrs_detailed_item in nsrs_detailed_list:
2844 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002845 if nsrs_detailed_item["nss-id"] == service["id"]:
2846 _id_nsr = nsrs_detailed_item["nsrId"]
2847 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002848 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2849 if netslice_subnet["nss-id"] == service["id"]:
2850 indata_ns = netslice_subnet
2851 break
2852 else:
2853 indata_ns = {}
2854 if service.get("instantiation-parameters"):
2855 indata_ns = deepcopy(service["instantiation-parameters"])
2856 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002857
Felipe Vicens09e65422019-01-22 15:06:46 +01002858 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002859 indata_ns["nsName"] = (
2860 slice_request.get("nsiName") + "." + service["id"]
2861 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002862 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2863 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002864 if slice_request.get("ssh_keys"):
2865 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002866
Felipe Vicens09e65422019-01-22 15:06:46 +01002867 if ns_params:
2868 for ns_param in ns_params:
2869 if ns_param.get("id") == service["id"]:
2870 copy_ns_param = deepcopy(ns_param)
2871 del copy_ns_param["id"]
2872 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002873 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002874
2875 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002876 _id_nsr, _ = self.nsrTopic.new(
2877 rollback, session, indata_ns, kwargs, headers
2878 )
2879 nsrs_item = {
2880 "nsrId": _id_nsr,
2881 "shared": service.get("is-shared-nss"),
2882 "nsd-id": service["nsd-ref"],
2883 "nss-id": service["id"],
2884 "nslcmop_instantiate": None,
2885 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002886 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002887 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002888 nsi_netslice_subnet.append(indata_ns)
2889 nsr_ref = {"nsr-ref": _id_nsr}
2890 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002891
2892 # Adding the nsrs list to the nsi
2893 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002894 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002895 self.db.set_one(
2896 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2897 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002898
Felipe Vicens07f31722018-10-29 15:16:44 +01002899 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002900 self.db.create("nsis", nsi_descriptor)
2901 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002902 return nsi_id, None
garciadeblasf2af4a12023-01-24 16:56:54 +01002903 except ValidationError as e:
2904 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
garciadeblas4568a372021-03-24 09:19:48 +01002905 except Exception as e: # TODO remove try Except, it is captured at nbi.py
rshri2d386cb2024-07-05 14:35:51 +00002906 # self.logger.exception(
2907 # "Exception {} at NsiTopic.new()".format(e), exc_info=True
2908 # )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002909 raise EngineException("Error {}: {}".format(step, e))
Felipe Vicensb57758d2018-10-16 16:00:20 +02002910
tierno65ca36d2019-02-12 19:27:52 +01002911 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002912 raise EngineException(
2913 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2914 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002915
2916
2917class NsiLcmOpTopic(BaseTopic):
2918 topic = "nsilcmops"
2919 topic_msg = "nsi"
2920 operation_schema = { # mapping between operation and jsonschema to validate
2921 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002922 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002923 }
garciadeblas4568a372021-03-24 09:19:48 +01002924
delacruzramo32bab472019-09-13 12:24:22 +02002925 def __init__(self, db, fs, msg, auth):
2926 BaseTopic.__init__(self, db, fs, msg, auth)
2927 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002928
2929 def _check_nsi_operation(self, session, nsir, operation, indata):
2930 """
2931 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002932 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002933 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2934 :param indata: descriptor with the parameters of the operation
2935 :return: None
2936 """
2937 nsds = {}
2938 nstd = nsir["network-slice-template"]
2939
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002940 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002941 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002942 for netslice_subnet in nstd["netslice-subnet"]:
2943 if nstId == netslice_subnet["id"]:
2944 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002945 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002946 _filter = self._get_project_filter(session)
2947 _filter["id"] = nsd_id
2948 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002949 return nsds[nsd_id]
2950 else:
garciadeblas4568a372021-03-24 09:19:48 +01002951 raise EngineException(
2952 "Invalid parameter nstId='{}' is not one of the "
2953 "nst:netslice-subnet".format(nstId)
2954 )
2955
Felipe Vicens07f31722018-10-29 15:16:44 +01002956 if operation == "instantiate":
2957 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002958 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002959 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002960
2961 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2962 now = time()
2963 _id = str(uuid4())
2964 nsilcmop = {
2965 "id": _id,
2966 "_id": _id,
2967 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2968 "statusEnteredTime": now,
2969 "netsliceInstanceId": netsliceInstanceId,
2970 "lcmOperationType": operation,
2971 "startTime": now,
2972 "isAutomaticInvocation": False,
2973 "operationParams": params,
2974 "isCancelPending": False,
2975 "links": {
2976 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002977 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2978 + netsliceInstanceId,
2979 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002980 }
2981 return nsilcmop
2982
Felipe Vicens09e65422019-01-22 15:06:46 +01002983 def add_shared_nsr_2vld(self, nsir, nsr_item):
2984 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2985 if nst_sb_item.get("is-shared-nss"):
2986 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2987 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2988 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002989 for admin_vld_nss_cp_ref_item in admin_vld_item[
2990 "nss-connection-point-ref"
2991 ]:
2992 if (
2993 admin_subnet_item["nss-id"]
2994 == admin_vld_nss_cp_ref_item["nss-ref"]
2995 ):
2996 if (
2997 not nsr_item["nsrId"]
2998 in admin_vld_item["shared-nsrs-list"]
2999 ):
3000 admin_vld_item["shared-nsrs-list"].append(
3001 nsr_item["nsrId"]
3002 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003003 break
3004 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01003005 self.db.set_one(
3006 "nsis",
3007 {"_id": nsir["_id"]},
3008 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
3009 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003010
tierno65ca36d2019-02-12 19:27:52 +01003011 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01003012 """
3013 Performs a new operation over a ns
3014 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01003015 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01003016 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02003017 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01003018 operation: it can be: instantiate, terminate, action, TODO: update, heal
3019 :param kwargs: used to override the indata descriptor
3020 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01003021 :return: id of the nslcmops
3022 """
3023 try:
3024 # Override descriptor with query string kwargs
3025 self._update_input_with_kwargs(indata, kwargs)
3026 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02003027 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01003028 validate_input(indata, self.operation_schema[operation])
3029
Felipe Vicens126af572019-06-05 19:13:04 +02003030 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00003031 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02003032 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01003033 nsir = self.db.get_one("nsis", _filter)
rshri2d386cb2024-07-05 14:35:51 +00003034 # logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00003035 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01003036
3037 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01003038 if (
3039 not nsir["_admin"].get("nsiState")
3040 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
3041 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01003042 if operation == "terminate" and indata.get("autoremove"):
3043 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01003044 return (
3045 None,
3046 None,
3047 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01003048 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01003049 raise EngineException(
3050 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
3051 netsliceInstanceId, operation
3052 ),
3053 HTTPStatus.CONFLICT,
3054 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003055 else:
tierno65ca36d2019-02-12 19:27:52 +01003056 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01003057 raise EngineException(
3058 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
3059 netsliceInstanceId, operation
3060 ),
3061 HTTPStatus.CONFLICT,
3062 )
3063
Felipe Vicens07f31722018-10-29 15:16:44 +01003064 # Creating all the NS_operation (nslcmop)
3065 # Get service list from db
3066 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
3067 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01003068 # nslcmops_item = None
3069 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00003070 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01003071 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003072 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00003073 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01003074 _filter[
3075 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
3076 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02003077 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01003078 nsi = self.db.get_one(
3079 "nsis", _filter, fail_on_empty=False, fail_on_more=False
3080 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003081 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01003082 _update = {
3083 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3084 index
3085 ): None
3086 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003087 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01003088 if (
3089 nsi
3090 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00003091 continue # do not create nsilcmop
3092 else: # instantiate
3093 # looks the first nsi fulfilling the conditions but not being the current NSIR
3094 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01003095 nsi_nsr_item = next(
3096 n
3097 for n in nsi["_admin"]["nsrs-detailed-list"]
3098 if n["nsrId"] == nsr_id
3099 and n["shared"]
3100 and n["nslcmop_instantiate"]
3101 )
tierno40f742b2020-06-23 15:25:26 +00003102 self.add_shared_nsr_2vld(nsir, nsr_item)
3103 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01003104 _update = {
3105 "_admin.nsrs-detailed-list.{}".format(
3106 index
3107 ): nsi_nsr_item
3108 }
tierno40f742b2020-06-23 15:25:26 +00003109 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
3110 # continue to not create nslcmop since nsrs is shared and nsrs was created
3111 continue
3112 else:
3113 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01003114
tierno40f742b2020-06-23 15:25:26 +00003115 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01003116 try:
tierno0b8752f2020-05-12 09:42:02 +00003117 indata_ns = {
3118 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00003119 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00003120 # Including netslice_id in the ns instantiate Operation
3121 "netsliceInstanceId": netsliceInstanceId,
3122 }
3123 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00003124 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00003125 indata_ns.update(service["instantiate_params"])
3126
tierno99d4b172019-07-02 09:28:40 +00003127 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01003128 # message via kafka bus
Adurti87c0e4b2024-07-16 07:33:42 +00003129 nslcmop, _, _ = self.nsi_NsLcmOpTopic.new(
garciadeblas4568a372021-03-24 09:19:48 +01003130 rollback, session, indata_ns, None, headers, slice_object=True
3131 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003132 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00003133 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01003134 _update = {
3135 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3136 index
3137 ): nslcmop
3138 }
tierno40f742b2020-06-23 15:25:26 +00003139 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01003140 except (DbException, EngineException) as e:
3141 if e.http_code == HTTPStatus.NOT_FOUND:
Felipe Vicens09e65422019-01-22 15:06:46 +01003142 pass
3143 else:
3144 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01003145
3146 # Creates nsilcmop
3147 indata["nslcmops_ids"] = nslcmops
3148 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01003149
garciadeblas4568a372021-03-24 09:19:48 +01003150 nsilcmop_desc = self._create_nsilcmop(
3151 session, netsliceInstanceId, operation, indata
3152 )
3153 self.format_on_new(
3154 nsilcmop_desc, session["project_id"], make_public=session["public"]
3155 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003156 _id = self.db.create("nsilcmops", nsilcmop_desc)
3157 rollback.append({"topic": "nsilcmops", "_id": _id})
3158 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00003159 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01003160 except ValidationError as e:
3161 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01003162
tiernobee3bad2019-12-05 12:26:01 +00003163 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01003164 raise EngineException(
3165 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3166 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003167
tierno65ca36d2019-02-12 19:27:52 +01003168 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01003169 raise EngineException(
3170 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3171 )