blob: c3362293b8a258d6d674360c5b4f76629a8b7fd9 [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernob24258a2018-10-04 18:39:49 +020016# import logging
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +010017import json
tiernob24258a2018-10-04 18:39:49 +020018from uuid import uuid4
19from http import HTTPStatus
20from time import time
tiernocc103432018-10-19 14:10:35 +020021from copy import copy, deepcopy
garciadeblas4568a372021-03-24 09:19:48 +010022from osm_nbi.validation import (
23 validate_input,
24 ValidationError,
25 ns_instantiate,
26 ns_terminate,
27 ns_action,
28 ns_scale,
aticig544a2ae2022-04-05 09:00:17 +030029 ns_update,
garciadeblas0964edf2022-02-11 00:43:44 +010030 ns_heal,
garciadeblas4568a372021-03-24 09:19:48 +010031 nsi_instantiate,
elumalai8e3806c2022-04-28 17:26:24 +053032 ns_migrate,
Gabriel Cuba84a60df2023-10-30 14:01:54 -050033 nslcmop_cancel,
garciadeblas4568a372021-03-24 09:19:48 +010034)
35from osm_nbi.base_topic import (
36 BaseTopic,
37 EngineException,
38 get_iterable,
39 deep_get,
40 increment_ip_mac,
aticig2b5e1232022-08-10 17:30:12 +030041 update_descriptor_usage_state,
garciadeblas4568a372021-03-24 09:19:48 +010042)
tiernobee085c2018-12-12 17:03:04 +000043from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010044from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000045from osm_common.msgbase import MsgException
46from osm_common.fsbase import FsException
garciaale7cbd03c2020-11-27 10:38:35 -030047from osm_nbi import utils
garciadeblas4568a372021-03-24 09:19:48 +010048from re import (
49 match,
50) # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020051
52__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
53
54
55class NsrTopic(BaseTopic):
56 topic = "nsrs"
57 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000058 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000059 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020060
delacruzramo32bab472019-09-13 12:24:22 +020061 def __init__(self, db, fs, msg, auth):
62 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020063
tiernob24258a2018-10-04 18:39:49 +020064 @staticmethod
65 def format_on_new(content, project_id=None, make_public=False):
66 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
67 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000068 return None
tiernob24258a2018-10-04 18:39:49 +020069
tiernob4844ab2019-05-23 08:42:12 +000070 def check_conflict_on_del(self, session, _id, db_content):
71 """
72 Check that NSR is not instantiated
73 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
74 :param _id: nsr internal id
75 :param db_content: The database content of the nsr
76 :return: None or raises EngineException with the conflict
77 """
tierno65ca36d2019-02-12 19:27:52 +010078 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020079 return
tiernob4844ab2019-05-23 08:42:12 +000080 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020081 if nsr["_admin"].get("nsState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +010082 raise EngineException(
83 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
84 "Launch 'terminate' operation first; or force deletion".format(_id),
85 http_code=HTTPStatus.CONFLICT,
86 )
tiernob24258a2018-10-04 18:39:49 +020087
tiernobee3bad2019-12-05 12:26:01 +000088 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +000089 """
90 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
91 Set usageState of pdu, vnfd, nsd
92 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
93 :param _id: server internal id
94 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +000095 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +000096 :return: None if ok or raises EngineException with the problem
97 """
tiernobee085c2018-12-12 17:03:04 +000098 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +020099 self.db.del_list("nslcmops", {"nsInstanceId": _id})
100 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +0000101
tiernob24258a2018-10-04 18:39:49 +0200102 # set all used pdus as free
garciadeblas4568a372021-03-24 09:19:48 +0100103 self.db.set_list(
104 "pdus",
105 {"_admin.usage.nsr_id": _id},
106 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
107 )
tiernob24258a2018-10-04 18:39:49 +0200108
tiernob4844ab2019-05-23 08:42:12 +0000109 # Set NSD usageState
110 nsr = db_content
111 used_nsd_id = nsr.get("nsd-id")
112 if used_nsd_id:
113 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100114 nsrs_list = self.db.get_one(
115 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
116 )
tiernob4844ab2019-05-23 08:42:12 +0000117 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100118 self.db.set_one(
119 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
120 )
tiernob4844ab2019-05-23 08:42:12 +0000121
kayal2001f71c2e82024-06-25 15:26:24 +0530122 # Set NS CONFIG TEMPLATE usageState
123 if nsr.get("instantiate_params", {}).get("nsConfigTemplateId"):
124 nsconfigtemplate_id = nsr.get("instantiate_params", {}).get(
125 "nsConfigTemplateId"
126 )
127 nsconfigtemplate_list = self.db.get_one(
128 "nsrs",
129 {"instantiate_params.nsConfigTemplateId": nsconfigtemplate_id},
130 fail_on_empty=False,
131 fail_on_more=False,
132 )
133 if not nsconfigtemplate_list:
134 self.db.set_one(
135 "ns_config_template",
136 {"_id": nsconfigtemplate_id},
137 {"_admin.usageState": "NOT_IN_USE"},
138 )
139
tiernob4844ab2019-05-23 08:42:12 +0000140 # Set VNFD usageState
141 used_vnfd_id_list = nsr.get("vnfd-id")
142 if used_vnfd_id_list:
143 for used_vnfd_id in used_vnfd_id_list:
144 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100145 nsrs_list = self.db.get_one(
146 "nsrs",
147 {"vnfd-id": used_vnfd_id},
148 fail_on_empty=False,
149 fail_on_more=False,
150 )
tiernob4844ab2019-05-23 08:42:12 +0000151 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100152 self.db.set_one(
153 "vnfds",
154 {"_id": used_vnfd_id},
155 {"_admin.usageState": "NOT_IN_USE"},
156 )
tiernob4844ab2019-05-23 08:42:12 +0000157
tiernof0441ea2020-05-26 15:39:18 +0000158 # delete extra ro_nsrs used for internal RO module
159 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
160
tiernobee085c2018-12-12 17:03:04 +0000161 @staticmethod
162 def _format_ns_request(ns_request):
163 formated_request = copy(ns_request)
164 formated_request.pop("additionalParamsForNs", None)
165 formated_request.pop("additionalParamsForVnf", None)
166 return formated_request
167
168 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +0100169 def _format_additional_params(
170 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
171 ):
tiernobee085c2018-12-12 17:03:04 +0000172 """
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100173 Get and format user additional params for NS or VNF.
174 The vdu_id and kdu_name params are mutually exclusive! If none of them are given, then the method will
175 exclusively search for the VNF/NS LCM additional params.
176
tiernobee085c2018-12-12 17:03:04 +0000177 :param ns_request: User instantiation additional parameters
178 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100179 :vdu_id: VDU's ID against which we want to format the additional params
180 :kdu_name: KDU's name against which we want to format the additional params
tiernobee085c2018-12-12 17:03:04 +0000181 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000182 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000183 """
184 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000185 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000186 if not member_vnf_index:
187 additional_params = copy(ns_request.get("additionalParamsForNs"))
188 where_ = "additionalParamsForNs"
189 elif ns_request.get("additionalParamsForVnf"):
garciadeblas4568a372021-03-24 09:19:48 +0100190 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
191 member_vnf_index
192 )
193 item = next(
194 (
195 x
196 for x in ns_request["additionalParamsForVnf"]
197 if x["member-vnf-index"] == member_vnf_index
198 ),
199 None,
200 )
tierno714954e2019-11-29 13:43:26 +0000201 if item:
tierno54db2e42020-04-06 15:29:42 +0000202 if not vdu_id and not kdu_name:
203 other_params = item
tierno714954e2019-11-29 13:43:26 +0000204 additional_params = copy(item.get("additionalParams")) or {}
205 if vdu_id and item.get("additionalParamsForVdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100206 item_vdu = next(
207 (
208 x
209 for x in item["additionalParamsForVdu"]
210 if x["vdu_id"] == vdu_id
211 ),
212 None,
213 )
tiernobce98f02020-04-17 11:27:47 +0000214 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000215 if item_vdu and item_vdu.get("additionalParams"):
216 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000217 additional_params = item_vdu["additionalParams"]
218 if kdu_name:
219 additional_params = {}
220 if item.get("additionalParamsForKdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100221 item_kdu = next(
222 (
223 x
224 for x in item["additionalParamsForKdu"]
225 if x["kdu_name"] == kdu_name
226 ),
227 None,
228 )
tiernobce98f02020-04-17 11:27:47 +0000229 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000230 if item_kdu and item_kdu.get("additionalParams"):
garciadeblas4568a372021-03-24 09:19:48 +0100231 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
232 kdu_name
233 )
tiernob091dc12019-12-02 15:53:25 +0000234 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000235
tiernobee085c2018-12-12 17:03:04 +0000236 if additional_params:
237 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000238 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
garciadeblas4568a372021-03-24 09:19:48 +0100239 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
240 raise EngineException(
241 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
242 "and underscores, and cannot start with a digit".format(
243 where_, k
244 )
245 )
delacruzramo36ffe552019-05-03 14:52:37 +0200246 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000247 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +0100248 raise EngineException(
249 "Invalid param at {}:{}. Only string keys are allowed".format(
250 where_, k
251 )
252 )
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100253 if "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +0100254 raise EngineException(
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100255 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
garciadeblas4568a372021-03-24 09:19:48 +0100256 where_, k
257 )
258 )
tiernobee085c2018-12-12 17:03:04 +0000259 if isinstance(v, (dict, tuple, list)):
260 additional_params[k] = "!!yaml " + safe_dump(v)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100261 if kdu_name:
262 additional_params = json.dumps(additional_params)
tiernobee085c2018-12-12 17:03:04 +0000263
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100264 # Select the VDU ID, KDU name or NS/VNF ID, depending on the method's call intent
265 selector = vdu_id if vdu_id else kdu_name if kdu_name else descriptor.get("id")
266
tiernobee085c2018-12-12 17:03:04 +0000267 if descriptor:
bravof41a52052021-02-17 18:08:01 -0300268 for df in descriptor.get("df", []):
269 # check that enough parameters are supplied for the initial-config-primitive
270 # TODO: check for cloud-init
271 if member_vnf_index:
garciaale7cbd03c2020-11-27 10:38:35 -0300272 initial_primitives = []
garciadeblas4568a372021-03-24 09:19:48 +0100273 if (
274 "lcm-operations-configuration" in df
275 and "operate-vnf-op-config"
276 in df["lcm-operations-configuration"]
277 ):
278 for config in df["lcm-operations-configuration"][
279 "operate-vnf-op-config"
280 ].get("day1-2", []):
garciadeblasf2af4a12023-01-24 16:56:54 +0100281 # Verify the target object (VNF|NS|VDU|KDU) where we need to populate
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100282 # the params with the additional ones given by the user
283 if config.get("id") == selector:
284 for primitive in get_iterable(
285 config.get("initial-config-primitive")
286 ):
287 initial_primitives.append(primitive)
bravof41a52052021-02-17 18:08:01 -0300288 else:
garciadeblas4568a372021-03-24 09:19:48 +0100289 initial_primitives = deep_get(
290 descriptor, ("ns-configuration", "initial-config-primitive")
291 )
tiernobee085c2018-12-12 17:03:04 +0000292
bravof41a52052021-02-17 18:08:01 -0300293 for initial_primitive in get_iterable(initial_primitives):
294 for param in get_iterable(initial_primitive.get("parameter")):
garciadeblas4568a372021-03-24 09:19:48 +0100295 if param["value"].startswith("<") and param["value"].endswith(
296 ">"
297 ):
298 if param["value"] in (
299 "<rw_mgmt_ip>",
300 "<VDU_SCALE_INFO>",
301 "<ns_config_info>",
garciadeblasf2af4a12023-01-24 16:56:54 +0100302 "<OSM>",
garciadeblas4568a372021-03-24 09:19:48 +0100303 ):
bravof41a52052021-02-17 18:08:01 -0300304 continue
garciadeblas4568a372021-03-24 09:19:48 +0100305 if (
306 not additional_params
307 or param["value"][1:-1] not in additional_params
308 ):
309 raise EngineException(
310 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
311 "initial-config-primitive[name={}] not supplied".format(
312 param["value"],
313 descriptor["id"],
314 initial_primitive["name"],
315 )
316 )
tierno714954e2019-11-29 13:43:26 +0000317
tierno54db2e42020-04-06 15:29:42 +0000318 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000319
tierno65ca36d2019-02-12 19:27:52 +0100320 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200321 """
322 Creates a new nsr into database. It also creates needed vnfrs
323 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100324 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200325 :param indata: params to be used for the nsr
326 :param kwargs: used to override the indata descriptor
327 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000328 :return: the _id of nsr descriptor created at database. Or an exception of type
329 EngineException, ValidationError, DbException, FsException, MsgException.
330 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200331 """
garciadeblasf2af4a12023-01-24 16:56:54 +0100332 step = "checking quotas" # first step must be defined outside try
tiernob24258a2018-10-04 18:39:49 +0200333 try:
delacruzramo32bab472019-09-13 12:24:22 +0200334 self.check_quota(session)
335
tierno99d4b172019-07-02 09:28:40 +0000336 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200337 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200338 self._update_input_with_kwargs(ns_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -0300339 ns_request = self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200340
tiernob24258a2018-10-04 18:39:49 +0200341 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale7cbd03c2020-11-27 10:38:35 -0300342 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
343 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200344
kayal2001f71c2e82024-06-25 15:26:24 +0530345 # Uploading the instantiation parameters to ns_request from ns config template
346 if ns_request.get("nsConfigTemplateId"):
347 step = "getting ns_config_template is='{}' from database".format(
348 ns_request.get("nsConfigTemplateId")
349 )
350 ns_config_template_db = self._get_nsConfigTemplate_from_db(
351 ns_request.get("nsConfigTemplateId"), session
352 )
353 ns_config_params = ns_config_template_db.get("config")
354 for key, value in ns_config_params.items():
355 if key == "vnf":
356 ns_request["vnf"] = ns_config_params.get("vnf")
357 elif key == "additionalParamsForVnf":
358 ns_request["additionalParamsForVnf"] = ns_config_params.get(
359 "additionalParamsForVnf"
360 )
361 elif key == "additionalParamsForNs":
362 ns_request["additionalParamsForNs"] = ns_config_params.get(
363 "additionalParamsForNs"
364 )
365 elif key == "vld":
366 ns_request["vld"] = ns_config_params.get("vld")
367 step = "checking ns_config_templateOperationalState"
368 self._check_ns_config_template_operational_state(
369 ns_config_template_db, ns_request
370 )
371
372 step = "Updating NSCONFIG TEMPLATE usageState"
373 update_descriptor_usage_state(
374 ns_config_template_db, "ns_config_template", self.db
375 )
376
kayal2001b16cf252024-11-28 10:47:32 +0530377 elif ns_request.get("vnf"):
378 vnf_data = ns_request.get("vnf")
379 for vnf in vnf_data:
380 for vdu in vnf.get("vdu"):
381 if vdu.get("vim-flavor-name") and vdu.get("vim-flavor-id"):
382 raise EngineException(
383 "Instantiation parameters vim-flavor-name and vim-flavor-id are mutually exclusive"
384 )
385
Frank Bryden3c64ab62020-07-21 14:25:32 +0000386 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300387 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000388
tiernob24258a2018-10-04 18:39:49 +0200389 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300390 nsr_id = str(uuid4())
garciadeblas4568a372021-03-24 09:19:48 +0100391 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
392 nsd, ns_request, nsr_id, session
393 )
tierno54db2e42020-04-06 15:29:42 +0000394
garciaale7cbd03c2020-11-27 10:38:35 -0300395 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200396 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300397 # TODO: Change for multiple df support
K Sai Kiranbb006022021-05-20 11:09:49 +0530398 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
garciaale7cbd03c2020-11-27 10:38:35 -0300399 for vnfp in vnf_profiles:
400 vnfd_id = vnfp.get("vnfd-id")
401 vnf_index = vnfp.get("id")
garciadeblas4568a372021-03-24 09:19:48 +0100402 step = (
403 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
404 vnfd_id, vnf_index
405 )
406 )
tiernob24258a2018-10-04 18:39:49 +0200407 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300408 vnfd = self._get_vnfd_from_db(vnfd_id, session)
beierlmcee2ebf2022-03-29 17:42:48 -0400409 if "revision" in vnfd["_admin"]:
410 vnfd["revision"] = vnfd["_admin"]["revision"]
411 vnfd.pop("_admin")
tiernob24258a2018-10-04 18:39:49 +0200412 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000413 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200414 else:
415 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100416
garciadeblas4568a372021-03-24 09:19:48 +0100417 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
418 vnfd_id, vnf_index
419 )
420 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
421 nsd,
422 vnfd,
423 vnfd_id,
424 vnf_index,
425 nsr_descriptor,
426 ns_request,
427 ns_k8s_namespace,
428 )
tierno36ec8602018-11-02 17:27:11 +0100429
garciadeblas4568a372021-03-24 09:19:48 +0100430 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
431 vnfd_id, vnf_index
432 )
garciaale7cbd03c2020-11-27 10:38:35 -0300433 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
434 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
aticig2b5e1232022-08-10 17:30:12 +0300435 step = "Updating VNFD usageState"
436 update_descriptor_usage_state(vnfd, "vnfds", self.db)
tiernob24258a2018-10-04 18:39:49 +0200437
438 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300439 self._add_nsr_to_db(nsr_descriptor, rollback, session)
aticig2b5e1232022-08-10 17:30:12 +0300440 step = "Updating NSD usageState"
441 update_descriptor_usage_state(nsd, "nsds", self.db)
tiernobee085c2018-12-12 17:03:04 +0000442
443 step = "creating nsr temporal folder"
444 self.fs.mkdir(nsr_id)
445
tiernobdebce92019-07-01 15:36:49 +0000446 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100447 except (
448 ValidationError,
449 EngineException,
450 DbException,
451 MsgException,
452 FsException,
453 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000454 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200455
garciaale7cbd03c2020-11-27 10:38:35 -0300456 def _get_nsd_from_db(self, nsd_id, session):
457 _filter = self._get_project_filter(session)
458 _filter["_id"] = nsd_id
459 return self.db.get_one("nsds", _filter)
460
kayal2001f71c2e82024-06-25 15:26:24 +0530461 def _get_nsConfigTemplate_from_db(self, nsConfigTemplate_id, session):
462 _filter = self._get_project_filter(session)
463 _filter["_id"] = nsConfigTemplate_id
464 ns_config_template_db = self.db.get_one(
465 "ns_config_template", _filter, fail_on_empty=False
466 )
467 return ns_config_template_db
468
garciaale7cbd03c2020-11-27 10:38:35 -0300469 def _get_vnfd_from_db(self, vnfd_id, session):
470 _filter = self._get_project_filter(session)
471 _filter["id"] = vnfd_id
472 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
garciaale7cbd03c2020-11-27 10:38:35 -0300473 return vnfd
474
475 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100476 self.format_on_new(
477 nsr_descriptor, session["project_id"], make_public=session["public"]
478 )
garciaale7cbd03c2020-11-27 10:38:35 -0300479 self.db.create("nsrs", nsr_descriptor)
480 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
481
482 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100483 self.format_on_new(
484 vnfr_descriptor, session["project_id"], make_public=session["public"]
485 )
garciaale7cbd03c2020-11-27 10:38:35 -0300486 self.db.create("vnfrs", vnfr_descriptor)
487 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
488
489 def _check_nsd_operational_state(self, nsd, ns_request):
490 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100491 raise EngineException(
492 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
493 "a network service".format(ns_request["nsdId"]),
494 http_code=HTTPStatus.CONFLICT,
495 )
garciaale7cbd03c2020-11-27 10:38:35 -0300496
kayal2001f71c2e82024-06-25 15:26:24 +0530497 def _check_ns_config_template_operational_state(
498 self, ns_config_template_db, ns_request
499 ):
500 if ns_config_template_db["_admin"]["operationalState"] == "DISABLED":
501 raise EngineException(
502 "ns_config_template with id '{}' is DISABLED, and thus cannot be used to create "
503 "a network service".format(ns_request["nsConfigTemplateId"]),
504 http_code=HTTPStatus.CONFLICT,
505 )
506
garciaale7cbd03c2020-11-27 10:38:35 -0300507 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100508 additional_params, _ = self._format_additional_params(
509 ns_request, descriptor=nsd
510 )
garciaale7cbd03c2020-11-27 10:38:35 -0300511 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
512 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
513 if ns_request and ns_request.get("k8s-namespace"):
514 ns_k8s_namespace = ns_request["k8s-namespace"]
515 if additional_params and additional_params.get("k8s-namespace"):
516 ns_k8s_namespace = additional_params["k8s-namespace"]
517
518 return ns_k8s_namespace
519
vegall18101ea2023-03-06 13:49:21 +0000520 def _add_shared_volumes_to_nsr(
521 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
522 ):
523 svsd = []
524 for vsd in vnfd.get("virtual-storage-desc", ()):
525 if vsd.get("vdu-storage-requirements"):
526 if (
527 vsd.get("vdu-storage-requirements")[0].get("key") == "multiattach"
528 and vsd.get("vdu-storage-requirements")[0].get("value") == "True"
529 ):
vegallf976a3a2023-06-02 21:25:32 +0000530 # Avoid setting the volume name multiple times
531 if not match(f"shared-.*-{vnfd['id']}", vsd["id"]):
vegall18101ea2023-03-06 13:49:21 +0000532 vsd["id"] = f"shared-{vsd['id']}-{vnfd['id']}"
533 svsd.append(vsd)
534 if svsd:
535 nsr_descriptor["shared-volumes"] = svsd
536
garciadeblasf2af4a12023-01-24 16:56:54 +0100537 def _add_flavor_to_nsr(
538 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
539 ):
elumalai6c5ea6b2022-04-25 22:27:59 +0530540 flavor_data = {}
541 guest_epa = {}
542 # Find this vdu compute and storage descriptors
543 vdu_virtual_compute = {}
544 vdu_virtual_storage = {}
545 for vcd in vnfd.get("virtual-compute-desc", ()):
546 if vcd.get("id") == vdu.get("virtual-compute-desc"):
547 vdu_virtual_compute = vcd
548 for vsd in vnfd.get("virtual-storage-desc", ()):
549 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
550 vdu_virtual_storage = vsd
551 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblasf2af4a12023-01-24 16:56:54 +0100552 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
elumalai6c5ea6b2022-04-25 22:27:59 +0530553 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
554 "num-virtual-cpu"
555 ]
556 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
557 flavor_data["memory-mb"] = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100558 float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
elumalai6c5ea6b2022-04-25 22:27:59 +0530559 )
560 if vdu_virtual_storage.get("size-of-storage"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100561 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530562 # Get this vdu EPA info for guest_epa
563 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100564 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530565 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
566 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
567 if vcpu_pinning.get("thread-policy"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100568 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530569 if vcpu_pinning.get("policy"):
570 cpu_policy = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100571 "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
elumalai6c5ea6b2022-04-25 22:27:59 +0530572 )
573 guest_epa["cpu-pinning-policy"] = cpu_policy
574 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100575 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
576 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
577 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"][
578 "mempage-size"
elumalai6c5ea6b2022-04-25 22:27:59 +0530579 ]
garciadeblasf2af4a12023-01-24 16:56:54 +0100580 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
581 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"][
582 "numa-node-policy"
583 ]
elumalai6c5ea6b2022-04-25 22:27:59 +0530584 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100585 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530586
587 if guest_epa:
588 flavor_data["guest-epa"] = guest_epa
589
elumalai99078a92022-07-05 17:53:59 +0530590 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +0100591 flavor_data["name"] = (
592 vdu["id"][:56] + "-" + member_vnf_index + "-" + str(revision) + "-flv"
593 )
elumalai6c5ea6b2022-04-25 22:27:59 +0530594 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
595 nsr_descriptor["flavor"].append(flavor_data)
596
bravofe76b8822021-02-26 16:57:52 -0300597 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300598 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100599 additional_params, _ = self._format_additional_params(
600 ns_request, descriptor=nsd
601 )
garciaale7cbd03c2020-11-27 10:38:35 -0300602
603 nsr_descriptor = {
604 "name": ns_request["nsName"],
605 "name-ref": ns_request["nsName"],
606 "short-name": ns_request["nsName"],
607 "admin-status": "ENABLED",
608 "nsState": "NOT_INSTANTIATED",
609 "currentOperation": "IDLE",
610 "currentOperationID": None,
611 "errorDescription": None,
612 "errorDetail": None,
613 "deploymentStatus": None,
614 "configurationStatus": None,
615 "vcaStatus": None,
616 "nsd": {k: v for k, v in nsd.items()},
617 "datacenter": ns_request["vimAccountId"],
618 "resource-orchestrator": "osmopenmano",
619 "description": ns_request.get("nsDescription", ""),
620 "constituent-vnfr-ref": [],
621 "operational-status": "init", # typedef ns-operational-
622 "config-status": "init", # typedef config-states
623 "detailed-status": "scheduled",
624 "orchestration-progress": {},
625 "create-time": now,
626 "nsd-name-ref": nsd["name"],
627 "operational-events": [], # "id", "timestamp", "description", "event",
628 "nsd-ref": nsd["id"],
629 "nsd-id": nsd["_id"],
630 "vnfd-id": [],
631 "instantiate_params": self._format_ns_request(ns_request),
632 "additionalParamsForNs": additional_params,
633 "ns-instance-config-ref": nsr_id,
634 "id": nsr_id,
635 "_id": nsr_id,
636 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
637 "flavor": [],
638 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100639 "affinity-or-anti-affinity-group": [],
vegall18101ea2023-03-06 13:49:21 +0000640 "shared-volumes": [],
selvi.j828f3f22023-05-16 05:43:48 +0000641 "vnffgd": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300642 }
beierlmbc5a5242022-05-17 21:25:29 -0400643 if "revision" in nsd["_admin"]:
644 nsr_descriptor["revision"] = nsd["_admin"]["revision"]
645
garciaale7cbd03c2020-11-27 10:38:35 -0300646 ns_request["nsr_id"] = nsr_id
647 if ns_request and ns_request.get("config-units"):
648 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300649 # Create vld
650 if nsd.get("virtual-link-desc"):
651 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
652 # Fill each vld with vnfd-connection-point-ref data
653 # TODO: Change for multiple df support
654 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
655 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
656 for vnf_profile in vnf_profiles:
657 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
658 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100659 all_vld_connection_point_data[
660 vlc.get("virtual-link-profile-id")
661 ].append(
662 {
663 "member-vnf-index-ref": cpd.get(
664 "constituent-base-element-id"
665 ),
666 "vnfd-connection-point-ref": cpd.get(
667 "constituent-cpd-id"
668 ),
669 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
670 }
671 )
garciaale7cbd03c2020-11-27 10:38:35 -0300672
bravofe76b8822021-02-26 16:57:52 -0300673 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400674 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300675
676 for vdu in vnfd.get("vdu", ()):
elumalai99078a92022-07-05 17:53:59 +0530677 member_vnf_index = vnf_profile.get("id")
678 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor, member_vnf_index)
vegall18101ea2023-03-06 13:49:21 +0000679 self._add_shared_volumes_to_nsr(
680 vdu, vnfd, nsr_descriptor, member_vnf_index
681 )
garciaale7cbd03c2020-11-27 10:38:35 -0300682 sw_image_id = vdu.get("sw-image-desc")
683 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000684 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
685 self._add_image_to_nsr(nsr_descriptor, image_data)
686
687 # also add alternative images to the list of images
688 for alt_image in vdu.get("alternative-sw-image-desc", ()):
689 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
690 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300691
Alexis Romero03fb5842022-03-11 15:53:40 +0100692 # Add Affinity or Anti-affinity group information to NSR
693 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200694 affinity_group_prefix_name = "{}-{}".format(
695 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
696 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100697
698 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200699 affinity_group_data = {}
700 for affinity_group in vdu_profile.get(
701 "affinity-or-anti-affinity-group", ()
702 ):
703 affinity_group_data = (
704 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
705 vnfd, affinity_group["id"]
706 )
707 )
708 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
709 self._add_affinity_or_anti_affinity_group_to_nsr(
710 nsr_descriptor,
711 affinity_group_data,
712 affinity_group_prefix_name,
713 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100714
garciaale7cbd03c2020-11-27 10:38:35 -0300715 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100716 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
717 vld.get("id"), []
718 )
garciaale7cbd03c2020-11-27 10:38:35 -0300719 vld["name"] = vld["id"]
720 nsr_descriptor["vld"] = nsr_vld
selvi.j828f3f22023-05-16 05:43:48 +0000721 if nsd.get("vnffgd"):
722 vnffgd = nsd.get("vnffgd")
723 for vnffg in vnffgd:
724 info = {}
725 for k, v in vnffg.items():
726 if k == "id":
727 info.update({k: v})
728 if k == "nfpd":
729 info.update({k: v})
730 nsr_descriptor["vnffgd"].append(info)
731
garciaale7cbd03c2020-11-27 10:38:35 -0300732 return nsr_descriptor
733
Alexis Romeroee31f532022-04-26 19:10:21 +0200734 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
735 self, vnfd, affinity_group_id
736 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100737 """
738 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
739 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200740 affinity_group = utils.find_in_list(
741 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
742 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100743 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200744 affinity_group_data = {}
745 if affinity_group:
746 if affinity_group.get("id"):
747 affinity_group_data["ag-id"] = affinity_group["id"]
748 if affinity_group.get("type"):
749 affinity_group_data["type"] = affinity_group["type"]
750 if affinity_group.get("scope"):
751 affinity_group_data["scope"] = affinity_group["scope"]
752 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100753
Alexis Romeroee31f532022-04-26 19:10:21 +0200754 def _add_affinity_or_anti_affinity_group_to_nsr(
755 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
756 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100757 """
758 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
759 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200760 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100761 (
762 f
763 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200764 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100765 ),
766 None,
767 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200768 if not affinity_group:
769 affinity_group_data["id"] = str(
770 len(nsr_descriptor["affinity-or-anti-affinity-group"])
771 )
772 affinity_group_data["name"] = "{}-{}".format(
773 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
774 )
775 nsr_descriptor["affinity-or-anti-affinity-group"].append(
776 affinity_group_data
777 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100778
lloretgalleg28c13b62021-02-08 11:48:48 +0000779 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100780 sw_image_desc = utils.find_in_list(
781 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
782 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000783 image_data = {}
784 if sw_image_desc.get("image"):
785 image_data["image"] = sw_image_desc["image"]
786 if sw_image_desc.get("checksum"):
787 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
788 if sw_image_desc.get("vim-type"):
789 image_data["vim-type"] = sw_image_desc["vim-type"]
790 return image_data
791
792 def _add_image_to_nsr(self, nsr_descriptor, image_data):
793 """
794 Adds image to nsr checking first it is not already added
795 """
garciadeblas4568a372021-03-24 09:19:48 +0100796 img = next(
797 (
798 f
799 for f in nsr_descriptor["image"]
800 if all(f.get(k) == image_data[k] for k in image_data)
801 ),
802 None,
803 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000804 if not img:
805 image_data["id"] = str(len(nsr_descriptor["image"]))
806 nsr_descriptor["image"].append(image_data)
807
garciadeblas4568a372021-03-24 09:19:48 +0100808 def _create_vnfr_descriptor_from_vnfd(
809 self,
810 nsd,
811 vnfd,
812 vnfd_id,
813 vnf_index,
814 nsr_descriptor,
815 ns_request,
816 ns_k8s_namespace,
elumalai99078a92022-07-05 17:53:59 +0530817 revision=None,
garciadeblas4568a372021-03-24 09:19:48 +0100818 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300819 vnfr_id = str(uuid4())
820 nsr_id = nsr_descriptor["id"]
821 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100822 additional_params, vnf_params = self._format_additional_params(
823 ns_request, vnf_index, descriptor=vnfd
824 )
garciaale7cbd03c2020-11-27 10:38:35 -0300825
826 vnfr_descriptor = {
827 "id": vnfr_id,
828 "_id": vnfr_id,
829 "nsr-id-ref": nsr_id,
830 "member-vnf-index-ref": vnf_index,
831 "additionalParamsForVnf": additional_params,
832 "created-time": now,
833 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
834 "vnfd-ref": vnfd_id,
835 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
836 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200837 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300838 "vdur": [],
839 "connection-point": [],
840 "ip-address": None, # mgmt-interface filled by LCM
841 }
beierlmcee2ebf2022-03-29 17:42:48 -0400842
843 # Revision backwards compatility. Only specify the revision in the record if
844 # the original VNFD has a revision.
845 if "revision" in vnfd:
846 vnfr_descriptor["revision"] = vnfd["revision"]
847
garciaale7cbd03c2020-11-27 10:38:35 -0300848 vnf_k8s_namespace = ns_k8s_namespace
849 if vnf_params:
850 if vnf_params.get("k8s-namespace"):
851 vnf_k8s_namespace = vnf_params["k8s-namespace"]
852 if vnf_params.get("config-units"):
853 vnfr_descriptor["config-units"] = vnf_params["config-units"]
854
855 # Create vld
856 if vnfd.get("int-virtual-link-desc"):
857 vnfr_descriptor["vld"] = []
858 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
859 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
860
861 for cp in vnfd.get("ext-cpd", ()):
862 vnf_cp = {
863 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100864 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
865 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300866 "id": cp.get("id"),
867 # "ip-address", "mac-address" # filled by LCM
868 # vim-id # TODO it would be nice having a vim port id
869 }
870 vnfr_descriptor["connection-point"].append(vnf_cp)
871
872 # Create k8s-cluster information
873 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
874 if vnfd.get("k8s-cluster"):
875 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
876 all_k8s_cluster_nets_cpds = {}
877 for cpd in get_iterable(vnfd.get("ext-cpd")):
878 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100879 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
880 "id"
881 )
garciaale7cbd03c2020-11-27 10:38:35 -0300882 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
883 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100884 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
885 net.get("id")
886 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300887
888 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300889 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100890 additional_params, kdu_params = self._format_additional_params(
891 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
892 )
garciaale7cbd03c2020-11-27 10:38:35 -0300893 kdu_k8s_namespace = vnf_k8s_namespace
894 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
895 if kdu_params and kdu_params.get("k8s-namespace"):
896 kdu_k8s_namespace = kdu_params["k8s-namespace"]
897
romeromonserbfebfc02021-05-28 10:51:35 +0200898 kdu_deployment_name = ""
899 if kdu_params and kdu_params.get("kdu-deployment-name"):
900 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
901
garciaale7cbd03c2020-11-27 10:38:35 -0300902 kdur = {
903 "additionalParams": additional_params,
904 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200905 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000906 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300907 # TODO "name": "" Name of the VDU in the VIM
908 "ip-address": None, # mgmt-interface filled by LCM
909 "k8s-cluster": {},
910 }
911 if kdu_params and kdu_params.get("config-units"):
912 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000913 if kdu.get("helm-version"):
914 kdur["helm-version"] = kdu["helm-version"]
915 for k8s_type in ("helm-chart", "juju-bundle"):
916 if kdu.get(k8s_type):
917 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300918 if not vnfr_descriptor.get("kdur"):
919 vnfr_descriptor["kdur"] = []
920 vnfr_descriptor["kdur"].append(kdur)
921
922 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300923
garciaale7cbd03c2020-11-27 10:38:35 -0300924 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300925 vdu_mgmt_cp = []
926 try:
garciadeblas4568a372021-03-24 09:19:48 +0100927 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
928 "operate-vnf-op-config"
929 ]["day1-2"]
930 vdu_config = utils.find_in_list(
931 configs, lambda config: config["id"] == vdu["id"]
932 )
bravoff3c39552021-02-24 17:22:24 -0300933 except Exception:
934 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400935
936 try:
937 vdu_instantiation_level = utils.find_in_list(
938 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100939 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400940 )
941 except Exception:
942 vdu_instantiation_level = None
943
bravoff3c39552021-02-24 17:22:24 -0300944 if vdu_config:
945 external_connection_ee = utils.filter_in_list(
946 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100947 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300948 )
949 for ee in external_connection_ee:
950 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
951
garciaale7cbd03c2020-11-27 10:38:35 -0300952 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100953 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
954 )
bravof65e22e52021-11-10 17:58:58 -0300955
956 try:
957 vdu_virtual_storage_descriptors = utils.filter_in_list(
958 vnfd.get("virtual-storage-desc", []),
garciadeblasf2af4a12023-01-24 16:56:54 +0100959 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"],
bravof65e22e52021-11-10 17:58:58 -0300960 )
961 except Exception:
962 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300963 vdur = {
964 "vdu-id-ref": vdu["id"],
965 # TODO "name": "" Name of the VDU in the VIM
966 "ip-address": None, # mgmt-interface filled by LCM
967 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
968 "internal-connection-point": [],
969 "interfaces": [],
970 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100971 "vdu-name": vdu["name"],
garciadeblasf2af4a12023-01-24 16:56:54 +0100972 "virtual-storages": vdu_virtual_storage_descriptors,
garciaale7cbd03c2020-11-27 10:38:35 -0300973 }
974 if vdu_params and vdu_params.get("config-units"):
975 vdur["config-units"] = vdu_params["config-units"]
976 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100977 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
978 "boot-data-drive"
979 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300980 if vdu.get("pdu-type"):
981 vdur["pdu-type"] = vdu["pdu-type"]
982 vdur["name"] = vdu["pdu-type"]
983 # TODO volumes: name, volume-id
984 for icp in vdu.get("int-cpd", ()):
985 vdu_icp = {
986 "id": icp["id"],
987 "connection-point-id": icp["id"],
988 "name": icp.get("id"),
989 }
bravof35766442021-02-04 14:58:04 -0300990
garciaale7cbd03c2020-11-27 10:38:35 -0300991 vdur["internal-connection-point"].append(vdu_icp)
992
993 for iface in icp.get("virtual-network-interface-requirement", ()):
aticigc9c03392022-06-16 01:39:44 +0300994 # Name, mac-address and interface position is taken from VNFD
995 # and included into VNFR. By this way RO can process this information
996 # while creating the VDU.
Gulsum Atici9af2a472023-03-28 17:50:48 +0300997 iface_fields = ("name", "mac-address", "position", "ip-address")
garciadeblas4568a372021-03-24 09:19:48 +0100998 vdu_iface = {
999 x: iface[x] for x in iface_fields if iface.get(x) is not None
1000 }
garciaale7cbd03c2020-11-27 10:38:35 -03001001
1002 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +01001003 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +01001004 vdu_iface["port-security-enabled"] = icp[
1005 "port-security-enabled"
1006 ]
sousaedu003844e2021-03-02 00:19:15 +01001007
1008 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +01001009 vdu_iface["port-security-disable-strategy"] = icp[
1010 "port-security-disable-strategy"
1011 ]
sousaedu003844e2021-03-02 00:19:15 +01001012
garciaale7cbd03c2020-11-27 10:38:35 -03001013 for ext_cp in vnfd.get("ext-cpd", ()):
1014 if not ext_cp.get("int-cpd"):
1015 continue
1016 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
1017 continue
1018 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +01001019 vdu_iface["external-connection-point-ref"] = ext_cp.get(
1020 "id"
1021 )
sousaedu003844e2021-03-02 00:19:15 +01001022
1023 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +01001024 vdu_iface["port-security-enabled"] = ext_cp[
1025 "port-security-enabled"
1026 ]
sousaedu003844e2021-03-02 00:19:15 +01001027
1028 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +01001029 vdu_iface["port-security-disable-strategy"] = ext_cp[
1030 "port-security-disable-strategy"
1031 ]
sousaedu003844e2021-03-02 00:19:15 +01001032
garciaale7cbd03c2020-11-27 10:38:35 -03001033 break
1034
garciadeblas4568a372021-03-24 09:19:48 +01001035 if (
1036 vnfd_mgmt_cp
1037 and vdu_iface.get("external-connection-point-ref")
1038 == vnfd_mgmt_cp
1039 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001040 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -03001041 vdu_iface["mgmt-interface"] = True
1042
1043 for ecp in vdu_mgmt_cp:
1044 if vdu_iface.get("external-connection-point-ref") == ecp:
1045 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001046
1047 if iface.get("virtual-interface"):
1048 vdu_iface.update(deepcopy(iface["virtual-interface"]))
1049
1050 # look for network where this interface is connected
1051 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
1052 if iface_ext_cp:
1053 # TODO: Change for multiple df support
1054 for df in get_iterable(nsd.get("df")):
1055 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +01001056 for vlc_index, vlc in enumerate(
1057 get_iterable(
1058 vnf_profile.get("virtual-link-connectivity")
1059 )
1060 ):
1061 for cpd in get_iterable(
1062 vlc.get("constituent-cpd-id")
1063 ):
1064 if (
1065 cpd.get("constituent-cpd-id")
1066 == iface_ext_cp
Pedro Escaleira4606e4a2023-05-31 14:32:17 +01001067 ) and vnf_profile.get("id") == vnf_index:
garciadeblas4568a372021-03-24 09:19:48 +01001068 vdu_iface["ns-vld-id"] = vlc.get(
1069 "virtual-link-profile-id"
1070 )
garciadeblas61c95912021-02-12 11:23:50 +00001071 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +01001072 if vdu_iface.get("type") in (
1073 "SR-IOV",
1074 "PCI-PASSTHROUGH",
1075 ):
1076 nsr_descriptor["vld"][vlc_index][
1077 "pci-interfaces"
1078 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001079 break
1080 elif vdu_iface.get("internal-connection-point-ref"):
1081 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +00001082 # TODO: store fixed IP address in the record (if it exists in the ICP)
1083 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
1084 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +01001085 ivld_index = utils.find_index_in_list(
1086 vnfd.get("int-virtual-link-desc", ()),
1087 lambda ivld: ivld["id"]
1088 == icp.get("int-virtual-link-desc"),
1089 )
garciadeblas61c95912021-02-12 11:23:50 +00001090 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001091
1092 vdur["interfaces"].append(vdu_iface)
1093
1094 if vdu.get("sw-image-desc"):
1095 sw_image = utils.find_in_list(
1096 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001097 lambda image: image["id"] == vdu.get("sw-image-desc"),
1098 )
garciaale7cbd03c2020-11-27 10:38:35 -03001099 nsr_sw_image_data = utils.find_in_list(
1100 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001101 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -03001102 )
1103 vdur["ns-image-id"] = nsr_sw_image_data["id"]
1104
lloretgalleg28c13b62021-02-08 11:48:48 +00001105 if vdu.get("alternative-sw-image-desc"):
1106 alt_image_ids = []
1107 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1108 sw_image = utils.find_in_list(
1109 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001110 lambda image: image["id"] == alt_image_id,
1111 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001112 nsr_sw_image_data = utils.find_in_list(
1113 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001114 lambda nsr_image: (
1115 nsr_image.get("image") == sw_image.get("image")
1116 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001117 )
1118 alt_image_ids.append(nsr_sw_image_data["id"])
1119 vdur["alt-image-ids"] = alt_image_ids
1120
elumalai99078a92022-07-05 17:53:59 +05301121 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +01001122 flavor_data_name = (
1123 vdu["id"][:56] + "-" + vnf_index + "-" + str(revision) + "-flv"
1124 )
garciaale7cbd03c2020-11-27 10:38:35 -03001125 nsr_flavor_desc = utils.find_in_list(
1126 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001127 lambda flavor: flavor["name"] == flavor_data_name,
1128 )
garciaale7cbd03c2020-11-27 10:38:35 -03001129
1130 if nsr_flavor_desc:
1131 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1132
vegall18101ea2023-03-06 13:49:21 +00001133 # Adding Shared Volume information to vdur
1134 if vdur.get("virtual-storages"):
1135 nsr_sv = []
1136 for vsd in vdur["virtual-storages"]:
1137 if vsd.get("vdu-storage-requirements"):
1138 if (
1139 vsd["vdu-storage-requirements"][0].get("key")
1140 == "multiattach"
1141 and vsd["vdu-storage-requirements"][0].get("value")
1142 == "True"
1143 ):
1144 nsr_sv.append(vsd["id"])
1145 if nsr_sv:
1146 vdur["shared-volumes-id"] = nsr_sv
1147
Alexis Romero03fb5842022-03-11 15:53:40 +01001148 # Adding Affinity groups information to vdur
1149 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001150 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001151 vnfd.get("df")[0]["vdu-profile"],
1152 lambda a_vdu: a_vdu["id"] == vdu["id"],
1153 )
1154 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001155 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001156
Alexis Romeroee31f532022-04-26 19:10:21 +02001157 if vdu_profile_affinity_group:
1158 affinity_group_ids = []
1159 for affinity_group in vdu_profile_affinity_group.get(
1160 "affinity-or-anti-affinity-group", ()
1161 ):
1162 vdu_affinity_group = utils.find_in_list(
1163 vdu_profile_affinity_group.get(
1164 "affinity-or-anti-affinity-group", ()
1165 ),
1166 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001167 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001168 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001169 nsr_descriptor["affinity-or-anti-affinity-group"],
1170 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001171 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1172 and nsr_ag.get("member-vnf-index")
1173 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001174 ),
1175 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001176 # Update Affinity Group VIM name if VDU instantiation parameter is present
1177 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1178 vnf_params_affinity_group = utils.find_in_list(
1179 vnf_params["affinity-or-anti-affinity-group"],
1180 lambda vnfp_ag: (
1181 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1182 ),
1183 )
1184 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1185 nsr_affinity_group[
1186 "vim-affinity-group-id"
1187 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1188 affinity_group_ids.append(nsr_affinity_group["id"])
1189 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001190
bravof4ca51522021-04-22 10:03:02 -04001191 if vdu_instantiation_level:
1192 count = vdu_instantiation_level.get("number-of-instances")
1193 else:
1194 count = 1
1195
garciaale7cbd03c2020-11-27 10:38:35 -03001196 for index in range(0, count):
1197 vdur = deepcopy(vdur)
1198 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001199 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001200 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001201 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001202 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1203
1204 vdur["_id"] = str(uuid4())
1205 vdur["id"] = vdur["_id"]
1206 vdur["count-index"] = index
1207 vnfr_descriptor["vdur"].append(vdur)
garciaale7cbd03c2020-11-27 10:38:35 -03001208 return vnfr_descriptor
1209
K Sai Kiran57589552021-01-27 21:38:34 +05301210 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1211 """
1212 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1213 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1214 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1215 :param ns_instance_content: ns instance content
1216 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1217 :return: None
1218 """
garciadeblasf2af4a12023-01-24 16:56:54 +01001219 time_now, time_delta = (
1220 time(),
1221 time() - ns_instance_content["_admin"]["modified"],
1222 )
1223 force_refresh = (
1224 isinstance(filter_q, dict) and filter_q.get("vcaStatusRefresh") == "true"
1225 )
K Sai Kiran57589552021-01-27 21:38:34 +05301226 threshold_reached = time_delta > 120
1227 if force_refresh or threshold_reached:
1228 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1229 ns_instance_content["_admin"]["modified"] = time_now
1230 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1231 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
garciadeblasf2af4a12023-01-24 16:56:54 +01001232 self.format_on_new(
1233 nslcmop_desc, session["project_id"], make_public=session["public"]
1234 )
K Sai Kiran57589552021-01-27 21:38:34 +05301235 nslcmop_desc["_admin"].pop("nsState")
1236 self.msg.write("ns", operation, nslcmop_desc)
1237 return
1238
1239 def show(self, session, _id, filter_q=None, api_req=False):
1240 """
1241 Get complete information on an ns instance.
1242 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1243 :param _id: string, ns instance id
1244 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1245 :param api_req: True if this call is serving an external API request. False if serving internal request.
1246 :return: dictionary, raise exception if not found.
1247 """
1248 ns_instance_content = super().show(session, _id, api_req)
1249 self.vca_status_refresh(session, ns_instance_content, filter_q)
1250 return ns_instance_content
1251
tierno65ca36d2019-02-12 19:27:52 +01001252 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001253 raise EngineException(
1254 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1255 )
tiernob24258a2018-10-04 18:39:49 +02001256
1257
1258class VnfrTopic(BaseTopic):
1259 topic = "vnfrs"
1260 topic_msg = None
1261
delacruzramo32bab472019-09-13 12:24:22 +02001262 def __init__(self, db, fs, msg, auth):
1263 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001264
tiernobee3bad2019-12-05 12:26:01 +00001265 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001266 raise EngineException(
1267 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1268 )
tiernob24258a2018-10-04 18:39:49 +02001269
tierno65ca36d2019-02-12 19:27:52 +01001270 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001271 raise EngineException(
1272 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1273 )
tiernob24258a2018-10-04 18:39:49 +02001274
tierno65ca36d2019-02-12 19:27:52 +01001275 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001276 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001277 raise EngineException(
1278 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1279 )
tiernob24258a2018-10-04 18:39:49 +02001280
1281
1282class NsLcmOpTopic(BaseTopic):
1283 topic = "nslcmops"
1284 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001285 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001286 "instantiate": ns_instantiate,
1287 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001288 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001289 "scale": ns_scale,
garciadeblas0964edf2022-02-11 00:43:44 +01001290 "heal": ns_heal,
tierno1c38f2f2020-03-24 11:51:39 +00001291 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301292 "migrate": ns_migrate,
Gabriel Cuba84a60df2023-10-30 14:01:54 -05001293 "cancel": nslcmop_cancel,
tiernob24258a2018-10-04 18:39:49 +02001294 }
1295
delacruzramo32bab472019-09-13 12:24:22 +02001296 def __init__(self, db, fs, msg, auth):
1297 BaseTopic.__init__(self, db, fs, msg, auth)
elumalai6c5ea6b2022-04-25 22:27:59 +05301298 self.nsrtopic = NsrTopic(db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001299
tiernob24258a2018-10-04 18:39:49 +02001300 def _check_ns_operation(self, session, nsr, operation, indata):
1301 """
1302 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001303 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
garciadeblas0964edf2022-02-11 00:43:44 +01001304 :param operation: it can be: instantiate, terminate, action, update, heal
tiernob24258a2018-10-04 18:39:49 +02001305 :param indata: descriptor with the parameters of the operation
1306 :return: None
1307 """
garciaale7cbd03c2020-11-27 10:38:35 -03001308 if operation == "action":
1309 self._check_action_ns_operation(indata, nsr)
1310 elif operation == "scale":
1311 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001312 elif operation == "update":
1313 self._check_update_ns_operation(indata, nsr)
garciadeblas0964edf2022-02-11 00:43:44 +01001314 elif operation == "heal":
1315 self._check_heal_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001316 elif operation == "instantiate":
1317 self._check_instantiate_ns_operation(indata, nsr, session)
1318
1319 def _check_action_ns_operation(self, indata, nsr):
1320 nsd = nsr["nsd"]
1321 # check vnf_member_index
1322 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001323 indata["member_vnf_index"] = indata.pop(
1324 "vnf_member_index"
1325 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001326 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001327 vnfd = self._get_vnfd_from_vnf_member_index(
1328 indata["member_vnf_index"], nsr["_id"]
1329 )
bravof41a52052021-02-17 18:08:01 -03001330 try:
garciadeblas4568a372021-03-24 09:19:48 +01001331 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1332 "operate-vnf-op-config"
1333 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001334 except Exception:
1335 configs = []
1336
garciaale7cbd03c2020-11-27 10:38:35 -03001337 if indata.get("vdu_id"):
1338 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001339 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001340 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001341 )
garciaale7cbd03c2020-11-27 10:38:35 -03001342 elif indata.get("kdu_name"):
1343 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001344 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001345 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001346 )
garciaale7cbd03c2020-11-27 10:38:35 -03001347 else:
bravof41a52052021-02-17 18:08:01 -03001348 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001349 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001350 )
1351 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001352 descriptor_configuration = descriptor_configuration.get(
1353 "config-primitive"
1354 )
garciaale7cbd03c2020-11-27 10:38:35 -03001355 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001356 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1357 "config-primitive"
1358 )
garciaale7cbd03c2020-11-27 10:38:35 -03001359
1360 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001361 if indata.get("kdu_name") and indata["primitive"] in (
1362 "upgrade",
1363 "rollback",
1364 "status",
1365 "inspect",
1366 "readme",
1367 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001368 # TODO should be checked that rollback only can contains revsision_numbe????
1369 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001370 raise EngineException(
1371 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1372 indata["primitive"]
1373 )
1374 )
garciaale7cbd03c2020-11-27 10:38:35 -03001375 return
1376 # if not, check primitive
1377 for config_primitive in get_iterable(descriptor_configuration):
1378 if indata["primitive"] == config_primitive["name"]:
1379 # check needed primitive_params are provided
1380 if indata.get("primitive_params"):
1381 in_primitive_params_copy = copy(indata["primitive_params"])
1382 else:
1383 in_primitive_params_copy = {}
1384 for paramd in get_iterable(config_primitive.get("parameter")):
1385 if paramd["name"] in in_primitive_params_copy:
1386 del in_primitive_params_copy[paramd["name"]]
1387 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001388 raise EngineException(
1389 "Needed parameter {} not provided for primitive '{}'".format(
1390 paramd["name"], indata["primitive"]
1391 )
1392 )
garciaale7cbd03c2020-11-27 10:38:35 -03001393 # check no extra primitive params are provided
1394 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001395 raise EngineException(
1396 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1397 list(in_primitive_params_copy.keys()), indata["primitive"]
1398 )
1399 )
garciaale7cbd03c2020-11-27 10:38:35 -03001400 break
1401 else:
garciadeblas4568a372021-03-24 09:19:48 +01001402 raise EngineException(
1403 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1404 indata["primitive"]
1405 )
1406 )
garciaale7cbd03c2020-11-27 10:38:35 -03001407
aticig544a2ae2022-04-05 09:00:17 +03001408 def _check_update_ns_operation(self, indata, nsr) -> None:
1409 """Validates the ns-update request according to updateType
1410
1411 If updateType is CHANGE_VNFPKG:
1412 - it checks the vnfInstanceId, whether it's available under ns instance
1413 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1414 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301415 If updateType is REMOVE_VNF:
1416 - it checks if the vnfInstanceId is available in the ns instance
1417 - Otherwise exception will be raised.
jegancd7d9f02024-05-16 07:07:27 +00001418 If updateType is OPERATE_VNF
1419 - it checks if the vdu-id is persent in the descriptor or not
1420 - it checks if the changeStateTo is either start, stop or rebuild
1421 If updateType is VERTICAL_SCALE
1422 - it checks if the vdu-id is persent in the descriptor or not
aticig544a2ae2022-04-05 09:00:17 +03001423
1424 Args:
1425 indata: includes updateType such as CHANGE_VNFPKG,
1426 nsr: network service record
1427
1428 Raises:
1429 EngineException:
1430 a meaningful error if given update parameters are not proper such as
1431 "Error in validating ns-update request: <ID> does not match
1432 with the vnfd-id of vnfinstance
1433 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1434
1435 """
1436 try:
1437 if indata["updateType"] == "CHANGE_VNFPKG":
1438 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1439 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1440 ns_instance_id = indata["nsInstanceId"]
1441 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1442
1443 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
aticig544a2ae2022-04-05 09:00:17 +03001444 raise EngineException(
1445 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1446 f"belong to NS {ns_instance_id}",
1447 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1448 )
1449
1450 # Getting vnfrs through the ns_instance_id
1451 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1452 constituent_vnfd_id = next(
1453 (
1454 vnfr["vnfd-id"]
1455 for vnfr in vnfrs
1456 if vnfr["id"] == vnf_instance_id
1457 ),
1458 None,
1459 )
1460
1461 # Check the given vnfd-id belongs to given vnf instance
1462 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
aticig544a2ae2022-04-05 09:00:17 +03001463 raise EngineException(
1464 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1465 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1466 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1467 )
1468
1469 # Validating the ns update timeout
1470 if (
1471 indata.get("timeout_ns_update")
1472 and indata["timeout_ns_update"] < 300
1473 ):
1474 raise EngineException(
1475 "Error in validating ns-update request: {} second is not enough "
1476 "to upgrade the VNF instance: {}".format(
1477 indata["timeout_ns_update"], vnf_instance_id
1478 ),
1479 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1480 )
elumalai6380e7c2022-04-28 00:15:59 +05301481 elif indata["updateType"] == "REMOVE_VNF":
1482 vnf_instance_id = indata["removeVnfInstanceId"]
1483 ns_instance_id = indata["nsInstanceId"]
1484 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1485 raise EngineException(
1486 "Invalid VNF Instance Id. '{}' is not "
1487 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1488 )
jegancd7d9f02024-05-16 07:07:27 +00001489 elif indata["updateType"] == "OPERATE_VNF":
1490 if indata.get("operateVnfData"):
1491 if indata["operateVnfData"]["changeStateTo"] not in (
1492 "start",
1493 "stop",
1494 "rebuild",
1495 ):
1496 raise EngineException(
1497 f"The operate type should be either start, stop or rebuild not {indata['operateVnfData']['changeStateTo']}",
1498 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1499 )
1500 if indata["operateVnfData"].get("additionalParam"):
1501 vdu_id = indata["operateVnfData"]["additionalParam"]["vdu_id"]
1502 vnfinstance_id = indata["operateVnfData"]["vnfInstanceId"]
1503 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1504 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1505 vnfd = self._get_vnfd_from_vnf_member_index(
1506 vnfd_member_vnf_index, nsr["_id"]
1507 )
1508 self._check_valid_vdu(vnfd, vdu_id)
1509 elif indata["updateType"] == "VERTICAL_SCALE":
1510 if indata.get("verticalScaleVnf"):
1511 vdu_id = indata["verticalScaleVnf"]["vduId"]
1512 vnfinstance_id = indata["verticalScaleVnf"]["vnfInstanceId"]
1513 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1514 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1515 vnfd = self._get_vnfd_from_vnf_member_index(
1516 vnfd_member_vnf_index, nsr["_id"]
1517 )
1518 self._check_valid_vdu(vnfd, vdu_id)
aticig544a2ae2022-04-05 09:00:17 +03001519
1520 except (
1521 DbException,
1522 AttributeError,
1523 IndexError,
1524 KeyError,
1525 ValueError,
1526 ) as e:
1527 raise type(e)(
1528 "Ns update request could not be processed with error: {}.".format(e)
1529 )
1530
garciaale7cbd03c2020-11-27 10:38:35 -03001531 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001532 vnfd = self._get_vnfd_from_vnf_member_index(
1533 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1534 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001535 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001536 if (
1537 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1538 == scaling_aspect["id"]
1539 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001540 break
1541 else:
garciadeblas4568a372021-03-24 09:19:48 +01001542 raise EngineException(
1543 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1544 "present at vnfd:scaling-aspect".format(
1545 indata["scaleVnfData"]["scaleByStepData"][
1546 "scaling-group-descriptor"
1547 ]
1548 )
1549 )
garciaale7cbd03c2020-11-27 10:38:35 -03001550
garciadeblas0964edf2022-02-11 00:43:44 +01001551 def _check_heal_ns_operation(self, indata, nsr):
1552 return
1553
garciaale7cbd03c2020-11-27 10:38:35 -03001554 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001555 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001556 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001557 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001558 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001559 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1560 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1561 for in_vnf in get_iterable(indata.get("vnf")):
1562 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001563 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001564 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001565 else:
garciadeblas4568a372021-03-24 09:19:48 +01001566 vnfd = self._get_vnfd_from_vnf_member_index(
1567 member_vnf_index, nsr["_id"]
1568 )
1569 vnf_member_index_to_vnfd[
1570 member_vnf_index
1571 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001572 self._check_vnf_instantiation_params(in_vnf, vnfd)
1573 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001574 self._check_valid_vim_account(
1575 in_vnf["vimAccountId"], vim_accounts, session
1576 )
tierno260dd6f2019-09-02 10:48:56 +00001577
garciaale7cbd03c2020-11-27 10:38:35 -03001578 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001579 self._check_valid_wim_account(
1580 in_vld.get("wimAccountId"), wim_accounts, session
1581 )
garciaale7cbd03c2020-11-27 10:38:35 -03001582 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1583 if in_vld["name"] == vldd["id"]:
1584 break
tierno9cb7d672019-10-30 12:13:48 +00001585 else:
garciadeblas4568a372021-03-24 09:19:48 +01001586 raise EngineException(
1587 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1588 in_vld["name"]
1589 )
1590 )
tierno9cb7d672019-10-30 12:13:48 +00001591
garciaale7cbd03c2020-11-27 10:38:35 -03001592 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1593 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001594 vnfr = self.db.get_one(
1595 "vnfrs",
1596 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1597 fail_on_empty=False,
1598 )
garciaale7cbd03c2020-11-27 10:38:35 -03001599 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001600 raise EngineException(
1601 "Invalid parameter member_vnf_index='{}' is not one of the "
1602 "nsd:constituent-vnfd".format(member_vnf_index)
1603 )
beierlmcee2ebf2022-03-29 17:42:48 -04001604
garciadeblasf2af4a12023-01-24 16:56:54 +01001605 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
beierlmcee2ebf2022-03-29 17:42:48 -04001606 if "revision" in vnfr:
1607 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
garciadeblasf2af4a12023-01-24 16:56:54 +01001608 vnfd = self.db.get_one(
1609 "vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False
1610 )
beierlmcee2ebf2022-03-29 17:42:48 -04001611 else:
garciadeblasf2af4a12023-01-24 16:56:54 +01001612 vnfd = self.db.get_one(
1613 "vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False
1614 )
beierlmcee2ebf2022-03-29 17:42:48 -04001615
garciaale7cbd03c2020-11-27 10:38:35 -03001616 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001617 raise EngineException(
1618 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1619 vnfr["vnfd-id"]
1620 )
1621 )
garciaale7cbd03c2020-11-27 10:38:35 -03001622 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001623
garciaale7cbd03c2020-11-27 10:38:35 -03001624 def _check_valid_vdu(self, vnfd, vdu_id):
1625 for vdud in get_iterable(vnfd.get("vdu")):
1626 if vdud["id"] == vdu_id:
1627 return vdud
1628 else:
garciadeblas4568a372021-03-24 09:19:48 +01001629 raise EngineException(
1630 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1631 vdu_id
1632 )
1633 )
garciaale7cbd03c2020-11-27 10:38:35 -03001634
1635 def _check_valid_kdu(self, vnfd, kdu_name):
1636 for kdud in get_iterable(vnfd.get("kdu")):
1637 if kdud["name"] == kdu_name:
1638 return kdud
1639 else:
garciadeblas4568a372021-03-24 09:19:48 +01001640 raise EngineException(
1641 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1642 kdu_name
1643 )
1644 )
garciaale7cbd03c2020-11-27 10:38:35 -03001645
1646 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1647 for in_vdu in get_iterable(in_vnf.get("vdu")):
1648 for vdu in get_iterable(vnfd.get("vdu")):
1649 if in_vdu["id"] == vdu["id"]:
1650 for volume in get_iterable(in_vdu.get("volume")):
1651 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
aticigd7753fc2022-05-18 18:55:23 +03001652 if volumed == volume["name"]:
garciaale7cbd03c2020-11-27 10:38:35 -03001653 break
1654 else:
garciadeblas4568a372021-03-24 09:19:48 +01001655 raise EngineException(
1656 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1657 "volume:name='{}' is not present at "
1658 "vnfd:vdu:virtual-storage-desc list".format(
1659 in_vnf["member-vnf-index"],
1660 in_vdu["id"],
1661 volume["id"],
1662 )
1663 )
garciaale7cbd03c2020-11-27 10:38:35 -03001664
1665 vdu_if_names = set()
1666 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001667 for iface in get_iterable(
1668 cpd.get("virtual-network-interface-requirement")
1669 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001670 vdu_if_names.add(iface.get("name"))
1671
aticigd7753fc2022-05-18 18:55:23 +03001672 for in_iface in get_iterable(in_vdu.get("interface")):
garciaale7cbd03c2020-11-27 10:38:35 -03001673 if in_iface["name"] in vdu_if_names:
1674 break
1675 else:
garciadeblas4568a372021-03-24 09:19:48 +01001676 raise EngineException(
1677 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1678 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1679 in_vnf["member-vnf-index"],
1680 in_vdu["id"],
1681 in_iface["name"],
1682 )
1683 )
garciaale7cbd03c2020-11-27 10:38:35 -03001684 break
1685
1686 else:
garciadeblas4568a372021-03-24 09:19:48 +01001687 raise EngineException(
1688 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1689 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1690 )
garciaale7cbd03c2020-11-27 10:38:35 -03001691
garciadeblas4568a372021-03-24 09:19:48 +01001692 vnfd_ivlds_cpds = {
1693 ivld.get("id"): set()
1694 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1695 }
Gulsum Atici9af2a472023-03-28 17:50:48 +03001696 for vdu in vnfd.get("vdu", {}):
1697 for cpd in vdu.get("int-cpd", {}):
garciaale7cbd03c2020-11-27 10:38:35 -03001698 if cpd.get("int-virtual-link-desc"):
1699 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1700
1701 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1702 if in_ivld.get("name") in vnfd_ivlds_cpds:
1703 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1704 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001705 break
tiernob24258a2018-10-04 18:39:49 +02001706 else:
garciadeblas4568a372021-03-24 09:19:48 +01001707 raise EngineException(
1708 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1709 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1710 "vnfd:internal-vld:name/id:internal-connection-point".format(
1711 in_vnf["member-vnf-index"],
1712 in_ivld["name"],
1713 in_icp["id-ref"],
1714 )
1715 )
tiernob24258a2018-10-04 18:39:49 +02001716 else:
garciadeblas4568a372021-03-24 09:19:48 +01001717 raise EngineException(
1718 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1719 " is not present at vnfd '{}'".format(
1720 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1721 )
1722 )
tiernob24258a2018-10-04 18:39:49 +02001723
garciaale7cbd03c2020-11-27 10:38:35 -03001724 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1725 if vim_account in vim_accounts:
1726 return
1727 try:
1728 db_filter = self._get_project_filter(session)
1729 db_filter["_id"] = vim_account
1730 self.db.get_one("vim_accounts", db_filter)
1731 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001732 raise EngineException(
1733 "Invalid vimAccountId='{}' not present for the project".format(
1734 vim_account
1735 )
1736 )
garciaale7cbd03c2020-11-27 10:38:35 -03001737 vim_accounts.append(vim_account)
1738
David Garcia98de2982021-10-13 17:14:01 +02001739 def _get_vim_account(self, vim_id: str, session):
1740 try:
1741 db_filter = self._get_project_filter(session)
1742 db_filter["_id"] = vim_id
1743 return self.db.get_one("vim_accounts", db_filter)
1744 except Exception:
1745 raise EngineException(
garciadeblasf2af4a12023-01-24 16:56:54 +01001746 "Invalid vimAccountId='{}' not present for the project".format(vim_id)
David Garcia98de2982021-10-13 17:14:01 +02001747 )
1748
garciaale7cbd03c2020-11-27 10:38:35 -03001749 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1750 if not isinstance(wim_account, str):
1751 return
1752 if wim_account in wim_accounts:
1753 return
1754 try:
gifrerenom44f5ec12022-03-07 16:57:25 +00001755 db_filter = self._get_project_filter(session)
garciaale7cbd03c2020-11-27 10:38:35 -03001756 db_filter["_id"] = wim_account
1757 self.db.get_one("wim_accounts", db_filter)
1758 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001759 raise EngineException(
1760 "Invalid wimAccountId='{}' not present for the project".format(
1761 wim_account
1762 )
1763 )
garciaale7cbd03c2020-11-27 10:38:35 -03001764 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001765
garciadeblas4568a372021-03-24 09:19:48 +01001766 def _look_for_pdu(
1767 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1768 ):
tiernocc103432018-10-19 14:10:35 +02001769 """
tierno36ec8602018-11-02 17:27:11 +01001770 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1771 (ip_address, ...) information.
1772 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001773 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001774 :param rollback: list with the database modifications to rollback if needed
1775 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1776 :param vim_account: vim_account where this vnfr should be deployed
1777 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1778 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1779 of the changed vnfr is needed
1780
1781 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1782 "vim-network-name": used at VIM
1783 "name": interface name
1784 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1785 "ns-vld-id": NSD vld where this interface is connected.
1786 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 +02001787 """
tierno36ec8602018-11-02 17:27:11 +01001788
1789 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001790 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1791 if not vdur.get("pdu-type"):
1792 continue
1793 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001794 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001795 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001796 pdu_filter["type"] = pdu_type
1797 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001798 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001799 # TODO feature 1417: "shared": True,
1800
1801 available_pdus = self.db.get_list("pdus", pdu_filter)
1802 for pdu in available_pdus:
1803 # step 1 check if this pdu contains needed interfaces:
1804 match_interfaces = True
1805 for vdur_interface in vdur["interfaces"]:
1806 for pdu_interface in pdu["interfaces"]:
1807 if pdu_interface["name"] == vdur_interface["name"]:
1808 # TODO feature 1417: match per mgmt type
1809 break
1810 else: # no interface found for name
1811 match_interfaces = False
1812 break
1813 if match_interfaces:
1814 break
1815 else:
1816 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001817 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001818 "names".format(
1819 pdu_type,
1820 vim_account,
1821 vnfr["member-vnf-index-ref"],
1822 vdur["vdu-id-ref"],
1823 )
1824 )
tiernocc103432018-10-19 14:10:35 +02001825
1826 # step 2. Update pdu
1827 rollback_pdu = {
1828 "_admin.usageState": pdu["_admin"]["usageState"],
1829 "_admin.usage.vnfr_id": None,
1830 "_admin.usage.nsr_id": None,
1831 "_admin.usage.vdur": None,
1832 }
garciadeblas4568a372021-03-24 09:19:48 +01001833 self.db.set_one(
1834 "pdus",
1835 {"_id": pdu["_id"]},
1836 {
1837 "_admin.usageState": "IN_USE",
1838 "_admin.usage": {
1839 "vnfr_id": vnfr["_id"],
1840 "nsr_id": vnfr["nsr-id-ref"],
1841 "vdur": vdur["vdu-id-ref"],
1842 },
1843 },
1844 )
1845 rollback.append(
1846 {
1847 "topic": "pdus",
1848 "_id": pdu["_id"],
1849 "operation": "set",
1850 "content": rollback_pdu,
1851 }
1852 )
tiernocc103432018-10-19 14:10:35 +02001853
1854 # step 3. Fill vnfr info by filling vdur
1855 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001856 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001857 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1858 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1859 for pdu_interface in pdu["interfaces"]:
1860 if pdu_interface["name"] == vdur_interface["name"]:
1861 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1862 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001863 if k in (
1864 "ip-address",
1865 "mac-address",
1866 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001867 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001868 vnfr_update_rollback[
1869 iface_text + ".{}".format(k)
1870 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001871 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001872 if vdur_interface.get(
1873 "mgmt-interface"
1874 ) or vdur_interface.get("mgmt-vnf"):
1875 vnfr_update_rollback[
1876 vdu_text + ".ip-address"
1877 ] = vdur.get("ip-address")
1878 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1879 "ip-address"
1880 ]
tierno36ec8602018-11-02 17:27:11 +01001881 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001882 vnfr_update_rollback["ip-address"] = vnfr.get(
1883 "ip-address"
1884 )
tierno36ec8602018-11-02 17:27:11 +01001885 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001886 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1887 "ip-address"
1888 ]
1889 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1890 "vim-network-id"
1891 ):
1892 ifaces_forcing_vim_network.append(
1893 {
1894 "name": vdur_interface.get("vnf-vld-id")
1895 or vdur_interface.get("ns-vld-id"),
1896 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1897 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1898 }
1899 )
gcalvino17d5b732018-12-17 16:26:21 +01001900 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001901 ifaces_forcing_vim_network[-1][
1902 "vim-network-id"
1903 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001904 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001905 ifaces_forcing_vim_network[-1][
1906 "vim-network-name"
1907 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001908 break
1909
tierno36ec8602018-11-02 17:27:11 +01001910 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001911
garciadeblas4568a372021-03-24 09:19:48 +01001912 def _look_for_k8scluster(
1913 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1914 ):
tierno9cb7d672019-10-30 12:13:48 +00001915 """
1916 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1917 Fills vnfr.kdur with the selected k8scluster
1918
1919 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1920 :param rollback: list with the database modifications to rollback if needed
1921 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1922 :param vim_account: vim_account where this vnfr should be deployed
1923 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1924 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1925 of the changed vnfr is needed
1926
1927 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1928 "vim-network-name": used at VIM
1929 "name": interface name
1930 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1931 "ns-vld-id": NSD vld where this interface is connected.
1932 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1933 """
1934
1935 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001936 if not vnfr.get("kdur"):
1937 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001938
tiernoc67b0e92019-11-05 12:45:29 +00001939 kdu_filter = self._get_project_filter(session)
1940 kdu_filter["vim_account"] = vim_account
1941 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1942 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1943
1944 k8s_requirements = {} # just for logging
1945 for k8scluster in available_k8sclusters:
1946 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001947 break
tiernoc67b0e92019-11-05 12:45:29 +00001948 # restrict by cni
1949 if vnfr["k8s-cluster"].get("cni"):
1950 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001951 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1952 k8scluster.get("cni", ())
1953 ):
tiernoc67b0e92019-11-05 12:45:29 +00001954 continue
1955 # restrict by version
1956 if vnfr["k8s-cluster"].get("version"):
1957 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1958 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1959 continue
1960 # restrict by number of networks
1961 if vnfr["k8s-cluster"].get("nets"):
1962 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001963 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1964 vnfr["k8s-cluster"]["nets"]
1965 ):
tiernoc67b0e92019-11-05 12:45:29 +00001966 continue
1967 break
1968 else:
garciadeblas4568a372021-03-24 09:19:48 +01001969 raise EngineException(
1970 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1971 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1972 )
1973 )
tierno9cb7d672019-10-30 12:13:48 +00001974
tiernoc67b0e92019-11-05 12:45:29 +00001975 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001976 # step 3. Fill vnfr info by filling kdur
1977 kdu_text = "kdur.{}.".format(kdur_index)
1978 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1979 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1980
tiernoc67b0e92019-11-05 12:45:29 +00001981 # step 4. Check VIM networks that forces the selected k8s_cluster
1982 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1983 k8scluster_net_list = list(k8scluster.get("nets").keys())
1984 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1985 # get a network from k8s_cluster nets. If name matches use this, if not use other
1986 if kdur_net["id"] in k8scluster_net_list: # name matches
1987 vim_net = k8scluster["nets"][kdur_net["id"]]
1988 k8scluster_net_list.remove(kdur_net["id"])
1989 else:
1990 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1991 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001992 vnfr_update_rollback[
1993 "k8s-cluster.nets.{}.vim_net".format(net_index)
1994 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001995 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001996 if vim_net and (
1997 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1998 ):
1999 ifaces_forcing_vim_network.append(
2000 {
2001 "name": kdur_net.get("vnf-vld-id")
2002 or kdur_net.get("ns-vld-id"),
2003 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
2004 "ns-vld-id": kdur_net.get("ns-vld-id"),
2005 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
2006 }
2007 )
tiernoc67b0e92019-11-05 12:45:29 +00002008 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00002009 return ifaces_forcing_vim_network
2010
Gulsum Aticie395aa42021-11-10 20:59:06 +03002011 def _update_vnfrs_from_nsd(self, nsr):
garciadeblasf2af4a12023-01-24 16:56:54 +01002012 step = "Getting vnf_profiles from nsd" # first step must be defined outside try
Gulsum Aticie395aa42021-11-10 20:59:06 +03002013 try:
2014 nsr_id = nsr["_id"]
2015 nsd = nsr["nsd"]
2016
Gulsum Aticie395aa42021-11-10 20:59:06 +03002017 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
2018 vld_fixed_ip_connection_point_data = {}
2019
2020 step = "Getting ip-address info from vnf_profile if it exists"
2021 for vnfp in vnf_profiles:
2022 # Checking ip-address info from nsd.vnf_profile and storing
2023 for vlc in vnfp.get("virtual-link-connectivity", ()):
2024 for cpd in vlc.get("constituent-cpd-id", ()):
2025 if cpd.get("ip-address"):
2026 step = "Storing ip-address info"
garciadeblasf2af4a12023-01-24 16:56:54 +01002027 vld_fixed_ip_connection_point_data.update(
2028 {
2029 vlc.get("virtual-link-profile-id")
2030 + "."
2031 + cpd.get("constituent-base-element-id"): {
2032 "vnfd-connection-point-ref": cpd.get(
2033 "constituent-cpd-id"
2034 ),
2035 "ip-address": cpd.get("ip-address"),
2036 }
2037 }
2038 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002039
2040 # Inserting ip address to vnfr
2041 if len(vld_fixed_ip_connection_point_data) > 0:
2042 step = "Getting vnfrs"
2043 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2044 for item in vld_fixed_ip_connection_point_data.keys():
2045 step = "Filtering vnfrs"
garciadeblasf2af4a12023-01-24 16:56:54 +01002046 vnfr = next(
2047 filter(
2048 lambda vnfr: vnfr["member-vnf-index-ref"]
2049 == item.split(".")[1],
2050 vnfrs,
2051 ),
2052 None,
2053 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002054 if vnfr:
2055 vnfr_update = {}
2056 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2057 for iface_index, iface in enumerate(vdur["interfaces"]):
2058 step = "Looking for matched interface"
2059 if (
garciadeblasf2af4a12023-01-24 16:56:54 +01002060 iface.get("external-connection-point-ref")
2061 == vld_fixed_ip_connection_point_data[item].get(
2062 "vnfd-connection-point-ref"
2063 )
2064 and iface.get("ns-vld-id") == item.split(".")[0]
Gulsum Aticie395aa42021-11-10 20:59:06 +03002065 ):
2066 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2067 vdur_index, iface_index
2068 )
2069 step = "Storing info in order to update vnfr"
2070 vnfr_update[
2071 vnfr_update_text + ".ip-address"
garciadeblasf2af4a12023-01-24 16:56:54 +01002072 ] = increment_ip_mac(
2073 vld_fixed_ip_connection_point_data[item].get(
2074 "ip-address"
2075 ),
2076 vdur.get("count-index", 0),
2077 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002078 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
2079
2080 step = "updating vnfr at database"
2081 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
2082 except (
garciadeblasf2af4a12023-01-24 16:56:54 +01002083 ValidationError,
2084 EngineException,
2085 DbException,
2086 MsgException,
2087 FsException,
Gulsum Aticie395aa42021-11-10 20:59:06 +03002088 ) as e:
2089 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
2090
tiernocc103432018-10-19 14:10:35 +02002091 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02002092 # get vnfr
2093 nsr_id = nsr["_id"]
2094 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2095
2096 for vnfr in vnfrs:
2097 vnfr_update = {}
2098 vnfr_update_rollback = {}
2099 member_vnf_index = vnfr["member-vnf-index-ref"]
2100 # update vim-account-id
2101
2102 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02002103 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002104 # check instantiate parameters
2105 for vnf_inst_params in get_iterable(indata.get("vnf")):
2106 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
2107 continue
2108 if vnf_inst_params.get("vimAccountId"):
2109 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02002110 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002111
tiernocddb07d2020-10-06 08:28:00 +00002112 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
2113 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
2114 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2115 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
2116 continue
garciadeblas4568a372021-03-24 09:19:48 +01002117 for iface_inst_param in get_iterable(
2118 vdu_inst_param.get("interface")
2119 ):
2120 iface_index, _ = next(
2121 i
2122 for i in enumerate(vdur["interfaces"])
2123 if i[1]["name"] == iface_inst_param["name"]
2124 )
2125 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2126 vdur_index, iface_index
2127 )
tiernocddb07d2020-10-06 08:28:00 +00002128 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002129 vnfr_update[
2130 vnfr_update_text + ".ip-address"
2131 ] = increment_ip_mac(
2132 iface_inst_param.get("ip-address"),
2133 vdur.get("count-index", 0),
2134 )
tierno1bd9d952020-11-13 15:56:51 +00002135 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002136 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002137 vnfr_update[
2138 vnfr_update_text + ".mac-address"
2139 ] = increment_ip_mac(
2140 iface_inst_param.get("mac-address"),
2141 vdur.get("count-index", 0),
2142 )
tierno1bd9d952020-11-13 15:56:51 +00002143 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03002144 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01002145 vnfr_update[
2146 vnfr_update_text + ".floating-ip-required"
2147 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002148 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2149 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01002150 for ivld_inst_param in get_iterable(
2151 vnf_inst_params.get("internal-vld")
2152 ):
2153 for icp_inst_param in get_iterable(
2154 ivld_inst_param.get("internal-connection-point")
2155 ):
tiernocddb07d2020-10-06 08:28:00 +00002156 # look for iface
2157 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2158 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002159 if (
2160 iface.get("internal-connection-point-ref")
2161 == icp_inst_param["id-ref"]
2162 ):
2163 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2164 vdur_index, iface_index
2165 )
tiernocddb07d2020-10-06 08:28:00 +00002166 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002167 vnfr_update[
2168 vnfr_update_text + ".ip-address"
2169 ] = increment_ip_mac(
2170 icp_inst_param.get("ip-address"),
2171 vdur.get("count-index", 0),
2172 )
2173 vnfr_update[
2174 vnfr_update_text + ".fixed-ip"
2175 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002176 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002177 vnfr_update[
2178 vnfr_update_text + ".mac-address"
2179 ] = increment_ip_mac(
2180 icp_inst_param.get("mac-address"),
2181 vdur.get("count-index", 0),
2182 )
2183 vnfr_update[
2184 vnfr_update_text + ".fixed-mac"
2185 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002186 break
2187 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2188 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01002189 for vnfcp_inst_param in get_iterable(
2190 vld_inst_param.get("vnfd-connection-point-ref")
2191 ):
tiernocddb07d2020-10-06 08:28:00 +00002192 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2193 continue
2194 # look for iface
2195 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2196 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002197 if (
2198 iface.get("external-connection-point-ref")
2199 == vnfcp_inst_param["vnfd-connection-point-ref"]
2200 ):
2201 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2202 vdur_index, iface_index
2203 )
tiernocddb07d2020-10-06 08:28:00 +00002204 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002205 vnfr_update[
2206 vnfr_update_text + ".ip-address"
2207 ] = increment_ip_mac(
2208 vnfcp_inst_param.get("ip-address"),
2209 vdur.get("count-index", 0),
2210 )
tierno1bd9d952020-11-13 15:56:51 +00002211 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002212 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002213 vnfr_update[
2214 vnfr_update_text + ".mac-address"
2215 ] = increment_ip_mac(
2216 vnfcp_inst_param.get("mac-address"),
2217 vdur.get("count-index", 0),
2218 )
tierno1bd9d952020-11-13 15:56:51 +00002219 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002220 break
2221
tiernocc103432018-10-19 14:10:35 +02002222 vnfr_update["vim-account-id"] = vim_account
2223 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2224
David Garciaecb41322021-03-31 19:10:46 +02002225 if vca_id:
2226 vnfr_update["vca-id"] = vca_id
2227 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2228
tiernocc103432018-10-19 14:10:35 +02002229 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002230 ifaces_forcing_vim_network = self._look_for_pdu(
2231 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2232 )
tiernocc103432018-10-19 14:10:35 +02002233
tierno9cb7d672019-10-30 12:13:48 +00002234 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002235 ifaces_forcing_vim_network += self._look_for_k8scluster(
2236 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2237 )
tierno9cb7d672019-10-30 12:13:48 +00002238 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002239 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002240 rollback.append(
2241 {
2242 "topic": "vnfrs",
2243 "_id": vnfr["_id"],
2244 "operation": "set",
2245 "content": vnfr_update_rollback,
2246 }
2247 )
tierno36ec8602018-11-02 17:27:11 +01002248
2249 # Update indada in case pdu forces to use a concrete vim-network-name
2250 # TODO check if user has already insert a vim-network-name and raises an error
2251 if not ifaces_forcing_vim_network:
2252 continue
2253 for iface_info in ifaces_forcing_vim_network:
2254 if iface_info.get("ns-vld-id"):
2255 if "vld" not in indata:
2256 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002257 indata["vld"].append(
2258 {
2259 key: iface_info[key]
2260 for key in ("name", "vim-network-name", "vim-network-id")
2261 if iface_info.get(key)
2262 }
2263 )
tierno36ec8602018-11-02 17:27:11 +01002264
2265 elif iface_info.get("vnf-vld-id"):
2266 if "vnf" not in indata:
2267 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002268 indata["vnf"].append(
2269 {
2270 "member-vnf-index": member_vnf_index,
2271 "internal-vld": [
2272 {
2273 key: iface_info[key]
2274 for key in (
2275 "name",
2276 "vim-network-name",
2277 "vim-network-id",
2278 )
2279 if iface_info.get(key)
2280 }
2281 ],
2282 }
2283 )
tierno36ec8602018-11-02 17:27:11 +01002284
2285 @staticmethod
2286 def _create_nslcmop(nsr_id, operation, params):
2287 """
2288 Creates a ns-lcm-opp content to be stored at database.
2289 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002290 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002291 :param params: user parameters for the operation
2292 :return: dictionary following SOL005 format
2293 """
tiernob24258a2018-10-04 18:39:49 +02002294 now = time()
2295 _id = str(uuid4())
2296 nslcmop = {
2297 "id": _id,
2298 "_id": _id,
2299 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002300 "queuePosition": None,
2301 "stage": None,
2302 "errorMessage": None,
2303 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002304 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002305 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002306 "lcmOperationType": operation,
2307 "startTime": now,
2308 "isAutomaticInvocation": False,
2309 "operationParams": params,
2310 "isCancelPending": False,
2311 "links": {
2312 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002313 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002314 },
tiernob24258a2018-10-04 18:39:49 +02002315 }
2316 return nslcmop
2317
magnussonlf318b302020-01-20 18:38:18 +01002318 def _get_enabled_vims(self, session):
2319 """
2320 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2321 :param session: current session with user information
2322 """
2323 db_filter = self._get_project_filter(session)
2324 db_filter["_admin.operationalState"] = "ENABLED"
2325 vims = self.db.get_list("vim_accounts", db_filter)
2326 vimAccounts = []
2327 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002328 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002329 return vimAccounts
2330
garciadeblas4568a372021-03-24 09:19:48 +01002331 def new(
2332 self,
2333 rollback,
2334 session,
2335 indata=None,
2336 kwargs=None,
2337 headers=None,
2338 slice_object=False,
2339 ):
tiernob24258a2018-10-04 18:39:49 +02002340 """
2341 Performs a new operation over a ns
2342 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002343 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002344 :param indata: descriptor with the parameters of the operation. It must contains among others
2345 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002346 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002347 :param kwargs: used to override the indata descriptor
2348 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002349 :return: id of the nslcmops
2350 """
garciadeblas4568a372021-03-24 09:19:48 +01002351
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002352 def check_if_nsr_is_not_slice_member(session, nsr_id):
2353 nsis = None
2354 db_filter = self._get_project_filter(session)
2355 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002356 nsis = self.db.get_one(
2357 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2358 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002359 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002360 raise EngineException(
2361 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2362 nsr_id, nsis["_id"]
2363 ),
2364 http_code=HTTPStatus.CONFLICT,
2365 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002366
tiernob24258a2018-10-04 18:39:49 +02002367 try:
2368 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002369 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002370 operation = indata["lcmOperationType"]
2371 nsInstanceId = indata["nsInstanceId"]
2372
2373 validate_input(indata, self.operation_schema[operation])
2374 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002375 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002376 _filter["_id"] = nsInstanceId
2377 nsr = self.db.get_one("nsrs", _filter)
2378
2379 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002380 if operation == "terminate" and slice_object is False:
2381 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002382 if (
2383 not nsr["_admin"].get("nsState")
2384 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2385 ):
tiernob24258a2018-10-04 18:39:49 +02002386 if operation == "terminate" and indata.get("autoremove"):
2387 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002388 return (
2389 None,
2390 None,
garciadeblasf53612b2024-07-12 14:44:37 +02002391 None,
garciadeblas4568a372021-03-24 09:19:48 +01002392 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002393 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002394 raise EngineException(
2395 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2396 nsInstanceId, operation
2397 ),
2398 HTTPStatus.CONFLICT,
2399 )
tiernob24258a2018-10-04 18:39:49 +02002400 else:
tierno65ca36d2019-02-12 19:27:52 +01002401 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002402 raise EngineException(
2403 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2404 nsInstanceId, operation
2405 ),
2406 HTTPStatus.CONFLICT,
2407 )
tiernob24258a2018-10-04 18:39:49 +02002408 self._check_ns_operation(session, nsr, operation, indata)
garciadeblasf2af4a12023-01-24 16:56:54 +01002409 if indata.get("primitive_params"):
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002410 indata["primitive_params"] = json.dumps(indata["primitive_params"])
garciadeblasf2af4a12023-01-24 16:56:54 +01002411 elif indata.get("additionalParamsForVnf"):
2412 indata["additionalParamsForVnf"] = json.dumps(
2413 indata["additionalParamsForVnf"]
2414 )
tierno36ec8602018-11-02 17:27:11 +01002415
tiernocc103432018-10-19 14:10:35 +02002416 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002417 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002418 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302419 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2420 nsr_update = {}
2421 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2422 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2423 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2424 ns_request = nsr["instantiate_params"]
garciadeblasf2af4a12023-01-24 16:56:54 +01002425 vnfr = self.db.get_one(
2426 "vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]}
2427 )
elumalai8bf978e2022-05-26 15:32:06 +05302428 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2429 vnfr_vnfd_revision = vnfr.get("revision", 1)
2430 if latest_vnfd_revision != vnfr_vnfd_revision:
2431 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
garciadeblasf2af4a12023-01-24 16:56:54 +01002432 old_db_vnfd = self.db.get_one(
2433 "vnfds_revisions", {"_id": old_vnfd_id}
2434 )
elumalai8bf978e2022-05-26 15:32:06 +05302435 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2436 new_sw_version = vnfd.get("software-version", "1.0")
2437 if new_sw_version != old_sw_version:
2438 vnf_index = vnfr["member-vnf-index-ref"]
elumalai8bf978e2022-05-26 15:32:06 +05302439 for vdu in vnfd["vdu"]:
vegall18101ea2023-03-06 13:49:21 +00002440 self.nsrtopic._add_shared_volumes_to_nsr(
2441 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2442 )
garciadeblasf2af4a12023-01-24 16:56:54 +01002443 self.nsrtopic._add_flavor_to_nsr(
2444 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2445 )
elumalai8bf978e2022-05-26 15:32:06 +05302446 sw_image_id = vdu.get("sw-image-desc")
2447 if sw_image_id:
garciadeblasf2af4a12023-01-24 16:56:54 +01002448 image_data = self.nsrtopic._get_image_data_from_vnfd(
2449 vnfd, sw_image_id
2450 )
elumalai8bf978e2022-05-26 15:32:06 +05302451 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2452 for alt_image in vdu.get("alternative-sw-image-desc", ()):
garciadeblasf2af4a12023-01-24 16:56:54 +01002453 image_data = self.nsrtopic._get_image_data_from_vnfd(
2454 vnfd, alt_image
2455 )
elumalai8bf978e2022-05-26 15:32:06 +05302456 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2457 nsr_update["image"] = nsr["image"]
2458 nsr_update["flavor"] = nsr["flavor"]
vegall18101ea2023-03-06 13:49:21 +00002459 nsr_update["shared-volumes"] = nsr["shared-volumes"]
elumalai8bf978e2022-05-26 15:32:06 +05302460 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
garciadeblasf2af4a12023-01-24 16:56:54 +01002461 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(
2462 nsd, ns_request, session
2463 )
2464 vnfr_descriptor = (
2465 self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2466 nsd,
2467 vnfd,
2468 vnfd_id,
2469 vnf_index,
2470 nsr,
2471 ns_request,
2472 ns_k8s_namespace,
2473 latest_vnfd_revision,
2474 )
elumalai8bf978e2022-05-26 15:32:06 +05302475 )
2476 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002477 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002478 _id = nslcmop_desc["_id"]
garciadeblasf53612b2024-07-12 14:44:37 +02002479 nsName = nsr.get("name")
garciadeblas4568a372021-03-24 09:19:48 +01002480 self.format_on_new(
2481 nslcmop_desc, session["project_id"], make_public=session["public"]
2482 )
magnussonlf318b302020-01-20 18:38:18 +01002483 if indata.get("placement-engine"):
2484 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002485 nslcmop_desc["operationParams"][
2486 "validVimAccounts"
2487 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002488 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002489 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002490 if not slice_object:
2491 self.msg.write("ns", operation, nslcmop_desc)
garciadeblasf53612b2024-07-12 14:44:37 +02002492 return _id, nsName, None
tiernobdebce92019-07-01 15:36:49 +00002493 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002494 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2495 # except DbException as e:
2496 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2497
Gabriel Cuba84a60df2023-10-30 14:01:54 -05002498 def cancel(self, rollback, session, indata=None, kwargs=None, headers=None):
2499 validate_input(indata, self.operation_schema["cancel"])
2500 # Override descriptor with query string kwargs
2501 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
2502 nsLcmOpOccId = indata["nsLcmOpOccId"]
2503 cancelMode = indata["cancelMode"]
2504 # get nslcmop from nsLcmOpOccId
2505 _filter = BaseTopic._get_project_filter(session)
2506 _filter["_id"] = nsLcmOpOccId
2507 nslcmop = self.db.get_one("nslcmops", _filter)
2508 # Fail is this is not an ongoing nslcmop
2509 if nslcmop.get("operationState") not in [
2510 "STARTING",
2511 "PROCESSING",
2512 "ROLLING_BACK",
2513 ]:
2514 raise EngineException(
2515 "Operation is not in STARTING, PROCESSING or ROLLING_BACK state",
2516 http_code=HTTPStatus.CONFLICT,
2517 )
2518 nsInstanceId = nslcmop["nsInstanceId"]
2519 update_dict = {
2520 "isCancelPending": True,
2521 "cancelMode": cancelMode,
2522 }
2523 self.db.set_one(
2524 "nslcmops", q_filter=_filter, update_dict=update_dict, fail_on_empty=False
2525 )
2526 data = {
2527 "_id": nsLcmOpOccId,
2528 "nsInstanceId": nsInstanceId,
2529 "cancelMode": cancelMode,
2530 }
2531 self.msg.write("nslcmops", "cancel", data)
2532
tiernobee3bad2019-12-05 12:26:01 +00002533 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002534 raise EngineException(
2535 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2536 )
tiernob24258a2018-10-04 18:39:49 +02002537
tierno65ca36d2019-02-12 19:27:52 +01002538 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002539 raise EngineException(
2540 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2541 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002542
2543
2544class NsiTopic(BaseTopic):
2545 topic = "nsis"
2546 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002547 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002548
delacruzramo32bab472019-09-13 12:24:22 +02002549 def __init__(self, db, fs, msg, auth):
2550 BaseTopic.__init__(self, db, fs, msg, auth)
2551 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002552
Felipe Vicensc37b3842019-01-12 12:24:42 +01002553 @staticmethod
2554 def _format_ns_request(ns_request):
2555 formated_request = copy(ns_request)
2556 # TODO: Add request params
2557 return formated_request
2558
2559 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002560 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002561 """
2562 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002563 :param slice_request: User instantiation additional parameters
2564 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002565 """
tiernofd160572019-01-21 10:41:37 +00002566 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2567 if additional_params:
2568 for k, v in additional_params.items():
2569 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002570 raise EngineException(
2571 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2572 k
2573 )
2574 )
tiernofd160572019-01-21 10:41:37 +00002575 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002576 raise EngineException(
2577 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2578 k
2579 )
2580 )
tiernofd160572019-01-21 10:41:37 +00002581 if isinstance(v, (dict, tuple, list)):
2582 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002583 return additional_params
2584
tiernob4844ab2019-05-23 08:42:12 +00002585 def check_conflict_on_del(self, session, _id, db_content):
2586 """
2587 Check that NSI is not instantiated
2588 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2589 :param _id: nsi internal id
2590 :param db_content: The database content of the _id
2591 :return: None or raises EngineException with the conflict
2592 """
tierno65ca36d2019-02-12 19:27:52 +01002593 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002594 return
tiernob4844ab2019-05-23 08:42:12 +00002595 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002596 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002597 raise EngineException(
2598 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2599 "Launch 'terminate' operation first; or force deletion".format(_id),
2600 http_code=HTTPStatus.CONFLICT,
2601 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002602
tiernobee3bad2019-12-05 12:26:01 +00002603 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002604 """
tiernob4844ab2019-05-23 08:42:12 +00002605 Deletes associated nsilcmops from database. Deletes associated filesystem.
2606 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002607 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002608 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002609 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002610 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002611 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002612 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002613
Felipe Vicens09e65422019-01-22 15:06:46 +01002614 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002615 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002616 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2617 nsr_id = nsrs_detailed_item["nsrId"]
2618 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002619 _filter = {
2620 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2621 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2622 "_id.ne": nsir["_id"],
2623 }
2624 nsi = self.db.get_one(
2625 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2626 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002627 if nsi: # last one using nsr
2628 continue
2629 try:
garciadeblas4568a372021-03-24 09:19:48 +01002630 self.nsrTopic.delete(
2631 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2632 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002633 except (DbException, EngineException) as e:
2634 if e.http_code == HTTPStatus.NOT_FOUND:
2635 pass
2636 else:
2637 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002638
tiernob4844ab2019-05-23 08:42:12 +00002639 # delete related nsilcmops database entries
2640 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002641
tiernob4844ab2019-05-23 08:42:12 +00002642 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002643 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002644 if nsir_admin and nsir_admin.get("nst-id"):
2645 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002646 nsis_list = self.db.get_one(
2647 "nsis",
2648 {"nst-id": nsir_admin["nst-id"]},
2649 fail_on_empty=False,
2650 fail_on_more=False,
2651 )
tiernob4844ab2019-05-23 08:42:12 +00002652 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002653 self.db.set_one(
2654 "nsts",
2655 {"_id": nsir_admin["nst-id"]},
2656 {"_admin.usageState": "NOT_IN_USE"},
2657 )
tiernob4844ab2019-05-23 08:42:12 +00002658
tierno65ca36d2019-02-12 19:27:52 +01002659 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002660 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002661 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002662 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002663 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002664 :param indata: params to be used for the nsir
2665 :param kwargs: used to override the indata descriptor
2666 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002667 :return: the _id of nsi descriptor created at database
2668 """
2669
garciadeblasf2af4a12023-01-24 16:56:54 +01002670 step = "checking quotas" # first step must be defined outside try
Felipe Vicensb57758d2018-10-16 16:00:20 +02002671 try:
delacruzramo32bab472019-09-13 12:24:22 +02002672 self.check_quota(session)
2673
tierno99d4b172019-07-02 09:28:40 +00002674 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002675 slice_request = self._remove_envelop(indata)
2676 # Override descriptor with query string kwargs
2677 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002678 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002679
Felipe Vicensb57758d2018-10-16 16:00:20 +02002680 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002681 step = "getting nstd id='{}' from database".format(
2682 slice_request.get("nstId")
2683 )
tiernob4844ab2019-05-23 08:42:12 +00002684 _filter = self._get_project_filter(session)
2685 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002686 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002687 # check NST is not disabled
2688 step = "checking NST operationalState"
2689 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002690 raise EngineException(
2691 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2692 "instance".format(slice_request["nstId"]),
2693 http_code=HTTPStatus.CONFLICT,
2694 )
tiernob4844ab2019-05-23 08:42:12 +00002695 del _filter["_id"]
2696
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002697 # check NSD is not disabled
2698 step = "checking operationalState"
2699 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002700 raise EngineException(
2701 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2702 "a network slice".format(slice_request["nstId"]),
2703 http_code=HTTPStatus.CONFLICT,
2704 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002705
Felipe Vicens07f31722018-10-29 15:16:44 +01002706 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002707 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002708 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002709 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002710
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002711 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002712 nsi_descriptor = {
2713 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002714 "name": slice_request["nsiName"],
2715 "description": slice_request.get("nsiDescription", ""),
2716 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002717 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002718 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002719 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002720 "nsr-ref-list": [],
2721 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002722 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002723 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002724 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002725
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002726 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002727 self.format_on_new(
2728 nsi_descriptor, session["project_id"], make_public=session["public"]
2729 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002730 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2731 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002732 nsi_descriptor["_admin"]["deployed"] = {}
2733 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2734 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2735
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002736 # Creating netslice-vld for the RO.
2737 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002738
2739 # Building the vlds list to be deployed
2740 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002741 nsi_vlds = []
2742
2743 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2744 # Getting template Instantiation parameters from NST
2745 nsi_vld = deepcopy(netslice_vlds)
2746 nsi_vld["shared-nsrs-list"] = []
2747 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2748 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002749
2750 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002751 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002752 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002753 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002754
Felipe Vicens09e65422019-01-22 15:06:46 +01002755 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002756 for member_ns in nstd["netslice-subnet"]:
2757 nsd_id = member_ns["nsd-ref"]
2758 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002759 member_ns["nsd-ref"], member_ns["id"]
2760 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002761 if nsd_id not in needed_nsds:
2762 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002763 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002764 nsd = self.db.get_one(
2765 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2766 )
tiernob4844ab2019-05-23 08:42:12 +00002767 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002768 nsd.pop("_admin")
2769 needed_nsds[nsd_id] = nsd
2770 else:
2771 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002772 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2773 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002774
Felipe Vicensb57758d2018-10-16 16:00:20 +02002775 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002776 member_ns["nsd-ref"], member_ns["id"]
2777 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002778
Felipe Vicens07f31722018-10-29 15:16:44 +01002779 # creates Network Services records (NSRs)
2780 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002781 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002782 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002783 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002784 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002785 # Check if the netslice-subnet is shared and if it is share if the nss exists
2786 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002787 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002788 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002789 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002790 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2791 "nsd-ref"
2792 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002793 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002794 nsi = self.db.get_one(
2795 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2796 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002797 if nsi and service.get("is-shared-nss"):
2798 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2799 for nsrs_detailed_item in nsrs_detailed_list:
2800 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002801 if nsrs_detailed_item["nss-id"] == service["id"]:
2802 _id_nsr = nsrs_detailed_item["nsrId"]
2803 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002804 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2805 if netslice_subnet["nss-id"] == service["id"]:
2806 indata_ns = netslice_subnet
2807 break
2808 else:
2809 indata_ns = {}
2810 if service.get("instantiation-parameters"):
2811 indata_ns = deepcopy(service["instantiation-parameters"])
2812 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002813
Felipe Vicens09e65422019-01-22 15:06:46 +01002814 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002815 indata_ns["nsName"] = (
2816 slice_request.get("nsiName") + "." + service["id"]
2817 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002818 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2819 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002820 if slice_request.get("ssh_keys"):
2821 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002822
Felipe Vicens09e65422019-01-22 15:06:46 +01002823 if ns_params:
2824 for ns_param in ns_params:
2825 if ns_param.get("id") == service["id"]:
2826 copy_ns_param = deepcopy(ns_param)
2827 del copy_ns_param["id"]
2828 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002829 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002830
2831 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002832 _id_nsr, _ = self.nsrTopic.new(
2833 rollback, session, indata_ns, kwargs, headers
2834 )
2835 nsrs_item = {
2836 "nsrId": _id_nsr,
2837 "shared": service.get("is-shared-nss"),
2838 "nsd-id": service["nsd-ref"],
2839 "nss-id": service["id"],
2840 "nslcmop_instantiate": None,
2841 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002842 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002843 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002844 nsi_netslice_subnet.append(indata_ns)
2845 nsr_ref = {"nsr-ref": _id_nsr}
2846 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002847
2848 # Adding the nsrs list to the nsi
2849 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002850 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002851 self.db.set_one(
2852 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2853 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002854
Felipe Vicens07f31722018-10-29 15:16:44 +01002855 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002856 self.db.create("nsis", nsi_descriptor)
2857 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002858 return nsi_id, None
garciadeblasf2af4a12023-01-24 16:56:54 +01002859 except ValidationError as e:
2860 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
garciadeblas4568a372021-03-24 09:19:48 +01002861 except Exception as e: # TODO remove try Except, it is captured at nbi.py
rshri2d386cb2024-07-05 14:35:51 +00002862 # self.logger.exception(
2863 # "Exception {} at NsiTopic.new()".format(e), exc_info=True
2864 # )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002865 raise EngineException("Error {}: {}".format(step, e))
Felipe Vicensb57758d2018-10-16 16:00:20 +02002866
tierno65ca36d2019-02-12 19:27:52 +01002867 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002868 raise EngineException(
2869 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2870 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002871
2872
2873class NsiLcmOpTopic(BaseTopic):
2874 topic = "nsilcmops"
2875 topic_msg = "nsi"
2876 operation_schema = { # mapping between operation and jsonschema to validate
2877 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002878 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002879 }
garciadeblas4568a372021-03-24 09:19:48 +01002880
delacruzramo32bab472019-09-13 12:24:22 +02002881 def __init__(self, db, fs, msg, auth):
2882 BaseTopic.__init__(self, db, fs, msg, auth)
2883 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002884
2885 def _check_nsi_operation(self, session, nsir, operation, indata):
2886 """
2887 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002888 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002889 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2890 :param indata: descriptor with the parameters of the operation
2891 :return: None
2892 """
2893 nsds = {}
2894 nstd = nsir["network-slice-template"]
2895
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002896 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002897 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002898 for netslice_subnet in nstd["netslice-subnet"]:
2899 if nstId == netslice_subnet["id"]:
2900 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002901 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002902 _filter = self._get_project_filter(session)
2903 _filter["id"] = nsd_id
2904 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002905 return nsds[nsd_id]
2906 else:
garciadeblas4568a372021-03-24 09:19:48 +01002907 raise EngineException(
2908 "Invalid parameter nstId='{}' is not one of the "
2909 "nst:netslice-subnet".format(nstId)
2910 )
2911
Felipe Vicens07f31722018-10-29 15:16:44 +01002912 if operation == "instantiate":
2913 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002914 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002915 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002916
2917 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2918 now = time()
2919 _id = str(uuid4())
2920 nsilcmop = {
2921 "id": _id,
2922 "_id": _id,
2923 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2924 "statusEnteredTime": now,
2925 "netsliceInstanceId": netsliceInstanceId,
2926 "lcmOperationType": operation,
2927 "startTime": now,
2928 "isAutomaticInvocation": False,
2929 "operationParams": params,
2930 "isCancelPending": False,
2931 "links": {
2932 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002933 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2934 + netsliceInstanceId,
2935 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002936 }
2937 return nsilcmop
2938
Felipe Vicens09e65422019-01-22 15:06:46 +01002939 def add_shared_nsr_2vld(self, nsir, nsr_item):
2940 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2941 if nst_sb_item.get("is-shared-nss"):
2942 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2943 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2944 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002945 for admin_vld_nss_cp_ref_item in admin_vld_item[
2946 "nss-connection-point-ref"
2947 ]:
2948 if (
2949 admin_subnet_item["nss-id"]
2950 == admin_vld_nss_cp_ref_item["nss-ref"]
2951 ):
2952 if (
2953 not nsr_item["nsrId"]
2954 in admin_vld_item["shared-nsrs-list"]
2955 ):
2956 admin_vld_item["shared-nsrs-list"].append(
2957 nsr_item["nsrId"]
2958 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002959 break
2960 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002961 self.db.set_one(
2962 "nsis",
2963 {"_id": nsir["_id"]},
2964 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2965 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002966
tierno65ca36d2019-02-12 19:27:52 +01002967 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002968 """
2969 Performs a new operation over a ns
2970 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002971 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002972 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002973 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002974 operation: it can be: instantiate, terminate, action, TODO: update, heal
2975 :param kwargs: used to override the indata descriptor
2976 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002977 :return: id of the nslcmops
2978 """
2979 try:
2980 # Override descriptor with query string kwargs
2981 self._update_input_with_kwargs(indata, kwargs)
2982 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002983 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002984 validate_input(indata, self.operation_schema[operation])
2985
Felipe Vicens126af572019-06-05 19:13:04 +02002986 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002987 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002988 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002989 nsir = self.db.get_one("nsis", _filter)
rshri2d386cb2024-07-05 14:35:51 +00002990 # logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002991 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002992
2993 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002994 if (
2995 not nsir["_admin"].get("nsiState")
2996 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2997 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002998 if operation == "terminate" and indata.get("autoremove"):
2999 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01003000 return (
3001 None,
3002 None,
3003 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01003004 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01003005 raise EngineException(
3006 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
3007 netsliceInstanceId, operation
3008 ),
3009 HTTPStatus.CONFLICT,
3010 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003011 else:
tierno65ca36d2019-02-12 19:27:52 +01003012 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01003013 raise EngineException(
3014 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
3015 netsliceInstanceId, operation
3016 ),
3017 HTTPStatus.CONFLICT,
3018 )
3019
Felipe Vicens07f31722018-10-29 15:16:44 +01003020 # Creating all the NS_operation (nslcmop)
3021 # Get service list from db
3022 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
3023 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01003024 # nslcmops_item = None
3025 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00003026 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01003027 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003028 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00003029 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01003030 _filter[
3031 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
3032 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02003033 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01003034 nsi = self.db.get_one(
3035 "nsis", _filter, fail_on_empty=False, fail_on_more=False
3036 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003037 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01003038 _update = {
3039 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3040 index
3041 ): None
3042 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02003043 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01003044 if (
3045 nsi
3046 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00003047 continue # do not create nsilcmop
3048 else: # instantiate
3049 # looks the first nsi fulfilling the conditions but not being the current NSIR
3050 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01003051 nsi_nsr_item = next(
3052 n
3053 for n in nsi["_admin"]["nsrs-detailed-list"]
3054 if n["nsrId"] == nsr_id
3055 and n["shared"]
3056 and n["nslcmop_instantiate"]
3057 )
tierno40f742b2020-06-23 15:25:26 +00003058 self.add_shared_nsr_2vld(nsir, nsr_item)
3059 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01003060 _update = {
3061 "_admin.nsrs-detailed-list.{}".format(
3062 index
3063 ): nsi_nsr_item
3064 }
tierno40f742b2020-06-23 15:25:26 +00003065 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
3066 # continue to not create nslcmop since nsrs is shared and nsrs was created
3067 continue
3068 else:
3069 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01003070
tierno40f742b2020-06-23 15:25:26 +00003071 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01003072 try:
tierno0b8752f2020-05-12 09:42:02 +00003073 indata_ns = {
3074 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00003075 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00003076 # Including netslice_id in the ns instantiate Operation
3077 "netsliceInstanceId": netsliceInstanceId,
3078 }
3079 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00003080 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00003081 indata_ns.update(service["instantiate_params"])
3082
tierno99d4b172019-07-02 09:28:40 +00003083 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01003084 # message via kafka bus
Adurti87c0e4b2024-07-16 07:33:42 +00003085 nslcmop, _, _ = self.nsi_NsLcmOpTopic.new(
garciadeblas4568a372021-03-24 09:19:48 +01003086 rollback, session, indata_ns, None, headers, slice_object=True
3087 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003088 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00003089 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01003090 _update = {
3091 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3092 index
3093 ): nslcmop
3094 }
tierno40f742b2020-06-23 15:25:26 +00003095 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01003096 except (DbException, EngineException) as e:
3097 if e.http_code == HTTPStatus.NOT_FOUND:
Felipe Vicens09e65422019-01-22 15:06:46 +01003098 pass
3099 else:
3100 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01003101
3102 # Creates nsilcmop
3103 indata["nslcmops_ids"] = nslcmops
3104 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01003105
garciadeblas4568a372021-03-24 09:19:48 +01003106 nsilcmop_desc = self._create_nsilcmop(
3107 session, netsliceInstanceId, operation, indata
3108 )
3109 self.format_on_new(
3110 nsilcmop_desc, session["project_id"], make_public=session["public"]
3111 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003112 _id = self.db.create("nsilcmops", nsilcmop_desc)
3113 rollback.append({"topic": "nsilcmops", "_id": _id})
3114 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00003115 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01003116 except ValidationError as e:
3117 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01003118
tiernobee3bad2019-12-05 12:26:01 +00003119 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01003120 raise EngineException(
3121 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3122 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003123
tierno65ca36d2019-02-12 19:27:52 +01003124 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01003125 raise EngineException(
3126 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3127 )