blob: 607dc73faf34cee66ae622849815f9ed34bf5427 [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:
garciadeblas938e5bf2025-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",
1495 ):
1496 raise EngineException(
1497 f"The operate type should be either start, stop or rebuild not {indata['operateVnfData']['changeStateTo']}",
1498 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1499 )
1500 if indata["operateVnfData"].get("additionalParam"):
1501 vdu_id = indata["operateVnfData"]["additionalParam"]["vdu_id"]
1502 vnfinstance_id = indata["operateVnfData"]["vnfInstanceId"]
1503 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1504 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1505 vnfd = self._get_vnfd_from_vnf_member_index(
1506 vnfd_member_vnf_index, nsr["_id"]
1507 )
1508 self._check_valid_vdu(vnfd, vdu_id)
1509 elif indata["updateType"] == "VERTICAL_SCALE":
1510 if indata.get("verticalScaleVnf"):
1511 vdu_id = indata["verticalScaleVnf"]["vduId"]
1512 vnfinstance_id = indata["verticalScaleVnf"]["vnfInstanceId"]
1513 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1514 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1515 vnfd = self._get_vnfd_from_vnf_member_index(
1516 vnfd_member_vnf_index, nsr["_id"]
1517 )
1518 self._check_valid_vdu(vnfd, vdu_id)
aticig544a2ae2022-04-05 09:00:17 +03001519
1520 except (
1521 DbException,
1522 AttributeError,
1523 IndexError,
1524 KeyError,
1525 ValueError,
1526 ) as e:
1527 raise type(e)(
1528 "Ns update request could not be processed with error: {}.".format(e)
1529 )
1530
garciaale7cbd03c2020-11-27 10:38:35 -03001531 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001532 vnfd = self._get_vnfd_from_vnf_member_index(
1533 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1534 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001535 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001536 if (
1537 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1538 == scaling_aspect["id"]
1539 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001540 break
1541 else:
garciadeblas4568a372021-03-24 09:19:48 +01001542 raise EngineException(
1543 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1544 "present at vnfd:scaling-aspect".format(
1545 indata["scaleVnfData"]["scaleByStepData"][
1546 "scaling-group-descriptor"
1547 ]
1548 )
1549 )
garciaale7cbd03c2020-11-27 10:38:35 -03001550
garciadeblas0964edf2022-02-11 00:43:44 +01001551 def _check_heal_ns_operation(self, indata, nsr):
jegan9f60b842023-11-13 05:01:53 +00001552 try:
1553 for data in indata.get("healVnfData"):
1554 vnf_id = data.get("vnfInstanceId")
1555 vnf = self.db.get_one("vnfrs", {"_id": vnf_id})
1556 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1557 vnfd = self._get_vnfd_from_vnf_member_index(
1558 vnfd_member_vnf_index, nsr["_id"]
1559 )
1560 if data.get("additionalParams"):
1561 vdu_id = data["additionalParams"].get("vdu")
1562 if vdu_id:
1563 for index in range(len(vdu_id)):
1564 vdu = vdu_id[index].get("vdu-id")
1565 self._check_valid_vdu(vnfd, vdu)
1566 except (DbException, AttributeError, IndexError, KeyError, ValueError) as e:
1567 raise type(e)(
1568 "Ns healing request could not be processed with error: {}.".format(e)
1569 )
garciadeblas0964edf2022-02-11 00:43:44 +01001570
garciaale7cbd03c2020-11-27 10:38:35 -03001571 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001572 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001573 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001574 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001575 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001576 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1577 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1578 for in_vnf in get_iterable(indata.get("vnf")):
1579 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001580 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001581 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001582 else:
garciadeblas4568a372021-03-24 09:19:48 +01001583 vnfd = self._get_vnfd_from_vnf_member_index(
1584 member_vnf_index, nsr["_id"]
1585 )
1586 vnf_member_index_to_vnfd[
1587 member_vnf_index
1588 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001589 self._check_vnf_instantiation_params(in_vnf, vnfd)
1590 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001591 self._check_valid_vim_account(
1592 in_vnf["vimAccountId"], vim_accounts, session
1593 )
tierno260dd6f2019-09-02 10:48:56 +00001594
garciaale7cbd03c2020-11-27 10:38:35 -03001595 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001596 self._check_valid_wim_account(
1597 in_vld.get("wimAccountId"), wim_accounts, session
1598 )
garciaale7cbd03c2020-11-27 10:38:35 -03001599 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1600 if in_vld["name"] == vldd["id"]:
1601 break
tierno9cb7d672019-10-30 12:13:48 +00001602 else:
garciadeblas4568a372021-03-24 09:19:48 +01001603 raise EngineException(
1604 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1605 in_vld["name"]
1606 )
1607 )
tierno9cb7d672019-10-30 12:13:48 +00001608
garciaale7cbd03c2020-11-27 10:38:35 -03001609 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1610 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001611 vnfr = self.db.get_one(
1612 "vnfrs",
1613 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1614 fail_on_empty=False,
1615 )
garciaale7cbd03c2020-11-27 10:38:35 -03001616 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001617 raise EngineException(
1618 "Invalid parameter member_vnf_index='{}' is not one of the "
1619 "nsd:constituent-vnfd".format(member_vnf_index)
1620 )
beierlmcee2ebf2022-03-29 17:42:48 -04001621
garciadeblasf2af4a12023-01-24 16:56:54 +01001622 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
beierlmcee2ebf2022-03-29 17:42:48 -04001623 if "revision" in vnfr:
1624 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
garciadeblasf2af4a12023-01-24 16:56:54 +01001625 vnfd = self.db.get_one(
1626 "vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False
1627 )
beierlmcee2ebf2022-03-29 17:42:48 -04001628 else:
garciadeblasf2af4a12023-01-24 16:56:54 +01001629 vnfd = self.db.get_one(
1630 "vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False
1631 )
beierlmcee2ebf2022-03-29 17:42:48 -04001632
garciaale7cbd03c2020-11-27 10:38:35 -03001633 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001634 raise EngineException(
1635 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1636 vnfr["vnfd-id"]
1637 )
1638 )
garciaale7cbd03c2020-11-27 10:38:35 -03001639 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001640
garciaale7cbd03c2020-11-27 10:38:35 -03001641 def _check_valid_vdu(self, vnfd, vdu_id):
1642 for vdud in get_iterable(vnfd.get("vdu")):
1643 if vdud["id"] == vdu_id:
1644 return vdud
1645 else:
garciadeblas4568a372021-03-24 09:19:48 +01001646 raise EngineException(
1647 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1648 vdu_id
1649 )
1650 )
garciaale7cbd03c2020-11-27 10:38:35 -03001651
1652 def _check_valid_kdu(self, vnfd, kdu_name):
1653 for kdud in get_iterable(vnfd.get("kdu")):
1654 if kdud["name"] == kdu_name:
1655 return kdud
1656 else:
garciadeblas4568a372021-03-24 09:19:48 +01001657 raise EngineException(
1658 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1659 kdu_name
1660 )
1661 )
garciaale7cbd03c2020-11-27 10:38:35 -03001662
1663 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1664 for in_vdu in get_iterable(in_vnf.get("vdu")):
1665 for vdu in get_iterable(vnfd.get("vdu")):
1666 if in_vdu["id"] == vdu["id"]:
1667 for volume in get_iterable(in_vdu.get("volume")):
1668 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
aticigd7753fc2022-05-18 18:55:23 +03001669 if volumed == volume["name"]:
garciaale7cbd03c2020-11-27 10:38:35 -03001670 break
1671 else:
garciadeblas4568a372021-03-24 09:19:48 +01001672 raise EngineException(
1673 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1674 "volume:name='{}' is not present at "
1675 "vnfd:vdu:virtual-storage-desc list".format(
1676 in_vnf["member-vnf-index"],
1677 in_vdu["id"],
1678 volume["id"],
1679 )
1680 )
garciaale7cbd03c2020-11-27 10:38:35 -03001681
1682 vdu_if_names = set()
1683 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001684 for iface in get_iterable(
1685 cpd.get("virtual-network-interface-requirement")
1686 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001687 vdu_if_names.add(iface.get("name"))
1688
aticigd7753fc2022-05-18 18:55:23 +03001689 for in_iface in get_iterable(in_vdu.get("interface")):
garciaale7cbd03c2020-11-27 10:38:35 -03001690 if in_iface["name"] in vdu_if_names:
1691 break
1692 else:
garciadeblas4568a372021-03-24 09:19:48 +01001693 raise EngineException(
1694 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1695 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1696 in_vnf["member-vnf-index"],
1697 in_vdu["id"],
1698 in_iface["name"],
1699 )
1700 )
garciaale7cbd03c2020-11-27 10:38:35 -03001701 break
1702
1703 else:
garciadeblas4568a372021-03-24 09:19:48 +01001704 raise EngineException(
1705 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1706 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1707 )
garciaale7cbd03c2020-11-27 10:38:35 -03001708
garciadeblas4568a372021-03-24 09:19:48 +01001709 vnfd_ivlds_cpds = {
1710 ivld.get("id"): set()
1711 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1712 }
Gulsum Atici9af2a472023-03-28 17:50:48 +03001713 for vdu in vnfd.get("vdu", {}):
1714 for cpd in vdu.get("int-cpd", {}):
garciaale7cbd03c2020-11-27 10:38:35 -03001715 if cpd.get("int-virtual-link-desc"):
1716 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1717
1718 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1719 if in_ivld.get("name") in vnfd_ivlds_cpds:
1720 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1721 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001722 break
tiernob24258a2018-10-04 18:39:49 +02001723 else:
garciadeblas4568a372021-03-24 09:19:48 +01001724 raise EngineException(
1725 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1726 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1727 "vnfd:internal-vld:name/id:internal-connection-point".format(
1728 in_vnf["member-vnf-index"],
1729 in_ivld["name"],
1730 in_icp["id-ref"],
1731 )
1732 )
tiernob24258a2018-10-04 18:39:49 +02001733 else:
garciadeblas4568a372021-03-24 09:19:48 +01001734 raise EngineException(
1735 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1736 " is not present at vnfd '{}'".format(
1737 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1738 )
1739 )
tiernob24258a2018-10-04 18:39:49 +02001740
garciaale7cbd03c2020-11-27 10:38:35 -03001741 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1742 if vim_account in vim_accounts:
1743 return
1744 try:
1745 db_filter = self._get_project_filter(session)
1746 db_filter["_id"] = vim_account
1747 self.db.get_one("vim_accounts", db_filter)
1748 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001749 raise EngineException(
1750 "Invalid vimAccountId='{}' not present for the project".format(
1751 vim_account
1752 )
1753 )
garciaale7cbd03c2020-11-27 10:38:35 -03001754 vim_accounts.append(vim_account)
1755
David Garcia98de2982021-10-13 17:14:01 +02001756 def _get_vim_account(self, vim_id: str, session):
1757 try:
1758 db_filter = self._get_project_filter(session)
1759 db_filter["_id"] = vim_id
1760 return self.db.get_one("vim_accounts", db_filter)
1761 except Exception:
1762 raise EngineException(
garciadeblasf2af4a12023-01-24 16:56:54 +01001763 "Invalid vimAccountId='{}' not present for the project".format(vim_id)
David Garcia98de2982021-10-13 17:14:01 +02001764 )
1765
garciaale7cbd03c2020-11-27 10:38:35 -03001766 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1767 if not isinstance(wim_account, str):
1768 return
1769 if wim_account in wim_accounts:
1770 return
1771 try:
gifrerenom44f5ec12022-03-07 16:57:25 +00001772 db_filter = self._get_project_filter(session)
garciaale7cbd03c2020-11-27 10:38:35 -03001773 db_filter["_id"] = wim_account
1774 self.db.get_one("wim_accounts", db_filter)
1775 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001776 raise EngineException(
1777 "Invalid wimAccountId='{}' not present for the project".format(
1778 wim_account
1779 )
1780 )
garciaale7cbd03c2020-11-27 10:38:35 -03001781 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001782
garciadeblas4568a372021-03-24 09:19:48 +01001783 def _look_for_pdu(
1784 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1785 ):
tiernocc103432018-10-19 14:10:35 +02001786 """
tierno36ec8602018-11-02 17:27:11 +01001787 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1788 (ip_address, ...) information.
1789 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001790 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001791 :param rollback: list with the database modifications to rollback if needed
1792 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1793 :param vim_account: vim_account where this vnfr should be deployed
1794 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1795 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1796 of the changed vnfr is needed
1797
1798 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1799 "vim-network-name": used at VIM
1800 "name": interface name
1801 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1802 "ns-vld-id": NSD vld where this interface is connected.
1803 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 +02001804 """
tierno36ec8602018-11-02 17:27:11 +01001805
1806 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001807 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1808 if not vdur.get("pdu-type"):
1809 continue
1810 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001811 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001812 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001813 pdu_filter["type"] = pdu_type
1814 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001815 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001816 # TODO feature 1417: "shared": True,
1817
1818 available_pdus = self.db.get_list("pdus", pdu_filter)
1819 for pdu in available_pdus:
1820 # step 1 check if this pdu contains needed interfaces:
1821 match_interfaces = True
1822 for vdur_interface in vdur["interfaces"]:
1823 for pdu_interface in pdu["interfaces"]:
1824 if pdu_interface["name"] == vdur_interface["name"]:
1825 # TODO feature 1417: match per mgmt type
1826 break
1827 else: # no interface found for name
1828 match_interfaces = False
1829 break
1830 if match_interfaces:
1831 break
1832 else:
1833 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001834 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001835 "names".format(
1836 pdu_type,
1837 vim_account,
1838 vnfr["member-vnf-index-ref"],
1839 vdur["vdu-id-ref"],
1840 )
1841 )
tiernocc103432018-10-19 14:10:35 +02001842
1843 # step 2. Update pdu
1844 rollback_pdu = {
1845 "_admin.usageState": pdu["_admin"]["usageState"],
1846 "_admin.usage.vnfr_id": None,
1847 "_admin.usage.nsr_id": None,
1848 "_admin.usage.vdur": None,
1849 }
garciadeblas4568a372021-03-24 09:19:48 +01001850 self.db.set_one(
1851 "pdus",
1852 {"_id": pdu["_id"]},
1853 {
1854 "_admin.usageState": "IN_USE",
1855 "_admin.usage": {
1856 "vnfr_id": vnfr["_id"],
1857 "nsr_id": vnfr["nsr-id-ref"],
1858 "vdur": vdur["vdu-id-ref"],
1859 },
1860 },
1861 )
1862 rollback.append(
1863 {
1864 "topic": "pdus",
1865 "_id": pdu["_id"],
1866 "operation": "set",
1867 "content": rollback_pdu,
1868 }
1869 )
tiernocc103432018-10-19 14:10:35 +02001870
1871 # step 3. Fill vnfr info by filling vdur
1872 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001873 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001874 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1875 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1876 for pdu_interface in pdu["interfaces"]:
1877 if pdu_interface["name"] == vdur_interface["name"]:
1878 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1879 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001880 if k in (
1881 "ip-address",
1882 "mac-address",
1883 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001884 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001885 vnfr_update_rollback[
1886 iface_text + ".{}".format(k)
1887 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001888 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001889 if vdur_interface.get(
1890 "mgmt-interface"
1891 ) or vdur_interface.get("mgmt-vnf"):
1892 vnfr_update_rollback[
1893 vdu_text + ".ip-address"
1894 ] = vdur.get("ip-address")
1895 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1896 "ip-address"
1897 ]
tierno36ec8602018-11-02 17:27:11 +01001898 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001899 vnfr_update_rollback["ip-address"] = vnfr.get(
1900 "ip-address"
1901 )
tierno36ec8602018-11-02 17:27:11 +01001902 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001903 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1904 "ip-address"
1905 ]
1906 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1907 "vim-network-id"
1908 ):
1909 ifaces_forcing_vim_network.append(
1910 {
1911 "name": vdur_interface.get("vnf-vld-id")
1912 or vdur_interface.get("ns-vld-id"),
1913 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1914 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1915 }
1916 )
gcalvino17d5b732018-12-17 16:26:21 +01001917 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001918 ifaces_forcing_vim_network[-1][
1919 "vim-network-id"
1920 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001921 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001922 ifaces_forcing_vim_network[-1][
1923 "vim-network-name"
1924 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001925 break
1926
tierno36ec8602018-11-02 17:27:11 +01001927 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001928
garciadeblas4568a372021-03-24 09:19:48 +01001929 def _look_for_k8scluster(
1930 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1931 ):
tierno9cb7d672019-10-30 12:13:48 +00001932 """
1933 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1934 Fills vnfr.kdur with the selected k8scluster
1935
1936 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1937 :param rollback: list with the database modifications to rollback if needed
1938 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1939 :param vim_account: vim_account where this vnfr should be deployed
1940 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1941 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1942 of the changed vnfr is needed
1943
1944 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1945 "vim-network-name": used at VIM
1946 "name": interface name
1947 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1948 "ns-vld-id": NSD vld where this interface is connected.
1949 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1950 """
1951
1952 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001953 if not vnfr.get("kdur"):
1954 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001955
tiernoc67b0e92019-11-05 12:45:29 +00001956 kdu_filter = self._get_project_filter(session)
1957 kdu_filter["vim_account"] = vim_account
1958 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1959 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1960
1961 k8s_requirements = {} # just for logging
1962 for k8scluster in available_k8sclusters:
1963 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001964 break
tiernoc67b0e92019-11-05 12:45:29 +00001965 # restrict by cni
1966 if vnfr["k8s-cluster"].get("cni"):
1967 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001968 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1969 k8scluster.get("cni", ())
1970 ):
tiernoc67b0e92019-11-05 12:45:29 +00001971 continue
1972 # restrict by version
1973 if vnfr["k8s-cluster"].get("version"):
1974 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1975 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1976 continue
1977 # restrict by number of networks
1978 if vnfr["k8s-cluster"].get("nets"):
1979 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001980 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1981 vnfr["k8s-cluster"]["nets"]
1982 ):
tiernoc67b0e92019-11-05 12:45:29 +00001983 continue
1984 break
1985 else:
garciadeblas4568a372021-03-24 09:19:48 +01001986 raise EngineException(
1987 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1988 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1989 )
1990 )
tierno9cb7d672019-10-30 12:13:48 +00001991
tiernoc67b0e92019-11-05 12:45:29 +00001992 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001993 # step 3. Fill vnfr info by filling kdur
1994 kdu_text = "kdur.{}.".format(kdur_index)
1995 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1996 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1997
tiernoc67b0e92019-11-05 12:45:29 +00001998 # step 4. Check VIM networks that forces the selected k8s_cluster
1999 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
2000 k8scluster_net_list = list(k8scluster.get("nets").keys())
2001 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
2002 # get a network from k8s_cluster nets. If name matches use this, if not use other
2003 if kdur_net["id"] in k8scluster_net_list: # name matches
2004 vim_net = k8scluster["nets"][kdur_net["id"]]
2005 k8scluster_net_list.remove(kdur_net["id"])
2006 else:
2007 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
2008 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01002009 vnfr_update_rollback[
2010 "k8s-cluster.nets.{}.vim_net".format(net_index)
2011 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00002012 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01002013 if vim_net and (
2014 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
2015 ):
2016 ifaces_forcing_vim_network.append(
2017 {
2018 "name": kdur_net.get("vnf-vld-id")
2019 or kdur_net.get("ns-vld-id"),
2020 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
2021 "ns-vld-id": kdur_net.get("ns-vld-id"),
2022 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
2023 }
2024 )
tiernoc67b0e92019-11-05 12:45:29 +00002025 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00002026 return ifaces_forcing_vim_network
2027
Gulsum Aticie395aa42021-11-10 20:59:06 +03002028 def _update_vnfrs_from_nsd(self, nsr):
garciadeblasf2af4a12023-01-24 16:56:54 +01002029 step = "Getting vnf_profiles from nsd" # first step must be defined outside try
Gulsum Aticie395aa42021-11-10 20:59:06 +03002030 try:
2031 nsr_id = nsr["_id"]
2032 nsd = nsr["nsd"]
2033
Gulsum Aticie395aa42021-11-10 20:59:06 +03002034 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
2035 vld_fixed_ip_connection_point_data = {}
2036
2037 step = "Getting ip-address info from vnf_profile if it exists"
2038 for vnfp in vnf_profiles:
2039 # Checking ip-address info from nsd.vnf_profile and storing
2040 for vlc in vnfp.get("virtual-link-connectivity", ()):
2041 for cpd in vlc.get("constituent-cpd-id", ()):
2042 if cpd.get("ip-address"):
2043 step = "Storing ip-address info"
garciadeblasf2af4a12023-01-24 16:56:54 +01002044 vld_fixed_ip_connection_point_data.update(
2045 {
2046 vlc.get("virtual-link-profile-id")
2047 + "."
2048 + cpd.get("constituent-base-element-id"): {
2049 "vnfd-connection-point-ref": cpd.get(
2050 "constituent-cpd-id"
2051 ),
2052 "ip-address": cpd.get("ip-address"),
2053 }
2054 }
2055 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002056
2057 # Inserting ip address to vnfr
2058 if len(vld_fixed_ip_connection_point_data) > 0:
2059 step = "Getting vnfrs"
2060 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2061 for item in vld_fixed_ip_connection_point_data.keys():
2062 step = "Filtering vnfrs"
garciadeblasf2af4a12023-01-24 16:56:54 +01002063 vnfr = next(
2064 filter(
2065 lambda vnfr: vnfr["member-vnf-index-ref"]
2066 == item.split(".")[1],
2067 vnfrs,
2068 ),
2069 None,
2070 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002071 if vnfr:
2072 vnfr_update = {}
2073 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2074 for iface_index, iface in enumerate(vdur["interfaces"]):
2075 step = "Looking for matched interface"
2076 if (
garciadeblasf2af4a12023-01-24 16:56:54 +01002077 iface.get("external-connection-point-ref")
2078 == vld_fixed_ip_connection_point_data[item].get(
2079 "vnfd-connection-point-ref"
2080 )
2081 and iface.get("ns-vld-id") == item.split(".")[0]
Gulsum Aticie395aa42021-11-10 20:59:06 +03002082 ):
2083 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2084 vdur_index, iface_index
2085 )
2086 step = "Storing info in order to update vnfr"
2087 vnfr_update[
2088 vnfr_update_text + ".ip-address"
garciadeblasf2af4a12023-01-24 16:56:54 +01002089 ] = increment_ip_mac(
2090 vld_fixed_ip_connection_point_data[item].get(
2091 "ip-address"
2092 ),
2093 vdur.get("count-index", 0),
2094 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002095 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
2096
2097 step = "updating vnfr at database"
2098 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
2099 except (
garciadeblasf2af4a12023-01-24 16:56:54 +01002100 ValidationError,
2101 EngineException,
2102 DbException,
2103 MsgException,
2104 FsException,
Gulsum Aticie395aa42021-11-10 20:59:06 +03002105 ) as e:
2106 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
2107
tiernocc103432018-10-19 14:10:35 +02002108 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02002109 # get vnfr
2110 nsr_id = nsr["_id"]
2111 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2112
2113 for vnfr in vnfrs:
2114 vnfr_update = {}
2115 vnfr_update_rollback = {}
2116 member_vnf_index = vnfr["member-vnf-index-ref"]
2117 # update vim-account-id
2118
2119 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02002120 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002121 # check instantiate parameters
2122 for vnf_inst_params in get_iterable(indata.get("vnf")):
2123 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
2124 continue
2125 if vnf_inst_params.get("vimAccountId"):
2126 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02002127 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002128
tiernocddb07d2020-10-06 08:28:00 +00002129 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
2130 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
2131 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2132 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
2133 continue
garciadeblas4568a372021-03-24 09:19:48 +01002134 for iface_inst_param in get_iterable(
2135 vdu_inst_param.get("interface")
2136 ):
2137 iface_index, _ = next(
2138 i
2139 for i in enumerate(vdur["interfaces"])
2140 if i[1]["name"] == iface_inst_param["name"]
2141 )
2142 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2143 vdur_index, iface_index
2144 )
tiernocddb07d2020-10-06 08:28:00 +00002145 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002146 vnfr_update[
2147 vnfr_update_text + ".ip-address"
2148 ] = increment_ip_mac(
2149 iface_inst_param.get("ip-address"),
2150 vdur.get("count-index", 0),
2151 )
tierno1bd9d952020-11-13 15:56:51 +00002152 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002153 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002154 vnfr_update[
2155 vnfr_update_text + ".mac-address"
2156 ] = increment_ip_mac(
2157 iface_inst_param.get("mac-address"),
2158 vdur.get("count-index", 0),
2159 )
tierno1bd9d952020-11-13 15:56:51 +00002160 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03002161 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01002162 vnfr_update[
2163 vnfr_update_text + ".floating-ip-required"
2164 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002165 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2166 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01002167 for ivld_inst_param in get_iterable(
2168 vnf_inst_params.get("internal-vld")
2169 ):
2170 for icp_inst_param in get_iterable(
2171 ivld_inst_param.get("internal-connection-point")
2172 ):
tiernocddb07d2020-10-06 08:28:00 +00002173 # look for iface
2174 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2175 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002176 if (
2177 iface.get("internal-connection-point-ref")
2178 == icp_inst_param["id-ref"]
2179 ):
2180 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2181 vdur_index, iface_index
2182 )
tiernocddb07d2020-10-06 08:28:00 +00002183 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002184 vnfr_update[
2185 vnfr_update_text + ".ip-address"
2186 ] = increment_ip_mac(
2187 icp_inst_param.get("ip-address"),
2188 vdur.get("count-index", 0),
2189 )
2190 vnfr_update[
2191 vnfr_update_text + ".fixed-ip"
2192 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002193 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002194 vnfr_update[
2195 vnfr_update_text + ".mac-address"
2196 ] = increment_ip_mac(
2197 icp_inst_param.get("mac-address"),
2198 vdur.get("count-index", 0),
2199 )
2200 vnfr_update[
2201 vnfr_update_text + ".fixed-mac"
2202 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002203 break
2204 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2205 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01002206 for vnfcp_inst_param in get_iterable(
2207 vld_inst_param.get("vnfd-connection-point-ref")
2208 ):
tiernocddb07d2020-10-06 08:28:00 +00002209 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2210 continue
2211 # look for iface
2212 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2213 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002214 if (
2215 iface.get("external-connection-point-ref")
2216 == vnfcp_inst_param["vnfd-connection-point-ref"]
2217 ):
2218 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2219 vdur_index, iface_index
2220 )
tiernocddb07d2020-10-06 08:28:00 +00002221 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002222 vnfr_update[
2223 vnfr_update_text + ".ip-address"
2224 ] = increment_ip_mac(
2225 vnfcp_inst_param.get("ip-address"),
2226 vdur.get("count-index", 0),
2227 )
tierno1bd9d952020-11-13 15:56:51 +00002228 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002229 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002230 vnfr_update[
2231 vnfr_update_text + ".mac-address"
2232 ] = increment_ip_mac(
2233 vnfcp_inst_param.get("mac-address"),
2234 vdur.get("count-index", 0),
2235 )
tierno1bd9d952020-11-13 15:56:51 +00002236 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002237 break
2238
tiernocc103432018-10-19 14:10:35 +02002239 vnfr_update["vim-account-id"] = vim_account
2240 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2241
David Garciaecb41322021-03-31 19:10:46 +02002242 if vca_id:
2243 vnfr_update["vca-id"] = vca_id
2244 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2245
tiernocc103432018-10-19 14:10:35 +02002246 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002247 ifaces_forcing_vim_network = self._look_for_pdu(
2248 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2249 )
tiernocc103432018-10-19 14:10:35 +02002250
tierno9cb7d672019-10-30 12:13:48 +00002251 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002252 ifaces_forcing_vim_network += self._look_for_k8scluster(
2253 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2254 )
tierno9cb7d672019-10-30 12:13:48 +00002255 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002256 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002257 rollback.append(
2258 {
2259 "topic": "vnfrs",
2260 "_id": vnfr["_id"],
2261 "operation": "set",
2262 "content": vnfr_update_rollback,
2263 }
2264 )
tierno36ec8602018-11-02 17:27:11 +01002265
2266 # Update indada in case pdu forces to use a concrete vim-network-name
2267 # TODO check if user has already insert a vim-network-name and raises an error
2268 if not ifaces_forcing_vim_network:
2269 continue
2270 for iface_info in ifaces_forcing_vim_network:
2271 if iface_info.get("ns-vld-id"):
2272 if "vld" not in indata:
2273 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002274 indata["vld"].append(
2275 {
2276 key: iface_info[key]
2277 for key in ("name", "vim-network-name", "vim-network-id")
2278 if iface_info.get(key)
2279 }
2280 )
tierno36ec8602018-11-02 17:27:11 +01002281
2282 elif iface_info.get("vnf-vld-id"):
2283 if "vnf" not in indata:
2284 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002285 indata["vnf"].append(
2286 {
2287 "member-vnf-index": member_vnf_index,
2288 "internal-vld": [
2289 {
2290 key: iface_info[key]
2291 for key in (
2292 "name",
2293 "vim-network-name",
2294 "vim-network-id",
2295 )
2296 if iface_info.get(key)
2297 }
2298 ],
2299 }
2300 )
tierno36ec8602018-11-02 17:27:11 +01002301
2302 @staticmethod
2303 def _create_nslcmop(nsr_id, operation, params):
2304 """
2305 Creates a ns-lcm-opp content to be stored at database.
2306 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002307 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002308 :param params: user parameters for the operation
2309 :return: dictionary following SOL005 format
2310 """
tiernob24258a2018-10-04 18:39:49 +02002311 now = time()
2312 _id = str(uuid4())
2313 nslcmop = {
2314 "id": _id,
2315 "_id": _id,
2316 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002317 "queuePosition": None,
2318 "stage": None,
2319 "errorMessage": None,
2320 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002321 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002322 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002323 "lcmOperationType": operation,
2324 "startTime": now,
2325 "isAutomaticInvocation": False,
2326 "operationParams": params,
2327 "isCancelPending": False,
2328 "links": {
2329 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002330 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002331 },
tiernob24258a2018-10-04 18:39:49 +02002332 }
2333 return nslcmop
2334
magnussonlf318b302020-01-20 18:38:18 +01002335 def _get_enabled_vims(self, session):
2336 """
2337 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2338 :param session: current session with user information
2339 """
2340 db_filter = self._get_project_filter(session)
2341 db_filter["_admin.operationalState"] = "ENABLED"
2342 vims = self.db.get_list("vim_accounts", db_filter)
2343 vimAccounts = []
2344 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002345 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002346 return vimAccounts
2347
garciadeblas4568a372021-03-24 09:19:48 +01002348 def new(
2349 self,
2350 rollback,
2351 session,
2352 indata=None,
2353 kwargs=None,
2354 headers=None,
2355 slice_object=False,
2356 ):
tiernob24258a2018-10-04 18:39:49 +02002357 """
2358 Performs a new operation over a ns
2359 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002360 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002361 :param indata: descriptor with the parameters of the operation. It must contains among others
2362 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002363 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002364 :param kwargs: used to override the indata descriptor
2365 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002366 :return: id of the nslcmops
2367 """
garciadeblas4568a372021-03-24 09:19:48 +01002368
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002369 def check_if_nsr_is_not_slice_member(session, nsr_id):
2370 nsis = None
2371 db_filter = self._get_project_filter(session)
2372 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002373 nsis = self.db.get_one(
2374 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2375 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002376 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002377 raise EngineException(
2378 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2379 nsr_id, nsis["_id"]
2380 ),
2381 http_code=HTTPStatus.CONFLICT,
2382 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002383
tiernob24258a2018-10-04 18:39:49 +02002384 try:
2385 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002386 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002387 operation = indata["lcmOperationType"]
2388 nsInstanceId = indata["nsInstanceId"]
2389
2390 validate_input(indata, self.operation_schema[operation])
2391 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002392 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002393 _filter["_id"] = nsInstanceId
2394 nsr = self.db.get_one("nsrs", _filter)
2395
2396 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002397 if operation == "terminate" and slice_object is False:
2398 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002399 if (
2400 not nsr["_admin"].get("nsState")
2401 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2402 ):
tiernob24258a2018-10-04 18:39:49 +02002403 if operation == "terminate" and indata.get("autoremove"):
2404 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002405 return (
2406 None,
2407 None,
garciadeblasf53612b2024-07-12 14:44:37 +02002408 None,
garciadeblas4568a372021-03-24 09:19:48 +01002409 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002410 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002411 raise EngineException(
2412 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2413 nsInstanceId, operation
2414 ),
2415 HTTPStatus.CONFLICT,
2416 )
tiernob24258a2018-10-04 18:39:49 +02002417 else:
tierno65ca36d2019-02-12 19:27:52 +01002418 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002419 raise EngineException(
2420 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2421 nsInstanceId, operation
2422 ),
2423 HTTPStatus.CONFLICT,
2424 )
tiernob24258a2018-10-04 18:39:49 +02002425 self._check_ns_operation(session, nsr, operation, indata)
garciadeblasf2af4a12023-01-24 16:56:54 +01002426 if indata.get("primitive_params"):
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002427 indata["primitive_params"] = json.dumps(indata["primitive_params"])
garciadeblasf2af4a12023-01-24 16:56:54 +01002428 elif indata.get("additionalParamsForVnf"):
2429 indata["additionalParamsForVnf"] = json.dumps(
2430 indata["additionalParamsForVnf"]
2431 )
tierno36ec8602018-11-02 17:27:11 +01002432
tiernocc103432018-10-19 14:10:35 +02002433 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002434 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002435 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302436 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2437 nsr_update = {}
2438 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2439 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2440 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2441 ns_request = nsr["instantiate_params"]
garciadeblasf2af4a12023-01-24 16:56:54 +01002442 vnfr = self.db.get_one(
2443 "vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]}
2444 )
elumalai8bf978e2022-05-26 15:32:06 +05302445 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2446 vnfr_vnfd_revision = vnfr.get("revision", 1)
2447 if latest_vnfd_revision != vnfr_vnfd_revision:
2448 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
garciadeblasf2af4a12023-01-24 16:56:54 +01002449 old_db_vnfd = self.db.get_one(
2450 "vnfds_revisions", {"_id": old_vnfd_id}
2451 )
elumalai8bf978e2022-05-26 15:32:06 +05302452 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2453 new_sw_version = vnfd.get("software-version", "1.0")
2454 if new_sw_version != old_sw_version:
2455 vnf_index = vnfr["member-vnf-index-ref"]
jeganb676cf32024-11-04 12:20:19 +00002456 for vdu in vnfd.get("vdu", []):
vegall18101ea2023-03-06 13:49:21 +00002457 self.nsrtopic._add_shared_volumes_to_nsr(
2458 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2459 )
garciadeblasf2af4a12023-01-24 16:56:54 +01002460 self.nsrtopic._add_flavor_to_nsr(
2461 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2462 )
elumalai8bf978e2022-05-26 15:32:06 +05302463 sw_image_id = vdu.get("sw-image-desc")
2464 if sw_image_id:
garciadeblasf2af4a12023-01-24 16:56:54 +01002465 image_data = self.nsrtopic._get_image_data_from_vnfd(
2466 vnfd, sw_image_id
2467 )
elumalai8bf978e2022-05-26 15:32:06 +05302468 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2469 for alt_image in vdu.get("alternative-sw-image-desc", ()):
garciadeblasf2af4a12023-01-24 16:56:54 +01002470 image_data = self.nsrtopic._get_image_data_from_vnfd(
2471 vnfd, alt_image
2472 )
elumalai8bf978e2022-05-26 15:32:06 +05302473 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2474 nsr_update["image"] = nsr["image"]
2475 nsr_update["flavor"] = nsr["flavor"]
vegall18101ea2023-03-06 13:49:21 +00002476 nsr_update["shared-volumes"] = nsr["shared-volumes"]
elumalai8bf978e2022-05-26 15:32:06 +05302477 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
garciadeblasf2af4a12023-01-24 16:56:54 +01002478 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(
2479 nsd, ns_request, session
2480 )
2481 vnfr_descriptor = (
2482 self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2483 nsd,
2484 vnfd,
2485 vnfd_id,
2486 vnf_index,
2487 nsr,
2488 ns_request,
2489 ns_k8s_namespace,
2490 latest_vnfd_revision,
2491 )
elumalai8bf978e2022-05-26 15:32:06 +05302492 )
elumalai73a47d52023-11-14 15:06:38 +05302493 self._update_vnfrs_from_nsd(nsr)
2494 vnfr_new = self.db.get_one(
2495 "vnfrs",
2496 {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]},
2497 )
2498 fixed_ip_dict = {}
2499 for vdu_record in vnfr_new.get("vdur"):
2500 if vdu_record.get("count-index") == 0:
2501 for interface in vdu_record.get("interfaces"):
2502 if (
2503 interface.get("external-connection-point-ref")
2504 and interface.get("fixed-ip") is True
2505 ):
2506 fixed_ip_dict[
2507 vdu_record.get("vdu-id-ref")
2508 ] = interface.get("ip-address")
2509 for new_vdu in vnfr_descriptor.get("vdur"):
2510 if fixed_ip_dict.get(new_vdu.get("vdu-id-ref")):
2511 for new_interface in new_vdu.get("interfaces"):
2512 if new_interface.get(
2513 "external-connection-point-ref"
2514 ):
2515 new_interface["ip-address"] = fixed_ip_dict.get(
2516 new_vdu.get("vdu-id-ref")
2517 )
2518 new_interface["fixed-ip"] = True
elumalai8bf978e2022-05-26 15:32:06 +05302519 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002520 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002521 _id = nslcmop_desc["_id"]
garciadeblasf53612b2024-07-12 14:44:37 +02002522 nsName = nsr.get("name")
garciadeblas4568a372021-03-24 09:19:48 +01002523 self.format_on_new(
2524 nslcmop_desc, session["project_id"], make_public=session["public"]
2525 )
magnussonlf318b302020-01-20 18:38:18 +01002526 if indata.get("placement-engine"):
2527 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002528 nslcmop_desc["operationParams"][
2529 "validVimAccounts"
2530 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002531 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002532 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002533 if not slice_object:
2534 self.msg.write("ns", operation, nslcmop_desc)
garciadeblasf53612b2024-07-12 14:44:37 +02002535 return _id, nsName, None
tiernobdebce92019-07-01 15:36:49 +00002536 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002537 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2538 # except DbException as e:
2539 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2540
Gabriel Cuba84a60df2023-10-30 14:01:54 -05002541 def cancel(self, rollback, session, indata=None, kwargs=None, headers=None):
2542 validate_input(indata, self.operation_schema["cancel"])
2543 # Override descriptor with query string kwargs
2544 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
2545 nsLcmOpOccId = indata["nsLcmOpOccId"]
2546 cancelMode = indata["cancelMode"]
2547 # get nslcmop from nsLcmOpOccId
2548 _filter = BaseTopic._get_project_filter(session)
2549 _filter["_id"] = nsLcmOpOccId
2550 nslcmop = self.db.get_one("nslcmops", _filter)
2551 # Fail is this is not an ongoing nslcmop
2552 if nslcmop.get("operationState") not in [
2553 "STARTING",
2554 "PROCESSING",
2555 "ROLLING_BACK",
2556 ]:
2557 raise EngineException(
2558 "Operation is not in STARTING, PROCESSING or ROLLING_BACK state",
2559 http_code=HTTPStatus.CONFLICT,
2560 )
2561 nsInstanceId = nslcmop["nsInstanceId"]
2562 update_dict = {
2563 "isCancelPending": True,
2564 "cancelMode": cancelMode,
2565 }
2566 self.db.set_one(
2567 "nslcmops", q_filter=_filter, update_dict=update_dict, fail_on_empty=False
2568 )
2569 data = {
2570 "_id": nsLcmOpOccId,
2571 "nsInstanceId": nsInstanceId,
2572 "cancelMode": cancelMode,
2573 }
2574 self.msg.write("nslcmops", "cancel", data)
2575
tiernobee3bad2019-12-05 12:26:01 +00002576 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002577 raise EngineException(
2578 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2579 )
tiernob24258a2018-10-04 18:39:49 +02002580
tierno65ca36d2019-02-12 19:27:52 +01002581 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002582 raise EngineException(
2583 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2584 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002585
2586
2587class NsiTopic(BaseTopic):
2588 topic = "nsis"
2589 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002590 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002591
delacruzramo32bab472019-09-13 12:24:22 +02002592 def __init__(self, db, fs, msg, auth):
2593 BaseTopic.__init__(self, db, fs, msg, auth)
2594 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002595
Felipe Vicensc37b3842019-01-12 12:24:42 +01002596 @staticmethod
2597 def _format_ns_request(ns_request):
2598 formated_request = copy(ns_request)
2599 # TODO: Add request params
2600 return formated_request
2601
2602 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002603 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002604 """
2605 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002606 :param slice_request: User instantiation additional parameters
2607 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002608 """
tiernofd160572019-01-21 10:41:37 +00002609 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2610 if additional_params:
2611 for k, v in additional_params.items():
2612 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002613 raise EngineException(
2614 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2615 k
2616 )
2617 )
tiernofd160572019-01-21 10:41:37 +00002618 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002619 raise EngineException(
2620 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2621 k
2622 )
2623 )
tiernofd160572019-01-21 10:41:37 +00002624 if isinstance(v, (dict, tuple, list)):
2625 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002626 return additional_params
2627
tiernob4844ab2019-05-23 08:42:12 +00002628 def check_conflict_on_del(self, session, _id, db_content):
2629 """
2630 Check that NSI is not instantiated
2631 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2632 :param _id: nsi internal id
2633 :param db_content: The database content of the _id
2634 :return: None or raises EngineException with the conflict
2635 """
tierno65ca36d2019-02-12 19:27:52 +01002636 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002637 return
tiernob4844ab2019-05-23 08:42:12 +00002638 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002639 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002640 raise EngineException(
2641 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2642 "Launch 'terminate' operation first; or force deletion".format(_id),
2643 http_code=HTTPStatus.CONFLICT,
2644 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002645
tiernobee3bad2019-12-05 12:26:01 +00002646 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002647 """
tiernob4844ab2019-05-23 08:42:12 +00002648 Deletes associated nsilcmops from database. Deletes associated filesystem.
2649 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002650 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002651 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002652 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002653 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002654 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002655 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002656
Felipe Vicens09e65422019-01-22 15:06:46 +01002657 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002658 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002659 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2660 nsr_id = nsrs_detailed_item["nsrId"]
2661 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002662 _filter = {
2663 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2664 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2665 "_id.ne": nsir["_id"],
2666 }
2667 nsi = self.db.get_one(
2668 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2669 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002670 if nsi: # last one using nsr
2671 continue
2672 try:
garciadeblas4568a372021-03-24 09:19:48 +01002673 self.nsrTopic.delete(
2674 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2675 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002676 except (DbException, EngineException) as e:
2677 if e.http_code == HTTPStatus.NOT_FOUND:
2678 pass
2679 else:
2680 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002681
tiernob4844ab2019-05-23 08:42:12 +00002682 # delete related nsilcmops database entries
2683 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002684
tiernob4844ab2019-05-23 08:42:12 +00002685 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002686 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002687 if nsir_admin and nsir_admin.get("nst-id"):
2688 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002689 nsis_list = self.db.get_one(
2690 "nsis",
2691 {"nst-id": nsir_admin["nst-id"]},
2692 fail_on_empty=False,
2693 fail_on_more=False,
2694 )
tiernob4844ab2019-05-23 08:42:12 +00002695 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002696 self.db.set_one(
2697 "nsts",
2698 {"_id": nsir_admin["nst-id"]},
2699 {"_admin.usageState": "NOT_IN_USE"},
2700 )
tiernob4844ab2019-05-23 08:42:12 +00002701
tierno65ca36d2019-02-12 19:27:52 +01002702 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002703 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002704 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002705 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002706 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002707 :param indata: params to be used for the nsir
2708 :param kwargs: used to override the indata descriptor
2709 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002710 :return: the _id of nsi descriptor created at database
2711 """
2712
garciadeblasf2af4a12023-01-24 16:56:54 +01002713 step = "checking quotas" # first step must be defined outside try
Felipe Vicensb57758d2018-10-16 16:00:20 +02002714 try:
delacruzramo32bab472019-09-13 12:24:22 +02002715 self.check_quota(session)
2716
tierno99d4b172019-07-02 09:28:40 +00002717 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002718 slice_request = self._remove_envelop(indata)
2719 # Override descriptor with query string kwargs
2720 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002721 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002722
Felipe Vicensb57758d2018-10-16 16:00:20 +02002723 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002724 step = "getting nstd id='{}' from database".format(
2725 slice_request.get("nstId")
2726 )
tiernob4844ab2019-05-23 08:42:12 +00002727 _filter = self._get_project_filter(session)
2728 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002729 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002730 # check NST is not disabled
2731 step = "checking NST operationalState"
2732 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002733 raise EngineException(
2734 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2735 "instance".format(slice_request["nstId"]),
2736 http_code=HTTPStatus.CONFLICT,
2737 )
tiernob4844ab2019-05-23 08:42:12 +00002738 del _filter["_id"]
2739
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002740 # check NSD is not disabled
2741 step = "checking operationalState"
2742 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002743 raise EngineException(
2744 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2745 "a network slice".format(slice_request["nstId"]),
2746 http_code=HTTPStatus.CONFLICT,
2747 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002748
Felipe Vicens07f31722018-10-29 15:16:44 +01002749 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002750 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002751 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002752 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002753
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002754 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002755 nsi_descriptor = {
2756 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002757 "name": slice_request["nsiName"],
2758 "description": slice_request.get("nsiDescription", ""),
2759 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002760 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002761 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002762 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002763 "nsr-ref-list": [],
2764 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002765 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002766 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002767 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002768
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002769 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002770 self.format_on_new(
2771 nsi_descriptor, session["project_id"], make_public=session["public"]
2772 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002773 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2774 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002775 nsi_descriptor["_admin"]["deployed"] = {}
2776 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2777 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2778
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002779 # Creating netslice-vld for the RO.
2780 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002781
2782 # Building the vlds list to be deployed
2783 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002784 nsi_vlds = []
2785
2786 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2787 # Getting template Instantiation parameters from NST
2788 nsi_vld = deepcopy(netslice_vlds)
2789 nsi_vld["shared-nsrs-list"] = []
2790 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2791 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002792
2793 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002794 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002795 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002796 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002797
Felipe Vicens09e65422019-01-22 15:06:46 +01002798 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002799 for member_ns in nstd["netslice-subnet"]:
2800 nsd_id = member_ns["nsd-ref"]
2801 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002802 member_ns["nsd-ref"], member_ns["id"]
2803 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002804 if nsd_id not in needed_nsds:
2805 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002806 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002807 nsd = self.db.get_one(
2808 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2809 )
tiernob4844ab2019-05-23 08:42:12 +00002810 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002811 nsd.pop("_admin")
2812 needed_nsds[nsd_id] = nsd
2813 else:
2814 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002815 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2816 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002817
Felipe Vicensb57758d2018-10-16 16:00:20 +02002818 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002819 member_ns["nsd-ref"], member_ns["id"]
2820 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002821
Felipe Vicens07f31722018-10-29 15:16:44 +01002822 # creates Network Services records (NSRs)
2823 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002824 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002825 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002826 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002827 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002828 # Check if the netslice-subnet is shared and if it is share if the nss exists
2829 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002830 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002831 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002832 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002833 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2834 "nsd-ref"
2835 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002836 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002837 nsi = self.db.get_one(
2838 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2839 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002840 if nsi and service.get("is-shared-nss"):
2841 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2842 for nsrs_detailed_item in nsrs_detailed_list:
2843 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002844 if nsrs_detailed_item["nss-id"] == service["id"]:
2845 _id_nsr = nsrs_detailed_item["nsrId"]
2846 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002847 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2848 if netslice_subnet["nss-id"] == service["id"]:
2849 indata_ns = netslice_subnet
2850 break
2851 else:
2852 indata_ns = {}
2853 if service.get("instantiation-parameters"):
2854 indata_ns = deepcopy(service["instantiation-parameters"])
2855 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002856
Felipe Vicens09e65422019-01-22 15:06:46 +01002857 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002858 indata_ns["nsName"] = (
2859 slice_request.get("nsiName") + "." + service["id"]
2860 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002861 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2862 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002863 if slice_request.get("ssh_keys"):
2864 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002865
Felipe Vicens09e65422019-01-22 15:06:46 +01002866 if ns_params:
2867 for ns_param in ns_params:
2868 if ns_param.get("id") == service["id"]:
2869 copy_ns_param = deepcopy(ns_param)
2870 del copy_ns_param["id"]
2871 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002872 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002873
2874 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002875 _id_nsr, _ = self.nsrTopic.new(
2876 rollback, session, indata_ns, kwargs, headers
2877 )
2878 nsrs_item = {
2879 "nsrId": _id_nsr,
2880 "shared": service.get("is-shared-nss"),
2881 "nsd-id": service["nsd-ref"],
2882 "nss-id": service["id"],
2883 "nslcmop_instantiate": None,
2884 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002885 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002886 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002887 nsi_netslice_subnet.append(indata_ns)
2888 nsr_ref = {"nsr-ref": _id_nsr}
2889 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002890
2891 # Adding the nsrs list to the nsi
2892 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002893 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002894 self.db.set_one(
2895 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2896 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002897
Felipe Vicens07f31722018-10-29 15:16:44 +01002898 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002899 self.db.create("nsis", nsi_descriptor)
2900 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002901 return nsi_id, None
garciadeblasf2af4a12023-01-24 16:56:54 +01002902 except ValidationError as e:
2903 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
garciadeblas4568a372021-03-24 09:19:48 +01002904 except Exception as e: # TODO remove try Except, it is captured at nbi.py
rshri2d386cb2024-07-05 14:35:51 +00002905 # self.logger.exception(
2906 # "Exception {} at NsiTopic.new()".format(e), exc_info=True
2907 # )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002908 raise EngineException("Error {}: {}".format(step, e))
Felipe Vicensb57758d2018-10-16 16:00:20 +02002909
tierno65ca36d2019-02-12 19:27:52 +01002910 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002911 raise EngineException(
2912 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2913 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002914
2915
2916class NsiLcmOpTopic(BaseTopic):
2917 topic = "nsilcmops"
2918 topic_msg = "nsi"
2919 operation_schema = { # mapping between operation and jsonschema to validate
2920 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002921 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002922 }
garciadeblas4568a372021-03-24 09:19:48 +01002923
delacruzramo32bab472019-09-13 12:24:22 +02002924 def __init__(self, db, fs, msg, auth):
2925 BaseTopic.__init__(self, db, fs, msg, auth)
2926 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002927
2928 def _check_nsi_operation(self, session, nsir, operation, indata):
2929 """
2930 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002931 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002932 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2933 :param indata: descriptor with the parameters of the operation
2934 :return: None
2935 """
2936 nsds = {}
2937 nstd = nsir["network-slice-template"]
2938
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002939 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002940 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002941 for netslice_subnet in nstd["netslice-subnet"]:
2942 if nstId == netslice_subnet["id"]:
2943 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002944 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002945 _filter = self._get_project_filter(session)
2946 _filter["id"] = nsd_id
2947 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002948 return nsds[nsd_id]
2949 else:
garciadeblas4568a372021-03-24 09:19:48 +01002950 raise EngineException(
2951 "Invalid parameter nstId='{}' is not one of the "
2952 "nst:netslice-subnet".format(nstId)
2953 )
2954
Felipe Vicens07f31722018-10-29 15:16:44 +01002955 if operation == "instantiate":
2956 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002957 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002958 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002959
2960 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2961 now = time()
2962 _id = str(uuid4())
2963 nsilcmop = {
2964 "id": _id,
2965 "_id": _id,
2966 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2967 "statusEnteredTime": now,
2968 "netsliceInstanceId": netsliceInstanceId,
2969 "lcmOperationType": operation,
2970 "startTime": now,
2971 "isAutomaticInvocation": False,
2972 "operationParams": params,
2973 "isCancelPending": False,
2974 "links": {
2975 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002976 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2977 + netsliceInstanceId,
2978 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002979 }
2980 return nsilcmop
2981
Felipe Vicens09e65422019-01-22 15:06:46 +01002982 def add_shared_nsr_2vld(self, nsir, nsr_item):
2983 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2984 if nst_sb_item.get("is-shared-nss"):
2985 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2986 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2987 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002988 for admin_vld_nss_cp_ref_item in admin_vld_item[
2989 "nss-connection-point-ref"
2990 ]:
2991 if (
2992 admin_subnet_item["nss-id"]
2993 == admin_vld_nss_cp_ref_item["nss-ref"]
2994 ):
2995 if (
2996 not nsr_item["nsrId"]
2997 in admin_vld_item["shared-nsrs-list"]
2998 ):
2999 admin_vld_item["shared-nsrs-list"].append(
3000 nsr_item["nsrId"]
3001 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003002 break
3003 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01003004 self.db.set_one(
3005 "nsis",
3006 {"_id": nsir["_id"]},
3007 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
3008 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003009
tierno65ca36d2019-02-12 19:27:52 +01003010 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01003011 """
3012 Performs a new operation over a ns
3013 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01003014 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01003015 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02003016 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01003017 operation: it can be: instantiate, terminate, action, TODO: update, heal
3018 :param kwargs: used to override the indata descriptor
3019 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01003020 :return: id of the nslcmops
3021 """
3022 try:
3023 # Override descriptor with query string kwargs
3024 self._update_input_with_kwargs(indata, kwargs)
3025 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02003026 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01003027 validate_input(indata, self.operation_schema[operation])
3028
Felipe Vicens126af572019-06-05 19:13:04 +02003029 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00003030 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02003031 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01003032 nsir = self.db.get_one("nsis", _filter)
rshri2d386cb2024-07-05 14:35:51 +00003033 # logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00003034 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01003035
3036 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01003037 if (
3038 not nsir["_admin"].get("nsiState")
3039 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
3040 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01003041 if operation == "terminate" and indata.get("autoremove"):
3042 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01003043 return (
3044 None,
3045 None,
3046 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01003047 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01003048 raise EngineException(
3049 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
3050 netsliceInstanceId, operation
3051 ),
3052 HTTPStatus.CONFLICT,
3053 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003054 else:
tierno65ca36d2019-02-12 19:27:52 +01003055 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01003056 raise EngineException(
3057 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
3058 netsliceInstanceId, operation
3059 ),
3060 HTTPStatus.CONFLICT,
3061 )
3062
Felipe Vicens07f31722018-10-29 15:16:44 +01003063 # Creating all the NS_operation (nslcmop)
3064 # Get service list from db
3065 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
3066 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01003067 # nslcmops_item = None
3068 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00003069 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01003070 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003071 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00003072 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01003073 _filter[
3074 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
3075 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02003076 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01003077 nsi = self.db.get_one(
3078 "nsis", _filter, fail_on_empty=False, fail_on_more=False
3079 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003080 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01003081 _update = {
3082 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3083 index
3084 ): None
3085 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003086 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01003087 if (
3088 nsi
3089 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00003090 continue # do not create nsilcmop
3091 else: # instantiate
3092 # looks the first nsi fulfilling the conditions but not being the current NSIR
3093 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01003094 nsi_nsr_item = next(
3095 n
3096 for n in nsi["_admin"]["nsrs-detailed-list"]
3097 if n["nsrId"] == nsr_id
3098 and n["shared"]
3099 and n["nslcmop_instantiate"]
3100 )
tierno40f742b2020-06-23 15:25:26 +00003101 self.add_shared_nsr_2vld(nsir, nsr_item)
3102 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01003103 _update = {
3104 "_admin.nsrs-detailed-list.{}".format(
3105 index
3106 ): nsi_nsr_item
3107 }
tierno40f742b2020-06-23 15:25:26 +00003108 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
3109 # continue to not create nslcmop since nsrs is shared and nsrs was created
3110 continue
3111 else:
3112 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01003113
tierno40f742b2020-06-23 15:25:26 +00003114 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01003115 try:
tierno0b8752f2020-05-12 09:42:02 +00003116 indata_ns = {
3117 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00003118 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00003119 # Including netslice_id in the ns instantiate Operation
3120 "netsliceInstanceId": netsliceInstanceId,
3121 }
3122 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00003123 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00003124 indata_ns.update(service["instantiate_params"])
3125
tierno99d4b172019-07-02 09:28:40 +00003126 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01003127 # message via kafka bus
Adurti87c0e4b2024-07-16 07:33:42 +00003128 nslcmop, _, _ = self.nsi_NsLcmOpTopic.new(
garciadeblas4568a372021-03-24 09:19:48 +01003129 rollback, session, indata_ns, None, headers, slice_object=True
3130 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003131 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00003132 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01003133 _update = {
3134 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3135 index
3136 ): nslcmop
3137 }
tierno40f742b2020-06-23 15:25:26 +00003138 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01003139 except (DbException, EngineException) as e:
3140 if e.http_code == HTTPStatus.NOT_FOUND:
Felipe Vicens09e65422019-01-22 15:06:46 +01003141 pass
3142 else:
3143 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01003144
3145 # Creates nsilcmop
3146 indata["nslcmops_ids"] = nslcmops
3147 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01003148
garciadeblas4568a372021-03-24 09:19:48 +01003149 nsilcmop_desc = self._create_nsilcmop(
3150 session, netsliceInstanceId, operation, indata
3151 )
3152 self.format_on_new(
3153 nsilcmop_desc, session["project_id"], make_public=session["public"]
3154 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003155 _id = self.db.create("nsilcmops", nsilcmop_desc)
3156 rollback.append({"topic": "nsilcmops", "_id": _id})
3157 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00003158 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01003159 except ValidationError as e:
3160 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01003161
tiernobee3bad2019-12-05 12:26:01 +00003162 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01003163 raise EngineException(
3164 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3165 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003166
tierno65ca36d2019-02-12 19:27:52 +01003167 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01003168 raise EngineException(
3169 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3170 )