blob: 6308e56b7f31616dc8554aad4179035115388d29 [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
Frank Bryden3c64ab62020-07-21 14:25:32 +0000377 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300378 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000379
tiernob24258a2018-10-04 18:39:49 +0200380 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300381 nsr_id = str(uuid4())
garciadeblas4568a372021-03-24 09:19:48 +0100382 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
383 nsd, ns_request, nsr_id, session
384 )
tierno54db2e42020-04-06 15:29:42 +0000385
garciaale7cbd03c2020-11-27 10:38:35 -0300386 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200387 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300388 # TODO: Change for multiple df support
K Sai Kiranbb006022021-05-20 11:09:49 +0530389 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
garciaale7cbd03c2020-11-27 10:38:35 -0300390 for vnfp in vnf_profiles:
391 vnfd_id = vnfp.get("vnfd-id")
392 vnf_index = vnfp.get("id")
garciadeblas4568a372021-03-24 09:19:48 +0100393 step = (
394 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
395 vnfd_id, vnf_index
396 )
397 )
tiernob24258a2018-10-04 18:39:49 +0200398 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300399 vnfd = self._get_vnfd_from_db(vnfd_id, session)
beierlmcee2ebf2022-03-29 17:42:48 -0400400 if "revision" in vnfd["_admin"]:
401 vnfd["revision"] = vnfd["_admin"]["revision"]
402 vnfd.pop("_admin")
tiernob24258a2018-10-04 18:39:49 +0200403 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000404 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200405 else:
406 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100407
garciadeblas4568a372021-03-24 09:19:48 +0100408 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
409 vnfd_id, vnf_index
410 )
411 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
412 nsd,
413 vnfd,
414 vnfd_id,
415 vnf_index,
416 nsr_descriptor,
417 ns_request,
418 ns_k8s_namespace,
419 )
tierno36ec8602018-11-02 17:27:11 +0100420
garciadeblas4568a372021-03-24 09:19:48 +0100421 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
422 vnfd_id, vnf_index
423 )
garciaale7cbd03c2020-11-27 10:38:35 -0300424 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
425 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
aticig2b5e1232022-08-10 17:30:12 +0300426 step = "Updating VNFD usageState"
427 update_descriptor_usage_state(vnfd, "vnfds", self.db)
tiernob24258a2018-10-04 18:39:49 +0200428
429 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300430 self._add_nsr_to_db(nsr_descriptor, rollback, session)
aticig2b5e1232022-08-10 17:30:12 +0300431 step = "Updating NSD usageState"
432 update_descriptor_usage_state(nsd, "nsds", self.db)
tiernobee085c2018-12-12 17:03:04 +0000433
434 step = "creating nsr temporal folder"
435 self.fs.mkdir(nsr_id)
436
tiernobdebce92019-07-01 15:36:49 +0000437 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100438 except (
439 ValidationError,
440 EngineException,
441 DbException,
442 MsgException,
443 FsException,
444 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000445 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200446
garciaale7cbd03c2020-11-27 10:38:35 -0300447 def _get_nsd_from_db(self, nsd_id, session):
448 _filter = self._get_project_filter(session)
449 _filter["_id"] = nsd_id
450 return self.db.get_one("nsds", _filter)
451
kayal2001f71c2e82024-06-25 15:26:24 +0530452 def _get_nsConfigTemplate_from_db(self, nsConfigTemplate_id, session):
453 _filter = self._get_project_filter(session)
454 _filter["_id"] = nsConfigTemplate_id
455 ns_config_template_db = self.db.get_one(
456 "ns_config_template", _filter, fail_on_empty=False
457 )
458 return ns_config_template_db
459
garciaale7cbd03c2020-11-27 10:38:35 -0300460 def _get_vnfd_from_db(self, vnfd_id, session):
461 _filter = self._get_project_filter(session)
462 _filter["id"] = vnfd_id
463 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
garciaale7cbd03c2020-11-27 10:38:35 -0300464 return vnfd
465
466 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100467 self.format_on_new(
468 nsr_descriptor, session["project_id"], make_public=session["public"]
469 )
garciaale7cbd03c2020-11-27 10:38:35 -0300470 self.db.create("nsrs", nsr_descriptor)
471 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
472
473 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100474 self.format_on_new(
475 vnfr_descriptor, session["project_id"], make_public=session["public"]
476 )
garciaale7cbd03c2020-11-27 10:38:35 -0300477 self.db.create("vnfrs", vnfr_descriptor)
478 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
479
480 def _check_nsd_operational_state(self, nsd, ns_request):
481 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100482 raise EngineException(
483 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
484 "a network service".format(ns_request["nsdId"]),
485 http_code=HTTPStatus.CONFLICT,
486 )
garciaale7cbd03c2020-11-27 10:38:35 -0300487
kayal2001f71c2e82024-06-25 15:26:24 +0530488 def _check_ns_config_template_operational_state(
489 self, ns_config_template_db, ns_request
490 ):
491 if ns_config_template_db["_admin"]["operationalState"] == "DISABLED":
492 raise EngineException(
493 "ns_config_template with id '{}' is DISABLED, and thus cannot be used to create "
494 "a network service".format(ns_request["nsConfigTemplateId"]),
495 http_code=HTTPStatus.CONFLICT,
496 )
497
garciaale7cbd03c2020-11-27 10:38:35 -0300498 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100499 additional_params, _ = self._format_additional_params(
500 ns_request, descriptor=nsd
501 )
garciaale7cbd03c2020-11-27 10:38:35 -0300502 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
503 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
504 if ns_request and ns_request.get("k8s-namespace"):
505 ns_k8s_namespace = ns_request["k8s-namespace"]
506 if additional_params and additional_params.get("k8s-namespace"):
507 ns_k8s_namespace = additional_params["k8s-namespace"]
508
509 return ns_k8s_namespace
510
vegall18101ea2023-03-06 13:49:21 +0000511 def _add_shared_volumes_to_nsr(
512 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
513 ):
514 svsd = []
515 for vsd in vnfd.get("virtual-storage-desc", ()):
516 if vsd.get("vdu-storage-requirements"):
517 if (
518 vsd.get("vdu-storage-requirements")[0].get("key") == "multiattach"
519 and vsd.get("vdu-storage-requirements")[0].get("value") == "True"
520 ):
vegallf976a3a2023-06-02 21:25:32 +0000521 # Avoid setting the volume name multiple times
522 if not match(f"shared-.*-{vnfd['id']}", vsd["id"]):
vegall18101ea2023-03-06 13:49:21 +0000523 vsd["id"] = f"shared-{vsd['id']}-{vnfd['id']}"
524 svsd.append(vsd)
525 if svsd:
526 nsr_descriptor["shared-volumes"] = svsd
527
garciadeblasf2af4a12023-01-24 16:56:54 +0100528 def _add_flavor_to_nsr(
529 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
530 ):
elumalai6c5ea6b2022-04-25 22:27:59 +0530531 flavor_data = {}
532 guest_epa = {}
533 # Find this vdu compute and storage descriptors
534 vdu_virtual_compute = {}
535 vdu_virtual_storage = {}
536 for vcd in vnfd.get("virtual-compute-desc", ()):
537 if vcd.get("id") == vdu.get("virtual-compute-desc"):
538 vdu_virtual_compute = vcd
539 for vsd in vnfd.get("virtual-storage-desc", ()):
540 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
541 vdu_virtual_storage = vsd
542 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblasf2af4a12023-01-24 16:56:54 +0100543 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
elumalai6c5ea6b2022-04-25 22:27:59 +0530544 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
545 "num-virtual-cpu"
546 ]
547 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
548 flavor_data["memory-mb"] = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100549 float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
elumalai6c5ea6b2022-04-25 22:27:59 +0530550 )
551 if vdu_virtual_storage.get("size-of-storage"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100552 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530553 # Get this vdu EPA info for guest_epa
554 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100555 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530556 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
557 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
558 if vcpu_pinning.get("thread-policy"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100559 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530560 if vcpu_pinning.get("policy"):
561 cpu_policy = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100562 "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
elumalai6c5ea6b2022-04-25 22:27:59 +0530563 )
564 guest_epa["cpu-pinning-policy"] = cpu_policy
565 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100566 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
567 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
568 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"][
569 "mempage-size"
elumalai6c5ea6b2022-04-25 22:27:59 +0530570 ]
garciadeblasf2af4a12023-01-24 16:56:54 +0100571 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
572 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"][
573 "numa-node-policy"
574 ]
elumalai6c5ea6b2022-04-25 22:27:59 +0530575 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100576 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530577
578 if guest_epa:
579 flavor_data["guest-epa"] = guest_epa
580
elumalai99078a92022-07-05 17:53:59 +0530581 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +0100582 flavor_data["name"] = (
583 vdu["id"][:56] + "-" + member_vnf_index + "-" + str(revision) + "-flv"
584 )
elumalai6c5ea6b2022-04-25 22:27:59 +0530585 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
586 nsr_descriptor["flavor"].append(flavor_data)
587
bravofe76b8822021-02-26 16:57:52 -0300588 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300589 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100590 additional_params, _ = self._format_additional_params(
591 ns_request, descriptor=nsd
592 )
garciaale7cbd03c2020-11-27 10:38:35 -0300593
594 nsr_descriptor = {
595 "name": ns_request["nsName"],
596 "name-ref": ns_request["nsName"],
597 "short-name": ns_request["nsName"],
598 "admin-status": "ENABLED",
599 "nsState": "NOT_INSTANTIATED",
600 "currentOperation": "IDLE",
601 "currentOperationID": None,
602 "errorDescription": None,
603 "errorDetail": None,
604 "deploymentStatus": None,
605 "configurationStatus": None,
606 "vcaStatus": None,
607 "nsd": {k: v for k, v in nsd.items()},
608 "datacenter": ns_request["vimAccountId"],
609 "resource-orchestrator": "osmopenmano",
610 "description": ns_request.get("nsDescription", ""),
611 "constituent-vnfr-ref": [],
612 "operational-status": "init", # typedef ns-operational-
613 "config-status": "init", # typedef config-states
614 "detailed-status": "scheduled",
615 "orchestration-progress": {},
616 "create-time": now,
617 "nsd-name-ref": nsd["name"],
618 "operational-events": [], # "id", "timestamp", "description", "event",
619 "nsd-ref": nsd["id"],
620 "nsd-id": nsd["_id"],
621 "vnfd-id": [],
622 "instantiate_params": self._format_ns_request(ns_request),
623 "additionalParamsForNs": additional_params,
624 "ns-instance-config-ref": nsr_id,
625 "id": nsr_id,
626 "_id": nsr_id,
627 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
628 "flavor": [],
629 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100630 "affinity-or-anti-affinity-group": [],
vegall18101ea2023-03-06 13:49:21 +0000631 "shared-volumes": [],
selvi.j828f3f22023-05-16 05:43:48 +0000632 "vnffgd": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300633 }
beierlmbc5a5242022-05-17 21:25:29 -0400634 if "revision" in nsd["_admin"]:
635 nsr_descriptor["revision"] = nsd["_admin"]["revision"]
636
garciaale7cbd03c2020-11-27 10:38:35 -0300637 ns_request["nsr_id"] = nsr_id
638 if ns_request and ns_request.get("config-units"):
639 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300640 # Create vld
641 if nsd.get("virtual-link-desc"):
642 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
643 # Fill each vld with vnfd-connection-point-ref data
644 # TODO: Change for multiple df support
645 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
646 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
647 for vnf_profile in vnf_profiles:
648 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
649 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100650 all_vld_connection_point_data[
651 vlc.get("virtual-link-profile-id")
652 ].append(
653 {
654 "member-vnf-index-ref": cpd.get(
655 "constituent-base-element-id"
656 ),
657 "vnfd-connection-point-ref": cpd.get(
658 "constituent-cpd-id"
659 ),
660 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
661 }
662 )
garciaale7cbd03c2020-11-27 10:38:35 -0300663
bravofe76b8822021-02-26 16:57:52 -0300664 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400665 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300666
667 for vdu in vnfd.get("vdu", ()):
elumalai99078a92022-07-05 17:53:59 +0530668 member_vnf_index = vnf_profile.get("id")
669 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor, member_vnf_index)
vegall18101ea2023-03-06 13:49:21 +0000670 self._add_shared_volumes_to_nsr(
671 vdu, vnfd, nsr_descriptor, member_vnf_index
672 )
garciaale7cbd03c2020-11-27 10:38:35 -0300673 sw_image_id = vdu.get("sw-image-desc")
674 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000675 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
676 self._add_image_to_nsr(nsr_descriptor, image_data)
677
678 # also add alternative images to the list of images
679 for alt_image in vdu.get("alternative-sw-image-desc", ()):
680 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
681 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300682
Alexis Romero03fb5842022-03-11 15:53:40 +0100683 # Add Affinity or Anti-affinity group information to NSR
684 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200685 affinity_group_prefix_name = "{}-{}".format(
686 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
687 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100688
689 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200690 affinity_group_data = {}
691 for affinity_group in vdu_profile.get(
692 "affinity-or-anti-affinity-group", ()
693 ):
694 affinity_group_data = (
695 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
696 vnfd, affinity_group["id"]
697 )
698 )
699 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
700 self._add_affinity_or_anti_affinity_group_to_nsr(
701 nsr_descriptor,
702 affinity_group_data,
703 affinity_group_prefix_name,
704 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100705
garciaale7cbd03c2020-11-27 10:38:35 -0300706 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100707 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
708 vld.get("id"), []
709 )
garciaale7cbd03c2020-11-27 10:38:35 -0300710 vld["name"] = vld["id"]
711 nsr_descriptor["vld"] = nsr_vld
selvi.j828f3f22023-05-16 05:43:48 +0000712 if nsd.get("vnffgd"):
713 vnffgd = nsd.get("vnffgd")
714 for vnffg in vnffgd:
715 info = {}
716 for k, v in vnffg.items():
717 if k == "id":
718 info.update({k: v})
719 if k == "nfpd":
720 info.update({k: v})
721 nsr_descriptor["vnffgd"].append(info)
722
garciaale7cbd03c2020-11-27 10:38:35 -0300723 return nsr_descriptor
724
Alexis Romeroee31f532022-04-26 19:10:21 +0200725 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
726 self, vnfd, affinity_group_id
727 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100728 """
729 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
730 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200731 affinity_group = utils.find_in_list(
732 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
733 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100734 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200735 affinity_group_data = {}
736 if affinity_group:
737 if affinity_group.get("id"):
738 affinity_group_data["ag-id"] = affinity_group["id"]
739 if affinity_group.get("type"):
740 affinity_group_data["type"] = affinity_group["type"]
741 if affinity_group.get("scope"):
742 affinity_group_data["scope"] = affinity_group["scope"]
743 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100744
Alexis Romeroee31f532022-04-26 19:10:21 +0200745 def _add_affinity_or_anti_affinity_group_to_nsr(
746 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
747 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100748 """
749 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
750 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200751 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100752 (
753 f
754 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200755 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100756 ),
757 None,
758 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200759 if not affinity_group:
760 affinity_group_data["id"] = str(
761 len(nsr_descriptor["affinity-or-anti-affinity-group"])
762 )
763 affinity_group_data["name"] = "{}-{}".format(
764 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
765 )
766 nsr_descriptor["affinity-or-anti-affinity-group"].append(
767 affinity_group_data
768 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100769
lloretgalleg28c13b62021-02-08 11:48:48 +0000770 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100771 sw_image_desc = utils.find_in_list(
772 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
773 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000774 image_data = {}
775 if sw_image_desc.get("image"):
776 image_data["image"] = sw_image_desc["image"]
777 if sw_image_desc.get("checksum"):
778 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
779 if sw_image_desc.get("vim-type"):
780 image_data["vim-type"] = sw_image_desc["vim-type"]
781 return image_data
782
783 def _add_image_to_nsr(self, nsr_descriptor, image_data):
784 """
785 Adds image to nsr checking first it is not already added
786 """
garciadeblas4568a372021-03-24 09:19:48 +0100787 img = next(
788 (
789 f
790 for f in nsr_descriptor["image"]
791 if all(f.get(k) == image_data[k] for k in image_data)
792 ),
793 None,
794 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000795 if not img:
796 image_data["id"] = str(len(nsr_descriptor["image"]))
797 nsr_descriptor["image"].append(image_data)
798
garciadeblas4568a372021-03-24 09:19:48 +0100799 def _create_vnfr_descriptor_from_vnfd(
800 self,
801 nsd,
802 vnfd,
803 vnfd_id,
804 vnf_index,
805 nsr_descriptor,
806 ns_request,
807 ns_k8s_namespace,
elumalai99078a92022-07-05 17:53:59 +0530808 revision=None,
garciadeblas4568a372021-03-24 09:19:48 +0100809 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300810 vnfr_id = str(uuid4())
811 nsr_id = nsr_descriptor["id"]
812 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100813 additional_params, vnf_params = self._format_additional_params(
814 ns_request, vnf_index, descriptor=vnfd
815 )
garciaale7cbd03c2020-11-27 10:38:35 -0300816
817 vnfr_descriptor = {
818 "id": vnfr_id,
819 "_id": vnfr_id,
820 "nsr-id-ref": nsr_id,
821 "member-vnf-index-ref": vnf_index,
822 "additionalParamsForVnf": additional_params,
823 "created-time": now,
824 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
825 "vnfd-ref": vnfd_id,
826 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
827 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200828 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300829 "vdur": [],
830 "connection-point": [],
831 "ip-address": None, # mgmt-interface filled by LCM
832 }
beierlmcee2ebf2022-03-29 17:42:48 -0400833
834 # Revision backwards compatility. Only specify the revision in the record if
835 # the original VNFD has a revision.
836 if "revision" in vnfd:
837 vnfr_descriptor["revision"] = vnfd["revision"]
838
garciaale7cbd03c2020-11-27 10:38:35 -0300839 vnf_k8s_namespace = ns_k8s_namespace
840 if vnf_params:
841 if vnf_params.get("k8s-namespace"):
842 vnf_k8s_namespace = vnf_params["k8s-namespace"]
843 if vnf_params.get("config-units"):
844 vnfr_descriptor["config-units"] = vnf_params["config-units"]
845
846 # Create vld
847 if vnfd.get("int-virtual-link-desc"):
848 vnfr_descriptor["vld"] = []
849 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
850 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
851
852 for cp in vnfd.get("ext-cpd", ()):
853 vnf_cp = {
854 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100855 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
856 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300857 "id": cp.get("id"),
858 # "ip-address", "mac-address" # filled by LCM
859 # vim-id # TODO it would be nice having a vim port id
860 }
861 vnfr_descriptor["connection-point"].append(vnf_cp)
862
863 # Create k8s-cluster information
864 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
865 if vnfd.get("k8s-cluster"):
866 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
867 all_k8s_cluster_nets_cpds = {}
868 for cpd in get_iterable(vnfd.get("ext-cpd")):
869 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100870 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
871 "id"
872 )
garciaale7cbd03c2020-11-27 10:38:35 -0300873 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
874 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100875 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
876 net.get("id")
877 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300878
879 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300880 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100881 additional_params, kdu_params = self._format_additional_params(
882 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
883 )
garciaale7cbd03c2020-11-27 10:38:35 -0300884 kdu_k8s_namespace = vnf_k8s_namespace
885 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
886 if kdu_params and kdu_params.get("k8s-namespace"):
887 kdu_k8s_namespace = kdu_params["k8s-namespace"]
888
romeromonserbfebfc02021-05-28 10:51:35 +0200889 kdu_deployment_name = ""
890 if kdu_params and kdu_params.get("kdu-deployment-name"):
891 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
892
garciaale7cbd03c2020-11-27 10:38:35 -0300893 kdur = {
894 "additionalParams": additional_params,
895 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200896 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000897 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300898 # TODO "name": "" Name of the VDU in the VIM
899 "ip-address": None, # mgmt-interface filled by LCM
900 "k8s-cluster": {},
901 }
902 if kdu_params and kdu_params.get("config-units"):
903 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000904 if kdu.get("helm-version"):
905 kdur["helm-version"] = kdu["helm-version"]
906 for k8s_type in ("helm-chart", "juju-bundle"):
907 if kdu.get(k8s_type):
908 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300909 if not vnfr_descriptor.get("kdur"):
910 vnfr_descriptor["kdur"] = []
911 vnfr_descriptor["kdur"].append(kdur)
912
913 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300914
garciaale7cbd03c2020-11-27 10:38:35 -0300915 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300916 vdu_mgmt_cp = []
917 try:
garciadeblas4568a372021-03-24 09:19:48 +0100918 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
919 "operate-vnf-op-config"
920 ]["day1-2"]
921 vdu_config = utils.find_in_list(
922 configs, lambda config: config["id"] == vdu["id"]
923 )
bravoff3c39552021-02-24 17:22:24 -0300924 except Exception:
925 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400926
927 try:
928 vdu_instantiation_level = utils.find_in_list(
929 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100930 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400931 )
932 except Exception:
933 vdu_instantiation_level = None
934
bravoff3c39552021-02-24 17:22:24 -0300935 if vdu_config:
936 external_connection_ee = utils.filter_in_list(
937 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100938 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300939 )
940 for ee in external_connection_ee:
941 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
942
garciaale7cbd03c2020-11-27 10:38:35 -0300943 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100944 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
945 )
bravof65e22e52021-11-10 17:58:58 -0300946
947 try:
948 vdu_virtual_storage_descriptors = utils.filter_in_list(
949 vnfd.get("virtual-storage-desc", []),
garciadeblasf2af4a12023-01-24 16:56:54 +0100950 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"],
bravof65e22e52021-11-10 17:58:58 -0300951 )
952 except Exception:
953 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300954 vdur = {
955 "vdu-id-ref": vdu["id"],
956 # TODO "name": "" Name of the VDU in the VIM
957 "ip-address": None, # mgmt-interface filled by LCM
958 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
959 "internal-connection-point": [],
960 "interfaces": [],
961 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100962 "vdu-name": vdu["name"],
garciadeblasf2af4a12023-01-24 16:56:54 +0100963 "virtual-storages": vdu_virtual_storage_descriptors,
garciaale7cbd03c2020-11-27 10:38:35 -0300964 }
965 if vdu_params and vdu_params.get("config-units"):
966 vdur["config-units"] = vdu_params["config-units"]
967 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100968 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
969 "boot-data-drive"
970 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300971 if vdu.get("pdu-type"):
972 vdur["pdu-type"] = vdu["pdu-type"]
973 vdur["name"] = vdu["pdu-type"]
974 # TODO volumes: name, volume-id
975 for icp in vdu.get("int-cpd", ()):
976 vdu_icp = {
977 "id": icp["id"],
978 "connection-point-id": icp["id"],
979 "name": icp.get("id"),
980 }
bravof35766442021-02-04 14:58:04 -0300981
garciaale7cbd03c2020-11-27 10:38:35 -0300982 vdur["internal-connection-point"].append(vdu_icp)
983
984 for iface in icp.get("virtual-network-interface-requirement", ()):
aticigc9c03392022-06-16 01:39:44 +0300985 # Name, mac-address and interface position is taken from VNFD
986 # and included into VNFR. By this way RO can process this information
987 # while creating the VDU.
Gulsum Atici9af2a472023-03-28 17:50:48 +0300988 iface_fields = ("name", "mac-address", "position", "ip-address")
garciadeblas4568a372021-03-24 09:19:48 +0100989 vdu_iface = {
990 x: iface[x] for x in iface_fields if iface.get(x) is not None
991 }
garciaale7cbd03c2020-11-27 10:38:35 -0300992
993 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100994 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100995 vdu_iface["port-security-enabled"] = icp[
996 "port-security-enabled"
997 ]
sousaedu003844e2021-03-02 00:19:15 +0100998
999 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +01001000 vdu_iface["port-security-disable-strategy"] = icp[
1001 "port-security-disable-strategy"
1002 ]
sousaedu003844e2021-03-02 00:19:15 +01001003
garciaale7cbd03c2020-11-27 10:38:35 -03001004 for ext_cp in vnfd.get("ext-cpd", ()):
1005 if not ext_cp.get("int-cpd"):
1006 continue
1007 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
1008 continue
1009 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +01001010 vdu_iface["external-connection-point-ref"] = ext_cp.get(
1011 "id"
1012 )
sousaedu003844e2021-03-02 00:19:15 +01001013
1014 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +01001015 vdu_iface["port-security-enabled"] = ext_cp[
1016 "port-security-enabled"
1017 ]
sousaedu003844e2021-03-02 00:19:15 +01001018
1019 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +01001020 vdu_iface["port-security-disable-strategy"] = ext_cp[
1021 "port-security-disable-strategy"
1022 ]
sousaedu003844e2021-03-02 00:19:15 +01001023
garciaale7cbd03c2020-11-27 10:38:35 -03001024 break
1025
garciadeblas4568a372021-03-24 09:19:48 +01001026 if (
1027 vnfd_mgmt_cp
1028 and vdu_iface.get("external-connection-point-ref")
1029 == vnfd_mgmt_cp
1030 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001031 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -03001032 vdu_iface["mgmt-interface"] = True
1033
1034 for ecp in vdu_mgmt_cp:
1035 if vdu_iface.get("external-connection-point-ref") == ecp:
1036 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001037
1038 if iface.get("virtual-interface"):
1039 vdu_iface.update(deepcopy(iface["virtual-interface"]))
1040
1041 # look for network where this interface is connected
1042 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
1043 if iface_ext_cp:
1044 # TODO: Change for multiple df support
1045 for df in get_iterable(nsd.get("df")):
1046 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +01001047 for vlc_index, vlc in enumerate(
1048 get_iterable(
1049 vnf_profile.get("virtual-link-connectivity")
1050 )
1051 ):
1052 for cpd in get_iterable(
1053 vlc.get("constituent-cpd-id")
1054 ):
1055 if (
1056 cpd.get("constituent-cpd-id")
1057 == iface_ext_cp
Pedro Escaleira4606e4a2023-05-31 14:32:17 +01001058 ) and vnf_profile.get("id") == vnf_index:
garciadeblas4568a372021-03-24 09:19:48 +01001059 vdu_iface["ns-vld-id"] = vlc.get(
1060 "virtual-link-profile-id"
1061 )
garciadeblas61c95912021-02-12 11:23:50 +00001062 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +01001063 if vdu_iface.get("type") in (
1064 "SR-IOV",
1065 "PCI-PASSTHROUGH",
1066 ):
1067 nsr_descriptor["vld"][vlc_index][
1068 "pci-interfaces"
1069 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001070 break
1071 elif vdu_iface.get("internal-connection-point-ref"):
1072 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +00001073 # TODO: store fixed IP address in the record (if it exists in the ICP)
1074 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
1075 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +01001076 ivld_index = utils.find_index_in_list(
1077 vnfd.get("int-virtual-link-desc", ()),
1078 lambda ivld: ivld["id"]
1079 == icp.get("int-virtual-link-desc"),
1080 )
garciadeblas61c95912021-02-12 11:23:50 +00001081 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001082
1083 vdur["interfaces"].append(vdu_iface)
1084
1085 if vdu.get("sw-image-desc"):
1086 sw_image = utils.find_in_list(
1087 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001088 lambda image: image["id"] == vdu.get("sw-image-desc"),
1089 )
garciaale7cbd03c2020-11-27 10:38:35 -03001090 nsr_sw_image_data = utils.find_in_list(
1091 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001092 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -03001093 )
1094 vdur["ns-image-id"] = nsr_sw_image_data["id"]
1095
lloretgalleg28c13b62021-02-08 11:48:48 +00001096 if vdu.get("alternative-sw-image-desc"):
1097 alt_image_ids = []
1098 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1099 sw_image = utils.find_in_list(
1100 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001101 lambda image: image["id"] == alt_image_id,
1102 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001103 nsr_sw_image_data = utils.find_in_list(
1104 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001105 lambda nsr_image: (
1106 nsr_image.get("image") == sw_image.get("image")
1107 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001108 )
1109 alt_image_ids.append(nsr_sw_image_data["id"])
1110 vdur["alt-image-ids"] = alt_image_ids
1111
elumalai99078a92022-07-05 17:53:59 +05301112 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +01001113 flavor_data_name = (
1114 vdu["id"][:56] + "-" + vnf_index + "-" + str(revision) + "-flv"
1115 )
garciaale7cbd03c2020-11-27 10:38:35 -03001116 nsr_flavor_desc = utils.find_in_list(
1117 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001118 lambda flavor: flavor["name"] == flavor_data_name,
1119 )
garciaale7cbd03c2020-11-27 10:38:35 -03001120
1121 if nsr_flavor_desc:
1122 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1123
vegall18101ea2023-03-06 13:49:21 +00001124 # Adding Shared Volume information to vdur
1125 if vdur.get("virtual-storages"):
1126 nsr_sv = []
1127 for vsd in vdur["virtual-storages"]:
1128 if vsd.get("vdu-storage-requirements"):
1129 if (
1130 vsd["vdu-storage-requirements"][0].get("key")
1131 == "multiattach"
1132 and vsd["vdu-storage-requirements"][0].get("value")
1133 == "True"
1134 ):
1135 nsr_sv.append(vsd["id"])
1136 if nsr_sv:
1137 vdur["shared-volumes-id"] = nsr_sv
1138
Alexis Romero03fb5842022-03-11 15:53:40 +01001139 # Adding Affinity groups information to vdur
1140 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001141 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001142 vnfd.get("df")[0]["vdu-profile"],
1143 lambda a_vdu: a_vdu["id"] == vdu["id"],
1144 )
1145 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001146 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001147
Alexis Romeroee31f532022-04-26 19:10:21 +02001148 if vdu_profile_affinity_group:
1149 affinity_group_ids = []
1150 for affinity_group in vdu_profile_affinity_group.get(
1151 "affinity-or-anti-affinity-group", ()
1152 ):
1153 vdu_affinity_group = utils.find_in_list(
1154 vdu_profile_affinity_group.get(
1155 "affinity-or-anti-affinity-group", ()
1156 ),
1157 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001158 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001159 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001160 nsr_descriptor["affinity-or-anti-affinity-group"],
1161 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001162 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1163 and nsr_ag.get("member-vnf-index")
1164 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001165 ),
1166 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001167 # Update Affinity Group VIM name if VDU instantiation parameter is present
1168 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1169 vnf_params_affinity_group = utils.find_in_list(
1170 vnf_params["affinity-or-anti-affinity-group"],
1171 lambda vnfp_ag: (
1172 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1173 ),
1174 )
1175 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1176 nsr_affinity_group[
1177 "vim-affinity-group-id"
1178 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1179 affinity_group_ids.append(nsr_affinity_group["id"])
1180 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001181
bravof4ca51522021-04-22 10:03:02 -04001182 if vdu_instantiation_level:
1183 count = vdu_instantiation_level.get("number-of-instances")
1184 else:
1185 count = 1
1186
garciaale7cbd03c2020-11-27 10:38:35 -03001187 for index in range(0, count):
1188 vdur = deepcopy(vdur)
1189 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001190 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001191 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001192 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001193 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1194
1195 vdur["_id"] = str(uuid4())
1196 vdur["id"] = vdur["_id"]
1197 vdur["count-index"] = index
1198 vnfr_descriptor["vdur"].append(vdur)
garciaale7cbd03c2020-11-27 10:38:35 -03001199 return vnfr_descriptor
1200
K Sai Kiran57589552021-01-27 21:38:34 +05301201 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1202 """
1203 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1204 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1205 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1206 :param ns_instance_content: ns instance content
1207 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1208 :return: None
1209 """
garciadeblasf2af4a12023-01-24 16:56:54 +01001210 time_now, time_delta = (
1211 time(),
1212 time() - ns_instance_content["_admin"]["modified"],
1213 )
1214 force_refresh = (
1215 isinstance(filter_q, dict) and filter_q.get("vcaStatusRefresh") == "true"
1216 )
K Sai Kiran57589552021-01-27 21:38:34 +05301217 threshold_reached = time_delta > 120
1218 if force_refresh or threshold_reached:
1219 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1220 ns_instance_content["_admin"]["modified"] = time_now
1221 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1222 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
garciadeblasf2af4a12023-01-24 16:56:54 +01001223 self.format_on_new(
1224 nslcmop_desc, session["project_id"], make_public=session["public"]
1225 )
K Sai Kiran57589552021-01-27 21:38:34 +05301226 nslcmop_desc["_admin"].pop("nsState")
1227 self.msg.write("ns", operation, nslcmop_desc)
1228 return
1229
1230 def show(self, session, _id, filter_q=None, api_req=False):
1231 """
1232 Get complete information on an ns instance.
1233 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1234 :param _id: string, ns instance id
1235 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1236 :param api_req: True if this call is serving an external API request. False if serving internal request.
1237 :return: dictionary, raise exception if not found.
1238 """
1239 ns_instance_content = super().show(session, _id, api_req)
1240 self.vca_status_refresh(session, ns_instance_content, filter_q)
1241 return ns_instance_content
1242
tierno65ca36d2019-02-12 19:27:52 +01001243 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001244 raise EngineException(
1245 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1246 )
tiernob24258a2018-10-04 18:39:49 +02001247
1248
1249class VnfrTopic(BaseTopic):
1250 topic = "vnfrs"
1251 topic_msg = None
1252
delacruzramo32bab472019-09-13 12:24:22 +02001253 def __init__(self, db, fs, msg, auth):
1254 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001255
tiernobee3bad2019-12-05 12:26:01 +00001256 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001257 raise EngineException(
1258 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1259 )
tiernob24258a2018-10-04 18:39:49 +02001260
tierno65ca36d2019-02-12 19:27:52 +01001261 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001262 raise EngineException(
1263 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1264 )
tiernob24258a2018-10-04 18:39:49 +02001265
tierno65ca36d2019-02-12 19:27:52 +01001266 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001267 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001268 raise EngineException(
1269 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1270 )
tiernob24258a2018-10-04 18:39:49 +02001271
1272
1273class NsLcmOpTopic(BaseTopic):
1274 topic = "nslcmops"
1275 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001276 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001277 "instantiate": ns_instantiate,
1278 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001279 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001280 "scale": ns_scale,
garciadeblas0964edf2022-02-11 00:43:44 +01001281 "heal": ns_heal,
tierno1c38f2f2020-03-24 11:51:39 +00001282 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301283 "migrate": ns_migrate,
Gabriel Cuba84a60df2023-10-30 14:01:54 -05001284 "cancel": nslcmop_cancel,
tiernob24258a2018-10-04 18:39:49 +02001285 }
1286
delacruzramo32bab472019-09-13 12:24:22 +02001287 def __init__(self, db, fs, msg, auth):
1288 BaseTopic.__init__(self, db, fs, msg, auth)
elumalai6c5ea6b2022-04-25 22:27:59 +05301289 self.nsrtopic = NsrTopic(db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001290
tiernob24258a2018-10-04 18:39:49 +02001291 def _check_ns_operation(self, session, nsr, operation, indata):
1292 """
1293 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001294 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
garciadeblas0964edf2022-02-11 00:43:44 +01001295 :param operation: it can be: instantiate, terminate, action, update, heal
tiernob24258a2018-10-04 18:39:49 +02001296 :param indata: descriptor with the parameters of the operation
1297 :return: None
1298 """
garciaale7cbd03c2020-11-27 10:38:35 -03001299 if operation == "action":
1300 self._check_action_ns_operation(indata, nsr)
1301 elif operation == "scale":
1302 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001303 elif operation == "update":
1304 self._check_update_ns_operation(indata, nsr)
garciadeblas0964edf2022-02-11 00:43:44 +01001305 elif operation == "heal":
1306 self._check_heal_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001307 elif operation == "instantiate":
1308 self._check_instantiate_ns_operation(indata, nsr, session)
1309
1310 def _check_action_ns_operation(self, indata, nsr):
1311 nsd = nsr["nsd"]
1312 # check vnf_member_index
1313 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001314 indata["member_vnf_index"] = indata.pop(
1315 "vnf_member_index"
1316 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001317 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001318 vnfd = self._get_vnfd_from_vnf_member_index(
1319 indata["member_vnf_index"], nsr["_id"]
1320 )
bravof41a52052021-02-17 18:08:01 -03001321 try:
garciadeblas4568a372021-03-24 09:19:48 +01001322 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1323 "operate-vnf-op-config"
1324 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001325 except Exception:
1326 configs = []
1327
garciaale7cbd03c2020-11-27 10:38:35 -03001328 if indata.get("vdu_id"):
1329 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001330 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001331 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001332 )
garciaale7cbd03c2020-11-27 10:38:35 -03001333 elif indata.get("kdu_name"):
1334 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001335 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001336 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001337 )
garciaale7cbd03c2020-11-27 10:38:35 -03001338 else:
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"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001341 )
1342 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001343 descriptor_configuration = descriptor_configuration.get(
1344 "config-primitive"
1345 )
garciaale7cbd03c2020-11-27 10:38:35 -03001346 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001347 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1348 "config-primitive"
1349 )
garciaale7cbd03c2020-11-27 10:38:35 -03001350
1351 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001352 if indata.get("kdu_name") and indata["primitive"] in (
1353 "upgrade",
1354 "rollback",
1355 "status",
1356 "inspect",
1357 "readme",
1358 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001359 # TODO should be checked that rollback only can contains revsision_numbe????
1360 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001361 raise EngineException(
1362 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1363 indata["primitive"]
1364 )
1365 )
garciaale7cbd03c2020-11-27 10:38:35 -03001366 return
1367 # if not, check primitive
1368 for config_primitive in get_iterable(descriptor_configuration):
1369 if indata["primitive"] == config_primitive["name"]:
1370 # check needed primitive_params are provided
1371 if indata.get("primitive_params"):
1372 in_primitive_params_copy = copy(indata["primitive_params"])
1373 else:
1374 in_primitive_params_copy = {}
1375 for paramd in get_iterable(config_primitive.get("parameter")):
1376 if paramd["name"] in in_primitive_params_copy:
1377 del in_primitive_params_copy[paramd["name"]]
1378 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001379 raise EngineException(
1380 "Needed parameter {} not provided for primitive '{}'".format(
1381 paramd["name"], indata["primitive"]
1382 )
1383 )
garciaale7cbd03c2020-11-27 10:38:35 -03001384 # check no extra primitive params are provided
1385 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001386 raise EngineException(
1387 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1388 list(in_primitive_params_copy.keys()), indata["primitive"]
1389 )
1390 )
garciaale7cbd03c2020-11-27 10:38:35 -03001391 break
1392 else:
garciadeblas4568a372021-03-24 09:19:48 +01001393 raise EngineException(
1394 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1395 indata["primitive"]
1396 )
1397 )
garciaale7cbd03c2020-11-27 10:38:35 -03001398
aticig544a2ae2022-04-05 09:00:17 +03001399 def _check_update_ns_operation(self, indata, nsr) -> None:
1400 """Validates the ns-update request according to updateType
1401
1402 If updateType is CHANGE_VNFPKG:
1403 - it checks the vnfInstanceId, whether it's available under ns instance
1404 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1405 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301406 If updateType is REMOVE_VNF:
1407 - it checks if the vnfInstanceId is available in the ns instance
1408 - Otherwise exception will be raised.
jegancd7d9f02024-05-16 07:07:27 +00001409 If updateType is OPERATE_VNF
1410 - it checks if the vdu-id is persent in the descriptor or not
1411 - it checks if the changeStateTo is either start, stop or rebuild
1412 If updateType is VERTICAL_SCALE
1413 - it checks if the vdu-id is persent in the descriptor or not
aticig544a2ae2022-04-05 09:00:17 +03001414
1415 Args:
1416 indata: includes updateType such as CHANGE_VNFPKG,
1417 nsr: network service record
1418
1419 Raises:
1420 EngineException:
1421 a meaningful error if given update parameters are not proper such as
1422 "Error in validating ns-update request: <ID> does not match
1423 with the vnfd-id of vnfinstance
1424 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1425
1426 """
1427 try:
1428 if indata["updateType"] == "CHANGE_VNFPKG":
1429 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1430 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1431 ns_instance_id = indata["nsInstanceId"]
1432 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1433
1434 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
aticig544a2ae2022-04-05 09:00:17 +03001435 raise EngineException(
1436 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1437 f"belong to NS {ns_instance_id}",
1438 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1439 )
1440
1441 # Getting vnfrs through the ns_instance_id
1442 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1443 constituent_vnfd_id = next(
1444 (
1445 vnfr["vnfd-id"]
1446 for vnfr in vnfrs
1447 if vnfr["id"] == vnf_instance_id
1448 ),
1449 None,
1450 )
1451
1452 # Check the given vnfd-id belongs to given vnf instance
1453 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
aticig544a2ae2022-04-05 09:00:17 +03001454 raise EngineException(
1455 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1456 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1457 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1458 )
1459
1460 # Validating the ns update timeout
1461 if (
1462 indata.get("timeout_ns_update")
1463 and indata["timeout_ns_update"] < 300
1464 ):
1465 raise EngineException(
1466 "Error in validating ns-update request: {} second is not enough "
1467 "to upgrade the VNF instance: {}".format(
1468 indata["timeout_ns_update"], vnf_instance_id
1469 ),
1470 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1471 )
elumalai6380e7c2022-04-28 00:15:59 +05301472 elif indata["updateType"] == "REMOVE_VNF":
1473 vnf_instance_id = indata["removeVnfInstanceId"]
1474 ns_instance_id = indata["nsInstanceId"]
1475 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1476 raise EngineException(
1477 "Invalid VNF Instance Id. '{}' is not "
1478 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1479 )
jegancd7d9f02024-05-16 07:07:27 +00001480 elif indata["updateType"] == "OPERATE_VNF":
1481 if indata.get("operateVnfData"):
1482 if indata["operateVnfData"]["changeStateTo"] not in (
1483 "start",
1484 "stop",
1485 "rebuild",
1486 ):
1487 raise EngineException(
1488 f"The operate type should be either start, stop or rebuild not {indata['operateVnfData']['changeStateTo']}",
1489 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1490 )
1491 if indata["operateVnfData"].get("additionalParam"):
1492 vdu_id = indata["operateVnfData"]["additionalParam"]["vdu_id"]
1493 vnfinstance_id = indata["operateVnfData"]["vnfInstanceId"]
1494 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1495 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1496 vnfd = self._get_vnfd_from_vnf_member_index(
1497 vnfd_member_vnf_index, nsr["_id"]
1498 )
1499 self._check_valid_vdu(vnfd, vdu_id)
1500 elif indata["updateType"] == "VERTICAL_SCALE":
1501 if indata.get("verticalScaleVnf"):
1502 vdu_id = indata["verticalScaleVnf"]["vduId"]
1503 vnfinstance_id = indata["verticalScaleVnf"]["vnfInstanceId"]
1504 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1505 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1506 vnfd = self._get_vnfd_from_vnf_member_index(
1507 vnfd_member_vnf_index, nsr["_id"]
1508 )
1509 self._check_valid_vdu(vnfd, vdu_id)
aticig544a2ae2022-04-05 09:00:17 +03001510
1511 except (
1512 DbException,
1513 AttributeError,
1514 IndexError,
1515 KeyError,
1516 ValueError,
1517 ) as e:
1518 raise type(e)(
1519 "Ns update request could not be processed with error: {}.".format(e)
1520 )
1521
garciaale7cbd03c2020-11-27 10:38:35 -03001522 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001523 vnfd = self._get_vnfd_from_vnf_member_index(
1524 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1525 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001526 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001527 if (
1528 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1529 == scaling_aspect["id"]
1530 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001531 break
1532 else:
garciadeblas4568a372021-03-24 09:19:48 +01001533 raise EngineException(
1534 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1535 "present at vnfd:scaling-aspect".format(
1536 indata["scaleVnfData"]["scaleByStepData"][
1537 "scaling-group-descriptor"
1538 ]
1539 )
1540 )
garciaale7cbd03c2020-11-27 10:38:35 -03001541
garciadeblas0964edf2022-02-11 00:43:44 +01001542 def _check_heal_ns_operation(self, indata, nsr):
1543 return
1544
garciaale7cbd03c2020-11-27 10:38:35 -03001545 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001546 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001547 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001548 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001549 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001550 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1551 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1552 for in_vnf in get_iterable(indata.get("vnf")):
1553 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001554 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001555 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001556 else:
garciadeblas4568a372021-03-24 09:19:48 +01001557 vnfd = self._get_vnfd_from_vnf_member_index(
1558 member_vnf_index, nsr["_id"]
1559 )
1560 vnf_member_index_to_vnfd[
1561 member_vnf_index
1562 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001563 self._check_vnf_instantiation_params(in_vnf, vnfd)
1564 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001565 self._check_valid_vim_account(
1566 in_vnf["vimAccountId"], vim_accounts, session
1567 )
tierno260dd6f2019-09-02 10:48:56 +00001568
garciaale7cbd03c2020-11-27 10:38:35 -03001569 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001570 self._check_valid_wim_account(
1571 in_vld.get("wimAccountId"), wim_accounts, session
1572 )
garciaale7cbd03c2020-11-27 10:38:35 -03001573 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1574 if in_vld["name"] == vldd["id"]:
1575 break
tierno9cb7d672019-10-30 12:13:48 +00001576 else:
garciadeblas4568a372021-03-24 09:19:48 +01001577 raise EngineException(
1578 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1579 in_vld["name"]
1580 )
1581 )
tierno9cb7d672019-10-30 12:13:48 +00001582
garciaale7cbd03c2020-11-27 10:38:35 -03001583 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1584 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001585 vnfr = self.db.get_one(
1586 "vnfrs",
1587 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1588 fail_on_empty=False,
1589 )
garciaale7cbd03c2020-11-27 10:38:35 -03001590 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001591 raise EngineException(
1592 "Invalid parameter member_vnf_index='{}' is not one of the "
1593 "nsd:constituent-vnfd".format(member_vnf_index)
1594 )
beierlmcee2ebf2022-03-29 17:42:48 -04001595
garciadeblasf2af4a12023-01-24 16:56:54 +01001596 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
beierlmcee2ebf2022-03-29 17:42:48 -04001597 if "revision" in vnfr:
1598 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
garciadeblasf2af4a12023-01-24 16:56:54 +01001599 vnfd = self.db.get_one(
1600 "vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False
1601 )
beierlmcee2ebf2022-03-29 17:42:48 -04001602 else:
garciadeblasf2af4a12023-01-24 16:56:54 +01001603 vnfd = self.db.get_one(
1604 "vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False
1605 )
beierlmcee2ebf2022-03-29 17:42:48 -04001606
garciaale7cbd03c2020-11-27 10:38:35 -03001607 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001608 raise EngineException(
1609 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1610 vnfr["vnfd-id"]
1611 )
1612 )
garciaale7cbd03c2020-11-27 10:38:35 -03001613 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001614
garciaale7cbd03c2020-11-27 10:38:35 -03001615 def _check_valid_vdu(self, vnfd, vdu_id):
1616 for vdud in get_iterable(vnfd.get("vdu")):
1617 if vdud["id"] == vdu_id:
1618 return vdud
1619 else:
garciadeblas4568a372021-03-24 09:19:48 +01001620 raise EngineException(
1621 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1622 vdu_id
1623 )
1624 )
garciaale7cbd03c2020-11-27 10:38:35 -03001625
1626 def _check_valid_kdu(self, vnfd, kdu_name):
1627 for kdud in get_iterable(vnfd.get("kdu")):
1628 if kdud["name"] == kdu_name:
1629 return kdud
1630 else:
garciadeblas4568a372021-03-24 09:19:48 +01001631 raise EngineException(
1632 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1633 kdu_name
1634 )
1635 )
garciaale7cbd03c2020-11-27 10:38:35 -03001636
1637 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1638 for in_vdu in get_iterable(in_vnf.get("vdu")):
1639 for vdu in get_iterable(vnfd.get("vdu")):
1640 if in_vdu["id"] == vdu["id"]:
1641 for volume in get_iterable(in_vdu.get("volume")):
1642 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
aticigd7753fc2022-05-18 18:55:23 +03001643 if volumed == volume["name"]:
garciaale7cbd03c2020-11-27 10:38:35 -03001644 break
1645 else:
garciadeblas4568a372021-03-24 09:19:48 +01001646 raise EngineException(
1647 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1648 "volume:name='{}' is not present at "
1649 "vnfd:vdu:virtual-storage-desc list".format(
1650 in_vnf["member-vnf-index"],
1651 in_vdu["id"],
1652 volume["id"],
1653 )
1654 )
garciaale7cbd03c2020-11-27 10:38:35 -03001655
1656 vdu_if_names = set()
1657 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001658 for iface in get_iterable(
1659 cpd.get("virtual-network-interface-requirement")
1660 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001661 vdu_if_names.add(iface.get("name"))
1662
aticigd7753fc2022-05-18 18:55:23 +03001663 for in_iface in get_iterable(in_vdu.get("interface")):
garciaale7cbd03c2020-11-27 10:38:35 -03001664 if in_iface["name"] in vdu_if_names:
1665 break
1666 else:
garciadeblas4568a372021-03-24 09:19:48 +01001667 raise EngineException(
1668 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1669 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1670 in_vnf["member-vnf-index"],
1671 in_vdu["id"],
1672 in_iface["name"],
1673 )
1674 )
garciaale7cbd03c2020-11-27 10:38:35 -03001675 break
1676
1677 else:
garciadeblas4568a372021-03-24 09:19:48 +01001678 raise EngineException(
1679 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1680 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1681 )
garciaale7cbd03c2020-11-27 10:38:35 -03001682
garciadeblas4568a372021-03-24 09:19:48 +01001683 vnfd_ivlds_cpds = {
1684 ivld.get("id"): set()
1685 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1686 }
Gulsum Atici9af2a472023-03-28 17:50:48 +03001687 for vdu in vnfd.get("vdu", {}):
1688 for cpd in vdu.get("int-cpd", {}):
garciaale7cbd03c2020-11-27 10:38:35 -03001689 if cpd.get("int-virtual-link-desc"):
1690 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1691
1692 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1693 if in_ivld.get("name") in vnfd_ivlds_cpds:
1694 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1695 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001696 break
tiernob24258a2018-10-04 18:39:49 +02001697 else:
garciadeblas4568a372021-03-24 09:19:48 +01001698 raise EngineException(
1699 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1700 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1701 "vnfd:internal-vld:name/id:internal-connection-point".format(
1702 in_vnf["member-vnf-index"],
1703 in_ivld["name"],
1704 in_icp["id-ref"],
1705 )
1706 )
tiernob24258a2018-10-04 18:39:49 +02001707 else:
garciadeblas4568a372021-03-24 09:19:48 +01001708 raise EngineException(
1709 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1710 " is not present at vnfd '{}'".format(
1711 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1712 )
1713 )
tiernob24258a2018-10-04 18:39:49 +02001714
garciaale7cbd03c2020-11-27 10:38:35 -03001715 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1716 if vim_account in vim_accounts:
1717 return
1718 try:
1719 db_filter = self._get_project_filter(session)
1720 db_filter["_id"] = vim_account
1721 self.db.get_one("vim_accounts", db_filter)
1722 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001723 raise EngineException(
1724 "Invalid vimAccountId='{}' not present for the project".format(
1725 vim_account
1726 )
1727 )
garciaale7cbd03c2020-11-27 10:38:35 -03001728 vim_accounts.append(vim_account)
1729
David Garcia98de2982021-10-13 17:14:01 +02001730 def _get_vim_account(self, vim_id: str, session):
1731 try:
1732 db_filter = self._get_project_filter(session)
1733 db_filter["_id"] = vim_id
1734 return self.db.get_one("vim_accounts", db_filter)
1735 except Exception:
1736 raise EngineException(
garciadeblasf2af4a12023-01-24 16:56:54 +01001737 "Invalid vimAccountId='{}' not present for the project".format(vim_id)
David Garcia98de2982021-10-13 17:14:01 +02001738 )
1739
garciaale7cbd03c2020-11-27 10:38:35 -03001740 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1741 if not isinstance(wim_account, str):
1742 return
1743 if wim_account in wim_accounts:
1744 return
1745 try:
gifrerenom44f5ec12022-03-07 16:57:25 +00001746 db_filter = self._get_project_filter(session)
garciaale7cbd03c2020-11-27 10:38:35 -03001747 db_filter["_id"] = wim_account
1748 self.db.get_one("wim_accounts", db_filter)
1749 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001750 raise EngineException(
1751 "Invalid wimAccountId='{}' not present for the project".format(
1752 wim_account
1753 )
1754 )
garciaale7cbd03c2020-11-27 10:38:35 -03001755 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001756
garciadeblas4568a372021-03-24 09:19:48 +01001757 def _look_for_pdu(
1758 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1759 ):
tiernocc103432018-10-19 14:10:35 +02001760 """
tierno36ec8602018-11-02 17:27:11 +01001761 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1762 (ip_address, ...) information.
1763 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001764 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001765 :param rollback: list with the database modifications to rollback if needed
1766 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1767 :param vim_account: vim_account where this vnfr should be deployed
1768 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1769 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1770 of the changed vnfr is needed
1771
1772 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1773 "vim-network-name": used at VIM
1774 "name": interface name
1775 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1776 "ns-vld-id": NSD vld where this interface is connected.
1777 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 +02001778 """
tierno36ec8602018-11-02 17:27:11 +01001779
1780 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001781 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1782 if not vdur.get("pdu-type"):
1783 continue
1784 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001785 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001786 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001787 pdu_filter["type"] = pdu_type
1788 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001789 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001790 # TODO feature 1417: "shared": True,
1791
1792 available_pdus = self.db.get_list("pdus", pdu_filter)
1793 for pdu in available_pdus:
1794 # step 1 check if this pdu contains needed interfaces:
1795 match_interfaces = True
1796 for vdur_interface in vdur["interfaces"]:
1797 for pdu_interface in pdu["interfaces"]:
1798 if pdu_interface["name"] == vdur_interface["name"]:
1799 # TODO feature 1417: match per mgmt type
1800 break
1801 else: # no interface found for name
1802 match_interfaces = False
1803 break
1804 if match_interfaces:
1805 break
1806 else:
1807 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001808 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001809 "names".format(
1810 pdu_type,
1811 vim_account,
1812 vnfr["member-vnf-index-ref"],
1813 vdur["vdu-id-ref"],
1814 )
1815 )
tiernocc103432018-10-19 14:10:35 +02001816
1817 # step 2. Update pdu
1818 rollback_pdu = {
1819 "_admin.usageState": pdu["_admin"]["usageState"],
1820 "_admin.usage.vnfr_id": None,
1821 "_admin.usage.nsr_id": None,
1822 "_admin.usage.vdur": None,
1823 }
garciadeblas4568a372021-03-24 09:19:48 +01001824 self.db.set_one(
1825 "pdus",
1826 {"_id": pdu["_id"]},
1827 {
1828 "_admin.usageState": "IN_USE",
1829 "_admin.usage": {
1830 "vnfr_id": vnfr["_id"],
1831 "nsr_id": vnfr["nsr-id-ref"],
1832 "vdur": vdur["vdu-id-ref"],
1833 },
1834 },
1835 )
1836 rollback.append(
1837 {
1838 "topic": "pdus",
1839 "_id": pdu["_id"],
1840 "operation": "set",
1841 "content": rollback_pdu,
1842 }
1843 )
tiernocc103432018-10-19 14:10:35 +02001844
1845 # step 3. Fill vnfr info by filling vdur
1846 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001847 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001848 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1849 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1850 for pdu_interface in pdu["interfaces"]:
1851 if pdu_interface["name"] == vdur_interface["name"]:
1852 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1853 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001854 if k in (
1855 "ip-address",
1856 "mac-address",
1857 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001858 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001859 vnfr_update_rollback[
1860 iface_text + ".{}".format(k)
1861 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001862 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001863 if vdur_interface.get(
1864 "mgmt-interface"
1865 ) or vdur_interface.get("mgmt-vnf"):
1866 vnfr_update_rollback[
1867 vdu_text + ".ip-address"
1868 ] = vdur.get("ip-address")
1869 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1870 "ip-address"
1871 ]
tierno36ec8602018-11-02 17:27:11 +01001872 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001873 vnfr_update_rollback["ip-address"] = vnfr.get(
1874 "ip-address"
1875 )
tierno36ec8602018-11-02 17:27:11 +01001876 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001877 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1878 "ip-address"
1879 ]
1880 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1881 "vim-network-id"
1882 ):
1883 ifaces_forcing_vim_network.append(
1884 {
1885 "name": vdur_interface.get("vnf-vld-id")
1886 or vdur_interface.get("ns-vld-id"),
1887 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1888 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1889 }
1890 )
gcalvino17d5b732018-12-17 16:26:21 +01001891 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001892 ifaces_forcing_vim_network[-1][
1893 "vim-network-id"
1894 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001895 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001896 ifaces_forcing_vim_network[-1][
1897 "vim-network-name"
1898 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001899 break
1900
tierno36ec8602018-11-02 17:27:11 +01001901 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001902
garciadeblas4568a372021-03-24 09:19:48 +01001903 def _look_for_k8scluster(
1904 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1905 ):
tierno9cb7d672019-10-30 12:13:48 +00001906 """
1907 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1908 Fills vnfr.kdur with the selected k8scluster
1909
1910 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1911 :param rollback: list with the database modifications to rollback if needed
1912 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1913 :param vim_account: vim_account where this vnfr should be deployed
1914 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1915 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1916 of the changed vnfr is needed
1917
1918 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1919 "vim-network-name": used at VIM
1920 "name": interface name
1921 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1922 "ns-vld-id": NSD vld where this interface is connected.
1923 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1924 """
1925
1926 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001927 if not vnfr.get("kdur"):
1928 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001929
tiernoc67b0e92019-11-05 12:45:29 +00001930 kdu_filter = self._get_project_filter(session)
1931 kdu_filter["vim_account"] = vim_account
1932 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1933 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1934
1935 k8s_requirements = {} # just for logging
1936 for k8scluster in available_k8sclusters:
1937 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001938 break
tiernoc67b0e92019-11-05 12:45:29 +00001939 # restrict by cni
1940 if vnfr["k8s-cluster"].get("cni"):
1941 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001942 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1943 k8scluster.get("cni", ())
1944 ):
tiernoc67b0e92019-11-05 12:45:29 +00001945 continue
1946 # restrict by version
1947 if vnfr["k8s-cluster"].get("version"):
1948 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1949 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1950 continue
1951 # restrict by number of networks
1952 if vnfr["k8s-cluster"].get("nets"):
1953 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001954 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1955 vnfr["k8s-cluster"]["nets"]
1956 ):
tiernoc67b0e92019-11-05 12:45:29 +00001957 continue
1958 break
1959 else:
garciadeblas4568a372021-03-24 09:19:48 +01001960 raise EngineException(
1961 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1962 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1963 )
1964 )
tierno9cb7d672019-10-30 12:13:48 +00001965
tiernoc67b0e92019-11-05 12:45:29 +00001966 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001967 # step 3. Fill vnfr info by filling kdur
1968 kdu_text = "kdur.{}.".format(kdur_index)
1969 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1970 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1971
tiernoc67b0e92019-11-05 12:45:29 +00001972 # step 4. Check VIM networks that forces the selected k8s_cluster
1973 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1974 k8scluster_net_list = list(k8scluster.get("nets").keys())
1975 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1976 # get a network from k8s_cluster nets. If name matches use this, if not use other
1977 if kdur_net["id"] in k8scluster_net_list: # name matches
1978 vim_net = k8scluster["nets"][kdur_net["id"]]
1979 k8scluster_net_list.remove(kdur_net["id"])
1980 else:
1981 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1982 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001983 vnfr_update_rollback[
1984 "k8s-cluster.nets.{}.vim_net".format(net_index)
1985 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001986 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001987 if vim_net and (
1988 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1989 ):
1990 ifaces_forcing_vim_network.append(
1991 {
1992 "name": kdur_net.get("vnf-vld-id")
1993 or kdur_net.get("ns-vld-id"),
1994 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1995 "ns-vld-id": kdur_net.get("ns-vld-id"),
1996 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1997 }
1998 )
tiernoc67b0e92019-11-05 12:45:29 +00001999 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00002000 return ifaces_forcing_vim_network
2001
Gulsum Aticie395aa42021-11-10 20:59:06 +03002002 def _update_vnfrs_from_nsd(self, nsr):
garciadeblasf2af4a12023-01-24 16:56:54 +01002003 step = "Getting vnf_profiles from nsd" # first step must be defined outside try
Gulsum Aticie395aa42021-11-10 20:59:06 +03002004 try:
2005 nsr_id = nsr["_id"]
2006 nsd = nsr["nsd"]
2007
Gulsum Aticie395aa42021-11-10 20:59:06 +03002008 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
2009 vld_fixed_ip_connection_point_data = {}
2010
2011 step = "Getting ip-address info from vnf_profile if it exists"
2012 for vnfp in vnf_profiles:
2013 # Checking ip-address info from nsd.vnf_profile and storing
2014 for vlc in vnfp.get("virtual-link-connectivity", ()):
2015 for cpd in vlc.get("constituent-cpd-id", ()):
2016 if cpd.get("ip-address"):
2017 step = "Storing ip-address info"
garciadeblasf2af4a12023-01-24 16:56:54 +01002018 vld_fixed_ip_connection_point_data.update(
2019 {
2020 vlc.get("virtual-link-profile-id")
2021 + "."
2022 + cpd.get("constituent-base-element-id"): {
2023 "vnfd-connection-point-ref": cpd.get(
2024 "constituent-cpd-id"
2025 ),
2026 "ip-address": cpd.get("ip-address"),
2027 }
2028 }
2029 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002030
2031 # Inserting ip address to vnfr
2032 if len(vld_fixed_ip_connection_point_data) > 0:
2033 step = "Getting vnfrs"
2034 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2035 for item in vld_fixed_ip_connection_point_data.keys():
2036 step = "Filtering vnfrs"
garciadeblasf2af4a12023-01-24 16:56:54 +01002037 vnfr = next(
2038 filter(
2039 lambda vnfr: vnfr["member-vnf-index-ref"]
2040 == item.split(".")[1],
2041 vnfrs,
2042 ),
2043 None,
2044 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002045 if vnfr:
2046 vnfr_update = {}
2047 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2048 for iface_index, iface in enumerate(vdur["interfaces"]):
2049 step = "Looking for matched interface"
2050 if (
garciadeblasf2af4a12023-01-24 16:56:54 +01002051 iface.get("external-connection-point-ref")
2052 == vld_fixed_ip_connection_point_data[item].get(
2053 "vnfd-connection-point-ref"
2054 )
2055 and iface.get("ns-vld-id") == item.split(".")[0]
Gulsum Aticie395aa42021-11-10 20:59:06 +03002056 ):
2057 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2058 vdur_index, iface_index
2059 )
2060 step = "Storing info in order to update vnfr"
2061 vnfr_update[
2062 vnfr_update_text + ".ip-address"
garciadeblasf2af4a12023-01-24 16:56:54 +01002063 ] = increment_ip_mac(
2064 vld_fixed_ip_connection_point_data[item].get(
2065 "ip-address"
2066 ),
2067 vdur.get("count-index", 0),
2068 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002069 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
2070
2071 step = "updating vnfr at database"
2072 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
2073 except (
garciadeblasf2af4a12023-01-24 16:56:54 +01002074 ValidationError,
2075 EngineException,
2076 DbException,
2077 MsgException,
2078 FsException,
Gulsum Aticie395aa42021-11-10 20:59:06 +03002079 ) as e:
2080 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
2081
tiernocc103432018-10-19 14:10:35 +02002082 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02002083 # get vnfr
2084 nsr_id = nsr["_id"]
2085 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2086
2087 for vnfr in vnfrs:
2088 vnfr_update = {}
2089 vnfr_update_rollback = {}
2090 member_vnf_index = vnfr["member-vnf-index-ref"]
2091 # update vim-account-id
2092
2093 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02002094 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002095 # check instantiate parameters
2096 for vnf_inst_params in get_iterable(indata.get("vnf")):
2097 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
2098 continue
2099 if vnf_inst_params.get("vimAccountId"):
2100 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02002101 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002102
tiernocddb07d2020-10-06 08:28:00 +00002103 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
2104 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
2105 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2106 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
2107 continue
garciadeblas4568a372021-03-24 09:19:48 +01002108 for iface_inst_param in get_iterable(
2109 vdu_inst_param.get("interface")
2110 ):
2111 iface_index, _ = next(
2112 i
2113 for i in enumerate(vdur["interfaces"])
2114 if i[1]["name"] == iface_inst_param["name"]
2115 )
2116 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2117 vdur_index, iface_index
2118 )
tiernocddb07d2020-10-06 08:28:00 +00002119 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002120 vnfr_update[
2121 vnfr_update_text + ".ip-address"
2122 ] = increment_ip_mac(
2123 iface_inst_param.get("ip-address"),
2124 vdur.get("count-index", 0),
2125 )
tierno1bd9d952020-11-13 15:56:51 +00002126 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002127 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002128 vnfr_update[
2129 vnfr_update_text + ".mac-address"
2130 ] = increment_ip_mac(
2131 iface_inst_param.get("mac-address"),
2132 vdur.get("count-index", 0),
2133 )
tierno1bd9d952020-11-13 15:56:51 +00002134 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03002135 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01002136 vnfr_update[
2137 vnfr_update_text + ".floating-ip-required"
2138 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002139 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2140 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01002141 for ivld_inst_param in get_iterable(
2142 vnf_inst_params.get("internal-vld")
2143 ):
2144 for icp_inst_param in get_iterable(
2145 ivld_inst_param.get("internal-connection-point")
2146 ):
tiernocddb07d2020-10-06 08:28:00 +00002147 # look for iface
2148 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2149 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002150 if (
2151 iface.get("internal-connection-point-ref")
2152 == icp_inst_param["id-ref"]
2153 ):
2154 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2155 vdur_index, iface_index
2156 )
tiernocddb07d2020-10-06 08:28:00 +00002157 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002158 vnfr_update[
2159 vnfr_update_text + ".ip-address"
2160 ] = increment_ip_mac(
2161 icp_inst_param.get("ip-address"),
2162 vdur.get("count-index", 0),
2163 )
2164 vnfr_update[
2165 vnfr_update_text + ".fixed-ip"
2166 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002167 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002168 vnfr_update[
2169 vnfr_update_text + ".mac-address"
2170 ] = increment_ip_mac(
2171 icp_inst_param.get("mac-address"),
2172 vdur.get("count-index", 0),
2173 )
2174 vnfr_update[
2175 vnfr_update_text + ".fixed-mac"
2176 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002177 break
2178 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2179 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01002180 for vnfcp_inst_param in get_iterable(
2181 vld_inst_param.get("vnfd-connection-point-ref")
2182 ):
tiernocddb07d2020-10-06 08:28:00 +00002183 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2184 continue
2185 # look for iface
2186 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2187 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002188 if (
2189 iface.get("external-connection-point-ref")
2190 == vnfcp_inst_param["vnfd-connection-point-ref"]
2191 ):
2192 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2193 vdur_index, iface_index
2194 )
tiernocddb07d2020-10-06 08:28:00 +00002195 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002196 vnfr_update[
2197 vnfr_update_text + ".ip-address"
2198 ] = increment_ip_mac(
2199 vnfcp_inst_param.get("ip-address"),
2200 vdur.get("count-index", 0),
2201 )
tierno1bd9d952020-11-13 15:56:51 +00002202 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002203 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002204 vnfr_update[
2205 vnfr_update_text + ".mac-address"
2206 ] = increment_ip_mac(
2207 vnfcp_inst_param.get("mac-address"),
2208 vdur.get("count-index", 0),
2209 )
tierno1bd9d952020-11-13 15:56:51 +00002210 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002211 break
2212
tiernocc103432018-10-19 14:10:35 +02002213 vnfr_update["vim-account-id"] = vim_account
2214 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2215
David Garciaecb41322021-03-31 19:10:46 +02002216 if vca_id:
2217 vnfr_update["vca-id"] = vca_id
2218 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2219
tiernocc103432018-10-19 14:10:35 +02002220 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002221 ifaces_forcing_vim_network = self._look_for_pdu(
2222 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2223 )
tiernocc103432018-10-19 14:10:35 +02002224
tierno9cb7d672019-10-30 12:13:48 +00002225 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002226 ifaces_forcing_vim_network += self._look_for_k8scluster(
2227 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2228 )
tierno9cb7d672019-10-30 12:13:48 +00002229 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002230 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002231 rollback.append(
2232 {
2233 "topic": "vnfrs",
2234 "_id": vnfr["_id"],
2235 "operation": "set",
2236 "content": vnfr_update_rollback,
2237 }
2238 )
tierno36ec8602018-11-02 17:27:11 +01002239
2240 # Update indada in case pdu forces to use a concrete vim-network-name
2241 # TODO check if user has already insert a vim-network-name and raises an error
2242 if not ifaces_forcing_vim_network:
2243 continue
2244 for iface_info in ifaces_forcing_vim_network:
2245 if iface_info.get("ns-vld-id"):
2246 if "vld" not in indata:
2247 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002248 indata["vld"].append(
2249 {
2250 key: iface_info[key]
2251 for key in ("name", "vim-network-name", "vim-network-id")
2252 if iface_info.get(key)
2253 }
2254 )
tierno36ec8602018-11-02 17:27:11 +01002255
2256 elif iface_info.get("vnf-vld-id"):
2257 if "vnf" not in indata:
2258 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002259 indata["vnf"].append(
2260 {
2261 "member-vnf-index": member_vnf_index,
2262 "internal-vld": [
2263 {
2264 key: iface_info[key]
2265 for key in (
2266 "name",
2267 "vim-network-name",
2268 "vim-network-id",
2269 )
2270 if iface_info.get(key)
2271 }
2272 ],
2273 }
2274 )
tierno36ec8602018-11-02 17:27:11 +01002275
2276 @staticmethod
2277 def _create_nslcmop(nsr_id, operation, params):
2278 """
2279 Creates a ns-lcm-opp content to be stored at database.
2280 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002281 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002282 :param params: user parameters for the operation
2283 :return: dictionary following SOL005 format
2284 """
tiernob24258a2018-10-04 18:39:49 +02002285 now = time()
2286 _id = str(uuid4())
2287 nslcmop = {
2288 "id": _id,
2289 "_id": _id,
2290 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002291 "queuePosition": None,
2292 "stage": None,
2293 "errorMessage": None,
2294 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002295 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002296 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002297 "lcmOperationType": operation,
2298 "startTime": now,
2299 "isAutomaticInvocation": False,
2300 "operationParams": params,
2301 "isCancelPending": False,
2302 "links": {
2303 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002304 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002305 },
tiernob24258a2018-10-04 18:39:49 +02002306 }
2307 return nslcmop
2308
magnussonlf318b302020-01-20 18:38:18 +01002309 def _get_enabled_vims(self, session):
2310 """
2311 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2312 :param session: current session with user information
2313 """
2314 db_filter = self._get_project_filter(session)
2315 db_filter["_admin.operationalState"] = "ENABLED"
2316 vims = self.db.get_list("vim_accounts", db_filter)
2317 vimAccounts = []
2318 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002319 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002320 return vimAccounts
2321
garciadeblas4568a372021-03-24 09:19:48 +01002322 def new(
2323 self,
2324 rollback,
2325 session,
2326 indata=None,
2327 kwargs=None,
2328 headers=None,
2329 slice_object=False,
2330 ):
tiernob24258a2018-10-04 18:39:49 +02002331 """
2332 Performs a new operation over a ns
2333 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002334 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002335 :param indata: descriptor with the parameters of the operation. It must contains among others
2336 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002337 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002338 :param kwargs: used to override the indata descriptor
2339 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002340 :return: id of the nslcmops
2341 """
garciadeblas4568a372021-03-24 09:19:48 +01002342
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002343 def check_if_nsr_is_not_slice_member(session, nsr_id):
2344 nsis = None
2345 db_filter = self._get_project_filter(session)
2346 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002347 nsis = self.db.get_one(
2348 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2349 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002350 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002351 raise EngineException(
2352 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2353 nsr_id, nsis["_id"]
2354 ),
2355 http_code=HTTPStatus.CONFLICT,
2356 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002357
tiernob24258a2018-10-04 18:39:49 +02002358 try:
2359 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002360 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002361 operation = indata["lcmOperationType"]
2362 nsInstanceId = indata["nsInstanceId"]
2363
2364 validate_input(indata, self.operation_schema[operation])
2365 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002366 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002367 _filter["_id"] = nsInstanceId
2368 nsr = self.db.get_one("nsrs", _filter)
2369
2370 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002371 if operation == "terminate" and slice_object is False:
2372 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002373 if (
2374 not nsr["_admin"].get("nsState")
2375 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2376 ):
tiernob24258a2018-10-04 18:39:49 +02002377 if operation == "terminate" and indata.get("autoremove"):
2378 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002379 return (
2380 None,
2381 None,
garciadeblasf53612b2024-07-12 14:44:37 +02002382 None,
garciadeblas4568a372021-03-24 09:19:48 +01002383 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002384 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002385 raise EngineException(
2386 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2387 nsInstanceId, operation
2388 ),
2389 HTTPStatus.CONFLICT,
2390 )
tiernob24258a2018-10-04 18:39:49 +02002391 else:
tierno65ca36d2019-02-12 19:27:52 +01002392 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002393 raise EngineException(
2394 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2395 nsInstanceId, operation
2396 ),
2397 HTTPStatus.CONFLICT,
2398 )
tiernob24258a2018-10-04 18:39:49 +02002399 self._check_ns_operation(session, nsr, operation, indata)
garciadeblasf2af4a12023-01-24 16:56:54 +01002400 if indata.get("primitive_params"):
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002401 indata["primitive_params"] = json.dumps(indata["primitive_params"])
garciadeblasf2af4a12023-01-24 16:56:54 +01002402 elif indata.get("additionalParamsForVnf"):
2403 indata["additionalParamsForVnf"] = json.dumps(
2404 indata["additionalParamsForVnf"]
2405 )
tierno36ec8602018-11-02 17:27:11 +01002406
tiernocc103432018-10-19 14:10:35 +02002407 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002408 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002409 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302410 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2411 nsr_update = {}
2412 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2413 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2414 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2415 ns_request = nsr["instantiate_params"]
garciadeblasf2af4a12023-01-24 16:56:54 +01002416 vnfr = self.db.get_one(
2417 "vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]}
2418 )
elumalai8bf978e2022-05-26 15:32:06 +05302419 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2420 vnfr_vnfd_revision = vnfr.get("revision", 1)
2421 if latest_vnfd_revision != vnfr_vnfd_revision:
2422 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
garciadeblasf2af4a12023-01-24 16:56:54 +01002423 old_db_vnfd = self.db.get_one(
2424 "vnfds_revisions", {"_id": old_vnfd_id}
2425 )
elumalai8bf978e2022-05-26 15:32:06 +05302426 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2427 new_sw_version = vnfd.get("software-version", "1.0")
2428 if new_sw_version != old_sw_version:
2429 vnf_index = vnfr["member-vnf-index-ref"]
elumalai8bf978e2022-05-26 15:32:06 +05302430 for vdu in vnfd["vdu"]:
vegall18101ea2023-03-06 13:49:21 +00002431 self.nsrtopic._add_shared_volumes_to_nsr(
2432 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2433 )
garciadeblasf2af4a12023-01-24 16:56:54 +01002434 self.nsrtopic._add_flavor_to_nsr(
2435 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2436 )
elumalai8bf978e2022-05-26 15:32:06 +05302437 sw_image_id = vdu.get("sw-image-desc")
2438 if sw_image_id:
garciadeblasf2af4a12023-01-24 16:56:54 +01002439 image_data = self.nsrtopic._get_image_data_from_vnfd(
2440 vnfd, sw_image_id
2441 )
elumalai8bf978e2022-05-26 15:32:06 +05302442 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2443 for alt_image in vdu.get("alternative-sw-image-desc", ()):
garciadeblasf2af4a12023-01-24 16:56:54 +01002444 image_data = self.nsrtopic._get_image_data_from_vnfd(
2445 vnfd, alt_image
2446 )
elumalai8bf978e2022-05-26 15:32:06 +05302447 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2448 nsr_update["image"] = nsr["image"]
2449 nsr_update["flavor"] = nsr["flavor"]
vegall18101ea2023-03-06 13:49:21 +00002450 nsr_update["shared-volumes"] = nsr["shared-volumes"]
elumalai8bf978e2022-05-26 15:32:06 +05302451 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
garciadeblasf2af4a12023-01-24 16:56:54 +01002452 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(
2453 nsd, ns_request, session
2454 )
2455 vnfr_descriptor = (
2456 self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2457 nsd,
2458 vnfd,
2459 vnfd_id,
2460 vnf_index,
2461 nsr,
2462 ns_request,
2463 ns_k8s_namespace,
2464 latest_vnfd_revision,
2465 )
elumalai8bf978e2022-05-26 15:32:06 +05302466 )
2467 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002468 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002469 _id = nslcmop_desc["_id"]
garciadeblasf53612b2024-07-12 14:44:37 +02002470 nsName = nsr.get("name")
garciadeblas4568a372021-03-24 09:19:48 +01002471 self.format_on_new(
2472 nslcmop_desc, session["project_id"], make_public=session["public"]
2473 )
magnussonlf318b302020-01-20 18:38:18 +01002474 if indata.get("placement-engine"):
2475 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002476 nslcmop_desc["operationParams"][
2477 "validVimAccounts"
2478 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002479 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002480 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002481 if not slice_object:
2482 self.msg.write("ns", operation, nslcmop_desc)
garciadeblasf53612b2024-07-12 14:44:37 +02002483 return _id, nsName, None
tiernobdebce92019-07-01 15:36:49 +00002484 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002485 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2486 # except DbException as e:
2487 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2488
Gabriel Cuba84a60df2023-10-30 14:01:54 -05002489 def cancel(self, rollback, session, indata=None, kwargs=None, headers=None):
2490 validate_input(indata, self.operation_schema["cancel"])
2491 # Override descriptor with query string kwargs
2492 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
2493 nsLcmOpOccId = indata["nsLcmOpOccId"]
2494 cancelMode = indata["cancelMode"]
2495 # get nslcmop from nsLcmOpOccId
2496 _filter = BaseTopic._get_project_filter(session)
2497 _filter["_id"] = nsLcmOpOccId
2498 nslcmop = self.db.get_one("nslcmops", _filter)
2499 # Fail is this is not an ongoing nslcmop
2500 if nslcmop.get("operationState") not in [
2501 "STARTING",
2502 "PROCESSING",
2503 "ROLLING_BACK",
2504 ]:
2505 raise EngineException(
2506 "Operation is not in STARTING, PROCESSING or ROLLING_BACK state",
2507 http_code=HTTPStatus.CONFLICT,
2508 )
2509 nsInstanceId = nslcmop["nsInstanceId"]
2510 update_dict = {
2511 "isCancelPending": True,
2512 "cancelMode": cancelMode,
2513 }
2514 self.db.set_one(
2515 "nslcmops", q_filter=_filter, update_dict=update_dict, fail_on_empty=False
2516 )
2517 data = {
2518 "_id": nsLcmOpOccId,
2519 "nsInstanceId": nsInstanceId,
2520 "cancelMode": cancelMode,
2521 }
2522 self.msg.write("nslcmops", "cancel", data)
2523
tiernobee3bad2019-12-05 12:26:01 +00002524 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002525 raise EngineException(
2526 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2527 )
tiernob24258a2018-10-04 18:39:49 +02002528
tierno65ca36d2019-02-12 19:27:52 +01002529 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002530 raise EngineException(
2531 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2532 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002533
2534
2535class NsiTopic(BaseTopic):
2536 topic = "nsis"
2537 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002538 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002539
delacruzramo32bab472019-09-13 12:24:22 +02002540 def __init__(self, db, fs, msg, auth):
2541 BaseTopic.__init__(self, db, fs, msg, auth)
2542 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002543
Felipe Vicensc37b3842019-01-12 12:24:42 +01002544 @staticmethod
2545 def _format_ns_request(ns_request):
2546 formated_request = copy(ns_request)
2547 # TODO: Add request params
2548 return formated_request
2549
2550 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002551 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002552 """
2553 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002554 :param slice_request: User instantiation additional parameters
2555 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002556 """
tiernofd160572019-01-21 10:41:37 +00002557 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2558 if additional_params:
2559 for k, v in additional_params.items():
2560 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002561 raise EngineException(
2562 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2563 k
2564 )
2565 )
tiernofd160572019-01-21 10:41:37 +00002566 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002567 raise EngineException(
2568 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2569 k
2570 )
2571 )
tiernofd160572019-01-21 10:41:37 +00002572 if isinstance(v, (dict, tuple, list)):
2573 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002574 return additional_params
2575
tiernob4844ab2019-05-23 08:42:12 +00002576 def check_conflict_on_del(self, session, _id, db_content):
2577 """
2578 Check that NSI is not instantiated
2579 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2580 :param _id: nsi internal id
2581 :param db_content: The database content of the _id
2582 :return: None or raises EngineException with the conflict
2583 """
tierno65ca36d2019-02-12 19:27:52 +01002584 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002585 return
tiernob4844ab2019-05-23 08:42:12 +00002586 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002587 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002588 raise EngineException(
2589 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2590 "Launch 'terminate' operation first; or force deletion".format(_id),
2591 http_code=HTTPStatus.CONFLICT,
2592 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002593
tiernobee3bad2019-12-05 12:26:01 +00002594 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002595 """
tiernob4844ab2019-05-23 08:42:12 +00002596 Deletes associated nsilcmops from database. Deletes associated filesystem.
2597 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002598 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002599 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002600 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002601 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002602 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002603 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002604
Felipe Vicens09e65422019-01-22 15:06:46 +01002605 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002606 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002607 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2608 nsr_id = nsrs_detailed_item["nsrId"]
2609 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002610 _filter = {
2611 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2612 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2613 "_id.ne": nsir["_id"],
2614 }
2615 nsi = self.db.get_one(
2616 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2617 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002618 if nsi: # last one using nsr
2619 continue
2620 try:
garciadeblas4568a372021-03-24 09:19:48 +01002621 self.nsrTopic.delete(
2622 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2623 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002624 except (DbException, EngineException) as e:
2625 if e.http_code == HTTPStatus.NOT_FOUND:
2626 pass
2627 else:
2628 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002629
tiernob4844ab2019-05-23 08:42:12 +00002630 # delete related nsilcmops database entries
2631 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002632
tiernob4844ab2019-05-23 08:42:12 +00002633 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002634 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002635 if nsir_admin and nsir_admin.get("nst-id"):
2636 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002637 nsis_list = self.db.get_one(
2638 "nsis",
2639 {"nst-id": nsir_admin["nst-id"]},
2640 fail_on_empty=False,
2641 fail_on_more=False,
2642 )
tiernob4844ab2019-05-23 08:42:12 +00002643 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002644 self.db.set_one(
2645 "nsts",
2646 {"_id": nsir_admin["nst-id"]},
2647 {"_admin.usageState": "NOT_IN_USE"},
2648 )
tiernob4844ab2019-05-23 08:42:12 +00002649
tierno65ca36d2019-02-12 19:27:52 +01002650 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002651 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002652 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002653 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002654 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002655 :param indata: params to be used for the nsir
2656 :param kwargs: used to override the indata descriptor
2657 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002658 :return: the _id of nsi descriptor created at database
2659 """
2660
garciadeblasf2af4a12023-01-24 16:56:54 +01002661 step = "checking quotas" # first step must be defined outside try
Felipe Vicensb57758d2018-10-16 16:00:20 +02002662 try:
delacruzramo32bab472019-09-13 12:24:22 +02002663 self.check_quota(session)
2664
tierno99d4b172019-07-02 09:28:40 +00002665 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002666 slice_request = self._remove_envelop(indata)
2667 # Override descriptor with query string kwargs
2668 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002669 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002670
Felipe Vicensb57758d2018-10-16 16:00:20 +02002671 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002672 step = "getting nstd id='{}' from database".format(
2673 slice_request.get("nstId")
2674 )
tiernob4844ab2019-05-23 08:42:12 +00002675 _filter = self._get_project_filter(session)
2676 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002677 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002678 # check NST is not disabled
2679 step = "checking NST operationalState"
2680 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002681 raise EngineException(
2682 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2683 "instance".format(slice_request["nstId"]),
2684 http_code=HTTPStatus.CONFLICT,
2685 )
tiernob4844ab2019-05-23 08:42:12 +00002686 del _filter["_id"]
2687
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002688 # check NSD is not disabled
2689 step = "checking operationalState"
2690 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002691 raise EngineException(
2692 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2693 "a network slice".format(slice_request["nstId"]),
2694 http_code=HTTPStatus.CONFLICT,
2695 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002696
Felipe Vicens07f31722018-10-29 15:16:44 +01002697 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002698 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002699 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002700 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002701
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002702 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002703 nsi_descriptor = {
2704 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002705 "name": slice_request["nsiName"],
2706 "description": slice_request.get("nsiDescription", ""),
2707 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002708 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002709 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002710 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002711 "nsr-ref-list": [],
2712 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002713 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002714 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002715 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002716
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002717 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002718 self.format_on_new(
2719 nsi_descriptor, session["project_id"], make_public=session["public"]
2720 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002721 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2722 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002723 nsi_descriptor["_admin"]["deployed"] = {}
2724 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2725 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2726
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002727 # Creating netslice-vld for the RO.
2728 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002729
2730 # Building the vlds list to be deployed
2731 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002732 nsi_vlds = []
2733
2734 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2735 # Getting template Instantiation parameters from NST
2736 nsi_vld = deepcopy(netslice_vlds)
2737 nsi_vld["shared-nsrs-list"] = []
2738 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2739 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002740
2741 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002742 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002743 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002744 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002745
Felipe Vicens09e65422019-01-22 15:06:46 +01002746 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002747 for member_ns in nstd["netslice-subnet"]:
2748 nsd_id = member_ns["nsd-ref"]
2749 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002750 member_ns["nsd-ref"], member_ns["id"]
2751 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002752 if nsd_id not in needed_nsds:
2753 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002754 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002755 nsd = self.db.get_one(
2756 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2757 )
tiernob4844ab2019-05-23 08:42:12 +00002758 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002759 nsd.pop("_admin")
2760 needed_nsds[nsd_id] = nsd
2761 else:
2762 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002763 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2764 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002765
Felipe Vicensb57758d2018-10-16 16:00:20 +02002766 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002767 member_ns["nsd-ref"], member_ns["id"]
2768 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002769
Felipe Vicens07f31722018-10-29 15:16:44 +01002770 # creates Network Services records (NSRs)
2771 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002772 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002773 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002774 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002775 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002776 # Check if the netslice-subnet is shared and if it is share if the nss exists
2777 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002778 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002779 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002780 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002781 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2782 "nsd-ref"
2783 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002784 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002785 nsi = self.db.get_one(
2786 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2787 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002788 if nsi and service.get("is-shared-nss"):
2789 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2790 for nsrs_detailed_item in nsrs_detailed_list:
2791 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002792 if nsrs_detailed_item["nss-id"] == service["id"]:
2793 _id_nsr = nsrs_detailed_item["nsrId"]
2794 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002795 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2796 if netslice_subnet["nss-id"] == service["id"]:
2797 indata_ns = netslice_subnet
2798 break
2799 else:
2800 indata_ns = {}
2801 if service.get("instantiation-parameters"):
2802 indata_ns = deepcopy(service["instantiation-parameters"])
2803 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002804
Felipe Vicens09e65422019-01-22 15:06:46 +01002805 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002806 indata_ns["nsName"] = (
2807 slice_request.get("nsiName") + "." + service["id"]
2808 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002809 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2810 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002811 if slice_request.get("ssh_keys"):
2812 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002813
Felipe Vicens09e65422019-01-22 15:06:46 +01002814 if ns_params:
2815 for ns_param in ns_params:
2816 if ns_param.get("id") == service["id"]:
2817 copy_ns_param = deepcopy(ns_param)
2818 del copy_ns_param["id"]
2819 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002820 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002821
2822 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002823 _id_nsr, _ = self.nsrTopic.new(
2824 rollback, session, indata_ns, kwargs, headers
2825 )
2826 nsrs_item = {
2827 "nsrId": _id_nsr,
2828 "shared": service.get("is-shared-nss"),
2829 "nsd-id": service["nsd-ref"],
2830 "nss-id": service["id"],
2831 "nslcmop_instantiate": None,
2832 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002833 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002834 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002835 nsi_netslice_subnet.append(indata_ns)
2836 nsr_ref = {"nsr-ref": _id_nsr}
2837 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002838
2839 # Adding the nsrs list to the nsi
2840 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002841 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002842 self.db.set_one(
2843 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2844 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002845
Felipe Vicens07f31722018-10-29 15:16:44 +01002846 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002847 self.db.create("nsis", nsi_descriptor)
2848 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002849 return nsi_id, None
garciadeblasf2af4a12023-01-24 16:56:54 +01002850 except ValidationError as e:
2851 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
garciadeblas4568a372021-03-24 09:19:48 +01002852 except Exception as e: # TODO remove try Except, it is captured at nbi.py
rshri2d386cb2024-07-05 14:35:51 +00002853 # self.logger.exception(
2854 # "Exception {} at NsiTopic.new()".format(e), exc_info=True
2855 # )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002856 raise EngineException("Error {}: {}".format(step, e))
Felipe Vicensb57758d2018-10-16 16:00:20 +02002857
tierno65ca36d2019-02-12 19:27:52 +01002858 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002859 raise EngineException(
2860 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2861 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002862
2863
2864class NsiLcmOpTopic(BaseTopic):
2865 topic = "nsilcmops"
2866 topic_msg = "nsi"
2867 operation_schema = { # mapping between operation and jsonschema to validate
2868 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002869 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002870 }
garciadeblas4568a372021-03-24 09:19:48 +01002871
delacruzramo32bab472019-09-13 12:24:22 +02002872 def __init__(self, db, fs, msg, auth):
2873 BaseTopic.__init__(self, db, fs, msg, auth)
2874 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002875
2876 def _check_nsi_operation(self, session, nsir, operation, indata):
2877 """
2878 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002879 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002880 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2881 :param indata: descriptor with the parameters of the operation
2882 :return: None
2883 """
2884 nsds = {}
2885 nstd = nsir["network-slice-template"]
2886
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002887 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002888 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002889 for netslice_subnet in nstd["netslice-subnet"]:
2890 if nstId == netslice_subnet["id"]:
2891 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002892 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002893 _filter = self._get_project_filter(session)
2894 _filter["id"] = nsd_id
2895 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002896 return nsds[nsd_id]
2897 else:
garciadeblas4568a372021-03-24 09:19:48 +01002898 raise EngineException(
2899 "Invalid parameter nstId='{}' is not one of the "
2900 "nst:netslice-subnet".format(nstId)
2901 )
2902
Felipe Vicens07f31722018-10-29 15:16:44 +01002903 if operation == "instantiate":
2904 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002905 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002906 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002907
2908 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2909 now = time()
2910 _id = str(uuid4())
2911 nsilcmop = {
2912 "id": _id,
2913 "_id": _id,
2914 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2915 "statusEnteredTime": now,
2916 "netsliceInstanceId": netsliceInstanceId,
2917 "lcmOperationType": operation,
2918 "startTime": now,
2919 "isAutomaticInvocation": False,
2920 "operationParams": params,
2921 "isCancelPending": False,
2922 "links": {
2923 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002924 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2925 + netsliceInstanceId,
2926 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002927 }
2928 return nsilcmop
2929
Felipe Vicens09e65422019-01-22 15:06:46 +01002930 def add_shared_nsr_2vld(self, nsir, nsr_item):
2931 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2932 if nst_sb_item.get("is-shared-nss"):
2933 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2934 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2935 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002936 for admin_vld_nss_cp_ref_item in admin_vld_item[
2937 "nss-connection-point-ref"
2938 ]:
2939 if (
2940 admin_subnet_item["nss-id"]
2941 == admin_vld_nss_cp_ref_item["nss-ref"]
2942 ):
2943 if (
2944 not nsr_item["nsrId"]
2945 in admin_vld_item["shared-nsrs-list"]
2946 ):
2947 admin_vld_item["shared-nsrs-list"].append(
2948 nsr_item["nsrId"]
2949 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002950 break
2951 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002952 self.db.set_one(
2953 "nsis",
2954 {"_id": nsir["_id"]},
2955 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2956 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002957
tierno65ca36d2019-02-12 19:27:52 +01002958 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002959 """
2960 Performs a new operation over a ns
2961 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002962 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002963 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002964 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002965 operation: it can be: instantiate, terminate, action, TODO: update, heal
2966 :param kwargs: used to override the indata descriptor
2967 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002968 :return: id of the nslcmops
2969 """
2970 try:
2971 # Override descriptor with query string kwargs
2972 self._update_input_with_kwargs(indata, kwargs)
2973 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002974 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002975 validate_input(indata, self.operation_schema[operation])
2976
Felipe Vicens126af572019-06-05 19:13:04 +02002977 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002978 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002979 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002980 nsir = self.db.get_one("nsis", _filter)
rshri2d386cb2024-07-05 14:35:51 +00002981 # logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002982 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002983
2984 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002985 if (
2986 not nsir["_admin"].get("nsiState")
2987 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2988 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002989 if operation == "terminate" and indata.get("autoremove"):
2990 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002991 return (
2992 None,
2993 None,
2994 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002995 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002996 raise EngineException(
2997 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2998 netsliceInstanceId, operation
2999 ),
3000 HTTPStatus.CONFLICT,
3001 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003002 else:
tierno65ca36d2019-02-12 19:27:52 +01003003 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01003004 raise EngineException(
3005 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
3006 netsliceInstanceId, operation
3007 ),
3008 HTTPStatus.CONFLICT,
3009 )
3010
Felipe Vicens07f31722018-10-29 15:16:44 +01003011 # Creating all the NS_operation (nslcmop)
3012 # Get service list from db
3013 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
3014 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01003015 # nslcmops_item = None
3016 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00003017 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01003018 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003019 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00003020 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01003021 _filter[
3022 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
3023 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02003024 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01003025 nsi = self.db.get_one(
3026 "nsis", _filter, fail_on_empty=False, fail_on_more=False
3027 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003028 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01003029 _update = {
3030 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3031 index
3032 ): None
3033 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003034 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01003035 if (
3036 nsi
3037 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00003038 continue # do not create nsilcmop
3039 else: # instantiate
3040 # looks the first nsi fulfilling the conditions but not being the current NSIR
3041 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01003042 nsi_nsr_item = next(
3043 n
3044 for n in nsi["_admin"]["nsrs-detailed-list"]
3045 if n["nsrId"] == nsr_id
3046 and n["shared"]
3047 and n["nslcmop_instantiate"]
3048 )
tierno40f742b2020-06-23 15:25:26 +00003049 self.add_shared_nsr_2vld(nsir, nsr_item)
3050 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01003051 _update = {
3052 "_admin.nsrs-detailed-list.{}".format(
3053 index
3054 ): nsi_nsr_item
3055 }
tierno40f742b2020-06-23 15:25:26 +00003056 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
3057 # continue to not create nslcmop since nsrs is shared and nsrs was created
3058 continue
3059 else:
3060 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01003061
tierno40f742b2020-06-23 15:25:26 +00003062 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01003063 try:
tierno0b8752f2020-05-12 09:42:02 +00003064 indata_ns = {
3065 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00003066 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00003067 # Including netslice_id in the ns instantiate Operation
3068 "netsliceInstanceId": netsliceInstanceId,
3069 }
3070 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00003071 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00003072 indata_ns.update(service["instantiate_params"])
3073
tierno99d4b172019-07-02 09:28:40 +00003074 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01003075 # message via kafka bus
Adurti87c0e4b2024-07-16 07:33:42 +00003076 nslcmop, _, _ = self.nsi_NsLcmOpTopic.new(
garciadeblas4568a372021-03-24 09:19:48 +01003077 rollback, session, indata_ns, None, headers, slice_object=True
3078 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003079 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00003080 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01003081 _update = {
3082 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3083 index
3084 ): nslcmop
3085 }
tierno40f742b2020-06-23 15:25:26 +00003086 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01003087 except (DbException, EngineException) as e:
3088 if e.http_code == HTTPStatus.NOT_FOUND:
Felipe Vicens09e65422019-01-22 15:06:46 +01003089 pass
3090 else:
3091 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01003092
3093 # Creates nsilcmop
3094 indata["nslcmops_ids"] = nslcmops
3095 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01003096
garciadeblas4568a372021-03-24 09:19:48 +01003097 nsilcmop_desc = self._create_nsilcmop(
3098 session, netsliceInstanceId, operation, indata
3099 )
3100 self.format_on_new(
3101 nsilcmop_desc, session["project_id"], make_public=session["public"]
3102 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003103 _id = self.db.create("nsilcmops", nsilcmop_desc)
3104 rollback.append({"topic": "nsilcmops", "_id": _id})
3105 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00003106 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01003107 except ValidationError as e:
3108 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01003109
tiernobee3bad2019-12-05 12:26:01 +00003110 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01003111 raise EngineException(
3112 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3113 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003114
tierno65ca36d2019-02-12 19:27:52 +01003115 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01003116 raise EngineException(
3117 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3118 )