blob: c2cd9ddf08729c5cdf588a57201e727f54bdcf89 [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,
govindarajul519da482022-04-29 19:05:22 +053033 ns_verticalscale,
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
Mark Beierlea3a2c22023-04-05 20:07:58 +000051from osm_nbi.temporal.nbi_temporal import NbiTemporal
tiernob24258a2018-10-04 18:39:49 +020052
53__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
54
55
56class NsrTopic(BaseTopic):
57 topic = "nsrs"
58 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000059 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000060 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020061
delacruzramo32bab472019-09-13 12:24:22 +020062 def __init__(self, db, fs, msg, auth):
63 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020064
tiernob24258a2018-10-04 18:39:49 +020065 @staticmethod
66 def format_on_new(content, project_id=None, make_public=False):
67 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
68 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000069 return None
tiernob24258a2018-10-04 18:39:49 +020070
tiernob4844ab2019-05-23 08:42:12 +000071 def check_conflict_on_del(self, session, _id, db_content):
72 """
73 Check that NSR is not instantiated
74 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
75 :param _id: nsr internal id
76 :param db_content: The database content of the nsr
77 :return: None or raises EngineException with the conflict
78 """
tierno65ca36d2019-02-12 19:27:52 +010079 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020080 return
tiernob4844ab2019-05-23 08:42:12 +000081 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020082 if nsr["_admin"].get("nsState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +010083 raise EngineException(
84 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
85 "Launch 'terminate' operation first; or force deletion".format(_id),
86 http_code=HTTPStatus.CONFLICT,
87 )
tiernob24258a2018-10-04 18:39:49 +020088
tiernobee3bad2019-12-05 12:26:01 +000089 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +000090 """
91 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
92 Set usageState of pdu, vnfd, nsd
93 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
94 :param _id: server internal id
95 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +000096 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +000097 :return: None if ok or raises EngineException with the problem
98 """
tiernobee085c2018-12-12 17:03:04 +000099 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +0200100 self.db.del_list("nslcmops", {"nsInstanceId": _id})
101 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +0000102
tiernob24258a2018-10-04 18:39:49 +0200103 # set all used pdus as free
garciadeblas4568a372021-03-24 09:19:48 +0100104 self.db.set_list(
105 "pdus",
106 {"_admin.usage.nsr_id": _id},
107 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
108 )
tiernob24258a2018-10-04 18:39:49 +0200109
tiernob4844ab2019-05-23 08:42:12 +0000110 # Set NSD usageState
111 nsr = db_content
112 used_nsd_id = nsr.get("nsd-id")
113 if used_nsd_id:
114 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100115 nsrs_list = self.db.get_one(
116 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
117 )
tiernob4844ab2019-05-23 08:42:12 +0000118 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100119 self.db.set_one(
120 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
121 )
tiernob4844ab2019-05-23 08:42:12 +0000122
123 # Set VNFD usageState
124 used_vnfd_id_list = nsr.get("vnfd-id")
125 if used_vnfd_id_list:
126 for used_vnfd_id in used_vnfd_id_list:
127 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100128 nsrs_list = self.db.get_one(
129 "nsrs",
130 {"vnfd-id": used_vnfd_id},
131 fail_on_empty=False,
132 fail_on_more=False,
133 )
tiernob4844ab2019-05-23 08:42:12 +0000134 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100135 self.db.set_one(
136 "vnfds",
137 {"_id": used_vnfd_id},
138 {"_admin.usageState": "NOT_IN_USE"},
139 )
tiernob4844ab2019-05-23 08:42:12 +0000140
tiernof0441ea2020-05-26 15:39:18 +0000141 # delete extra ro_nsrs used for internal RO module
142 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
143
tiernobee085c2018-12-12 17:03:04 +0000144 @staticmethod
145 def _format_ns_request(ns_request):
146 formated_request = copy(ns_request)
147 formated_request.pop("additionalParamsForNs", None)
148 formated_request.pop("additionalParamsForVnf", None)
149 return formated_request
150
151 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +0100152 def _format_additional_params(
153 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
154 ):
tiernobee085c2018-12-12 17:03:04 +0000155 """
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100156 Get and format user additional params for NS or VNF.
157 The vdu_id and kdu_name params are mutually exclusive! If none of them are given, then the method will
158 exclusively search for the VNF/NS LCM additional params.
159
tiernobee085c2018-12-12 17:03:04 +0000160 :param ns_request: User instantiation additional parameters
161 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100162 :vdu_id: VDU's ID against which we want to format the additional params
163 :kdu_name: KDU's name against which we want to format the additional params
tiernobee085c2018-12-12 17:03:04 +0000164 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000165 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000166 """
167 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000168 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000169 if not member_vnf_index:
170 additional_params = copy(ns_request.get("additionalParamsForNs"))
171 where_ = "additionalParamsForNs"
172 elif ns_request.get("additionalParamsForVnf"):
garciadeblas4568a372021-03-24 09:19:48 +0100173 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
174 member_vnf_index
175 )
176 item = next(
177 (
178 x
179 for x in ns_request["additionalParamsForVnf"]
180 if x["member-vnf-index"] == member_vnf_index
181 ),
182 None,
183 )
tierno714954e2019-11-29 13:43:26 +0000184 if item:
tierno54db2e42020-04-06 15:29:42 +0000185 if not vdu_id and not kdu_name:
186 other_params = item
tierno714954e2019-11-29 13:43:26 +0000187 additional_params = copy(item.get("additionalParams")) or {}
188 if vdu_id and item.get("additionalParamsForVdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100189 item_vdu = next(
190 (
191 x
192 for x in item["additionalParamsForVdu"]
193 if x["vdu_id"] == vdu_id
194 ),
195 None,
196 )
tiernobce98f02020-04-17 11:27:47 +0000197 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000198 if item_vdu and item_vdu.get("additionalParams"):
199 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000200 additional_params = item_vdu["additionalParams"]
201 if kdu_name:
202 additional_params = {}
203 if item.get("additionalParamsForKdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100204 item_kdu = next(
205 (
206 x
207 for x in item["additionalParamsForKdu"]
208 if x["kdu_name"] == kdu_name
209 ),
210 None,
211 )
tiernobce98f02020-04-17 11:27:47 +0000212 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000213 if item_kdu and item_kdu.get("additionalParams"):
garciadeblas4568a372021-03-24 09:19:48 +0100214 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
215 kdu_name
216 )
tiernob091dc12019-12-02 15:53:25 +0000217 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000218
tiernobee085c2018-12-12 17:03:04 +0000219 if additional_params:
220 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000221 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
garciadeblas4568a372021-03-24 09:19:48 +0100222 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
223 raise EngineException(
224 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
225 "and underscores, and cannot start with a digit".format(
226 where_, k
227 )
228 )
delacruzramo36ffe552019-05-03 14:52:37 +0200229 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000230 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +0100231 raise EngineException(
232 "Invalid param at {}:{}. Only string keys are allowed".format(
233 where_, k
234 )
235 )
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100236 if "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +0100237 raise EngineException(
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100238 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
garciadeblas4568a372021-03-24 09:19:48 +0100239 where_, k
240 )
241 )
tiernobee085c2018-12-12 17:03:04 +0000242 if isinstance(v, (dict, tuple, list)):
243 additional_params[k] = "!!yaml " + safe_dump(v)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100244 if kdu_name:
245 additional_params = json.dumps(additional_params)
tiernobee085c2018-12-12 17:03:04 +0000246
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100247 # Select the VDU ID, KDU name or NS/VNF ID, depending on the method's call intent
248 selector = vdu_id if vdu_id else kdu_name if kdu_name else descriptor.get("id")
249
tiernobee085c2018-12-12 17:03:04 +0000250 if descriptor:
bravof41a52052021-02-17 18:08:01 -0300251 for df in descriptor.get("df", []):
252 # check that enough parameters are supplied for the initial-config-primitive
253 # TODO: check for cloud-init
254 if member_vnf_index:
garciaale7cbd03c2020-11-27 10:38:35 -0300255 initial_primitives = []
garciadeblas4568a372021-03-24 09:19:48 +0100256 if (
257 "lcm-operations-configuration" in df
258 and "operate-vnf-op-config"
259 in df["lcm-operations-configuration"]
260 ):
261 for config in df["lcm-operations-configuration"][
262 "operate-vnf-op-config"
263 ].get("day1-2", []):
garciadeblasf2af4a12023-01-24 16:56:54 +0100264 # Verify the target object (VNF|NS|VDU|KDU) where we need to populate
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100265 # the params with the additional ones given by the user
266 if config.get("id") == selector:
267 for primitive in get_iterable(
268 config.get("initial-config-primitive")
269 ):
270 initial_primitives.append(primitive)
bravof41a52052021-02-17 18:08:01 -0300271 else:
garciadeblas4568a372021-03-24 09:19:48 +0100272 initial_primitives = deep_get(
273 descriptor, ("ns-configuration", "initial-config-primitive")
274 )
tiernobee085c2018-12-12 17:03:04 +0000275
bravof41a52052021-02-17 18:08:01 -0300276 for initial_primitive in get_iterable(initial_primitives):
277 for param in get_iterable(initial_primitive.get("parameter")):
garciadeblas4568a372021-03-24 09:19:48 +0100278 if param["value"].startswith("<") and param["value"].endswith(
279 ">"
280 ):
281 if param["value"] in (
282 "<rw_mgmt_ip>",
283 "<VDU_SCALE_INFO>",
284 "<ns_config_info>",
garciadeblasf2af4a12023-01-24 16:56:54 +0100285 "<OSM>",
garciadeblas4568a372021-03-24 09:19:48 +0100286 ):
bravof41a52052021-02-17 18:08:01 -0300287 continue
garciadeblas4568a372021-03-24 09:19:48 +0100288 if (
289 not additional_params
290 or param["value"][1:-1] not in additional_params
291 ):
292 raise EngineException(
293 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
294 "initial-config-primitive[name={}] not supplied".format(
295 param["value"],
296 descriptor["id"],
297 initial_primitive["name"],
298 )
299 )
tierno714954e2019-11-29 13:43:26 +0000300
tierno54db2e42020-04-06 15:29:42 +0000301 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000302
tierno65ca36d2019-02-12 19:27:52 +0100303 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200304 """
305 Creates a new nsr into database. It also creates needed vnfrs
306 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200308 :param indata: params to be used for the nsr
309 :param kwargs: used to override the indata descriptor
310 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000311 :return: the _id of nsr descriptor created at database. Or an exception of type
312 EngineException, ValidationError, DbException, FsException, MsgException.
313 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200314 """
garciadeblasf2af4a12023-01-24 16:56:54 +0100315 step = "checking quotas" # first step must be defined outside try
tiernob24258a2018-10-04 18:39:49 +0200316 try:
delacruzramo32bab472019-09-13 12:24:22 +0200317 self.check_quota(session)
318
tierno99d4b172019-07-02 09:28:40 +0000319 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200320 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200321 self._update_input_with_kwargs(ns_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -0300322 ns_request = self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200323
tiernob24258a2018-10-04 18:39:49 +0200324 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale7cbd03c2020-11-27 10:38:35 -0300325 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
326 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200327
Frank Bryden3c64ab62020-07-21 14:25:32 +0000328 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300329 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000330
tiernob24258a2018-10-04 18:39:49 +0200331 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300332 nsr_id = str(uuid4())
garciadeblas4568a372021-03-24 09:19:48 +0100333 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
334 nsd, ns_request, nsr_id, session
335 )
tierno54db2e42020-04-06 15:29:42 +0000336
garciaale7cbd03c2020-11-27 10:38:35 -0300337 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200338 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300339 # TODO: Change for multiple df support
K Sai Kiranbb006022021-05-20 11:09:49 +0530340 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
garciaale7cbd03c2020-11-27 10:38:35 -0300341 for vnfp in vnf_profiles:
342 vnfd_id = vnfp.get("vnfd-id")
343 vnf_index = vnfp.get("id")
garciadeblas4568a372021-03-24 09:19:48 +0100344 step = (
345 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
346 vnfd_id, vnf_index
347 )
348 )
tiernob24258a2018-10-04 18:39:49 +0200349 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300350 vnfd = self._get_vnfd_from_db(vnfd_id, session)
beierlmcee2ebf2022-03-29 17:42:48 -0400351 if "revision" in vnfd["_admin"]:
352 vnfd["revision"] = vnfd["_admin"]["revision"]
353 vnfd.pop("_admin")
tiernob24258a2018-10-04 18:39:49 +0200354 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000355 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200356 else:
357 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100358
garciadeblas4568a372021-03-24 09:19:48 +0100359 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
360 vnfd_id, vnf_index
361 )
362 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
363 nsd,
364 vnfd,
365 vnfd_id,
366 vnf_index,
367 nsr_descriptor,
368 ns_request,
369 ns_k8s_namespace,
370 )
tierno36ec8602018-11-02 17:27:11 +0100371
garciadeblas4568a372021-03-24 09:19:48 +0100372 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
373 vnfd_id, vnf_index
374 )
garciaale7cbd03c2020-11-27 10:38:35 -0300375 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
376 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
aticig2b5e1232022-08-10 17:30:12 +0300377 step = "Updating VNFD usageState"
378 update_descriptor_usage_state(vnfd, "vnfds", self.db)
tiernob24258a2018-10-04 18:39:49 +0200379
380 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300381 self._add_nsr_to_db(nsr_descriptor, rollback, session)
aticig2b5e1232022-08-10 17:30:12 +0300382 step = "Updating NSD usageState"
383 update_descriptor_usage_state(nsd, "nsds", self.db)
tiernobee085c2018-12-12 17:03:04 +0000384
385 step = "creating nsr temporal folder"
386 self.fs.mkdir(nsr_id)
387
tiernobdebce92019-07-01 15:36:49 +0000388 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100389 except (
390 ValidationError,
391 EngineException,
392 DbException,
393 MsgException,
394 FsException,
395 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000396 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200397
garciaale7cbd03c2020-11-27 10:38:35 -0300398 def _get_nsd_from_db(self, nsd_id, session):
399 _filter = self._get_project_filter(session)
400 _filter["_id"] = nsd_id
401 return self.db.get_one("nsds", _filter)
402
403 def _get_vnfd_from_db(self, vnfd_id, session):
404 _filter = self._get_project_filter(session)
405 _filter["id"] = vnfd_id
406 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
garciaale7cbd03c2020-11-27 10:38:35 -0300407 return vnfd
408
409 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100410 self.format_on_new(
411 nsr_descriptor, session["project_id"], make_public=session["public"]
412 )
garciaale7cbd03c2020-11-27 10:38:35 -0300413 self.db.create("nsrs", nsr_descriptor)
414 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
415
416 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100417 self.format_on_new(
418 vnfr_descriptor, session["project_id"], make_public=session["public"]
419 )
garciaale7cbd03c2020-11-27 10:38:35 -0300420 self.db.create("vnfrs", vnfr_descriptor)
421 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
422
423 def _check_nsd_operational_state(self, nsd, ns_request):
424 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100425 raise EngineException(
426 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
427 "a network service".format(ns_request["nsdId"]),
428 http_code=HTTPStatus.CONFLICT,
429 )
garciaale7cbd03c2020-11-27 10:38:35 -0300430
431 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100432 additional_params, _ = self._format_additional_params(
433 ns_request, descriptor=nsd
434 )
garciaale7cbd03c2020-11-27 10:38:35 -0300435 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
436 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
437 if ns_request and ns_request.get("k8s-namespace"):
438 ns_k8s_namespace = ns_request["k8s-namespace"]
439 if additional_params and additional_params.get("k8s-namespace"):
440 ns_k8s_namespace = additional_params["k8s-namespace"]
441
442 return ns_k8s_namespace
443
garciadeblasf2af4a12023-01-24 16:56:54 +0100444 def _add_flavor_to_nsr(
445 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
446 ):
elumalai6c5ea6b2022-04-25 22:27:59 +0530447 flavor_data = {}
448 guest_epa = {}
449 # Find this vdu compute and storage descriptors
450 vdu_virtual_compute = {}
451 vdu_virtual_storage = {}
452 for vcd in vnfd.get("virtual-compute-desc", ()):
453 if vcd.get("id") == vdu.get("virtual-compute-desc"):
454 vdu_virtual_compute = vcd
455 for vsd in vnfd.get("virtual-storage-desc", ()):
456 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
457 vdu_virtual_storage = vsd
458 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblasf2af4a12023-01-24 16:56:54 +0100459 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
elumalai6c5ea6b2022-04-25 22:27:59 +0530460 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
461 "num-virtual-cpu"
462 ]
463 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
464 flavor_data["memory-mb"] = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100465 float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
elumalai6c5ea6b2022-04-25 22:27:59 +0530466 )
467 if vdu_virtual_storage.get("size-of-storage"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100468 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530469 # Get this vdu EPA info for guest_epa
470 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100471 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530472 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
473 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
474 if vcpu_pinning.get("thread-policy"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100475 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530476 if vcpu_pinning.get("policy"):
477 cpu_policy = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100478 "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
elumalai6c5ea6b2022-04-25 22:27:59 +0530479 )
480 guest_epa["cpu-pinning-policy"] = cpu_policy
481 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100482 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
483 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
484 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"][
485 "mempage-size"
elumalai6c5ea6b2022-04-25 22:27:59 +0530486 ]
garciadeblasf2af4a12023-01-24 16:56:54 +0100487 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
488 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"][
489 "numa-node-policy"
490 ]
elumalai6c5ea6b2022-04-25 22:27:59 +0530491 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100492 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530493
494 if guest_epa:
495 flavor_data["guest-epa"] = guest_epa
496
elumalai99078a92022-07-05 17:53:59 +0530497 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +0100498 flavor_data["name"] = (
499 vdu["id"][:56] + "-" + member_vnf_index + "-" + str(revision) + "-flv"
500 )
elumalai6c5ea6b2022-04-25 22:27:59 +0530501 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
502 nsr_descriptor["flavor"].append(flavor_data)
503
bravofe76b8822021-02-26 16:57:52 -0300504 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300505 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100506 additional_params, _ = self._format_additional_params(
507 ns_request, descriptor=nsd
508 )
garciaale7cbd03c2020-11-27 10:38:35 -0300509
510 nsr_descriptor = {
511 "name": ns_request["nsName"],
512 "name-ref": ns_request["nsName"],
513 "short-name": ns_request["nsName"],
514 "admin-status": "ENABLED",
515 "nsState": "NOT_INSTANTIATED",
516 "currentOperation": "IDLE",
517 "currentOperationID": None,
518 "errorDescription": None,
519 "errorDetail": None,
520 "deploymentStatus": None,
521 "configurationStatus": None,
522 "vcaStatus": None,
523 "nsd": {k: v for k, v in nsd.items()},
Mark Beierlc528d882023-01-06 12:56:16 -0500524 "datacenter": ns_request["vimAccountId"],
garciaale7cbd03c2020-11-27 10:38:35 -0300525 "resource-orchestrator": "osmopenmano",
526 "description": ns_request.get("nsDescription", ""),
527 "constituent-vnfr-ref": [],
528 "operational-status": "init", # typedef ns-operational-
529 "config-status": "init", # typedef config-states
530 "detailed-status": "scheduled",
531 "orchestration-progress": {},
532 "create-time": now,
533 "nsd-name-ref": nsd["name"],
534 "operational-events": [], # "id", "timestamp", "description", "event",
535 "nsd-ref": nsd["id"],
536 "nsd-id": nsd["_id"],
537 "vnfd-id": [],
538 "instantiate_params": self._format_ns_request(ns_request),
539 "additionalParamsForNs": additional_params,
540 "ns-instance-config-ref": nsr_id,
541 "id": nsr_id,
542 "_id": nsr_id,
543 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
544 "flavor": [],
545 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100546 "affinity-or-anti-affinity-group": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300547 }
beierlmbc5a5242022-05-17 21:25:29 -0400548 if "revision" in nsd["_admin"]:
549 nsr_descriptor["revision"] = nsd["_admin"]["revision"]
550
garciaale7cbd03c2020-11-27 10:38:35 -0300551 ns_request["nsr_id"] = nsr_id
552 if ns_request and ns_request.get("config-units"):
553 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300554 # Create vld
555 if nsd.get("virtual-link-desc"):
556 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
557 # Fill each vld with vnfd-connection-point-ref data
558 # TODO: Change for multiple df support
559 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
560 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
561 for vnf_profile in vnf_profiles:
562 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
563 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100564 all_vld_connection_point_data[
565 vlc.get("virtual-link-profile-id")
566 ].append(
567 {
568 "member-vnf-index-ref": cpd.get(
569 "constituent-base-element-id"
570 ),
571 "vnfd-connection-point-ref": cpd.get(
572 "constituent-cpd-id"
573 ),
574 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
575 }
576 )
garciaale7cbd03c2020-11-27 10:38:35 -0300577
bravofe76b8822021-02-26 16:57:52 -0300578 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400579 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300580
581 for vdu in vnfd.get("vdu", ()):
elumalai99078a92022-07-05 17:53:59 +0530582 member_vnf_index = vnf_profile.get("id")
583 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor, member_vnf_index)
garciaale7cbd03c2020-11-27 10:38:35 -0300584 sw_image_id = vdu.get("sw-image-desc")
585 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000586 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
587 self._add_image_to_nsr(nsr_descriptor, image_data)
588
589 # also add alternative images to the list of images
590 for alt_image in vdu.get("alternative-sw-image-desc", ()):
591 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
592 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300593
Alexis Romero03fb5842022-03-11 15:53:40 +0100594 # Add Affinity or Anti-affinity group information to NSR
595 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200596 affinity_group_prefix_name = "{}-{}".format(
597 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
598 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100599
600 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200601 affinity_group_data = {}
602 for affinity_group in vdu_profile.get(
603 "affinity-or-anti-affinity-group", ()
604 ):
605 affinity_group_data = (
606 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
607 vnfd, affinity_group["id"]
608 )
609 )
610 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
611 self._add_affinity_or_anti_affinity_group_to_nsr(
612 nsr_descriptor,
613 affinity_group_data,
614 affinity_group_prefix_name,
615 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100616
garciaale7cbd03c2020-11-27 10:38:35 -0300617 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100618 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
619 vld.get("id"), []
620 )
garciaale7cbd03c2020-11-27 10:38:35 -0300621 vld["name"] = vld["id"]
622 nsr_descriptor["vld"] = nsr_vld
623
624 return nsr_descriptor
625
Alexis Romeroee31f532022-04-26 19:10:21 +0200626 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
627 self, vnfd, affinity_group_id
628 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100629 """
630 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
631 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200632 affinity_group = utils.find_in_list(
633 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
634 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100635 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200636 affinity_group_data = {}
637 if affinity_group:
638 if affinity_group.get("id"):
639 affinity_group_data["ag-id"] = affinity_group["id"]
640 if affinity_group.get("type"):
641 affinity_group_data["type"] = affinity_group["type"]
642 if affinity_group.get("scope"):
643 affinity_group_data["scope"] = affinity_group["scope"]
644 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100645
Alexis Romeroee31f532022-04-26 19:10:21 +0200646 def _add_affinity_or_anti_affinity_group_to_nsr(
647 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
648 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100649 """
650 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
651 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200652 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100653 (
654 f
655 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200656 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100657 ),
658 None,
659 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200660 if not affinity_group:
661 affinity_group_data["id"] = str(
662 len(nsr_descriptor["affinity-or-anti-affinity-group"])
663 )
664 affinity_group_data["name"] = "{}-{}".format(
665 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
666 )
667 nsr_descriptor["affinity-or-anti-affinity-group"].append(
668 affinity_group_data
669 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100670
lloretgalleg28c13b62021-02-08 11:48:48 +0000671 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100672 sw_image_desc = utils.find_in_list(
673 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
674 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000675 image_data = {}
676 if sw_image_desc.get("image"):
677 image_data["image"] = sw_image_desc["image"]
678 if sw_image_desc.get("checksum"):
679 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
680 if sw_image_desc.get("vim-type"):
681 image_data["vim-type"] = sw_image_desc["vim-type"]
682 return image_data
683
684 def _add_image_to_nsr(self, nsr_descriptor, image_data):
685 """
686 Adds image to nsr checking first it is not already added
687 """
garciadeblas4568a372021-03-24 09:19:48 +0100688 img = next(
689 (
690 f
691 for f in nsr_descriptor["image"]
692 if all(f.get(k) == image_data[k] for k in image_data)
693 ),
694 None,
695 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000696 if not img:
697 image_data["id"] = str(len(nsr_descriptor["image"]))
698 nsr_descriptor["image"].append(image_data)
699
garciadeblas4568a372021-03-24 09:19:48 +0100700 def _create_vnfr_descriptor_from_vnfd(
701 self,
702 nsd,
703 vnfd,
704 vnfd_id,
705 vnf_index,
706 nsr_descriptor,
707 ns_request,
708 ns_k8s_namespace,
elumalai99078a92022-07-05 17:53:59 +0530709 revision=None,
garciadeblas4568a372021-03-24 09:19:48 +0100710 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300711 vnfr_id = str(uuid4())
712 nsr_id = nsr_descriptor["id"]
713 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100714 additional_params, vnf_params = self._format_additional_params(
715 ns_request, vnf_index, descriptor=vnfd
716 )
garciaale7cbd03c2020-11-27 10:38:35 -0300717
718 vnfr_descriptor = {
719 "id": vnfr_id,
720 "_id": vnfr_id,
721 "nsr-id-ref": nsr_id,
722 "member-vnf-index-ref": vnf_index,
723 "additionalParamsForVnf": additional_params,
724 "created-time": now,
725 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
726 "vnfd-ref": vnfd_id,
727 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
728 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200729 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300730 "vdur": [],
731 "connection-point": [],
732 "ip-address": None, # mgmt-interface filled by LCM
733 }
beierlmcee2ebf2022-03-29 17:42:48 -0400734
735 # Revision backwards compatility. Only specify the revision in the record if
736 # the original VNFD has a revision.
737 if "revision" in vnfd:
738 vnfr_descriptor["revision"] = vnfd["revision"]
739
garciaale7cbd03c2020-11-27 10:38:35 -0300740 vnf_k8s_namespace = ns_k8s_namespace
741 if vnf_params:
742 if vnf_params.get("k8s-namespace"):
743 vnf_k8s_namespace = vnf_params["k8s-namespace"]
744 if vnf_params.get("config-units"):
745 vnfr_descriptor["config-units"] = vnf_params["config-units"]
746
747 # Create vld
748 if vnfd.get("int-virtual-link-desc"):
749 vnfr_descriptor["vld"] = []
750 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
751 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
752
753 for cp in vnfd.get("ext-cpd", ()):
754 vnf_cp = {
755 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100756 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
757 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300758 "id": cp.get("id"),
759 # "ip-address", "mac-address" # filled by LCM
760 # vim-id # TODO it would be nice having a vim port id
761 }
762 vnfr_descriptor["connection-point"].append(vnf_cp)
763
764 # Create k8s-cluster information
765 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
766 if vnfd.get("k8s-cluster"):
767 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
768 all_k8s_cluster_nets_cpds = {}
769 for cpd in get_iterable(vnfd.get("ext-cpd")):
770 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100771 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
772 "id"
773 )
garciaale7cbd03c2020-11-27 10:38:35 -0300774 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
775 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100776 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
777 net.get("id")
778 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300779
780 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300781 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100782 additional_params, kdu_params = self._format_additional_params(
783 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
784 )
garciaale7cbd03c2020-11-27 10:38:35 -0300785 kdu_k8s_namespace = vnf_k8s_namespace
786 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
787 if kdu_params and kdu_params.get("k8s-namespace"):
788 kdu_k8s_namespace = kdu_params["k8s-namespace"]
789
romeromonserbfebfc02021-05-28 10:51:35 +0200790 kdu_deployment_name = ""
791 if kdu_params and kdu_params.get("kdu-deployment-name"):
792 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
793
garciaale7cbd03c2020-11-27 10:38:35 -0300794 kdur = {
795 "additionalParams": additional_params,
796 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200797 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000798 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300799 # TODO "name": "" Name of the VDU in the VIM
800 "ip-address": None, # mgmt-interface filled by LCM
801 "k8s-cluster": {},
802 }
803 if kdu_params and kdu_params.get("config-units"):
804 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000805 if kdu.get("helm-version"):
806 kdur["helm-version"] = kdu["helm-version"]
807 for k8s_type in ("helm-chart", "juju-bundle"):
808 if kdu.get(k8s_type):
809 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300810 if not vnfr_descriptor.get("kdur"):
811 vnfr_descriptor["kdur"] = []
812 vnfr_descriptor["kdur"].append(kdur)
813
814 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300815
garciaale7cbd03c2020-11-27 10:38:35 -0300816 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300817 vdu_mgmt_cp = []
818 try:
garciadeblas4568a372021-03-24 09:19:48 +0100819 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
820 "operate-vnf-op-config"
821 ]["day1-2"]
822 vdu_config = utils.find_in_list(
823 configs, lambda config: config["id"] == vdu["id"]
824 )
bravoff3c39552021-02-24 17:22:24 -0300825 except Exception:
826 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400827
828 try:
829 vdu_instantiation_level = utils.find_in_list(
830 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100831 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400832 )
833 except Exception:
834 vdu_instantiation_level = None
835
bravoff3c39552021-02-24 17:22:24 -0300836 if vdu_config:
837 external_connection_ee = utils.filter_in_list(
838 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100839 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300840 )
841 for ee in external_connection_ee:
842 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
843
garciaale7cbd03c2020-11-27 10:38:35 -0300844 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100845 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
846 )
bravof65e22e52021-11-10 17:58:58 -0300847
848 try:
849 vdu_virtual_storage_descriptors = utils.filter_in_list(
850 vnfd.get("virtual-storage-desc", []),
garciadeblasf2af4a12023-01-24 16:56:54 +0100851 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"],
bravof65e22e52021-11-10 17:58:58 -0300852 )
853 except Exception:
854 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300855 vdur = {
856 "vdu-id-ref": vdu["id"],
857 # TODO "name": "" Name of the VDU in the VIM
858 "ip-address": None, # mgmt-interface filled by LCM
859 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
860 "internal-connection-point": [],
861 "interfaces": [],
862 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100863 "vdu-name": vdu["name"],
garciadeblasf2af4a12023-01-24 16:56:54 +0100864 "virtual-storages": vdu_virtual_storage_descriptors,
garciaale7cbd03c2020-11-27 10:38:35 -0300865 }
866 if vdu_params and vdu_params.get("config-units"):
867 vdur["config-units"] = vdu_params["config-units"]
868 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100869 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
870 "boot-data-drive"
871 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300872 if vdu.get("pdu-type"):
873 vdur["pdu-type"] = vdu["pdu-type"]
874 vdur["name"] = vdu["pdu-type"]
875 # TODO volumes: name, volume-id
876 for icp in vdu.get("int-cpd", ()):
877 vdu_icp = {
878 "id": icp["id"],
879 "connection-point-id": icp["id"],
880 "name": icp.get("id"),
881 }
bravof35766442021-02-04 14:58:04 -0300882
garciaale7cbd03c2020-11-27 10:38:35 -0300883 vdur["internal-connection-point"].append(vdu_icp)
884
885 for iface in icp.get("virtual-network-interface-requirement", ()):
aticigc9c03392022-06-16 01:39:44 +0300886 # Name, mac-address and interface position is taken from VNFD
887 # and included into VNFR. By this way RO can process this information
888 # while creating the VDU.
889 iface_fields = ("name", "mac-address", "position")
garciadeblas4568a372021-03-24 09:19:48 +0100890 vdu_iface = {
891 x: iface[x] for x in iface_fields if iface.get(x) is not None
892 }
garciaale7cbd03c2020-11-27 10:38:35 -0300893
894 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100895 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100896 vdu_iface["port-security-enabled"] = icp[
897 "port-security-enabled"
898 ]
sousaedu003844e2021-03-02 00:19:15 +0100899
900 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100901 vdu_iface["port-security-disable-strategy"] = icp[
902 "port-security-disable-strategy"
903 ]
sousaedu003844e2021-03-02 00:19:15 +0100904
garciaale7cbd03c2020-11-27 10:38:35 -0300905 for ext_cp in vnfd.get("ext-cpd", ()):
906 if not ext_cp.get("int-cpd"):
907 continue
908 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
909 continue
910 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100911 vdu_iface["external-connection-point-ref"] = ext_cp.get(
912 "id"
913 )
sousaedu003844e2021-03-02 00:19:15 +0100914
915 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100916 vdu_iface["port-security-enabled"] = ext_cp[
917 "port-security-enabled"
918 ]
sousaedu003844e2021-03-02 00:19:15 +0100919
920 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100921 vdu_iface["port-security-disable-strategy"] = ext_cp[
922 "port-security-disable-strategy"
923 ]
sousaedu003844e2021-03-02 00:19:15 +0100924
garciaale7cbd03c2020-11-27 10:38:35 -0300925 break
926
garciadeblas4568a372021-03-24 09:19:48 +0100927 if (
928 vnfd_mgmt_cp
929 and vdu_iface.get("external-connection-point-ref")
930 == vnfd_mgmt_cp
931 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300932 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300933 vdu_iface["mgmt-interface"] = True
934
935 for ecp in vdu_mgmt_cp:
936 if vdu_iface.get("external-connection-point-ref") == ecp:
937 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300938
939 if iface.get("virtual-interface"):
940 vdu_iface.update(deepcopy(iface["virtual-interface"]))
941
942 # look for network where this interface is connected
943 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
944 if iface_ext_cp:
945 # TODO: Change for multiple df support
946 for df in get_iterable(nsd.get("df")):
947 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100948 for vlc_index, vlc in enumerate(
949 get_iterable(
950 vnf_profile.get("virtual-link-connectivity")
951 )
952 ):
953 for cpd in get_iterable(
954 vlc.get("constituent-cpd-id")
955 ):
956 if (
957 cpd.get("constituent-cpd-id")
958 == iface_ext_cp
959 ):
960 vdu_iface["ns-vld-id"] = vlc.get(
961 "virtual-link-profile-id"
962 )
garciadeblas61c95912021-02-12 11:23:50 +0000963 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100964 if vdu_iface.get("type") in (
965 "SR-IOV",
966 "PCI-PASSTHROUGH",
967 ):
968 nsr_descriptor["vld"][vlc_index][
969 "pci-interfaces"
970 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300971 break
972 elif vdu_iface.get("internal-connection-point-ref"):
973 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000974 # TODO: store fixed IP address in the record (if it exists in the ICP)
975 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
976 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100977 ivld_index = utils.find_index_in_list(
978 vnfd.get("int-virtual-link-desc", ()),
979 lambda ivld: ivld["id"]
980 == icp.get("int-virtual-link-desc"),
981 )
garciadeblas61c95912021-02-12 11:23:50 +0000982 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300983
984 vdur["interfaces"].append(vdu_iface)
985
986 if vdu.get("sw-image-desc"):
987 sw_image = utils.find_in_list(
988 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100989 lambda image: image["id"] == vdu.get("sw-image-desc"),
990 )
garciaale7cbd03c2020-11-27 10:38:35 -0300991 nsr_sw_image_data = utils.find_in_list(
992 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100993 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300994 )
995 vdur["ns-image-id"] = nsr_sw_image_data["id"]
996
lloretgalleg28c13b62021-02-08 11:48:48 +0000997 if vdu.get("alternative-sw-image-desc"):
998 alt_image_ids = []
999 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1000 sw_image = utils.find_in_list(
1001 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001002 lambda image: image["id"] == alt_image_id,
1003 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001004 nsr_sw_image_data = utils.find_in_list(
1005 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001006 lambda nsr_image: (
1007 nsr_image.get("image") == sw_image.get("image")
1008 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001009 )
1010 alt_image_ids.append(nsr_sw_image_data["id"])
1011 vdur["alt-image-ids"] = alt_image_ids
1012
elumalai99078a92022-07-05 17:53:59 +05301013 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +01001014 flavor_data_name = (
1015 vdu["id"][:56] + "-" + vnf_index + "-" + str(revision) + "-flv"
1016 )
garciaale7cbd03c2020-11-27 10:38:35 -03001017 nsr_flavor_desc = utils.find_in_list(
1018 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001019 lambda flavor: flavor["name"] == flavor_data_name,
1020 )
garciaale7cbd03c2020-11-27 10:38:35 -03001021
1022 if nsr_flavor_desc:
1023 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1024
Alexis Romero03fb5842022-03-11 15:53:40 +01001025 # Adding Affinity groups information to vdur
1026 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001027 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001028 vnfd.get("df")[0]["vdu-profile"],
1029 lambda a_vdu: a_vdu["id"] == vdu["id"],
1030 )
1031 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001032 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001033
Alexis Romeroee31f532022-04-26 19:10:21 +02001034 if vdu_profile_affinity_group:
1035 affinity_group_ids = []
1036 for affinity_group in vdu_profile_affinity_group.get(
1037 "affinity-or-anti-affinity-group", ()
1038 ):
1039 vdu_affinity_group = utils.find_in_list(
1040 vdu_profile_affinity_group.get(
1041 "affinity-or-anti-affinity-group", ()
1042 ),
1043 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001044 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001045 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001046 nsr_descriptor["affinity-or-anti-affinity-group"],
1047 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001048 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1049 and nsr_ag.get("member-vnf-index")
1050 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001051 ),
1052 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001053 # Update Affinity Group VIM name if VDU instantiation parameter is present
1054 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1055 vnf_params_affinity_group = utils.find_in_list(
1056 vnf_params["affinity-or-anti-affinity-group"],
1057 lambda vnfp_ag: (
1058 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1059 ),
1060 )
1061 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1062 nsr_affinity_group[
1063 "vim-affinity-group-id"
1064 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1065 affinity_group_ids.append(nsr_affinity_group["id"])
1066 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001067
bravof4ca51522021-04-22 10:03:02 -04001068 if vdu_instantiation_level:
1069 count = vdu_instantiation_level.get("number-of-instances")
1070 else:
1071 count = 1
1072
garciaale7cbd03c2020-11-27 10:38:35 -03001073 for index in range(0, count):
1074 vdur = deepcopy(vdur)
1075 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001076 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001077 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001078 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001079 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1080
1081 vdur["_id"] = str(uuid4())
1082 vdur["id"] = vdur["_id"]
1083 vdur["count-index"] = index
1084 vnfr_descriptor["vdur"].append(vdur)
1085
1086 return vnfr_descriptor
1087
K Sai Kiran57589552021-01-27 21:38:34 +05301088 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1089 """
1090 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1091 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1092 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1093 :param ns_instance_content: ns instance content
1094 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1095 :return: None
1096 """
garciadeblasf2af4a12023-01-24 16:56:54 +01001097 time_now, time_delta = (
1098 time(),
1099 time() - ns_instance_content["_admin"]["modified"],
1100 )
1101 force_refresh = (
1102 isinstance(filter_q, dict) and filter_q.get("vcaStatusRefresh") == "true"
1103 )
K Sai Kiran57589552021-01-27 21:38:34 +05301104 threshold_reached = time_delta > 120
1105 if force_refresh or threshold_reached:
1106 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1107 ns_instance_content["_admin"]["modified"] = time_now
1108 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1109 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
garciadeblasf2af4a12023-01-24 16:56:54 +01001110 self.format_on_new(
1111 nslcmop_desc, session["project_id"], make_public=session["public"]
1112 )
K Sai Kiran57589552021-01-27 21:38:34 +05301113 nslcmop_desc["_admin"].pop("nsState")
1114 self.msg.write("ns", operation, nslcmop_desc)
1115 return
1116
1117 def show(self, session, _id, filter_q=None, api_req=False):
1118 """
1119 Get complete information on an ns instance.
1120 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1121 :param _id: string, ns instance id
1122 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1123 :param api_req: True if this call is serving an external API request. False if serving internal request.
1124 :return: dictionary, raise exception if not found.
1125 """
1126 ns_instance_content = super().show(session, _id, api_req)
1127 self.vca_status_refresh(session, ns_instance_content, filter_q)
1128 return ns_instance_content
1129
tierno65ca36d2019-02-12 19:27:52 +01001130 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001131 raise EngineException(
1132 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1133 )
tiernob24258a2018-10-04 18:39:49 +02001134
1135
1136class VnfrTopic(BaseTopic):
1137 topic = "vnfrs"
1138 topic_msg = None
1139
delacruzramo32bab472019-09-13 12:24:22 +02001140 def __init__(self, db, fs, msg, auth):
1141 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001142
tiernobee3bad2019-12-05 12:26:01 +00001143 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001144 raise EngineException(
1145 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1146 )
tiernob24258a2018-10-04 18:39:49 +02001147
tierno65ca36d2019-02-12 19:27:52 +01001148 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001149 raise EngineException(
1150 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1151 )
tiernob24258a2018-10-04 18:39:49 +02001152
tierno65ca36d2019-02-12 19:27:52 +01001153 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001154 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001155 raise EngineException(
1156 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1157 )
tiernob24258a2018-10-04 18:39:49 +02001158
1159
1160class NsLcmOpTopic(BaseTopic):
1161 topic = "nslcmops"
1162 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001163 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001164 "instantiate": ns_instantiate,
1165 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001166 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001167 "scale": ns_scale,
garciadeblas0964edf2022-02-11 00:43:44 +01001168 "heal": ns_heal,
tierno1c38f2f2020-03-24 11:51:39 +00001169 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301170 "migrate": ns_migrate,
govindarajul519da482022-04-29 19:05:22 +05301171 "verticalscale": ns_verticalscale,
tiernob24258a2018-10-04 18:39:49 +02001172 }
1173
delacruzramo32bab472019-09-13 12:24:22 +02001174 def __init__(self, db, fs, msg, auth):
1175 BaseTopic.__init__(self, db, fs, msg, auth)
elumalai6c5ea6b2022-04-25 22:27:59 +05301176 self.nsrtopic = NsrTopic(db, fs, msg, auth)
Mark Beierlea3a2c22023-04-05 20:07:58 +00001177 self.temporal = NbiTemporal()
tiernob24258a2018-10-04 18:39:49 +02001178
tiernob24258a2018-10-04 18:39:49 +02001179 def _check_ns_operation(self, session, nsr, operation, indata):
1180 """
1181 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001182 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
garciadeblas0964edf2022-02-11 00:43:44 +01001183 :param operation: it can be: instantiate, terminate, action, update, heal
tiernob24258a2018-10-04 18:39:49 +02001184 :param indata: descriptor with the parameters of the operation
1185 :return: None
1186 """
garciaale7cbd03c2020-11-27 10:38:35 -03001187 if operation == "action":
1188 self._check_action_ns_operation(indata, nsr)
1189 elif operation == "scale":
1190 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001191 elif operation == "update":
1192 self._check_update_ns_operation(indata, nsr)
garciadeblas0964edf2022-02-11 00:43:44 +01001193 elif operation == "heal":
1194 self._check_heal_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001195 elif operation == "instantiate":
1196 self._check_instantiate_ns_operation(indata, nsr, session)
1197
1198 def _check_action_ns_operation(self, indata, nsr):
1199 nsd = nsr["nsd"]
1200 # check vnf_member_index
1201 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001202 indata["member_vnf_index"] = indata.pop(
1203 "vnf_member_index"
1204 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001205 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001206 vnfd = self._get_vnfd_from_vnf_member_index(
1207 indata["member_vnf_index"], nsr["_id"]
1208 )
bravof41a52052021-02-17 18:08:01 -03001209 try:
garciadeblas4568a372021-03-24 09:19:48 +01001210 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1211 "operate-vnf-op-config"
1212 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001213 except Exception:
1214 configs = []
1215
garciaale7cbd03c2020-11-27 10:38:35 -03001216 if indata.get("vdu_id"):
1217 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001218 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001219 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001220 )
garciaale7cbd03c2020-11-27 10:38:35 -03001221 elif indata.get("kdu_name"):
1222 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001223 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001224 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001225 )
garciaale7cbd03c2020-11-27 10:38:35 -03001226 else:
bravof41a52052021-02-17 18:08:01 -03001227 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001228 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001229 )
1230 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001231 descriptor_configuration = descriptor_configuration.get(
1232 "config-primitive"
1233 )
garciaale7cbd03c2020-11-27 10:38:35 -03001234 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001235 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1236 "config-primitive"
1237 )
garciaale7cbd03c2020-11-27 10:38:35 -03001238
1239 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001240 if indata.get("kdu_name") and indata["primitive"] in (
1241 "upgrade",
1242 "rollback",
1243 "status",
1244 "inspect",
1245 "readme",
1246 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001247 # TODO should be checked that rollback only can contains revsision_numbe????
1248 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001249 raise EngineException(
1250 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1251 indata["primitive"]
1252 )
1253 )
garciaale7cbd03c2020-11-27 10:38:35 -03001254 return
1255 # if not, check primitive
1256 for config_primitive in get_iterable(descriptor_configuration):
1257 if indata["primitive"] == config_primitive["name"]:
1258 # check needed primitive_params are provided
1259 if indata.get("primitive_params"):
1260 in_primitive_params_copy = copy(indata["primitive_params"])
1261 else:
1262 in_primitive_params_copy = {}
1263 for paramd in get_iterable(config_primitive.get("parameter")):
1264 if paramd["name"] in in_primitive_params_copy:
1265 del in_primitive_params_copy[paramd["name"]]
1266 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001267 raise EngineException(
1268 "Needed parameter {} not provided for primitive '{}'".format(
1269 paramd["name"], indata["primitive"]
1270 )
1271 )
garciaale7cbd03c2020-11-27 10:38:35 -03001272 # check no extra primitive params are provided
1273 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001274 raise EngineException(
1275 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1276 list(in_primitive_params_copy.keys()), indata["primitive"]
1277 )
1278 )
garciaale7cbd03c2020-11-27 10:38:35 -03001279 break
1280 else:
garciadeblas4568a372021-03-24 09:19:48 +01001281 raise EngineException(
1282 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1283 indata["primitive"]
1284 )
1285 )
garciaale7cbd03c2020-11-27 10:38:35 -03001286
aticig544a2ae2022-04-05 09:00:17 +03001287 def _check_update_ns_operation(self, indata, nsr) -> None:
1288 """Validates the ns-update request according to updateType
1289
1290 If updateType is CHANGE_VNFPKG:
1291 - it checks the vnfInstanceId, whether it's available under ns instance
1292 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1293 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301294 If updateType is REMOVE_VNF:
1295 - it checks if the vnfInstanceId is available in the ns instance
1296 - Otherwise exception will be raised.
aticig544a2ae2022-04-05 09:00:17 +03001297
1298 Args:
1299 indata: includes updateType such as CHANGE_VNFPKG,
1300 nsr: network service record
1301
1302 Raises:
1303 EngineException:
1304 a meaningful error if given update parameters are not proper such as
1305 "Error in validating ns-update request: <ID> does not match
1306 with the vnfd-id of vnfinstance
1307 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1308
1309 """
1310 try:
1311 if indata["updateType"] == "CHANGE_VNFPKG":
1312 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1313 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1314 ns_instance_id = indata["nsInstanceId"]
1315 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1316
1317 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
aticig544a2ae2022-04-05 09:00:17 +03001318 raise EngineException(
1319 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1320 f"belong to NS {ns_instance_id}",
1321 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1322 )
1323
1324 # Getting vnfrs through the ns_instance_id
1325 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1326 constituent_vnfd_id = next(
1327 (
1328 vnfr["vnfd-id"]
1329 for vnfr in vnfrs
1330 if vnfr["id"] == vnf_instance_id
1331 ),
1332 None,
1333 )
1334
1335 # Check the given vnfd-id belongs to given vnf instance
1336 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
aticig544a2ae2022-04-05 09:00:17 +03001337 raise EngineException(
1338 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1339 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1340 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1341 )
1342
1343 # Validating the ns update timeout
1344 if (
1345 indata.get("timeout_ns_update")
1346 and indata["timeout_ns_update"] < 300
1347 ):
1348 raise EngineException(
1349 "Error in validating ns-update request: {} second is not enough "
1350 "to upgrade the VNF instance: {}".format(
1351 indata["timeout_ns_update"], vnf_instance_id
1352 ),
1353 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1354 )
elumalai6380e7c2022-04-28 00:15:59 +05301355 elif indata["updateType"] == "REMOVE_VNF":
1356 vnf_instance_id = indata["removeVnfInstanceId"]
1357 ns_instance_id = indata["nsInstanceId"]
1358 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1359 raise EngineException(
1360 "Invalid VNF Instance Id. '{}' is not "
1361 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1362 )
aticig544a2ae2022-04-05 09:00:17 +03001363
1364 except (
1365 DbException,
1366 AttributeError,
1367 IndexError,
1368 KeyError,
1369 ValueError,
1370 ) as e:
1371 raise type(e)(
1372 "Ns update request could not be processed with error: {}.".format(e)
1373 )
1374
garciaale7cbd03c2020-11-27 10:38:35 -03001375 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001376 vnfd = self._get_vnfd_from_vnf_member_index(
1377 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1378 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001379 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001380 if (
1381 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1382 == scaling_aspect["id"]
1383 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001384 break
1385 else:
garciadeblas4568a372021-03-24 09:19:48 +01001386 raise EngineException(
1387 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1388 "present at vnfd:scaling-aspect".format(
1389 indata["scaleVnfData"]["scaleByStepData"][
1390 "scaling-group-descriptor"
1391 ]
1392 )
1393 )
garciaale7cbd03c2020-11-27 10:38:35 -03001394
garciadeblas0964edf2022-02-11 00:43:44 +01001395 def _check_heal_ns_operation(self, indata, nsr):
1396 return
1397
Mark Beierlc528d882023-01-06 12:56:16 -05001398 def _check_instantiate_ns_operation(self, indata, nsr, session):
1399 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
1400 vim_accounts = []
1401 wim_accounts = []
1402 nsd = nsr["nsd"]
1403 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1404 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
garciaale7cbd03c2020-11-27 10:38:35 -03001405 for in_vnf in get_iterable(indata.get("vnf")):
1406 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001407 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001408 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001409 else:
garciadeblas4568a372021-03-24 09:19:48 +01001410 vnfd = self._get_vnfd_from_vnf_member_index(
1411 member_vnf_index, nsr["_id"]
1412 )
1413 vnf_member_index_to_vnfd[
1414 member_vnf_index
1415 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001416 self._check_vnf_instantiation_params(in_vnf, vnfd)
1417 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001418 self._check_valid_vim_account(
1419 in_vnf["vimAccountId"], vim_accounts, session
1420 )
tierno260dd6f2019-09-02 10:48:56 +00001421
garciaale7cbd03c2020-11-27 10:38:35 -03001422 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001423 self._check_valid_wim_account(
1424 in_vld.get("wimAccountId"), wim_accounts, session
1425 )
garciaale7cbd03c2020-11-27 10:38:35 -03001426 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1427 if in_vld["name"] == vldd["id"]:
1428 break
tierno9cb7d672019-10-30 12:13:48 +00001429 else:
garciadeblas4568a372021-03-24 09:19:48 +01001430 raise EngineException(
1431 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1432 in_vld["name"]
1433 )
1434 )
tierno9cb7d672019-10-30 12:13:48 +00001435
garciaale7cbd03c2020-11-27 10:38:35 -03001436 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1437 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001438 vnfr = self.db.get_one(
1439 "vnfrs",
1440 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1441 fail_on_empty=False,
1442 )
garciaale7cbd03c2020-11-27 10:38:35 -03001443 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001444 raise EngineException(
1445 "Invalid parameter member_vnf_index='{}' is not one of the "
1446 "nsd:constituent-vnfd".format(member_vnf_index)
1447 )
beierlmcee2ebf2022-03-29 17:42:48 -04001448
garciadeblasf2af4a12023-01-24 16:56:54 +01001449 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
beierlmcee2ebf2022-03-29 17:42:48 -04001450 if "revision" in vnfr:
1451 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
garciadeblasf2af4a12023-01-24 16:56:54 +01001452 vnfd = self.db.get_one(
1453 "vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False
1454 )
beierlmcee2ebf2022-03-29 17:42:48 -04001455 else:
garciadeblasf2af4a12023-01-24 16:56:54 +01001456 vnfd = self.db.get_one(
1457 "vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False
1458 )
beierlmcee2ebf2022-03-29 17:42:48 -04001459
garciaale7cbd03c2020-11-27 10:38:35 -03001460 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001461 raise EngineException(
1462 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1463 vnfr["vnfd-id"]
1464 )
1465 )
garciaale7cbd03c2020-11-27 10:38:35 -03001466 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001467
garciaale7cbd03c2020-11-27 10:38:35 -03001468 def _check_valid_vdu(self, vnfd, vdu_id):
1469 for vdud in get_iterable(vnfd.get("vdu")):
1470 if vdud["id"] == vdu_id:
1471 return vdud
1472 else:
garciadeblas4568a372021-03-24 09:19:48 +01001473 raise EngineException(
1474 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1475 vdu_id
1476 )
1477 )
garciaale7cbd03c2020-11-27 10:38:35 -03001478
1479 def _check_valid_kdu(self, vnfd, kdu_name):
1480 for kdud in get_iterable(vnfd.get("kdu")):
1481 if kdud["name"] == kdu_name:
1482 return kdud
1483 else:
garciadeblas4568a372021-03-24 09:19:48 +01001484 raise EngineException(
1485 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1486 kdu_name
1487 )
1488 )
garciaale7cbd03c2020-11-27 10:38:35 -03001489
1490 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1491 for in_vdu in get_iterable(in_vnf.get("vdu")):
1492 for vdu in get_iterable(vnfd.get("vdu")):
1493 if in_vdu["id"] == vdu["id"]:
1494 for volume in get_iterable(in_vdu.get("volume")):
1495 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
aticigd7753fc2022-05-18 18:55:23 +03001496 if volumed == volume["name"]:
garciaale7cbd03c2020-11-27 10:38:35 -03001497 break
1498 else:
garciadeblas4568a372021-03-24 09:19:48 +01001499 raise EngineException(
1500 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1501 "volume:name='{}' is not present at "
1502 "vnfd:vdu:virtual-storage-desc list".format(
1503 in_vnf["member-vnf-index"],
1504 in_vdu["id"],
1505 volume["id"],
1506 )
1507 )
garciaale7cbd03c2020-11-27 10:38:35 -03001508
1509 vdu_if_names = set()
1510 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001511 for iface in get_iterable(
1512 cpd.get("virtual-network-interface-requirement")
1513 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001514 vdu_if_names.add(iface.get("name"))
1515
aticigd7753fc2022-05-18 18:55:23 +03001516 for in_iface in get_iterable(in_vdu.get("interface")):
garciaale7cbd03c2020-11-27 10:38:35 -03001517 if in_iface["name"] in vdu_if_names:
1518 break
1519 else:
garciadeblas4568a372021-03-24 09:19:48 +01001520 raise EngineException(
1521 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1522 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1523 in_vnf["member-vnf-index"],
1524 in_vdu["id"],
1525 in_iface["name"],
1526 )
1527 )
garciaale7cbd03c2020-11-27 10:38:35 -03001528 break
1529
1530 else:
garciadeblas4568a372021-03-24 09:19:48 +01001531 raise EngineException(
1532 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1533 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1534 )
garciaale7cbd03c2020-11-27 10:38:35 -03001535
garciadeblas4568a372021-03-24 09:19:48 +01001536 vnfd_ivlds_cpds = {
1537 ivld.get("id"): set()
1538 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1539 }
garciaale7cbd03c2020-11-27 10:38:35 -03001540 for vdu in get_iterable(vnfd.get("vdu")):
1541 for cpd in get_iterable(vnfd.get("int-cpd")):
1542 if cpd.get("int-virtual-link-desc"):
1543 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1544
1545 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1546 if in_ivld.get("name") in vnfd_ivlds_cpds:
1547 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1548 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001549 break
tiernob24258a2018-10-04 18:39:49 +02001550 else:
garciadeblas4568a372021-03-24 09:19:48 +01001551 raise EngineException(
1552 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1553 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1554 "vnfd:internal-vld:name/id:internal-connection-point".format(
1555 in_vnf["member-vnf-index"],
1556 in_ivld["name"],
1557 in_icp["id-ref"],
1558 )
1559 )
tiernob24258a2018-10-04 18:39:49 +02001560 else:
garciadeblas4568a372021-03-24 09:19:48 +01001561 raise EngineException(
1562 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1563 " is not present at vnfd '{}'".format(
1564 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1565 )
1566 )
tiernob24258a2018-10-04 18:39:49 +02001567
Mark Beierlc528d882023-01-06 12:56:16 -05001568 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1569 if vim_account in vim_accounts:
1570 return
garciaale7cbd03c2020-11-27 10:38:35 -03001571 try:
Mark Beierlc528d882023-01-06 12:56:16 -05001572 db_filter = self._get_project_filter(session)
1573 db_filter["_id"] = vim_account
1574 self.db.get_one("vim_accounts", db_filter)
garciaale7cbd03c2020-11-27 10:38:35 -03001575 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001576 raise EngineException(
1577 "Invalid vimAccountId='{}' not present for the project".format(
1578 vim_account
1579 )
1580 )
Mark Beierlc528d882023-01-06 12:56:16 -05001581 vim_accounts.append(vim_account)
garciaale7cbd03c2020-11-27 10:38:35 -03001582
David Garcia98de2982021-10-13 17:14:01 +02001583 def _get_vim_account(self, vim_id: str, session):
1584 try:
1585 db_filter = self._get_project_filter(session)
1586 db_filter["_id"] = vim_id
1587 return self.db.get_one("vim_accounts", db_filter)
1588 except Exception:
1589 raise EngineException(
garciadeblasf2af4a12023-01-24 16:56:54 +01001590 "Invalid vimAccountId='{}' not present for the project".format(vim_id)
David Garcia98de2982021-10-13 17:14:01 +02001591 )
1592
Mark Beierlc528d882023-01-06 12:56:16 -05001593 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1594 if not isinstance(wim_account, str):
1595 return
1596 if wim_account in wim_accounts:
1597 return
garciaale7cbd03c2020-11-27 10:38:35 -03001598 try:
Mark Beierlc528d882023-01-06 12:56:16 -05001599 db_filter = self._get_project_filter(session)
1600 db_filter["_id"] = wim_account
1601 self.db.get_one("wim_accounts", db_filter)
garciaale7cbd03c2020-11-27 10:38:35 -03001602 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001603 raise EngineException(
1604 "Invalid wimAccountId='{}' not present for the project".format(
1605 wim_account
1606 )
1607 )
Mark Beierlc528d882023-01-06 12:56:16 -05001608 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001609
garciadeblas4568a372021-03-24 09:19:48 +01001610 def _look_for_pdu(
1611 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1612 ):
tiernocc103432018-10-19 14:10:35 +02001613 """
tierno36ec8602018-11-02 17:27:11 +01001614 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1615 (ip_address, ...) information.
1616 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001617 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001618 :param rollback: list with the database modifications to rollback if needed
1619 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1620 :param vim_account: vim_account where this vnfr should be deployed
1621 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1622 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1623 of the changed vnfr is needed
1624
1625 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1626 "vim-network-name": used at VIM
1627 "name": interface name
1628 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1629 "ns-vld-id": NSD vld where this interface is connected.
1630 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 +02001631 """
Mark Beierlc528d882023-01-06 12:56:16 -05001632
tierno36ec8602018-11-02 17:27:11 +01001633 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001634 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1635 if not vdur.get("pdu-type"):
1636 continue
1637 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001638 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001639 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001640 pdu_filter["type"] = pdu_type
1641 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001642 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001643 # TODO feature 1417: "shared": True,
1644
1645 available_pdus = self.db.get_list("pdus", pdu_filter)
1646 for pdu in available_pdus:
1647 # step 1 check if this pdu contains needed interfaces:
1648 match_interfaces = True
1649 for vdur_interface in vdur["interfaces"]:
1650 for pdu_interface in pdu["interfaces"]:
1651 if pdu_interface["name"] == vdur_interface["name"]:
1652 # TODO feature 1417: match per mgmt type
1653 break
1654 else: # no interface found for name
1655 match_interfaces = False
1656 break
1657 if match_interfaces:
1658 break
1659 else:
1660 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001661 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001662 "names".format(
1663 pdu_type,
1664 vim_account,
1665 vnfr["member-vnf-index-ref"],
1666 vdur["vdu-id-ref"],
1667 )
1668 )
tiernocc103432018-10-19 14:10:35 +02001669
1670 # step 2. Update pdu
1671 rollback_pdu = {
1672 "_admin.usageState": pdu["_admin"]["usageState"],
1673 "_admin.usage.vnfr_id": None,
1674 "_admin.usage.nsr_id": None,
1675 "_admin.usage.vdur": None,
1676 }
garciadeblas4568a372021-03-24 09:19:48 +01001677 self.db.set_one(
1678 "pdus",
1679 {"_id": pdu["_id"]},
1680 {
1681 "_admin.usageState": "IN_USE",
1682 "_admin.usage": {
1683 "vnfr_id": vnfr["_id"],
1684 "nsr_id": vnfr["nsr-id-ref"],
1685 "vdur": vdur["vdu-id-ref"],
1686 },
1687 },
1688 )
1689 rollback.append(
1690 {
1691 "topic": "pdus",
1692 "_id": pdu["_id"],
1693 "operation": "set",
1694 "content": rollback_pdu,
1695 }
1696 )
tiernocc103432018-10-19 14:10:35 +02001697
1698 # step 3. Fill vnfr info by filling vdur
1699 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001700 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001701 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1702 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1703 for pdu_interface in pdu["interfaces"]:
1704 if pdu_interface["name"] == vdur_interface["name"]:
1705 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1706 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001707 if k in (
1708 "ip-address",
1709 "mac-address",
1710 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001711 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001712 vnfr_update_rollback[
1713 iface_text + ".{}".format(k)
1714 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001715 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001716 if vdur_interface.get(
1717 "mgmt-interface"
1718 ) or vdur_interface.get("mgmt-vnf"):
1719 vnfr_update_rollback[
1720 vdu_text + ".ip-address"
1721 ] = vdur.get("ip-address")
1722 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1723 "ip-address"
1724 ]
tierno36ec8602018-11-02 17:27:11 +01001725 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001726 vnfr_update_rollback["ip-address"] = vnfr.get(
1727 "ip-address"
1728 )
tierno36ec8602018-11-02 17:27:11 +01001729 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001730 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1731 "ip-address"
1732 ]
1733 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1734 "vim-network-id"
1735 ):
1736 ifaces_forcing_vim_network.append(
1737 {
1738 "name": vdur_interface.get("vnf-vld-id")
1739 or vdur_interface.get("ns-vld-id"),
1740 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1741 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1742 }
1743 )
gcalvino17d5b732018-12-17 16:26:21 +01001744 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001745 ifaces_forcing_vim_network[-1][
1746 "vim-network-id"
1747 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001748 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001749 ifaces_forcing_vim_network[-1][
1750 "vim-network-name"
1751 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001752 break
1753
tierno36ec8602018-11-02 17:27:11 +01001754 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001755
garciadeblas4568a372021-03-24 09:19:48 +01001756 def _look_for_k8scluster(
1757 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1758 ):
tierno9cb7d672019-10-30 12:13:48 +00001759 """
1760 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1761 Fills vnfr.kdur with the selected k8scluster
1762
1763 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1764 :param rollback: list with the database modifications to rollback if needed
1765 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1766 :param vim_account: vim_account where this vnfr should be deployed
1767 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1768 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1769 of the changed vnfr is needed
1770
1771 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1772 "vim-network-name": used at VIM
1773 "name": interface name
1774 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1775 "ns-vld-id": NSD vld where this interface is connected.
1776 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1777 """
Mark Beierlc528d882023-01-06 12:56:16 -05001778
tierno9cb7d672019-10-30 12:13:48 +00001779 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001780 if not vnfr.get("kdur"):
1781 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001782
tiernoc67b0e92019-11-05 12:45:29 +00001783 kdu_filter = self._get_project_filter(session)
1784 kdu_filter["vim_account"] = vim_account
1785 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1786 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1787
1788 k8s_requirements = {} # just for logging
1789 for k8scluster in available_k8sclusters:
1790 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001791 break
tiernoc67b0e92019-11-05 12:45:29 +00001792 # restrict by cni
1793 if vnfr["k8s-cluster"].get("cni"):
1794 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001795 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1796 k8scluster.get("cni", ())
1797 ):
tiernoc67b0e92019-11-05 12:45:29 +00001798 continue
1799 # restrict by version
1800 if vnfr["k8s-cluster"].get("version"):
1801 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1802 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1803 continue
1804 # restrict by number of networks
1805 if vnfr["k8s-cluster"].get("nets"):
1806 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001807 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1808 vnfr["k8s-cluster"]["nets"]
1809 ):
tiernoc67b0e92019-11-05 12:45:29 +00001810 continue
1811 break
1812 else:
garciadeblas4568a372021-03-24 09:19:48 +01001813 raise EngineException(
1814 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1815 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1816 )
1817 )
tierno9cb7d672019-10-30 12:13:48 +00001818
tiernoc67b0e92019-11-05 12:45:29 +00001819 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001820 # step 3. Fill vnfr info by filling kdur
1821 kdu_text = "kdur.{}.".format(kdur_index)
1822 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1823 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1824
tiernoc67b0e92019-11-05 12:45:29 +00001825 # step 4. Check VIM networks that forces the selected k8s_cluster
1826 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1827 k8scluster_net_list = list(k8scluster.get("nets").keys())
1828 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1829 # get a network from k8s_cluster nets. If name matches use this, if not use other
1830 if kdur_net["id"] in k8scluster_net_list: # name matches
1831 vim_net = k8scluster["nets"][kdur_net["id"]]
1832 k8scluster_net_list.remove(kdur_net["id"])
1833 else:
1834 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1835 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001836 vnfr_update_rollback[
1837 "k8s-cluster.nets.{}.vim_net".format(net_index)
1838 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001839 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001840 if vim_net and (
1841 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1842 ):
1843 ifaces_forcing_vim_network.append(
1844 {
1845 "name": kdur_net.get("vnf-vld-id")
1846 or kdur_net.get("ns-vld-id"),
1847 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1848 "ns-vld-id": kdur_net.get("ns-vld-id"),
1849 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1850 }
1851 )
tiernoc67b0e92019-11-05 12:45:29 +00001852 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001853 return ifaces_forcing_vim_network
1854
Gulsum Aticie395aa42021-11-10 20:59:06 +03001855 def _update_vnfrs_from_nsd(self, nsr):
garciadeblasf2af4a12023-01-24 16:56:54 +01001856 step = "Getting vnf_profiles from nsd" # first step must be defined outside try
Gulsum Aticie395aa42021-11-10 20:59:06 +03001857 try:
1858 nsr_id = nsr["_id"]
1859 nsd = nsr["nsd"]
1860
Gulsum Aticie395aa42021-11-10 20:59:06 +03001861 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1862 vld_fixed_ip_connection_point_data = {}
1863
1864 step = "Getting ip-address info from vnf_profile if it exists"
1865 for vnfp in vnf_profiles:
1866 # Checking ip-address info from nsd.vnf_profile and storing
1867 for vlc in vnfp.get("virtual-link-connectivity", ()):
1868 for cpd in vlc.get("constituent-cpd-id", ()):
1869 if cpd.get("ip-address"):
1870 step = "Storing ip-address info"
garciadeblasf2af4a12023-01-24 16:56:54 +01001871 vld_fixed_ip_connection_point_data.update(
1872 {
1873 vlc.get("virtual-link-profile-id")
1874 + "."
1875 + cpd.get("constituent-base-element-id"): {
1876 "vnfd-connection-point-ref": cpd.get(
1877 "constituent-cpd-id"
1878 ),
1879 "ip-address": cpd.get("ip-address"),
1880 }
1881 }
1882 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001883
1884 # Inserting ip address to vnfr
1885 if len(vld_fixed_ip_connection_point_data) > 0:
1886 step = "Getting vnfrs"
1887 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1888 for item in vld_fixed_ip_connection_point_data.keys():
1889 step = "Filtering vnfrs"
garciadeblasf2af4a12023-01-24 16:56:54 +01001890 vnfr = next(
1891 filter(
1892 lambda vnfr: vnfr["member-vnf-index-ref"]
1893 == item.split(".")[1],
1894 vnfrs,
1895 ),
1896 None,
1897 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001898 if vnfr:
1899 vnfr_update = {}
1900 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1901 for iface_index, iface in enumerate(vdur["interfaces"]):
1902 step = "Looking for matched interface"
1903 if (
garciadeblasf2af4a12023-01-24 16:56:54 +01001904 iface.get("external-connection-point-ref")
1905 == vld_fixed_ip_connection_point_data[item].get(
1906 "vnfd-connection-point-ref"
1907 )
1908 and iface.get("ns-vld-id") == item.split(".")[0]
Gulsum Aticie395aa42021-11-10 20:59:06 +03001909 ):
1910 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1911 vdur_index, iface_index
1912 )
1913 step = "Storing info in order to update vnfr"
1914 vnfr_update[
1915 vnfr_update_text + ".ip-address"
garciadeblasf2af4a12023-01-24 16:56:54 +01001916 ] = increment_ip_mac(
1917 vld_fixed_ip_connection_point_data[item].get(
1918 "ip-address"
1919 ),
1920 vdur.get("count-index", 0),
1921 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001922 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1923
1924 step = "updating vnfr at database"
1925 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1926 except (
garciadeblasf2af4a12023-01-24 16:56:54 +01001927 ValidationError,
1928 EngineException,
1929 DbException,
1930 MsgException,
1931 FsException,
Gulsum Aticie395aa42021-11-10 20:59:06 +03001932 ) as e:
1933 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1934
Mark Beierlc528d882023-01-06 12:56:16 -05001935 def _update_vnfrs(self, session, rollback, nsr, indata):
1936 # get vnfr
tiernocc103432018-10-19 14:10:35 +02001937 nsr_id = nsr["_id"]
1938 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1939
1940 for vnfr in vnfrs:
1941 vnfr_update = {}
1942 vnfr_update_rollback = {}
1943 member_vnf_index = vnfr["member-vnf-index-ref"]
Mark Beierlc528d882023-01-06 12:56:16 -05001944 # update vim-account-id
tiernocc103432018-10-19 14:10:35 +02001945
Mark Beierlc528d882023-01-06 12:56:16 -05001946 vim_account = indata["vimAccountId"]
1947 vca_id = self._get_vim_account(vim_account, session).get("vca")
1948 # check instantiate parameters
tiernocc103432018-10-19 14:10:35 +02001949 for vnf_inst_params in get_iterable(indata.get("vnf")):
1950 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1951 continue
1952 if vnf_inst_params.get("vimAccountId"):
Mark Beierlc528d882023-01-06 12:56:16 -05001953 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02001954 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001955
Mark Beierlc528d882023-01-06 12:56:16 -05001956 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1957 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1958 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1959 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1960 continue
1961 for iface_inst_param in get_iterable(
1962 vdu_inst_param.get("interface")
1963 ):
1964 iface_index, _ = next(
1965 i
1966 for i in enumerate(vdur["interfaces"])
1967 if i[1]["name"] == iface_inst_param["name"]
1968 )
1969 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1970 vdur_index, iface_index
1971 )
1972 if iface_inst_param.get("ip-address"):
1973 vnfr_update[
1974 vnfr_update_text + ".ip-address"
1975 ] = increment_ip_mac(
1976 iface_inst_param.get("ip-address"),
1977 vdur.get("count-index", 0),
1978 )
1979 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1980 if iface_inst_param.get("mac-address"):
1981 vnfr_update[
1982 vnfr_update_text + ".mac-address"
1983 ] = increment_ip_mac(
1984 iface_inst_param.get("mac-address"),
1985 vdur.get("count-index", 0),
1986 )
1987 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1988 if iface_inst_param.get("floating-ip-required"):
1989 vnfr_update[
1990 vnfr_update_text + ".floating-ip-required"
1991 ] = True
1992 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
tiernocddb07d2020-10-06 08:28:00 +00001993 # TODO update vld with the ip-profile
Mark Beierlc528d882023-01-06 12:56:16 -05001994 for ivld_inst_param in get_iterable(
1995 vnf_inst_params.get("internal-vld")
1996 ):
1997 for icp_inst_param in get_iterable(
1998 ivld_inst_param.get("internal-connection-point")
1999 ):
2000 # look for iface
2001 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2002 for iface_index, iface in enumerate(vdur["interfaces"]):
2003 if (
2004 iface.get("internal-connection-point-ref")
2005 == icp_inst_param["id-ref"]
2006 ):
2007 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2008 vdur_index, iface_index
2009 )
2010 if icp_inst_param.get("ip-address"):
2011 vnfr_update[
2012 vnfr_update_text + ".ip-address"
2013 ] = increment_ip_mac(
2014 icp_inst_param.get("ip-address"),
2015 vdur.get("count-index", 0),
2016 )
2017 vnfr_update[
2018 vnfr_update_text + ".fixed-ip"
2019 ] = True
2020 if icp_inst_param.get("mac-address"):
2021 vnfr_update[
2022 vnfr_update_text + ".mac-address"
2023 ] = increment_ip_mac(
2024 icp_inst_param.get("mac-address"),
2025 vdur.get("count-index", 0),
2026 )
2027 vnfr_update[
2028 vnfr_update_text + ".fixed-mac"
2029 ] = True
2030 break
2031 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2032 for vld_inst_param in get_iterable(indata.get("vld")):
2033 for vnfcp_inst_param in get_iterable(
2034 vld_inst_param.get("vnfd-connection-point-ref")
2035 ):
2036 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2037 continue
2038 # look for iface
2039 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2040 for iface_index, iface in enumerate(vdur["interfaces"]):
2041 if (
2042 iface.get("external-connection-point-ref")
2043 == vnfcp_inst_param["vnfd-connection-point-ref"]
2044 ):
2045 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2046 vdur_index, iface_index
2047 )
2048 if vnfcp_inst_param.get("ip-address"):
2049 vnfr_update[
2050 vnfr_update_text + ".ip-address"
2051 ] = increment_ip_mac(
2052 vnfcp_inst_param.get("ip-address"),
2053 vdur.get("count-index", 0),
2054 )
2055 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
2056 if vnfcp_inst_param.get("mac-address"):
2057 vnfr_update[
2058 vnfr_update_text + ".mac-address"
2059 ] = increment_ip_mac(
2060 vnfcp_inst_param.get("mac-address"),
2061 vdur.get("count-index", 0),
2062 )
2063 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
2064 break
tiernocddb07d2020-10-06 08:28:00 +00002065
Mark Beierlc528d882023-01-06 12:56:16 -05002066 vnfr_update["vim-account-id"] = vim_account
2067 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
tiernocc103432018-10-19 14:10:35 +02002068
David Garciaecb41322021-03-31 19:10:46 +02002069 if vca_id:
2070 vnfr_update["vca-id"] = vca_id
2071 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2072
Mark Beierlc528d882023-01-06 12:56:16 -05002073 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002074 ifaces_forcing_vim_network = self._look_for_pdu(
2075 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2076 )
tiernocc103432018-10-19 14:10:35 +02002077
Mark Beierlc528d882023-01-06 12:56:16 -05002078 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002079 ifaces_forcing_vim_network += self._look_for_k8scluster(
2080 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2081 )
Mark Beierlc528d882023-01-06 12:56:16 -05002082 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002083 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002084 rollback.append(
2085 {
2086 "topic": "vnfrs",
2087 "_id": vnfr["_id"],
2088 "operation": "set",
2089 "content": vnfr_update_rollback,
2090 }
2091 )
tierno36ec8602018-11-02 17:27:11 +01002092
Mark Beierlc528d882023-01-06 12:56:16 -05002093 # Update indada in case pdu forces to use a concrete vim-network-name
tierno36ec8602018-11-02 17:27:11 +01002094 # TODO check if user has already insert a vim-network-name and raises an error
2095 if not ifaces_forcing_vim_network:
2096 continue
Mark Beierlc528d882023-01-06 12:56:16 -05002097 for iface_info in ifaces_forcing_vim_network:
2098 if iface_info.get("ns-vld-id"):
2099 if "vld" not in indata:
2100 indata["vld"] = []
2101 indata["vld"].append(
2102 {
2103 key: iface_info[key]
2104 for key in ("name", "vim-network-name", "vim-network-id")
2105 if iface_info.get(key)
2106 }
2107 )
2108
2109 elif iface_info.get("vnf-vld-id"):
2110 if "vnf" not in indata:
2111 indata["vnf"] = []
2112 indata["vnf"].append(
2113 {
2114 "member-vnf-index": member_vnf_index,
2115 "internal-vld": [
2116 {
2117 key: iface_info[key]
2118 for key in (
2119 "name",
2120 "vim-network-name",
2121 "vim-network-id",
2122 )
2123 if iface_info.get(key)
2124 }
2125 ],
2126 }
2127 )
tierno36ec8602018-11-02 17:27:11 +01002128
2129 @staticmethod
2130 def _create_nslcmop(nsr_id, operation, params):
2131 """
2132 Creates a ns-lcm-opp content to be stored at database.
2133 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002134 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002135 :param params: user parameters for the operation
2136 :return: dictionary following SOL005 format
2137 """
tiernob24258a2018-10-04 18:39:49 +02002138 now = time()
2139 _id = str(uuid4())
2140 nslcmop = {
2141 "id": _id,
2142 "_id": _id,
2143 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002144 "queuePosition": None,
2145 "stage": None,
2146 "errorMessage": None,
2147 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002148 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002149 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002150 "lcmOperationType": operation,
2151 "startTime": now,
2152 "isAutomaticInvocation": False,
2153 "operationParams": params,
2154 "isCancelPending": False,
2155 "links": {
2156 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002157 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002158 },
tiernob24258a2018-10-04 18:39:49 +02002159 }
2160 return nslcmop
2161
magnussonlf318b302020-01-20 18:38:18 +01002162 def _get_enabled_vims(self, session):
2163 """
2164 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2165 :param session: current session with user information
2166 """
2167 db_filter = self._get_project_filter(session)
2168 db_filter["_admin.operationalState"] = "ENABLED"
2169 vims = self.db.get_list("vim_accounts", db_filter)
2170 vimAccounts = []
2171 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002172 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002173 return vimAccounts
2174
garciadeblas4568a372021-03-24 09:19:48 +01002175 def new(
2176 self,
2177 rollback,
2178 session,
2179 indata=None,
2180 kwargs=None,
2181 headers=None,
2182 slice_object=False,
2183 ):
tiernob24258a2018-10-04 18:39:49 +02002184 """
2185 Performs a new operation over a ns
2186 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002187 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002188 :param indata: descriptor with the parameters of the operation. It must contains among others
2189 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002190 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002191 :param kwargs: used to override the indata descriptor
2192 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002193 :return: id of the nslcmops
2194 """
garciadeblas4568a372021-03-24 09:19:48 +01002195
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002196 def check_if_nsr_is_not_slice_member(session, nsr_id):
2197 nsis = None
2198 db_filter = self._get_project_filter(session)
2199 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002200 nsis = self.db.get_one(
2201 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2202 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002203 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002204 raise EngineException(
2205 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2206 nsr_id, nsis["_id"]
2207 ),
2208 http_code=HTTPStatus.CONFLICT,
2209 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002210
tiernob24258a2018-10-04 18:39:49 +02002211 try:
2212 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002213 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002214 operation = indata["lcmOperationType"]
2215 nsInstanceId = indata["nsInstanceId"]
2216
2217 validate_input(indata, self.operation_schema[operation])
2218 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002219 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002220 _filter["_id"] = nsInstanceId
2221 nsr = self.db.get_one("nsrs", _filter)
2222
2223 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002224 if operation == "terminate" and slice_object is False:
2225 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002226 if (
2227 not nsr["_admin"].get("nsState")
2228 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2229 ):
tiernob24258a2018-10-04 18:39:49 +02002230 if operation == "terminate" and indata.get("autoremove"):
2231 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002232 return (
2233 None,
2234 None,
2235 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002236 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002237 raise EngineException(
2238 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2239 nsInstanceId, operation
2240 ),
2241 HTTPStatus.CONFLICT,
2242 )
tiernob24258a2018-10-04 18:39:49 +02002243 else:
tierno65ca36d2019-02-12 19:27:52 +01002244 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002245 raise EngineException(
2246 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2247 nsInstanceId, operation
2248 ),
2249 HTTPStatus.CONFLICT,
2250 )
tiernob24258a2018-10-04 18:39:49 +02002251 self._check_ns_operation(session, nsr, operation, indata)
garciadeblasf2af4a12023-01-24 16:56:54 +01002252 if indata.get("primitive_params"):
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002253 indata["primitive_params"] = json.dumps(indata["primitive_params"])
garciadeblasf2af4a12023-01-24 16:56:54 +01002254 elif indata.get("additionalParamsForVnf"):
2255 indata["additionalParamsForVnf"] = json.dumps(
2256 indata["additionalParamsForVnf"]
2257 )
tierno36ec8602018-11-02 17:27:11 +01002258
tiernocc103432018-10-19 14:10:35 +02002259 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002260 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002261 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302262 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2263 nsr_update = {}
2264 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2265 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2266 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2267 ns_request = nsr["instantiate_params"]
garciadeblasf2af4a12023-01-24 16:56:54 +01002268 vnfr = self.db.get_one(
2269 "vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]}
2270 )
elumalai8bf978e2022-05-26 15:32:06 +05302271 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2272 vnfr_vnfd_revision = vnfr.get("revision", 1)
2273 if latest_vnfd_revision != vnfr_vnfd_revision:
2274 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
garciadeblasf2af4a12023-01-24 16:56:54 +01002275 old_db_vnfd = self.db.get_one(
2276 "vnfds_revisions", {"_id": old_vnfd_id}
2277 )
elumalai8bf978e2022-05-26 15:32:06 +05302278 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2279 new_sw_version = vnfd.get("software-version", "1.0")
2280 if new_sw_version != old_sw_version:
2281 vnf_index = vnfr["member-vnf-index-ref"]
2282 self.logger.info("nsr {}".format(nsr))
2283 for vdu in vnfd["vdu"]:
garciadeblasf2af4a12023-01-24 16:56:54 +01002284 self.nsrtopic._add_flavor_to_nsr(
2285 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2286 )
elumalai8bf978e2022-05-26 15:32:06 +05302287 sw_image_id = vdu.get("sw-image-desc")
2288 if sw_image_id:
garciadeblasf2af4a12023-01-24 16:56:54 +01002289 image_data = self.nsrtopic._get_image_data_from_vnfd(
2290 vnfd, sw_image_id
2291 )
elumalai8bf978e2022-05-26 15:32:06 +05302292 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2293 for alt_image in vdu.get("alternative-sw-image-desc", ()):
garciadeblasf2af4a12023-01-24 16:56:54 +01002294 image_data = self.nsrtopic._get_image_data_from_vnfd(
2295 vnfd, alt_image
2296 )
elumalai8bf978e2022-05-26 15:32:06 +05302297 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2298 nsr_update["image"] = nsr["image"]
2299 nsr_update["flavor"] = nsr["flavor"]
2300 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
garciadeblasf2af4a12023-01-24 16:56:54 +01002301 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(
2302 nsd, ns_request, session
2303 )
2304 vnfr_descriptor = (
2305 self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2306 nsd,
2307 vnfd,
2308 vnfd_id,
2309 vnf_index,
2310 nsr,
2311 ns_request,
2312 ns_k8s_namespace,
2313 latest_vnfd_revision,
2314 )
elumalai8bf978e2022-05-26 15:32:06 +05302315 )
2316 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002317 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002318 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002319 self.format_on_new(
2320 nslcmop_desc, session["project_id"], make_public=session["public"]
2321 )
magnussonlf318b302020-01-20 18:38:18 +01002322 if indata.get("placement-engine"):
2323 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002324 nslcmop_desc["operationParams"][
2325 "validVimAccounts"
2326 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002327 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002328 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002329 if not slice_object:
Mark Beierlea3a2c22023-04-05 20:07:58 +00002330 if "instantiate_params" in nsr:
2331 if "vimAccountId" in nsr["instantiate_params"]:
2332 vim = self._get_vim_account(
2333 vim_id=nsr["instantiate_params"]["vimAccountId"],
2334 session=session,
2335 )
2336 if vim["vim_type"] == "paas":
2337 self.logger.info("Starting {} workflow".format(operation))
2338 self.temporal.start_ns_workflow(nslcmop_desc)
2339 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002340 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002341 return _id, None
2342 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002343 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Mark Beierlea3a2c22023-04-05 20:07:58 +00002344 return _id, None
2345 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
2346 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
tiernob24258a2018-10-04 18:39:49 +02002347 # except DbException as e:
2348 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2349
tiernobee3bad2019-12-05 12:26:01 +00002350 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002351 raise EngineException(
2352 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2353 )
tiernob24258a2018-10-04 18:39:49 +02002354
tierno65ca36d2019-02-12 19:27:52 +01002355 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002356 raise EngineException(
2357 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2358 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002359
2360
2361class NsiTopic(BaseTopic):
2362 topic = "nsis"
2363 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002364 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002365
delacruzramo32bab472019-09-13 12:24:22 +02002366 def __init__(self, db, fs, msg, auth):
2367 BaseTopic.__init__(self, db, fs, msg, auth)
2368 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002369
Felipe Vicensc37b3842019-01-12 12:24:42 +01002370 @staticmethod
2371 def _format_ns_request(ns_request):
2372 formated_request = copy(ns_request)
2373 # TODO: Add request params
2374 return formated_request
2375
2376 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002377 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002378 """
2379 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002380 :param slice_request: User instantiation additional parameters
2381 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002382 """
tiernofd160572019-01-21 10:41:37 +00002383 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2384 if additional_params:
2385 for k, v in additional_params.items():
2386 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002387 raise EngineException(
2388 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2389 k
2390 )
2391 )
tiernofd160572019-01-21 10:41:37 +00002392 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002393 raise EngineException(
2394 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2395 k
2396 )
2397 )
tiernofd160572019-01-21 10:41:37 +00002398 if isinstance(v, (dict, tuple, list)):
2399 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002400 return additional_params
2401
tiernob4844ab2019-05-23 08:42:12 +00002402 def check_conflict_on_del(self, session, _id, db_content):
2403 """
2404 Check that NSI is not instantiated
2405 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2406 :param _id: nsi internal id
2407 :param db_content: The database content of the _id
2408 :return: None or raises EngineException with the conflict
2409 """
tierno65ca36d2019-02-12 19:27:52 +01002410 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002411 return
tiernob4844ab2019-05-23 08:42:12 +00002412 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002413 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002414 raise EngineException(
2415 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2416 "Launch 'terminate' operation first; or force deletion".format(_id),
2417 http_code=HTTPStatus.CONFLICT,
2418 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002419
tiernobee3bad2019-12-05 12:26:01 +00002420 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002421 """
tiernob4844ab2019-05-23 08:42:12 +00002422 Deletes associated nsilcmops from database. Deletes associated filesystem.
2423 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002424 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002425 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002426 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002427 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002428 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002429 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002430
Felipe Vicens09e65422019-01-22 15:06:46 +01002431 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002432 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002433 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2434 nsr_id = nsrs_detailed_item["nsrId"]
2435 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002436 _filter = {
2437 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2438 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2439 "_id.ne": nsir["_id"],
2440 }
2441 nsi = self.db.get_one(
2442 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2443 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002444 if nsi: # last one using nsr
2445 continue
2446 try:
garciadeblas4568a372021-03-24 09:19:48 +01002447 self.nsrTopic.delete(
2448 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2449 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002450 except (DbException, EngineException) as e:
2451 if e.http_code == HTTPStatus.NOT_FOUND:
2452 pass
2453 else:
2454 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002455
tiernob4844ab2019-05-23 08:42:12 +00002456 # delete related nsilcmops database entries
2457 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002458
tiernob4844ab2019-05-23 08:42:12 +00002459 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002460 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002461 if nsir_admin and nsir_admin.get("nst-id"):
2462 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002463 nsis_list = self.db.get_one(
2464 "nsis",
2465 {"nst-id": nsir_admin["nst-id"]},
2466 fail_on_empty=False,
2467 fail_on_more=False,
2468 )
tiernob4844ab2019-05-23 08:42:12 +00002469 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002470 self.db.set_one(
2471 "nsts",
2472 {"_id": nsir_admin["nst-id"]},
2473 {"_admin.usageState": "NOT_IN_USE"},
2474 )
tiernob4844ab2019-05-23 08:42:12 +00002475
tierno65ca36d2019-02-12 19:27:52 +01002476 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002477 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002478 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002479 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002480 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002481 :param indata: params to be used for the nsir
2482 :param kwargs: used to override the indata descriptor
2483 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002484 :return: the _id of nsi descriptor created at database
2485 """
2486
garciadeblasf2af4a12023-01-24 16:56:54 +01002487 step = "checking quotas" # first step must be defined outside try
Felipe Vicensb57758d2018-10-16 16:00:20 +02002488 try:
delacruzramo32bab472019-09-13 12:24:22 +02002489 self.check_quota(session)
2490
tierno99d4b172019-07-02 09:28:40 +00002491 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002492 slice_request = self._remove_envelop(indata)
2493 # Override descriptor with query string kwargs
2494 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002495 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002496
Felipe Vicensb57758d2018-10-16 16:00:20 +02002497 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002498 step = "getting nstd id='{}' from database".format(
2499 slice_request.get("nstId")
2500 )
tiernob4844ab2019-05-23 08:42:12 +00002501 _filter = self._get_project_filter(session)
2502 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002503 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002504 # check NST is not disabled
2505 step = "checking NST operationalState"
2506 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002507 raise EngineException(
2508 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2509 "instance".format(slice_request["nstId"]),
2510 http_code=HTTPStatus.CONFLICT,
2511 )
tiernob4844ab2019-05-23 08:42:12 +00002512 del _filter["_id"]
2513
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002514 # check NSD is not disabled
2515 step = "checking operationalState"
2516 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002517 raise EngineException(
2518 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2519 "a network slice".format(slice_request["nstId"]),
2520 http_code=HTTPStatus.CONFLICT,
2521 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002522
Felipe Vicens07f31722018-10-29 15:16:44 +01002523 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002524 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002525 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002526 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002527
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002528 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002529 nsi_descriptor = {
2530 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002531 "name": slice_request["nsiName"],
2532 "description": slice_request.get("nsiDescription", ""),
2533 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002534 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002535 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002536 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002537 "nsr-ref-list": [],
2538 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002539 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002540 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002541 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002542
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002543 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002544 self.format_on_new(
2545 nsi_descriptor, session["project_id"], make_public=session["public"]
2546 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002547 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2548 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002549 nsi_descriptor["_admin"]["deployed"] = {}
2550 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2551 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2552
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002553 # Creating netslice-vld for the RO.
2554 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002555
2556 # Building the vlds list to be deployed
2557 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002558 nsi_vlds = []
2559
2560 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2561 # Getting template Instantiation parameters from NST
2562 nsi_vld = deepcopy(netslice_vlds)
2563 nsi_vld["shared-nsrs-list"] = []
2564 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2565 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002566
2567 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002568 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002569 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002570 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002571
Felipe Vicens09e65422019-01-22 15:06:46 +01002572 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002573 for member_ns in nstd["netslice-subnet"]:
2574 nsd_id = member_ns["nsd-ref"]
2575 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002576 member_ns["nsd-ref"], member_ns["id"]
2577 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002578 if nsd_id not in needed_nsds:
2579 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002580 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002581 nsd = self.db.get_one(
2582 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2583 )
tiernob4844ab2019-05-23 08:42:12 +00002584 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002585 nsd.pop("_admin")
2586 needed_nsds[nsd_id] = nsd
2587 else:
2588 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002589 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2590 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002591
Felipe Vicensb57758d2018-10-16 16:00:20 +02002592 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002593 member_ns["nsd-ref"], member_ns["id"]
2594 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002595
Felipe Vicens07f31722018-10-29 15:16:44 +01002596 # creates Network Services records (NSRs)
2597 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002598 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002599 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002600 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002601 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002602 # Check if the netslice-subnet is shared and if it is share if the nss exists
2603 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002604 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002605 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002606 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002607 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2608 "nsd-ref"
2609 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002610 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002611 nsi = self.db.get_one(
2612 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2613 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002614 if nsi and service.get("is-shared-nss"):
2615 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2616 for nsrs_detailed_item in nsrs_detailed_list:
2617 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002618 if nsrs_detailed_item["nss-id"] == service["id"]:
2619 _id_nsr = nsrs_detailed_item["nsrId"]
2620 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002621 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2622 if netslice_subnet["nss-id"] == service["id"]:
2623 indata_ns = netslice_subnet
2624 break
2625 else:
2626 indata_ns = {}
2627 if service.get("instantiation-parameters"):
2628 indata_ns = deepcopy(service["instantiation-parameters"])
2629 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002630
Felipe Vicens09e65422019-01-22 15:06:46 +01002631 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002632 indata_ns["nsName"] = (
2633 slice_request.get("nsiName") + "." + service["id"]
2634 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002635 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2636 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002637 if slice_request.get("ssh_keys"):
2638 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002639
Felipe Vicens09e65422019-01-22 15:06:46 +01002640 if ns_params:
2641 for ns_param in ns_params:
2642 if ns_param.get("id") == service["id"]:
2643 copy_ns_param = deepcopy(ns_param)
2644 del copy_ns_param["id"]
2645 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002646 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002647
2648 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002649 _id_nsr, _ = self.nsrTopic.new(
2650 rollback, session, indata_ns, kwargs, headers
2651 )
2652 nsrs_item = {
2653 "nsrId": _id_nsr,
2654 "shared": service.get("is-shared-nss"),
2655 "nsd-id": service["nsd-ref"],
2656 "nss-id": service["id"],
2657 "nslcmop_instantiate": None,
2658 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002659 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002660 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002661 nsi_netslice_subnet.append(indata_ns)
2662 nsr_ref = {"nsr-ref": _id_nsr}
2663 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002664
2665 # Adding the nsrs list to the nsi
2666 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002667 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002668 self.db.set_one(
2669 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2670 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002671
Felipe Vicens07f31722018-10-29 15:16:44 +01002672 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002673 self.db.create("nsis", nsi_descriptor)
2674 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002675 return nsi_id, None
garciadeblasf2af4a12023-01-24 16:56:54 +01002676 except ValidationError as e:
2677 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
garciadeblas4568a372021-03-24 09:19:48 +01002678 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2679 self.logger.exception(
2680 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2681 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002682 raise EngineException("Error {}: {}".format(step, e))
Felipe Vicensb57758d2018-10-16 16:00:20 +02002683
tierno65ca36d2019-02-12 19:27:52 +01002684 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002685 raise EngineException(
2686 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2687 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002688
2689
2690class NsiLcmOpTopic(BaseTopic):
2691 topic = "nsilcmops"
2692 topic_msg = "nsi"
2693 operation_schema = { # mapping between operation and jsonschema to validate
2694 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002695 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002696 }
garciadeblas4568a372021-03-24 09:19:48 +01002697
delacruzramo32bab472019-09-13 12:24:22 +02002698 def __init__(self, db, fs, msg, auth):
2699 BaseTopic.__init__(self, db, fs, msg, auth)
2700 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002701
2702 def _check_nsi_operation(self, session, nsir, operation, indata):
2703 """
2704 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002705 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002706 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2707 :param indata: descriptor with the parameters of the operation
2708 :return: None
2709 """
2710 nsds = {}
2711 nstd = nsir["network-slice-template"]
2712
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002713 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002714 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002715 for netslice_subnet in nstd["netslice-subnet"]:
2716 if nstId == netslice_subnet["id"]:
2717 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002718 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002719 _filter = self._get_project_filter(session)
2720 _filter["id"] = nsd_id
2721 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002722 return nsds[nsd_id]
2723 else:
garciadeblas4568a372021-03-24 09:19:48 +01002724 raise EngineException(
2725 "Invalid parameter nstId='{}' is not one of the "
2726 "nst:netslice-subnet".format(nstId)
2727 )
2728
Felipe Vicens07f31722018-10-29 15:16:44 +01002729 if operation == "instantiate":
2730 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002731 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002732 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002733
2734 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2735 now = time()
2736 _id = str(uuid4())
2737 nsilcmop = {
2738 "id": _id,
2739 "_id": _id,
2740 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2741 "statusEnteredTime": now,
2742 "netsliceInstanceId": netsliceInstanceId,
2743 "lcmOperationType": operation,
2744 "startTime": now,
2745 "isAutomaticInvocation": False,
2746 "operationParams": params,
2747 "isCancelPending": False,
2748 "links": {
2749 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002750 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2751 + netsliceInstanceId,
2752 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002753 }
2754 return nsilcmop
2755
Felipe Vicens09e65422019-01-22 15:06:46 +01002756 def add_shared_nsr_2vld(self, nsir, nsr_item):
2757 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2758 if nst_sb_item.get("is-shared-nss"):
2759 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2760 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2761 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002762 for admin_vld_nss_cp_ref_item in admin_vld_item[
2763 "nss-connection-point-ref"
2764 ]:
2765 if (
2766 admin_subnet_item["nss-id"]
2767 == admin_vld_nss_cp_ref_item["nss-ref"]
2768 ):
2769 if (
2770 not nsr_item["nsrId"]
2771 in admin_vld_item["shared-nsrs-list"]
2772 ):
2773 admin_vld_item["shared-nsrs-list"].append(
2774 nsr_item["nsrId"]
2775 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002776 break
2777 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002778 self.db.set_one(
2779 "nsis",
2780 {"_id": nsir["_id"]},
2781 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2782 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002783
tierno65ca36d2019-02-12 19:27:52 +01002784 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002785 """
2786 Performs a new operation over a ns
2787 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002788 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002789 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002790 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002791 operation: it can be: instantiate, terminate, action, TODO: update, heal
2792 :param kwargs: used to override the indata descriptor
2793 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002794 :return: id of the nslcmops
2795 """
2796 try:
2797 # Override descriptor with query string kwargs
2798 self._update_input_with_kwargs(indata, kwargs)
2799 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002800 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002801 validate_input(indata, self.operation_schema[operation])
2802
Felipe Vicens126af572019-06-05 19:13:04 +02002803 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002804 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002805 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002806 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002807 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002808 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002809
2810 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002811 if (
2812 not nsir["_admin"].get("nsiState")
2813 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2814 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002815 if operation == "terminate" and indata.get("autoremove"):
2816 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002817 return (
2818 None,
2819 None,
2820 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002821 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002822 raise EngineException(
2823 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2824 netsliceInstanceId, operation
2825 ),
2826 HTTPStatus.CONFLICT,
2827 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002828 else:
tierno65ca36d2019-02-12 19:27:52 +01002829 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002830 raise EngineException(
2831 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2832 netsliceInstanceId, operation
2833 ),
2834 HTTPStatus.CONFLICT,
2835 )
2836
Felipe Vicens07f31722018-10-29 15:16:44 +01002837 # Creating all the NS_operation (nslcmop)
2838 # Get service list from db
2839 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2840 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002841 # nslcmops_item = None
2842 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002843 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002844 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002845 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002846 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002847 _filter[
2848 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2849 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002850 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002851 nsi = self.db.get_one(
2852 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2853 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002854 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002855 _update = {
2856 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2857 index
2858 ): None
2859 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002860 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002861 if (
2862 nsi
2863 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002864 continue # do not create nsilcmop
2865 else: # instantiate
2866 # looks the first nsi fulfilling the conditions but not being the current NSIR
2867 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002868 nsi_nsr_item = next(
2869 n
2870 for n in nsi["_admin"]["nsrs-detailed-list"]
2871 if n["nsrId"] == nsr_id
2872 and n["shared"]
2873 and n["nslcmop_instantiate"]
2874 )
tierno40f742b2020-06-23 15:25:26 +00002875 self.add_shared_nsr_2vld(nsir, nsr_item)
2876 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002877 _update = {
2878 "_admin.nsrs-detailed-list.{}".format(
2879 index
2880 ): nsi_nsr_item
2881 }
tierno40f742b2020-06-23 15:25:26 +00002882 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2883 # continue to not create nslcmop since nsrs is shared and nsrs was created
2884 continue
2885 else:
2886 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002887
tierno40f742b2020-06-23 15:25:26 +00002888 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002889 try:
tierno0b8752f2020-05-12 09:42:02 +00002890 indata_ns = {
2891 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002892 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002893 # Including netslice_id in the ns instantiate Operation
2894 "netsliceInstanceId": netsliceInstanceId,
2895 }
2896 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002897 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002898 indata_ns.update(service["instantiate_params"])
2899
tierno99d4b172019-07-02 09:28:40 +00002900 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002901 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002902 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2903 rollback, session, indata_ns, None, headers, slice_object=True
2904 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002905 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002906 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002907 _update = {
2908 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2909 index
2910 ): nslcmop
2911 }
tierno40f742b2020-06-23 15:25:26 +00002912 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002913 except (DbException, EngineException) as e:
2914 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002915 self.logger.info(
2916 logging_prefix
2917 + "skipping NS={} because not found".format(nsr_id)
2918 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002919 pass
2920 else:
2921 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002922
2923 # Creates nsilcmop
2924 indata["nslcmops_ids"] = nslcmops
2925 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002926
garciadeblas4568a372021-03-24 09:19:48 +01002927 nsilcmop_desc = self._create_nsilcmop(
2928 session, netsliceInstanceId, operation, indata
2929 )
2930 self.format_on_new(
2931 nsilcmop_desc, session["project_id"], make_public=session["public"]
2932 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002933 _id = self.db.create("nsilcmops", nsilcmop_desc)
2934 rollback.append({"topic": "nsilcmops", "_id": _id})
2935 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002936 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002937 except ValidationError as e:
2938 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002939
tiernobee3bad2019-12-05 12:26:01 +00002940 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002941 raise EngineException(
2942 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2943 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002944
tierno65ca36d2019-02-12 19:27:52 +01002945 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002946 raise EngineException(
2947 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2948 )