blob: 9d2da9966ab4cbe726c5ad460fc02542092a82ab [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernob24258a2018-10-04 18:39:49 +020016# import logging
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +010017import json
tiernob24258a2018-10-04 18:39:49 +020018from uuid import uuid4
19from http import HTTPStatus
20from time import time
tiernocc103432018-10-19 14:10:35 +020021from copy import copy, deepcopy
garciadeblas4568a372021-03-24 09:19:48 +010022from osm_nbi.validation import (
23 validate_input,
24 ValidationError,
25 ns_instantiate,
26 ns_terminate,
27 ns_action,
28 ns_scale,
aticig544a2ae2022-04-05 09:00:17 +030029 ns_update,
garciadeblas0964edf2022-02-11 00:43:44 +010030 ns_heal,
garciadeblas4568a372021-03-24 09:19:48 +010031 nsi_instantiate,
elumalai8e3806c2022-04-28 17:26:24 +053032 ns_migrate,
Gabriel Cuba84a60df2023-10-30 14:01:54 -050033 nslcmop_cancel,
garciadeblas4568a372021-03-24 09:19:48 +010034)
35from osm_nbi.base_topic import (
36 BaseTopic,
37 EngineException,
38 get_iterable,
39 deep_get,
40 increment_ip_mac,
aticig2b5e1232022-08-10 17:30:12 +030041 update_descriptor_usage_state,
garciadeblas4568a372021-03-24 09:19:48 +010042)
tiernobee085c2018-12-12 17:03:04 +000043from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010044from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000045from osm_common.msgbase import MsgException
46from osm_common.fsbase import FsException
garciaale7cbd03c2020-11-27 10:38:35 -030047from osm_nbi import utils
garciadeblas4568a372021-03-24 09:19:48 +010048from re import (
49 match,
50) # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020051
52__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
53
54
55class NsrTopic(BaseTopic):
56 topic = "nsrs"
57 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000058 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000059 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020060
delacruzramo32bab472019-09-13 12:24:22 +020061 def __init__(self, db, fs, msg, auth):
62 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020063
tiernob24258a2018-10-04 18:39:49 +020064 @staticmethod
65 def format_on_new(content, project_id=None, make_public=False):
66 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
67 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000068 return None
tiernob24258a2018-10-04 18:39:49 +020069
tiernob4844ab2019-05-23 08:42:12 +000070 def check_conflict_on_del(self, session, _id, db_content):
71 """
72 Check that NSR is not instantiated
73 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
74 :param _id: nsr internal id
75 :param db_content: The database content of the nsr
76 :return: None or raises EngineException with the conflict
77 """
tierno65ca36d2019-02-12 19:27:52 +010078 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020079 return
tiernob4844ab2019-05-23 08:42:12 +000080 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020081 if nsr["_admin"].get("nsState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +010082 raise EngineException(
83 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
84 "Launch 'terminate' operation first; or force deletion".format(_id),
85 http_code=HTTPStatus.CONFLICT,
86 )
tiernob24258a2018-10-04 18:39:49 +020087
tiernobee3bad2019-12-05 12:26:01 +000088 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +000089 """
90 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
91 Set usageState of pdu, vnfd, nsd
92 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
93 :param _id: server internal id
94 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +000095 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +000096 :return: None if ok or raises EngineException with the problem
97 """
tiernobee085c2018-12-12 17:03:04 +000098 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +020099 self.db.del_list("nslcmops", {"nsInstanceId": _id})
100 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +0000101
tiernob24258a2018-10-04 18:39:49 +0200102 # set all used pdus as free
garciadeblas4568a372021-03-24 09:19:48 +0100103 self.db.set_list(
104 "pdus",
105 {"_admin.usage.nsr_id": _id},
106 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
107 )
tiernob24258a2018-10-04 18:39:49 +0200108
tiernob4844ab2019-05-23 08:42:12 +0000109 # Set NSD usageState
110 nsr = db_content
111 used_nsd_id = nsr.get("nsd-id")
112 if used_nsd_id:
113 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100114 nsrs_list = self.db.get_one(
115 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
116 )
tiernob4844ab2019-05-23 08:42:12 +0000117 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100118 self.db.set_one(
119 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
120 )
tiernob4844ab2019-05-23 08:42:12 +0000121
122 # Set VNFD usageState
123 used_vnfd_id_list = nsr.get("vnfd-id")
124 if used_vnfd_id_list:
125 for used_vnfd_id in used_vnfd_id_list:
126 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100127 nsrs_list = self.db.get_one(
128 "nsrs",
129 {"vnfd-id": used_vnfd_id},
130 fail_on_empty=False,
131 fail_on_more=False,
132 )
tiernob4844ab2019-05-23 08:42:12 +0000133 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100134 self.db.set_one(
135 "vnfds",
136 {"_id": used_vnfd_id},
137 {"_admin.usageState": "NOT_IN_USE"},
138 )
tiernob4844ab2019-05-23 08:42:12 +0000139
tiernof0441ea2020-05-26 15:39:18 +0000140 # delete extra ro_nsrs used for internal RO module
141 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
142
tiernobee085c2018-12-12 17:03:04 +0000143 @staticmethod
144 def _format_ns_request(ns_request):
145 formated_request = copy(ns_request)
146 formated_request.pop("additionalParamsForNs", None)
147 formated_request.pop("additionalParamsForVnf", None)
148 return formated_request
149
150 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +0100151 def _format_additional_params(
152 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
153 ):
tiernobee085c2018-12-12 17:03:04 +0000154 """
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100155 Get and format user additional params for NS or VNF.
156 The vdu_id and kdu_name params are mutually exclusive! If none of them are given, then the method will
157 exclusively search for the VNF/NS LCM additional params.
158
tiernobee085c2018-12-12 17:03:04 +0000159 :param ns_request: User instantiation additional parameters
160 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100161 :vdu_id: VDU's ID against which we want to format the additional params
162 :kdu_name: KDU's name against which we want to format the additional params
tiernobee085c2018-12-12 17:03:04 +0000163 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000164 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000165 """
166 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000167 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000168 if not member_vnf_index:
169 additional_params = copy(ns_request.get("additionalParamsForNs"))
170 where_ = "additionalParamsForNs"
171 elif ns_request.get("additionalParamsForVnf"):
garciadeblas4568a372021-03-24 09:19:48 +0100172 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
173 member_vnf_index
174 )
175 item = next(
176 (
177 x
178 for x in ns_request["additionalParamsForVnf"]
179 if x["member-vnf-index"] == member_vnf_index
180 ),
181 None,
182 )
tierno714954e2019-11-29 13:43:26 +0000183 if item:
tierno54db2e42020-04-06 15:29:42 +0000184 if not vdu_id and not kdu_name:
185 other_params = item
tierno714954e2019-11-29 13:43:26 +0000186 additional_params = copy(item.get("additionalParams")) or {}
187 if vdu_id and item.get("additionalParamsForVdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100188 item_vdu = next(
189 (
190 x
191 for x in item["additionalParamsForVdu"]
192 if x["vdu_id"] == vdu_id
193 ),
194 None,
195 )
tiernobce98f02020-04-17 11:27:47 +0000196 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000197 if item_vdu and item_vdu.get("additionalParams"):
198 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000199 additional_params = item_vdu["additionalParams"]
200 if kdu_name:
201 additional_params = {}
202 if item.get("additionalParamsForKdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100203 item_kdu = next(
204 (
205 x
206 for x in item["additionalParamsForKdu"]
207 if x["kdu_name"] == kdu_name
208 ),
209 None,
210 )
tiernobce98f02020-04-17 11:27:47 +0000211 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000212 if item_kdu and item_kdu.get("additionalParams"):
garciadeblas4568a372021-03-24 09:19:48 +0100213 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
214 kdu_name
215 )
tiernob091dc12019-12-02 15:53:25 +0000216 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000217
tiernobee085c2018-12-12 17:03:04 +0000218 if additional_params:
219 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000220 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
garciadeblas4568a372021-03-24 09:19:48 +0100221 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
222 raise EngineException(
223 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
224 "and underscores, and cannot start with a digit".format(
225 where_, k
226 )
227 )
delacruzramo36ffe552019-05-03 14:52:37 +0200228 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000229 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +0100230 raise EngineException(
231 "Invalid param at {}:{}. Only string keys are allowed".format(
232 where_, k
233 )
234 )
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100235 if "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +0100236 raise EngineException(
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100237 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
garciadeblas4568a372021-03-24 09:19:48 +0100238 where_, k
239 )
240 )
tiernobee085c2018-12-12 17:03:04 +0000241 if isinstance(v, (dict, tuple, list)):
242 additional_params[k] = "!!yaml " + safe_dump(v)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100243 if kdu_name:
244 additional_params = json.dumps(additional_params)
tiernobee085c2018-12-12 17:03:04 +0000245
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100246 # Select the VDU ID, KDU name or NS/VNF ID, depending on the method's call intent
247 selector = vdu_id if vdu_id else kdu_name if kdu_name else descriptor.get("id")
248
tiernobee085c2018-12-12 17:03:04 +0000249 if descriptor:
bravof41a52052021-02-17 18:08:01 -0300250 for df in descriptor.get("df", []):
251 # check that enough parameters are supplied for the initial-config-primitive
252 # TODO: check for cloud-init
253 if member_vnf_index:
garciaale7cbd03c2020-11-27 10:38:35 -0300254 initial_primitives = []
garciadeblas4568a372021-03-24 09:19:48 +0100255 if (
256 "lcm-operations-configuration" in df
257 and "operate-vnf-op-config"
258 in df["lcm-operations-configuration"]
259 ):
260 for config in df["lcm-operations-configuration"][
261 "operate-vnf-op-config"
262 ].get("day1-2", []):
garciadeblasf2af4a12023-01-24 16:56:54 +0100263 # Verify the target object (VNF|NS|VDU|KDU) where we need to populate
Pedro Escaleiradadeccd2022-05-20 15:29:20 +0100264 # the params with the additional ones given by the user
265 if config.get("id") == selector:
266 for primitive in get_iterable(
267 config.get("initial-config-primitive")
268 ):
269 initial_primitives.append(primitive)
bravof41a52052021-02-17 18:08:01 -0300270 else:
garciadeblas4568a372021-03-24 09:19:48 +0100271 initial_primitives = deep_get(
272 descriptor, ("ns-configuration", "initial-config-primitive")
273 )
tiernobee085c2018-12-12 17:03:04 +0000274
bravof41a52052021-02-17 18:08:01 -0300275 for initial_primitive in get_iterable(initial_primitives):
276 for param in get_iterable(initial_primitive.get("parameter")):
garciadeblas4568a372021-03-24 09:19:48 +0100277 if param["value"].startswith("<") and param["value"].endswith(
278 ">"
279 ):
280 if param["value"] in (
281 "<rw_mgmt_ip>",
282 "<VDU_SCALE_INFO>",
283 "<ns_config_info>",
garciadeblasf2af4a12023-01-24 16:56:54 +0100284 "<OSM>",
garciadeblas4568a372021-03-24 09:19:48 +0100285 ):
bravof41a52052021-02-17 18:08:01 -0300286 continue
garciadeblas4568a372021-03-24 09:19:48 +0100287 if (
288 not additional_params
289 or param["value"][1:-1] not in additional_params
290 ):
291 raise EngineException(
292 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
293 "initial-config-primitive[name={}] not supplied".format(
294 param["value"],
295 descriptor["id"],
296 initial_primitive["name"],
297 )
298 )
tierno714954e2019-11-29 13:43:26 +0000299
tierno54db2e42020-04-06 15:29:42 +0000300 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000301
tierno65ca36d2019-02-12 19:27:52 +0100302 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200303 """
304 Creates a new nsr into database. It also creates needed vnfrs
305 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100306 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200307 :param indata: params to be used for the nsr
308 :param kwargs: used to override the indata descriptor
309 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000310 :return: the _id of nsr descriptor created at database. Or an exception of type
311 EngineException, ValidationError, DbException, FsException, MsgException.
312 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200313 """
garciadeblasf2af4a12023-01-24 16:56:54 +0100314 step = "checking quotas" # first step must be defined outside try
tiernob24258a2018-10-04 18:39:49 +0200315 try:
delacruzramo32bab472019-09-13 12:24:22 +0200316 self.check_quota(session)
317
tierno99d4b172019-07-02 09:28:40 +0000318 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200319 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200320 self._update_input_with_kwargs(ns_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -0300321 ns_request = self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200322
tiernob24258a2018-10-04 18:39:49 +0200323 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale7cbd03c2020-11-27 10:38:35 -0300324 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
325 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200326
Frank Bryden3c64ab62020-07-21 14:25:32 +0000327 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300328 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000329
tiernob24258a2018-10-04 18:39:49 +0200330 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300331 nsr_id = str(uuid4())
garciadeblas4568a372021-03-24 09:19:48 +0100332 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
333 nsd, ns_request, nsr_id, session
334 )
tierno54db2e42020-04-06 15:29:42 +0000335
garciaale7cbd03c2020-11-27 10:38:35 -0300336 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200337 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300338 # TODO: Change for multiple df support
K Sai Kiranbb006022021-05-20 11:09:49 +0530339 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
garciaale7cbd03c2020-11-27 10:38:35 -0300340 for vnfp in vnf_profiles:
341 vnfd_id = vnfp.get("vnfd-id")
342 vnf_index = vnfp.get("id")
garciadeblas4568a372021-03-24 09:19:48 +0100343 step = (
344 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
345 vnfd_id, vnf_index
346 )
347 )
tiernob24258a2018-10-04 18:39:49 +0200348 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300349 vnfd = self._get_vnfd_from_db(vnfd_id, session)
beierlmcee2ebf2022-03-29 17:42:48 -0400350 if "revision" in vnfd["_admin"]:
351 vnfd["revision"] = vnfd["_admin"]["revision"]
352 vnfd.pop("_admin")
tiernob24258a2018-10-04 18:39:49 +0200353 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000354 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200355 else:
356 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100357
garciadeblas4568a372021-03-24 09:19:48 +0100358 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
359 vnfd_id, vnf_index
360 )
361 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
362 nsd,
363 vnfd,
364 vnfd_id,
365 vnf_index,
366 nsr_descriptor,
367 ns_request,
368 ns_k8s_namespace,
369 )
tierno36ec8602018-11-02 17:27:11 +0100370
garciadeblas4568a372021-03-24 09:19:48 +0100371 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
372 vnfd_id, vnf_index
373 )
garciaale7cbd03c2020-11-27 10:38:35 -0300374 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
375 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
aticig2b5e1232022-08-10 17:30:12 +0300376 step = "Updating VNFD usageState"
377 update_descriptor_usage_state(vnfd, "vnfds", self.db)
tiernob24258a2018-10-04 18:39:49 +0200378
379 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300380 self._add_nsr_to_db(nsr_descriptor, rollback, session)
aticig2b5e1232022-08-10 17:30:12 +0300381 step = "Updating NSD usageState"
382 update_descriptor_usage_state(nsd, "nsds", self.db)
tiernobee085c2018-12-12 17:03:04 +0000383
384 step = "creating nsr temporal folder"
385 self.fs.mkdir(nsr_id)
386
tiernobdebce92019-07-01 15:36:49 +0000387 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100388 except (
389 ValidationError,
390 EngineException,
391 DbException,
392 MsgException,
393 FsException,
394 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000395 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200396
garciaale7cbd03c2020-11-27 10:38:35 -0300397 def _get_nsd_from_db(self, nsd_id, session):
398 _filter = self._get_project_filter(session)
399 _filter["_id"] = nsd_id
400 return self.db.get_one("nsds", _filter)
401
402 def _get_vnfd_from_db(self, vnfd_id, session):
403 _filter = self._get_project_filter(session)
404 _filter["id"] = vnfd_id
405 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
garciaale7cbd03c2020-11-27 10:38:35 -0300406 return vnfd
407
408 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100409 self.format_on_new(
410 nsr_descriptor, session["project_id"], make_public=session["public"]
411 )
garciaale7cbd03c2020-11-27 10:38:35 -0300412 self.db.create("nsrs", nsr_descriptor)
413 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
414
415 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100416 self.format_on_new(
417 vnfr_descriptor, session["project_id"], make_public=session["public"]
418 )
garciaale7cbd03c2020-11-27 10:38:35 -0300419 self.db.create("vnfrs", vnfr_descriptor)
420 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
421
422 def _check_nsd_operational_state(self, nsd, ns_request):
423 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100424 raise EngineException(
425 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
426 "a network service".format(ns_request["nsdId"]),
427 http_code=HTTPStatus.CONFLICT,
428 )
garciaale7cbd03c2020-11-27 10:38:35 -0300429
430 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100431 additional_params, _ = self._format_additional_params(
432 ns_request, descriptor=nsd
433 )
garciaale7cbd03c2020-11-27 10:38:35 -0300434 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
435 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
436 if ns_request and ns_request.get("k8s-namespace"):
437 ns_k8s_namespace = ns_request["k8s-namespace"]
438 if additional_params and additional_params.get("k8s-namespace"):
439 ns_k8s_namespace = additional_params["k8s-namespace"]
440
441 return ns_k8s_namespace
442
vegall18101ea2023-03-06 13:49:21 +0000443 def _add_shared_volumes_to_nsr(
444 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
445 ):
446 svsd = []
447 for vsd in vnfd.get("virtual-storage-desc", ()):
448 if vsd.get("vdu-storage-requirements"):
449 if (
450 vsd.get("vdu-storage-requirements")[0].get("key") == "multiattach"
451 and vsd.get("vdu-storage-requirements")[0].get("value") == "True"
452 ):
vegallf976a3a2023-06-02 21:25:32 +0000453 # Avoid setting the volume name multiple times
454 if not match(f"shared-.*-{vnfd['id']}", vsd["id"]):
vegall18101ea2023-03-06 13:49:21 +0000455 vsd["id"] = f"shared-{vsd['id']}-{vnfd['id']}"
456 svsd.append(vsd)
457 if svsd:
458 nsr_descriptor["shared-volumes"] = svsd
459
garciadeblasf2af4a12023-01-24 16:56:54 +0100460 def _add_flavor_to_nsr(
461 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
462 ):
elumalai6c5ea6b2022-04-25 22:27:59 +0530463 flavor_data = {}
464 guest_epa = {}
465 # Find this vdu compute and storage descriptors
466 vdu_virtual_compute = {}
467 vdu_virtual_storage = {}
468 for vcd in vnfd.get("virtual-compute-desc", ()):
469 if vcd.get("id") == vdu.get("virtual-compute-desc"):
470 vdu_virtual_compute = vcd
471 for vsd in vnfd.get("virtual-storage-desc", ()):
472 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
473 vdu_virtual_storage = vsd
474 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblasf2af4a12023-01-24 16:56:54 +0100475 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
elumalai6c5ea6b2022-04-25 22:27:59 +0530476 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
477 "num-virtual-cpu"
478 ]
479 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
480 flavor_data["memory-mb"] = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100481 float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
elumalai6c5ea6b2022-04-25 22:27:59 +0530482 )
483 if vdu_virtual_storage.get("size-of-storage"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100484 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530485 # Get this vdu EPA info for guest_epa
486 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100487 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530488 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
489 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
490 if vcpu_pinning.get("thread-policy"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100491 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530492 if vcpu_pinning.get("policy"):
493 cpu_policy = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100494 "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
elumalai6c5ea6b2022-04-25 22:27:59 +0530495 )
496 guest_epa["cpu-pinning-policy"] = cpu_policy
497 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100498 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
499 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
500 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"][
501 "mempage-size"
elumalai6c5ea6b2022-04-25 22:27:59 +0530502 ]
garciadeblasf2af4a12023-01-24 16:56:54 +0100503 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
504 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"][
505 "numa-node-policy"
506 ]
elumalai6c5ea6b2022-04-25 22:27:59 +0530507 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100508 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530509
510 if guest_epa:
511 flavor_data["guest-epa"] = guest_epa
512
elumalai99078a92022-07-05 17:53:59 +0530513 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +0100514 flavor_data["name"] = (
515 vdu["id"][:56] + "-" + member_vnf_index + "-" + str(revision) + "-flv"
516 )
elumalai6c5ea6b2022-04-25 22:27:59 +0530517 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
518 nsr_descriptor["flavor"].append(flavor_data)
519
bravofe76b8822021-02-26 16:57:52 -0300520 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300521 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100522 additional_params, _ = self._format_additional_params(
523 ns_request, descriptor=nsd
524 )
garciaale7cbd03c2020-11-27 10:38:35 -0300525
526 nsr_descriptor = {
527 "name": ns_request["nsName"],
528 "name-ref": ns_request["nsName"],
529 "short-name": ns_request["nsName"],
530 "admin-status": "ENABLED",
531 "nsState": "NOT_INSTANTIATED",
532 "currentOperation": "IDLE",
533 "currentOperationID": None,
534 "errorDescription": None,
535 "errorDetail": None,
536 "deploymentStatus": None,
537 "configurationStatus": None,
538 "vcaStatus": None,
539 "nsd": {k: v for k, v in nsd.items()},
540 "datacenter": ns_request["vimAccountId"],
541 "resource-orchestrator": "osmopenmano",
542 "description": ns_request.get("nsDescription", ""),
543 "constituent-vnfr-ref": [],
544 "operational-status": "init", # typedef ns-operational-
545 "config-status": "init", # typedef config-states
546 "detailed-status": "scheduled",
547 "orchestration-progress": {},
548 "create-time": now,
549 "nsd-name-ref": nsd["name"],
550 "operational-events": [], # "id", "timestamp", "description", "event",
551 "nsd-ref": nsd["id"],
552 "nsd-id": nsd["_id"],
553 "vnfd-id": [],
554 "instantiate_params": self._format_ns_request(ns_request),
555 "additionalParamsForNs": additional_params,
556 "ns-instance-config-ref": nsr_id,
557 "id": nsr_id,
558 "_id": nsr_id,
559 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
560 "flavor": [],
561 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100562 "affinity-or-anti-affinity-group": [],
vegall18101ea2023-03-06 13:49:21 +0000563 "shared-volumes": [],
selvi.j828f3f22023-05-16 05:43:48 +0000564 "vnffgd": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300565 }
beierlmbc5a5242022-05-17 21:25:29 -0400566 if "revision" in nsd["_admin"]:
567 nsr_descriptor["revision"] = nsd["_admin"]["revision"]
568
garciaale7cbd03c2020-11-27 10:38:35 -0300569 ns_request["nsr_id"] = nsr_id
570 if ns_request and ns_request.get("config-units"):
571 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300572 # Create vld
573 if nsd.get("virtual-link-desc"):
574 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
575 # Fill each vld with vnfd-connection-point-ref data
576 # TODO: Change for multiple df support
577 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
578 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
579 for vnf_profile in vnf_profiles:
580 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
581 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100582 all_vld_connection_point_data[
583 vlc.get("virtual-link-profile-id")
584 ].append(
585 {
586 "member-vnf-index-ref": cpd.get(
587 "constituent-base-element-id"
588 ),
589 "vnfd-connection-point-ref": cpd.get(
590 "constituent-cpd-id"
591 ),
592 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
593 }
594 )
garciaale7cbd03c2020-11-27 10:38:35 -0300595
bravofe76b8822021-02-26 16:57:52 -0300596 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400597 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300598
599 for vdu in vnfd.get("vdu", ()):
elumalai99078a92022-07-05 17:53:59 +0530600 member_vnf_index = vnf_profile.get("id")
601 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor, member_vnf_index)
vegall18101ea2023-03-06 13:49:21 +0000602 self._add_shared_volumes_to_nsr(
603 vdu, vnfd, nsr_descriptor, member_vnf_index
604 )
garciaale7cbd03c2020-11-27 10:38:35 -0300605 sw_image_id = vdu.get("sw-image-desc")
606 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000607 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
608 self._add_image_to_nsr(nsr_descriptor, image_data)
609
610 # also add alternative images to the list of images
611 for alt_image in vdu.get("alternative-sw-image-desc", ()):
612 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
613 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300614
Alexis Romero03fb5842022-03-11 15:53:40 +0100615 # Add Affinity or Anti-affinity group information to NSR
616 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200617 affinity_group_prefix_name = "{}-{}".format(
618 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
619 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100620
621 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200622 affinity_group_data = {}
623 for affinity_group in vdu_profile.get(
624 "affinity-or-anti-affinity-group", ()
625 ):
626 affinity_group_data = (
627 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
628 vnfd, affinity_group["id"]
629 )
630 )
631 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
632 self._add_affinity_or_anti_affinity_group_to_nsr(
633 nsr_descriptor,
634 affinity_group_data,
635 affinity_group_prefix_name,
636 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100637
garciaale7cbd03c2020-11-27 10:38:35 -0300638 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100639 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
640 vld.get("id"), []
641 )
garciaale7cbd03c2020-11-27 10:38:35 -0300642 vld["name"] = vld["id"]
643 nsr_descriptor["vld"] = nsr_vld
selvi.j828f3f22023-05-16 05:43:48 +0000644 if nsd.get("vnffgd"):
645 vnffgd = nsd.get("vnffgd")
646 for vnffg in vnffgd:
647 info = {}
648 for k, v in vnffg.items():
649 if k == "id":
650 info.update({k: v})
651 if k == "nfpd":
652 info.update({k: v})
653 nsr_descriptor["vnffgd"].append(info)
654
garciaale7cbd03c2020-11-27 10:38:35 -0300655 return nsr_descriptor
656
Alexis Romeroee31f532022-04-26 19:10:21 +0200657 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
658 self, vnfd, affinity_group_id
659 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100660 """
661 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
662 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200663 affinity_group = utils.find_in_list(
664 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
665 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100666 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200667 affinity_group_data = {}
668 if affinity_group:
669 if affinity_group.get("id"):
670 affinity_group_data["ag-id"] = affinity_group["id"]
671 if affinity_group.get("type"):
672 affinity_group_data["type"] = affinity_group["type"]
673 if affinity_group.get("scope"):
674 affinity_group_data["scope"] = affinity_group["scope"]
675 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100676
Alexis Romeroee31f532022-04-26 19:10:21 +0200677 def _add_affinity_or_anti_affinity_group_to_nsr(
678 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
679 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100680 """
681 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
682 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200683 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100684 (
685 f
686 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200687 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100688 ),
689 None,
690 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200691 if not affinity_group:
692 affinity_group_data["id"] = str(
693 len(nsr_descriptor["affinity-or-anti-affinity-group"])
694 )
695 affinity_group_data["name"] = "{}-{}".format(
696 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
697 )
698 nsr_descriptor["affinity-or-anti-affinity-group"].append(
699 affinity_group_data
700 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100701
lloretgalleg28c13b62021-02-08 11:48:48 +0000702 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100703 sw_image_desc = utils.find_in_list(
704 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
705 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000706 image_data = {}
707 if sw_image_desc.get("image"):
708 image_data["image"] = sw_image_desc["image"]
709 if sw_image_desc.get("checksum"):
710 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
711 if sw_image_desc.get("vim-type"):
712 image_data["vim-type"] = sw_image_desc["vim-type"]
713 return image_data
714
715 def _add_image_to_nsr(self, nsr_descriptor, image_data):
716 """
717 Adds image to nsr checking first it is not already added
718 """
garciadeblas4568a372021-03-24 09:19:48 +0100719 img = next(
720 (
721 f
722 for f in nsr_descriptor["image"]
723 if all(f.get(k) == image_data[k] for k in image_data)
724 ),
725 None,
726 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000727 if not img:
728 image_data["id"] = str(len(nsr_descriptor["image"]))
729 nsr_descriptor["image"].append(image_data)
730
garciadeblas4568a372021-03-24 09:19:48 +0100731 def _create_vnfr_descriptor_from_vnfd(
732 self,
733 nsd,
734 vnfd,
735 vnfd_id,
736 vnf_index,
737 nsr_descriptor,
738 ns_request,
739 ns_k8s_namespace,
elumalai99078a92022-07-05 17:53:59 +0530740 revision=None,
garciadeblas4568a372021-03-24 09:19:48 +0100741 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300742 vnfr_id = str(uuid4())
743 nsr_id = nsr_descriptor["id"]
744 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100745 additional_params, vnf_params = self._format_additional_params(
746 ns_request, vnf_index, descriptor=vnfd
747 )
garciaale7cbd03c2020-11-27 10:38:35 -0300748
749 vnfr_descriptor = {
750 "id": vnfr_id,
751 "_id": vnfr_id,
752 "nsr-id-ref": nsr_id,
753 "member-vnf-index-ref": vnf_index,
754 "additionalParamsForVnf": additional_params,
755 "created-time": now,
756 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
757 "vnfd-ref": vnfd_id,
758 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
759 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200760 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300761 "vdur": [],
762 "connection-point": [],
763 "ip-address": None, # mgmt-interface filled by LCM
764 }
beierlmcee2ebf2022-03-29 17:42:48 -0400765
766 # Revision backwards compatility. Only specify the revision in the record if
767 # the original VNFD has a revision.
768 if "revision" in vnfd:
769 vnfr_descriptor["revision"] = vnfd["revision"]
770
garciaale7cbd03c2020-11-27 10:38:35 -0300771 vnf_k8s_namespace = ns_k8s_namespace
772 if vnf_params:
773 if vnf_params.get("k8s-namespace"):
774 vnf_k8s_namespace = vnf_params["k8s-namespace"]
775 if vnf_params.get("config-units"):
776 vnfr_descriptor["config-units"] = vnf_params["config-units"]
777
778 # Create vld
779 if vnfd.get("int-virtual-link-desc"):
780 vnfr_descriptor["vld"] = []
781 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
782 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
783
784 for cp in vnfd.get("ext-cpd", ()):
785 vnf_cp = {
786 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100787 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
788 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300789 "id": cp.get("id"),
790 # "ip-address", "mac-address" # filled by LCM
791 # vim-id # TODO it would be nice having a vim port id
792 }
793 vnfr_descriptor["connection-point"].append(vnf_cp)
794
795 # Create k8s-cluster information
796 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
797 if vnfd.get("k8s-cluster"):
798 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
799 all_k8s_cluster_nets_cpds = {}
800 for cpd in get_iterable(vnfd.get("ext-cpd")):
801 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100802 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
803 "id"
804 )
garciaale7cbd03c2020-11-27 10:38:35 -0300805 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
806 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100807 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
808 net.get("id")
809 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300810
811 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300812 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100813 additional_params, kdu_params = self._format_additional_params(
814 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
815 )
garciaale7cbd03c2020-11-27 10:38:35 -0300816 kdu_k8s_namespace = vnf_k8s_namespace
817 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
818 if kdu_params and kdu_params.get("k8s-namespace"):
819 kdu_k8s_namespace = kdu_params["k8s-namespace"]
820
romeromonserbfebfc02021-05-28 10:51:35 +0200821 kdu_deployment_name = ""
822 if kdu_params and kdu_params.get("kdu-deployment-name"):
823 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
824
garciaale7cbd03c2020-11-27 10:38:35 -0300825 kdur = {
826 "additionalParams": additional_params,
827 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200828 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000829 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300830 # TODO "name": "" Name of the VDU in the VIM
831 "ip-address": None, # mgmt-interface filled by LCM
832 "k8s-cluster": {},
833 }
834 if kdu_params and kdu_params.get("config-units"):
835 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000836 if kdu.get("helm-version"):
837 kdur["helm-version"] = kdu["helm-version"]
838 for k8s_type in ("helm-chart", "juju-bundle"):
839 if kdu.get(k8s_type):
840 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300841 if not vnfr_descriptor.get("kdur"):
842 vnfr_descriptor["kdur"] = []
843 vnfr_descriptor["kdur"].append(kdur)
844
845 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300846
garciaale7cbd03c2020-11-27 10:38:35 -0300847 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300848 vdu_mgmt_cp = []
849 try:
garciadeblas4568a372021-03-24 09:19:48 +0100850 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
851 "operate-vnf-op-config"
852 ]["day1-2"]
853 vdu_config = utils.find_in_list(
854 configs, lambda config: config["id"] == vdu["id"]
855 )
bravoff3c39552021-02-24 17:22:24 -0300856 except Exception:
857 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400858
859 try:
860 vdu_instantiation_level = utils.find_in_list(
861 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100862 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400863 )
864 except Exception:
865 vdu_instantiation_level = None
866
bravoff3c39552021-02-24 17:22:24 -0300867 if vdu_config:
868 external_connection_ee = utils.filter_in_list(
869 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100870 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300871 )
872 for ee in external_connection_ee:
873 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
874
garciaale7cbd03c2020-11-27 10:38:35 -0300875 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100876 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
877 )
bravof65e22e52021-11-10 17:58:58 -0300878
879 try:
880 vdu_virtual_storage_descriptors = utils.filter_in_list(
881 vnfd.get("virtual-storage-desc", []),
garciadeblasf2af4a12023-01-24 16:56:54 +0100882 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"],
bravof65e22e52021-11-10 17:58:58 -0300883 )
884 except Exception:
885 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300886 vdur = {
887 "vdu-id-ref": vdu["id"],
888 # TODO "name": "" Name of the VDU in the VIM
889 "ip-address": None, # mgmt-interface filled by LCM
890 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
891 "internal-connection-point": [],
892 "interfaces": [],
893 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100894 "vdu-name": vdu["name"],
garciadeblasf2af4a12023-01-24 16:56:54 +0100895 "virtual-storages": vdu_virtual_storage_descriptors,
garciaale7cbd03c2020-11-27 10:38:35 -0300896 }
897 if vdu_params and vdu_params.get("config-units"):
898 vdur["config-units"] = vdu_params["config-units"]
899 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100900 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
901 "boot-data-drive"
902 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300903 if vdu.get("pdu-type"):
904 vdur["pdu-type"] = vdu["pdu-type"]
905 vdur["name"] = vdu["pdu-type"]
906 # TODO volumes: name, volume-id
907 for icp in vdu.get("int-cpd", ()):
908 vdu_icp = {
909 "id": icp["id"],
910 "connection-point-id": icp["id"],
911 "name": icp.get("id"),
912 }
bravof35766442021-02-04 14:58:04 -0300913
garciaale7cbd03c2020-11-27 10:38:35 -0300914 vdur["internal-connection-point"].append(vdu_icp)
915
916 for iface in icp.get("virtual-network-interface-requirement", ()):
aticigc9c03392022-06-16 01:39:44 +0300917 # Name, mac-address and interface position is taken from VNFD
918 # and included into VNFR. By this way RO can process this information
919 # while creating the VDU.
Gulsum Atici9af2a472023-03-28 17:50:48 +0300920 iface_fields = ("name", "mac-address", "position", "ip-address")
garciadeblas4568a372021-03-24 09:19:48 +0100921 vdu_iface = {
922 x: iface[x] for x in iface_fields if iface.get(x) is not None
923 }
garciaale7cbd03c2020-11-27 10:38:35 -0300924
925 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100926 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100927 vdu_iface["port-security-enabled"] = icp[
928 "port-security-enabled"
929 ]
sousaedu003844e2021-03-02 00:19:15 +0100930
931 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100932 vdu_iface["port-security-disable-strategy"] = icp[
933 "port-security-disable-strategy"
934 ]
sousaedu003844e2021-03-02 00:19:15 +0100935
garciaale7cbd03c2020-11-27 10:38:35 -0300936 for ext_cp in vnfd.get("ext-cpd", ()):
937 if not ext_cp.get("int-cpd"):
938 continue
939 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
940 continue
941 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100942 vdu_iface["external-connection-point-ref"] = ext_cp.get(
943 "id"
944 )
sousaedu003844e2021-03-02 00:19:15 +0100945
946 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100947 vdu_iface["port-security-enabled"] = ext_cp[
948 "port-security-enabled"
949 ]
sousaedu003844e2021-03-02 00:19:15 +0100950
951 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100952 vdu_iface["port-security-disable-strategy"] = ext_cp[
953 "port-security-disable-strategy"
954 ]
sousaedu003844e2021-03-02 00:19:15 +0100955
garciaale7cbd03c2020-11-27 10:38:35 -0300956 break
957
garciadeblas4568a372021-03-24 09:19:48 +0100958 if (
959 vnfd_mgmt_cp
960 and vdu_iface.get("external-connection-point-ref")
961 == vnfd_mgmt_cp
962 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300963 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300964 vdu_iface["mgmt-interface"] = True
965
966 for ecp in vdu_mgmt_cp:
967 if vdu_iface.get("external-connection-point-ref") == ecp:
968 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300969
970 if iface.get("virtual-interface"):
971 vdu_iface.update(deepcopy(iface["virtual-interface"]))
972
973 # look for network where this interface is connected
974 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
975 if iface_ext_cp:
976 # TODO: Change for multiple df support
977 for df in get_iterable(nsd.get("df")):
978 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100979 for vlc_index, vlc in enumerate(
980 get_iterable(
981 vnf_profile.get("virtual-link-connectivity")
982 )
983 ):
984 for cpd in get_iterable(
985 vlc.get("constituent-cpd-id")
986 ):
987 if (
988 cpd.get("constituent-cpd-id")
989 == iface_ext_cp
Pedro Escaleira4606e4a2023-05-31 14:32:17 +0100990 ) and vnf_profile.get("id") == vnf_index:
garciadeblas4568a372021-03-24 09:19:48 +0100991 vdu_iface["ns-vld-id"] = vlc.get(
992 "virtual-link-profile-id"
993 )
garciadeblas61c95912021-02-12 11:23:50 +0000994 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100995 if vdu_iface.get("type") in (
996 "SR-IOV",
997 "PCI-PASSTHROUGH",
998 ):
999 nsr_descriptor["vld"][vlc_index][
1000 "pci-interfaces"
1001 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001002 break
1003 elif vdu_iface.get("internal-connection-point-ref"):
1004 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +00001005 # TODO: store fixed IP address in the record (if it exists in the ICP)
1006 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
1007 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +01001008 ivld_index = utils.find_index_in_list(
1009 vnfd.get("int-virtual-link-desc", ()),
1010 lambda ivld: ivld["id"]
1011 == icp.get("int-virtual-link-desc"),
1012 )
garciadeblas61c95912021-02-12 11:23:50 +00001013 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001014
1015 vdur["interfaces"].append(vdu_iface)
1016
1017 if vdu.get("sw-image-desc"):
1018 sw_image = utils.find_in_list(
1019 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001020 lambda image: image["id"] == vdu.get("sw-image-desc"),
1021 )
garciaale7cbd03c2020-11-27 10:38:35 -03001022 nsr_sw_image_data = utils.find_in_list(
1023 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001024 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -03001025 )
1026 vdur["ns-image-id"] = nsr_sw_image_data["id"]
1027
lloretgalleg28c13b62021-02-08 11:48:48 +00001028 if vdu.get("alternative-sw-image-desc"):
1029 alt_image_ids = []
1030 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1031 sw_image = utils.find_in_list(
1032 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001033 lambda image: image["id"] == alt_image_id,
1034 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001035 nsr_sw_image_data = utils.find_in_list(
1036 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001037 lambda nsr_image: (
1038 nsr_image.get("image") == sw_image.get("image")
1039 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001040 )
1041 alt_image_ids.append(nsr_sw_image_data["id"])
1042 vdur["alt-image-ids"] = alt_image_ids
1043
elumalai99078a92022-07-05 17:53:59 +05301044 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +01001045 flavor_data_name = (
1046 vdu["id"][:56] + "-" + vnf_index + "-" + str(revision) + "-flv"
1047 )
garciaale7cbd03c2020-11-27 10:38:35 -03001048 nsr_flavor_desc = utils.find_in_list(
1049 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001050 lambda flavor: flavor["name"] == flavor_data_name,
1051 )
garciaale7cbd03c2020-11-27 10:38:35 -03001052
1053 if nsr_flavor_desc:
1054 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1055
vegall18101ea2023-03-06 13:49:21 +00001056 # Adding Shared Volume information to vdur
1057 if vdur.get("virtual-storages"):
1058 nsr_sv = []
1059 for vsd in vdur["virtual-storages"]:
1060 if vsd.get("vdu-storage-requirements"):
1061 if (
1062 vsd["vdu-storage-requirements"][0].get("key")
1063 == "multiattach"
1064 and vsd["vdu-storage-requirements"][0].get("value")
1065 == "True"
1066 ):
1067 nsr_sv.append(vsd["id"])
1068 if nsr_sv:
1069 vdur["shared-volumes-id"] = nsr_sv
1070
Alexis Romero03fb5842022-03-11 15:53:40 +01001071 # Adding Affinity groups information to vdur
1072 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001073 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001074 vnfd.get("df")[0]["vdu-profile"],
1075 lambda a_vdu: a_vdu["id"] == vdu["id"],
1076 )
1077 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001078 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001079
Alexis Romeroee31f532022-04-26 19:10:21 +02001080 if vdu_profile_affinity_group:
1081 affinity_group_ids = []
1082 for affinity_group in vdu_profile_affinity_group.get(
1083 "affinity-or-anti-affinity-group", ()
1084 ):
1085 vdu_affinity_group = utils.find_in_list(
1086 vdu_profile_affinity_group.get(
1087 "affinity-or-anti-affinity-group", ()
1088 ),
1089 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001090 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001091 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001092 nsr_descriptor["affinity-or-anti-affinity-group"],
1093 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001094 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1095 and nsr_ag.get("member-vnf-index")
1096 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001097 ),
1098 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001099 # Update Affinity Group VIM name if VDU instantiation parameter is present
1100 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1101 vnf_params_affinity_group = utils.find_in_list(
1102 vnf_params["affinity-or-anti-affinity-group"],
1103 lambda vnfp_ag: (
1104 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1105 ),
1106 )
1107 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1108 nsr_affinity_group[
1109 "vim-affinity-group-id"
1110 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1111 affinity_group_ids.append(nsr_affinity_group["id"])
1112 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001113
bravof4ca51522021-04-22 10:03:02 -04001114 if vdu_instantiation_level:
1115 count = vdu_instantiation_level.get("number-of-instances")
1116 else:
1117 count = 1
1118
garciaale7cbd03c2020-11-27 10:38:35 -03001119 for index in range(0, count):
1120 vdur = deepcopy(vdur)
1121 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001122 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001123 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001124 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001125 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1126
1127 vdur["_id"] = str(uuid4())
1128 vdur["id"] = vdur["_id"]
1129 vdur["count-index"] = index
1130 vnfr_descriptor["vdur"].append(vdur)
garciaale7cbd03c2020-11-27 10:38:35 -03001131 return vnfr_descriptor
1132
K Sai Kiran57589552021-01-27 21:38:34 +05301133 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1134 """
1135 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1136 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1137 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1138 :param ns_instance_content: ns instance content
1139 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1140 :return: None
1141 """
garciadeblasf2af4a12023-01-24 16:56:54 +01001142 time_now, time_delta = (
1143 time(),
1144 time() - ns_instance_content["_admin"]["modified"],
1145 )
1146 force_refresh = (
1147 isinstance(filter_q, dict) and filter_q.get("vcaStatusRefresh") == "true"
1148 )
K Sai Kiran57589552021-01-27 21:38:34 +05301149 threshold_reached = time_delta > 120
1150 if force_refresh or threshold_reached:
1151 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1152 ns_instance_content["_admin"]["modified"] = time_now
1153 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1154 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
garciadeblasf2af4a12023-01-24 16:56:54 +01001155 self.format_on_new(
1156 nslcmop_desc, session["project_id"], make_public=session["public"]
1157 )
K Sai Kiran57589552021-01-27 21:38:34 +05301158 nslcmop_desc["_admin"].pop("nsState")
1159 self.msg.write("ns", operation, nslcmop_desc)
1160 return
1161
1162 def show(self, session, _id, filter_q=None, api_req=False):
1163 """
1164 Get complete information on an ns instance.
1165 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1166 :param _id: string, ns instance id
1167 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1168 :param api_req: True if this call is serving an external API request. False if serving internal request.
1169 :return: dictionary, raise exception if not found.
1170 """
1171 ns_instance_content = super().show(session, _id, api_req)
1172 self.vca_status_refresh(session, ns_instance_content, filter_q)
1173 return ns_instance_content
1174
tierno65ca36d2019-02-12 19:27:52 +01001175 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001176 raise EngineException(
1177 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1178 )
tiernob24258a2018-10-04 18:39:49 +02001179
1180
1181class VnfrTopic(BaseTopic):
1182 topic = "vnfrs"
1183 topic_msg = None
1184
delacruzramo32bab472019-09-13 12:24:22 +02001185 def __init__(self, db, fs, msg, auth):
1186 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001187
tiernobee3bad2019-12-05 12:26:01 +00001188 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001189 raise EngineException(
1190 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1191 )
tiernob24258a2018-10-04 18:39:49 +02001192
tierno65ca36d2019-02-12 19:27:52 +01001193 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001194 raise EngineException(
1195 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1196 )
tiernob24258a2018-10-04 18:39:49 +02001197
tierno65ca36d2019-02-12 19:27:52 +01001198 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001199 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001200 raise EngineException(
1201 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1202 )
tiernob24258a2018-10-04 18:39:49 +02001203
1204
1205class NsLcmOpTopic(BaseTopic):
1206 topic = "nslcmops"
1207 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001208 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001209 "instantiate": ns_instantiate,
1210 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001211 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001212 "scale": ns_scale,
garciadeblas0964edf2022-02-11 00:43:44 +01001213 "heal": ns_heal,
tierno1c38f2f2020-03-24 11:51:39 +00001214 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301215 "migrate": ns_migrate,
Gabriel Cuba84a60df2023-10-30 14:01:54 -05001216 "cancel": nslcmop_cancel,
tiernob24258a2018-10-04 18:39:49 +02001217 }
1218
delacruzramo32bab472019-09-13 12:24:22 +02001219 def __init__(self, db, fs, msg, auth):
1220 BaseTopic.__init__(self, db, fs, msg, auth)
elumalai6c5ea6b2022-04-25 22:27:59 +05301221 self.nsrtopic = NsrTopic(db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001222
tiernob24258a2018-10-04 18:39:49 +02001223 def _check_ns_operation(self, session, nsr, operation, indata):
1224 """
1225 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
garciadeblas0964edf2022-02-11 00:43:44 +01001227 :param operation: it can be: instantiate, terminate, action, update, heal
tiernob24258a2018-10-04 18:39:49 +02001228 :param indata: descriptor with the parameters of the operation
1229 :return: None
1230 """
garciaale7cbd03c2020-11-27 10:38:35 -03001231 if operation == "action":
1232 self._check_action_ns_operation(indata, nsr)
1233 elif operation == "scale":
1234 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001235 elif operation == "update":
1236 self._check_update_ns_operation(indata, nsr)
garciadeblas0964edf2022-02-11 00:43:44 +01001237 elif operation == "heal":
1238 self._check_heal_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001239 elif operation == "instantiate":
1240 self._check_instantiate_ns_operation(indata, nsr, session)
1241
1242 def _check_action_ns_operation(self, indata, nsr):
1243 nsd = nsr["nsd"]
1244 # check vnf_member_index
1245 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001246 indata["member_vnf_index"] = indata.pop(
1247 "vnf_member_index"
1248 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001249 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001250 vnfd = self._get_vnfd_from_vnf_member_index(
1251 indata["member_vnf_index"], nsr["_id"]
1252 )
bravof41a52052021-02-17 18:08:01 -03001253 try:
garciadeblas4568a372021-03-24 09:19:48 +01001254 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1255 "operate-vnf-op-config"
1256 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001257 except Exception:
1258 configs = []
1259
garciaale7cbd03c2020-11-27 10:38:35 -03001260 if indata.get("vdu_id"):
1261 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001262 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001263 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001264 )
garciaale7cbd03c2020-11-27 10:38:35 -03001265 elif indata.get("kdu_name"):
1266 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001267 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001268 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001269 )
garciaale7cbd03c2020-11-27 10:38:35 -03001270 else:
bravof41a52052021-02-17 18:08:01 -03001271 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001272 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001273 )
1274 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001275 descriptor_configuration = descriptor_configuration.get(
1276 "config-primitive"
1277 )
garciaale7cbd03c2020-11-27 10:38:35 -03001278 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001279 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1280 "config-primitive"
1281 )
garciaale7cbd03c2020-11-27 10:38:35 -03001282
1283 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001284 if indata.get("kdu_name") and indata["primitive"] in (
1285 "upgrade",
1286 "rollback",
1287 "status",
1288 "inspect",
1289 "readme",
1290 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001291 # TODO should be checked that rollback only can contains revsision_numbe????
1292 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001293 raise EngineException(
1294 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1295 indata["primitive"]
1296 )
1297 )
garciaale7cbd03c2020-11-27 10:38:35 -03001298 return
1299 # if not, check primitive
1300 for config_primitive in get_iterable(descriptor_configuration):
1301 if indata["primitive"] == config_primitive["name"]:
1302 # check needed primitive_params are provided
1303 if indata.get("primitive_params"):
1304 in_primitive_params_copy = copy(indata["primitive_params"])
1305 else:
1306 in_primitive_params_copy = {}
1307 for paramd in get_iterable(config_primitive.get("parameter")):
1308 if paramd["name"] in in_primitive_params_copy:
1309 del in_primitive_params_copy[paramd["name"]]
1310 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001311 raise EngineException(
1312 "Needed parameter {} not provided for primitive '{}'".format(
1313 paramd["name"], indata["primitive"]
1314 )
1315 )
garciaale7cbd03c2020-11-27 10:38:35 -03001316 # check no extra primitive params are provided
1317 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001318 raise EngineException(
1319 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1320 list(in_primitive_params_copy.keys()), indata["primitive"]
1321 )
1322 )
garciaale7cbd03c2020-11-27 10:38:35 -03001323 break
1324 else:
garciadeblas4568a372021-03-24 09:19:48 +01001325 raise EngineException(
1326 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1327 indata["primitive"]
1328 )
1329 )
garciaale7cbd03c2020-11-27 10:38:35 -03001330
aticig544a2ae2022-04-05 09:00:17 +03001331 def _check_update_ns_operation(self, indata, nsr) -> None:
1332 """Validates the ns-update request according to updateType
1333
1334 If updateType is CHANGE_VNFPKG:
1335 - it checks the vnfInstanceId, whether it's available under ns instance
1336 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1337 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301338 If updateType is REMOVE_VNF:
1339 - it checks if the vnfInstanceId is available in the ns instance
1340 - Otherwise exception will be raised.
jegancd7d9f02024-05-16 07:07:27 +00001341 If updateType is OPERATE_VNF
1342 - it checks if the vdu-id is persent in the descriptor or not
1343 - it checks if the changeStateTo is either start, stop or rebuild
1344 If updateType is VERTICAL_SCALE
1345 - it checks if the vdu-id is persent in the descriptor or not
aticig544a2ae2022-04-05 09:00:17 +03001346
1347 Args:
1348 indata: includes updateType such as CHANGE_VNFPKG,
1349 nsr: network service record
1350
1351 Raises:
1352 EngineException:
1353 a meaningful error if given update parameters are not proper such as
1354 "Error in validating ns-update request: <ID> does not match
1355 with the vnfd-id of vnfinstance
1356 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1357
1358 """
1359 try:
1360 if indata["updateType"] == "CHANGE_VNFPKG":
1361 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1362 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1363 ns_instance_id = indata["nsInstanceId"]
1364 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1365
1366 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
aticig544a2ae2022-04-05 09:00:17 +03001367 raise EngineException(
1368 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1369 f"belong to NS {ns_instance_id}",
1370 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1371 )
1372
1373 # Getting vnfrs through the ns_instance_id
1374 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1375 constituent_vnfd_id = next(
1376 (
1377 vnfr["vnfd-id"]
1378 for vnfr in vnfrs
1379 if vnfr["id"] == vnf_instance_id
1380 ),
1381 None,
1382 )
1383
1384 # Check the given vnfd-id belongs to given vnf instance
1385 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
aticig544a2ae2022-04-05 09:00:17 +03001386 raise EngineException(
1387 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1388 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1389 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1390 )
1391
1392 # Validating the ns update timeout
1393 if (
1394 indata.get("timeout_ns_update")
1395 and indata["timeout_ns_update"] < 300
1396 ):
1397 raise EngineException(
1398 "Error in validating ns-update request: {} second is not enough "
1399 "to upgrade the VNF instance: {}".format(
1400 indata["timeout_ns_update"], vnf_instance_id
1401 ),
1402 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1403 )
elumalai6380e7c2022-04-28 00:15:59 +05301404 elif indata["updateType"] == "REMOVE_VNF":
1405 vnf_instance_id = indata["removeVnfInstanceId"]
1406 ns_instance_id = indata["nsInstanceId"]
1407 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1408 raise EngineException(
1409 "Invalid VNF Instance Id. '{}' is not "
1410 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1411 )
jegancd7d9f02024-05-16 07:07:27 +00001412 elif indata["updateType"] == "OPERATE_VNF":
1413 if indata.get("operateVnfData"):
1414 if indata["operateVnfData"]["changeStateTo"] not in (
1415 "start",
1416 "stop",
1417 "rebuild",
1418 ):
1419 raise EngineException(
1420 f"The operate type should be either start, stop or rebuild not {indata['operateVnfData']['changeStateTo']}",
1421 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1422 )
1423 if indata["operateVnfData"].get("additionalParam"):
1424 vdu_id = indata["operateVnfData"]["additionalParam"]["vdu_id"]
1425 vnfinstance_id = indata["operateVnfData"]["vnfInstanceId"]
1426 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1427 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1428 vnfd = self._get_vnfd_from_vnf_member_index(
1429 vnfd_member_vnf_index, nsr["_id"]
1430 )
1431 self._check_valid_vdu(vnfd, vdu_id)
1432 elif indata["updateType"] == "VERTICAL_SCALE":
1433 if indata.get("verticalScaleVnf"):
1434 vdu_id = indata["verticalScaleVnf"]["vduId"]
1435 vnfinstance_id = indata["verticalScaleVnf"]["vnfInstanceId"]
1436 vnf = self.db.get_one("vnfrs", {"_id": vnfinstance_id})
1437 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1438 vnfd = self._get_vnfd_from_vnf_member_index(
1439 vnfd_member_vnf_index, nsr["_id"]
1440 )
1441 self._check_valid_vdu(vnfd, vdu_id)
aticig544a2ae2022-04-05 09:00:17 +03001442
1443 except (
1444 DbException,
1445 AttributeError,
1446 IndexError,
1447 KeyError,
1448 ValueError,
1449 ) as e:
1450 raise type(e)(
1451 "Ns update request could not be processed with error: {}.".format(e)
1452 )
1453
garciaale7cbd03c2020-11-27 10:38:35 -03001454 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001455 vnfd = self._get_vnfd_from_vnf_member_index(
1456 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1457 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001458 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001459 if (
1460 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1461 == scaling_aspect["id"]
1462 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001463 break
1464 else:
garciadeblas4568a372021-03-24 09:19:48 +01001465 raise EngineException(
1466 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1467 "present at vnfd:scaling-aspect".format(
1468 indata["scaleVnfData"]["scaleByStepData"][
1469 "scaling-group-descriptor"
1470 ]
1471 )
1472 )
garciaale7cbd03c2020-11-27 10:38:35 -03001473
garciadeblas0964edf2022-02-11 00:43:44 +01001474 def _check_heal_ns_operation(self, indata, nsr):
1475 return
1476
garciaale7cbd03c2020-11-27 10:38:35 -03001477 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001478 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001479 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001480 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001481 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001482 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1483 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1484 for in_vnf in get_iterable(indata.get("vnf")):
1485 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001486 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001487 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001488 else:
garciadeblas4568a372021-03-24 09:19:48 +01001489 vnfd = self._get_vnfd_from_vnf_member_index(
1490 member_vnf_index, nsr["_id"]
1491 )
1492 vnf_member_index_to_vnfd[
1493 member_vnf_index
1494 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001495 self._check_vnf_instantiation_params(in_vnf, vnfd)
1496 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001497 self._check_valid_vim_account(
1498 in_vnf["vimAccountId"], vim_accounts, session
1499 )
tierno260dd6f2019-09-02 10:48:56 +00001500
garciaale7cbd03c2020-11-27 10:38:35 -03001501 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001502 self._check_valid_wim_account(
1503 in_vld.get("wimAccountId"), wim_accounts, session
1504 )
garciaale7cbd03c2020-11-27 10:38:35 -03001505 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1506 if in_vld["name"] == vldd["id"]:
1507 break
tierno9cb7d672019-10-30 12:13:48 +00001508 else:
garciadeblas4568a372021-03-24 09:19:48 +01001509 raise EngineException(
1510 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1511 in_vld["name"]
1512 )
1513 )
tierno9cb7d672019-10-30 12:13:48 +00001514
garciaale7cbd03c2020-11-27 10:38:35 -03001515 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1516 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001517 vnfr = self.db.get_one(
1518 "vnfrs",
1519 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1520 fail_on_empty=False,
1521 )
garciaale7cbd03c2020-11-27 10:38:35 -03001522 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001523 raise EngineException(
1524 "Invalid parameter member_vnf_index='{}' is not one of the "
1525 "nsd:constituent-vnfd".format(member_vnf_index)
1526 )
beierlmcee2ebf2022-03-29 17:42:48 -04001527
garciadeblasf2af4a12023-01-24 16:56:54 +01001528 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
beierlmcee2ebf2022-03-29 17:42:48 -04001529 if "revision" in vnfr:
1530 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
garciadeblasf2af4a12023-01-24 16:56:54 +01001531 vnfd = self.db.get_one(
1532 "vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False
1533 )
beierlmcee2ebf2022-03-29 17:42:48 -04001534 else:
garciadeblasf2af4a12023-01-24 16:56:54 +01001535 vnfd = self.db.get_one(
1536 "vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False
1537 )
beierlmcee2ebf2022-03-29 17:42:48 -04001538
garciaale7cbd03c2020-11-27 10:38:35 -03001539 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001540 raise EngineException(
1541 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1542 vnfr["vnfd-id"]
1543 )
1544 )
garciaale7cbd03c2020-11-27 10:38:35 -03001545 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001546
garciaale7cbd03c2020-11-27 10:38:35 -03001547 def _check_valid_vdu(self, vnfd, vdu_id):
1548 for vdud in get_iterable(vnfd.get("vdu")):
1549 if vdud["id"] == vdu_id:
1550 return vdud
1551 else:
garciadeblas4568a372021-03-24 09:19:48 +01001552 raise EngineException(
1553 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1554 vdu_id
1555 )
1556 )
garciaale7cbd03c2020-11-27 10:38:35 -03001557
1558 def _check_valid_kdu(self, vnfd, kdu_name):
1559 for kdud in get_iterable(vnfd.get("kdu")):
1560 if kdud["name"] == kdu_name:
1561 return kdud
1562 else:
garciadeblas4568a372021-03-24 09:19:48 +01001563 raise EngineException(
1564 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1565 kdu_name
1566 )
1567 )
garciaale7cbd03c2020-11-27 10:38:35 -03001568
1569 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1570 for in_vdu in get_iterable(in_vnf.get("vdu")):
1571 for vdu in get_iterable(vnfd.get("vdu")):
1572 if in_vdu["id"] == vdu["id"]:
1573 for volume in get_iterable(in_vdu.get("volume")):
1574 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
aticigd7753fc2022-05-18 18:55:23 +03001575 if volumed == volume["name"]:
garciaale7cbd03c2020-11-27 10:38:35 -03001576 break
1577 else:
garciadeblas4568a372021-03-24 09:19:48 +01001578 raise EngineException(
1579 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1580 "volume:name='{}' is not present at "
1581 "vnfd:vdu:virtual-storage-desc list".format(
1582 in_vnf["member-vnf-index"],
1583 in_vdu["id"],
1584 volume["id"],
1585 )
1586 )
garciaale7cbd03c2020-11-27 10:38:35 -03001587
1588 vdu_if_names = set()
1589 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001590 for iface in get_iterable(
1591 cpd.get("virtual-network-interface-requirement")
1592 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001593 vdu_if_names.add(iface.get("name"))
1594
aticigd7753fc2022-05-18 18:55:23 +03001595 for in_iface in get_iterable(in_vdu.get("interface")):
garciaale7cbd03c2020-11-27 10:38:35 -03001596 if in_iface["name"] in vdu_if_names:
1597 break
1598 else:
garciadeblas4568a372021-03-24 09:19:48 +01001599 raise EngineException(
1600 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1601 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1602 in_vnf["member-vnf-index"],
1603 in_vdu["id"],
1604 in_iface["name"],
1605 )
1606 )
garciaale7cbd03c2020-11-27 10:38:35 -03001607 break
1608
1609 else:
garciadeblas4568a372021-03-24 09:19:48 +01001610 raise EngineException(
1611 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1612 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1613 )
garciaale7cbd03c2020-11-27 10:38:35 -03001614
garciadeblas4568a372021-03-24 09:19:48 +01001615 vnfd_ivlds_cpds = {
1616 ivld.get("id"): set()
1617 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1618 }
Gulsum Atici9af2a472023-03-28 17:50:48 +03001619 for vdu in vnfd.get("vdu", {}):
1620 for cpd in vdu.get("int-cpd", {}):
garciaale7cbd03c2020-11-27 10:38:35 -03001621 if cpd.get("int-virtual-link-desc"):
1622 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1623
1624 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1625 if in_ivld.get("name") in vnfd_ivlds_cpds:
1626 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1627 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001628 break
tiernob24258a2018-10-04 18:39:49 +02001629 else:
garciadeblas4568a372021-03-24 09:19:48 +01001630 raise EngineException(
1631 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1632 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1633 "vnfd:internal-vld:name/id:internal-connection-point".format(
1634 in_vnf["member-vnf-index"],
1635 in_ivld["name"],
1636 in_icp["id-ref"],
1637 )
1638 )
tiernob24258a2018-10-04 18:39:49 +02001639 else:
garciadeblas4568a372021-03-24 09:19:48 +01001640 raise EngineException(
1641 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1642 " is not present at vnfd '{}'".format(
1643 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1644 )
1645 )
tiernob24258a2018-10-04 18:39:49 +02001646
garciaale7cbd03c2020-11-27 10:38:35 -03001647 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1648 if vim_account in vim_accounts:
1649 return
1650 try:
1651 db_filter = self._get_project_filter(session)
1652 db_filter["_id"] = vim_account
1653 self.db.get_one("vim_accounts", db_filter)
1654 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001655 raise EngineException(
1656 "Invalid vimAccountId='{}' not present for the project".format(
1657 vim_account
1658 )
1659 )
garciaale7cbd03c2020-11-27 10:38:35 -03001660 vim_accounts.append(vim_account)
1661
David Garcia98de2982021-10-13 17:14:01 +02001662 def _get_vim_account(self, vim_id: str, session):
1663 try:
1664 db_filter = self._get_project_filter(session)
1665 db_filter["_id"] = vim_id
1666 return self.db.get_one("vim_accounts", db_filter)
1667 except Exception:
1668 raise EngineException(
garciadeblasf2af4a12023-01-24 16:56:54 +01001669 "Invalid vimAccountId='{}' not present for the project".format(vim_id)
David Garcia98de2982021-10-13 17:14:01 +02001670 )
1671
garciaale7cbd03c2020-11-27 10:38:35 -03001672 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1673 if not isinstance(wim_account, str):
1674 return
1675 if wim_account in wim_accounts:
1676 return
1677 try:
gifrerenom44f5ec12022-03-07 16:57:25 +00001678 db_filter = self._get_project_filter(session)
garciaale7cbd03c2020-11-27 10:38:35 -03001679 db_filter["_id"] = wim_account
1680 self.db.get_one("wim_accounts", db_filter)
1681 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001682 raise EngineException(
1683 "Invalid wimAccountId='{}' not present for the project".format(
1684 wim_account
1685 )
1686 )
garciaale7cbd03c2020-11-27 10:38:35 -03001687 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001688
garciadeblas4568a372021-03-24 09:19:48 +01001689 def _look_for_pdu(
1690 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1691 ):
tiernocc103432018-10-19 14:10:35 +02001692 """
tierno36ec8602018-11-02 17:27:11 +01001693 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1694 (ip_address, ...) information.
1695 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001696 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001697 :param rollback: list with the database modifications to rollback if needed
1698 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1699 :param vim_account: vim_account where this vnfr should be deployed
1700 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1701 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1702 of the changed vnfr is needed
1703
1704 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1705 "vim-network-name": used at VIM
1706 "name": interface name
1707 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1708 "ns-vld-id": NSD vld where this interface is connected.
1709 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 +02001710 """
tierno36ec8602018-11-02 17:27:11 +01001711
1712 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001713 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1714 if not vdur.get("pdu-type"):
1715 continue
1716 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001717 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001718 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001719 pdu_filter["type"] = pdu_type
1720 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001721 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001722 # TODO feature 1417: "shared": True,
1723
1724 available_pdus = self.db.get_list("pdus", pdu_filter)
1725 for pdu in available_pdus:
1726 # step 1 check if this pdu contains needed interfaces:
1727 match_interfaces = True
1728 for vdur_interface in vdur["interfaces"]:
1729 for pdu_interface in pdu["interfaces"]:
1730 if pdu_interface["name"] == vdur_interface["name"]:
1731 # TODO feature 1417: match per mgmt type
1732 break
1733 else: # no interface found for name
1734 match_interfaces = False
1735 break
1736 if match_interfaces:
1737 break
1738 else:
1739 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001740 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001741 "names".format(
1742 pdu_type,
1743 vim_account,
1744 vnfr["member-vnf-index-ref"],
1745 vdur["vdu-id-ref"],
1746 )
1747 )
tiernocc103432018-10-19 14:10:35 +02001748
1749 # step 2. Update pdu
1750 rollback_pdu = {
1751 "_admin.usageState": pdu["_admin"]["usageState"],
1752 "_admin.usage.vnfr_id": None,
1753 "_admin.usage.nsr_id": None,
1754 "_admin.usage.vdur": None,
1755 }
garciadeblas4568a372021-03-24 09:19:48 +01001756 self.db.set_one(
1757 "pdus",
1758 {"_id": pdu["_id"]},
1759 {
1760 "_admin.usageState": "IN_USE",
1761 "_admin.usage": {
1762 "vnfr_id": vnfr["_id"],
1763 "nsr_id": vnfr["nsr-id-ref"],
1764 "vdur": vdur["vdu-id-ref"],
1765 },
1766 },
1767 )
1768 rollback.append(
1769 {
1770 "topic": "pdus",
1771 "_id": pdu["_id"],
1772 "operation": "set",
1773 "content": rollback_pdu,
1774 }
1775 )
tiernocc103432018-10-19 14:10:35 +02001776
1777 # step 3. Fill vnfr info by filling vdur
1778 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001779 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001780 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1781 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1782 for pdu_interface in pdu["interfaces"]:
1783 if pdu_interface["name"] == vdur_interface["name"]:
1784 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1785 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001786 if k in (
1787 "ip-address",
1788 "mac-address",
1789 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001790 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001791 vnfr_update_rollback[
1792 iface_text + ".{}".format(k)
1793 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001794 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001795 if vdur_interface.get(
1796 "mgmt-interface"
1797 ) or vdur_interface.get("mgmt-vnf"):
1798 vnfr_update_rollback[
1799 vdu_text + ".ip-address"
1800 ] = vdur.get("ip-address")
1801 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1802 "ip-address"
1803 ]
tierno36ec8602018-11-02 17:27:11 +01001804 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001805 vnfr_update_rollback["ip-address"] = vnfr.get(
1806 "ip-address"
1807 )
tierno36ec8602018-11-02 17:27:11 +01001808 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001809 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1810 "ip-address"
1811 ]
1812 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1813 "vim-network-id"
1814 ):
1815 ifaces_forcing_vim_network.append(
1816 {
1817 "name": vdur_interface.get("vnf-vld-id")
1818 or vdur_interface.get("ns-vld-id"),
1819 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1820 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1821 }
1822 )
gcalvino17d5b732018-12-17 16:26:21 +01001823 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001824 ifaces_forcing_vim_network[-1][
1825 "vim-network-id"
1826 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001827 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001828 ifaces_forcing_vim_network[-1][
1829 "vim-network-name"
1830 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001831 break
1832
tierno36ec8602018-11-02 17:27:11 +01001833 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001834
garciadeblas4568a372021-03-24 09:19:48 +01001835 def _look_for_k8scluster(
1836 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1837 ):
tierno9cb7d672019-10-30 12:13:48 +00001838 """
1839 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1840 Fills vnfr.kdur with the selected k8scluster
1841
1842 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1843 :param rollback: list with the database modifications to rollback if needed
1844 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1845 :param vim_account: vim_account where this vnfr should be deployed
1846 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1847 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1848 of the changed vnfr is needed
1849
1850 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1851 "vim-network-name": used at VIM
1852 "name": interface name
1853 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1854 "ns-vld-id": NSD vld where this interface is connected.
1855 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1856 """
1857
1858 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001859 if not vnfr.get("kdur"):
1860 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001861
tiernoc67b0e92019-11-05 12:45:29 +00001862 kdu_filter = self._get_project_filter(session)
1863 kdu_filter["vim_account"] = vim_account
1864 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1865 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1866
1867 k8s_requirements = {} # just for logging
1868 for k8scluster in available_k8sclusters:
1869 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001870 break
tiernoc67b0e92019-11-05 12:45:29 +00001871 # restrict by cni
1872 if vnfr["k8s-cluster"].get("cni"):
1873 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001874 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1875 k8scluster.get("cni", ())
1876 ):
tiernoc67b0e92019-11-05 12:45:29 +00001877 continue
1878 # restrict by version
1879 if vnfr["k8s-cluster"].get("version"):
1880 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1881 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1882 continue
1883 # restrict by number of networks
1884 if vnfr["k8s-cluster"].get("nets"):
1885 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001886 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1887 vnfr["k8s-cluster"]["nets"]
1888 ):
tiernoc67b0e92019-11-05 12:45:29 +00001889 continue
1890 break
1891 else:
garciadeblas4568a372021-03-24 09:19:48 +01001892 raise EngineException(
1893 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1894 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1895 )
1896 )
tierno9cb7d672019-10-30 12:13:48 +00001897
tiernoc67b0e92019-11-05 12:45:29 +00001898 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001899 # step 3. Fill vnfr info by filling kdur
1900 kdu_text = "kdur.{}.".format(kdur_index)
1901 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1902 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1903
tiernoc67b0e92019-11-05 12:45:29 +00001904 # step 4. Check VIM networks that forces the selected k8s_cluster
1905 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1906 k8scluster_net_list = list(k8scluster.get("nets").keys())
1907 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1908 # get a network from k8s_cluster nets. If name matches use this, if not use other
1909 if kdur_net["id"] in k8scluster_net_list: # name matches
1910 vim_net = k8scluster["nets"][kdur_net["id"]]
1911 k8scluster_net_list.remove(kdur_net["id"])
1912 else:
1913 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1914 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001915 vnfr_update_rollback[
1916 "k8s-cluster.nets.{}.vim_net".format(net_index)
1917 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001918 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001919 if vim_net and (
1920 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1921 ):
1922 ifaces_forcing_vim_network.append(
1923 {
1924 "name": kdur_net.get("vnf-vld-id")
1925 or kdur_net.get("ns-vld-id"),
1926 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1927 "ns-vld-id": kdur_net.get("ns-vld-id"),
1928 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1929 }
1930 )
tiernoc67b0e92019-11-05 12:45:29 +00001931 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001932 return ifaces_forcing_vim_network
1933
Gulsum Aticie395aa42021-11-10 20:59:06 +03001934 def _update_vnfrs_from_nsd(self, nsr):
garciadeblasf2af4a12023-01-24 16:56:54 +01001935 step = "Getting vnf_profiles from nsd" # first step must be defined outside try
Gulsum Aticie395aa42021-11-10 20:59:06 +03001936 try:
1937 nsr_id = nsr["_id"]
1938 nsd = nsr["nsd"]
1939
Gulsum Aticie395aa42021-11-10 20:59:06 +03001940 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1941 vld_fixed_ip_connection_point_data = {}
1942
1943 step = "Getting ip-address info from vnf_profile if it exists"
1944 for vnfp in vnf_profiles:
1945 # Checking ip-address info from nsd.vnf_profile and storing
1946 for vlc in vnfp.get("virtual-link-connectivity", ()):
1947 for cpd in vlc.get("constituent-cpd-id", ()):
1948 if cpd.get("ip-address"):
1949 step = "Storing ip-address info"
garciadeblasf2af4a12023-01-24 16:56:54 +01001950 vld_fixed_ip_connection_point_data.update(
1951 {
1952 vlc.get("virtual-link-profile-id")
1953 + "."
1954 + cpd.get("constituent-base-element-id"): {
1955 "vnfd-connection-point-ref": cpd.get(
1956 "constituent-cpd-id"
1957 ),
1958 "ip-address": cpd.get("ip-address"),
1959 }
1960 }
1961 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001962
1963 # Inserting ip address to vnfr
1964 if len(vld_fixed_ip_connection_point_data) > 0:
1965 step = "Getting vnfrs"
1966 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1967 for item in vld_fixed_ip_connection_point_data.keys():
1968 step = "Filtering vnfrs"
garciadeblasf2af4a12023-01-24 16:56:54 +01001969 vnfr = next(
1970 filter(
1971 lambda vnfr: vnfr["member-vnf-index-ref"]
1972 == item.split(".")[1],
1973 vnfrs,
1974 ),
1975 None,
1976 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001977 if vnfr:
1978 vnfr_update = {}
1979 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1980 for iface_index, iface in enumerate(vdur["interfaces"]):
1981 step = "Looking for matched interface"
1982 if (
garciadeblasf2af4a12023-01-24 16:56:54 +01001983 iface.get("external-connection-point-ref")
1984 == vld_fixed_ip_connection_point_data[item].get(
1985 "vnfd-connection-point-ref"
1986 )
1987 and iface.get("ns-vld-id") == item.split(".")[0]
Gulsum Aticie395aa42021-11-10 20:59:06 +03001988 ):
1989 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1990 vdur_index, iface_index
1991 )
1992 step = "Storing info in order to update vnfr"
1993 vnfr_update[
1994 vnfr_update_text + ".ip-address"
garciadeblasf2af4a12023-01-24 16:56:54 +01001995 ] = increment_ip_mac(
1996 vld_fixed_ip_connection_point_data[item].get(
1997 "ip-address"
1998 ),
1999 vdur.get("count-index", 0),
2000 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03002001 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
2002
2003 step = "updating vnfr at database"
2004 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
2005 except (
garciadeblasf2af4a12023-01-24 16:56:54 +01002006 ValidationError,
2007 EngineException,
2008 DbException,
2009 MsgException,
2010 FsException,
Gulsum Aticie395aa42021-11-10 20:59:06 +03002011 ) as e:
2012 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
2013
tiernocc103432018-10-19 14:10:35 +02002014 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02002015 # get vnfr
2016 nsr_id = nsr["_id"]
2017 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2018
2019 for vnfr in vnfrs:
2020 vnfr_update = {}
2021 vnfr_update_rollback = {}
2022 member_vnf_index = vnfr["member-vnf-index-ref"]
2023 # update vim-account-id
2024
2025 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02002026 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002027 # check instantiate parameters
2028 for vnf_inst_params in get_iterable(indata.get("vnf")):
2029 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
2030 continue
2031 if vnf_inst_params.get("vimAccountId"):
2032 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02002033 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002034
tiernocddb07d2020-10-06 08:28:00 +00002035 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
2036 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
2037 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2038 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
2039 continue
garciadeblas4568a372021-03-24 09:19:48 +01002040 for iface_inst_param in get_iterable(
2041 vdu_inst_param.get("interface")
2042 ):
2043 iface_index, _ = next(
2044 i
2045 for i in enumerate(vdur["interfaces"])
2046 if i[1]["name"] == iface_inst_param["name"]
2047 )
2048 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2049 vdur_index, iface_index
2050 )
tiernocddb07d2020-10-06 08:28:00 +00002051 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002052 vnfr_update[
2053 vnfr_update_text + ".ip-address"
2054 ] = increment_ip_mac(
2055 iface_inst_param.get("ip-address"),
2056 vdur.get("count-index", 0),
2057 )
tierno1bd9d952020-11-13 15:56:51 +00002058 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002059 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002060 vnfr_update[
2061 vnfr_update_text + ".mac-address"
2062 ] = increment_ip_mac(
2063 iface_inst_param.get("mac-address"),
2064 vdur.get("count-index", 0),
2065 )
tierno1bd9d952020-11-13 15:56:51 +00002066 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03002067 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01002068 vnfr_update[
2069 vnfr_update_text + ".floating-ip-required"
2070 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002071 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2072 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01002073 for ivld_inst_param in get_iterable(
2074 vnf_inst_params.get("internal-vld")
2075 ):
2076 for icp_inst_param in get_iterable(
2077 ivld_inst_param.get("internal-connection-point")
2078 ):
tiernocddb07d2020-10-06 08:28:00 +00002079 # look for iface
2080 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2081 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002082 if (
2083 iface.get("internal-connection-point-ref")
2084 == icp_inst_param["id-ref"]
2085 ):
2086 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2087 vdur_index, iface_index
2088 )
tiernocddb07d2020-10-06 08:28:00 +00002089 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002090 vnfr_update[
2091 vnfr_update_text + ".ip-address"
2092 ] = increment_ip_mac(
2093 icp_inst_param.get("ip-address"),
2094 vdur.get("count-index", 0),
2095 )
2096 vnfr_update[
2097 vnfr_update_text + ".fixed-ip"
2098 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002099 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002100 vnfr_update[
2101 vnfr_update_text + ".mac-address"
2102 ] = increment_ip_mac(
2103 icp_inst_param.get("mac-address"),
2104 vdur.get("count-index", 0),
2105 )
2106 vnfr_update[
2107 vnfr_update_text + ".fixed-mac"
2108 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002109 break
2110 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2111 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01002112 for vnfcp_inst_param in get_iterable(
2113 vld_inst_param.get("vnfd-connection-point-ref")
2114 ):
tiernocddb07d2020-10-06 08:28:00 +00002115 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2116 continue
2117 # look for iface
2118 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2119 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002120 if (
2121 iface.get("external-connection-point-ref")
2122 == vnfcp_inst_param["vnfd-connection-point-ref"]
2123 ):
2124 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2125 vdur_index, iface_index
2126 )
tiernocddb07d2020-10-06 08:28:00 +00002127 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002128 vnfr_update[
2129 vnfr_update_text + ".ip-address"
2130 ] = increment_ip_mac(
2131 vnfcp_inst_param.get("ip-address"),
2132 vdur.get("count-index", 0),
2133 )
tierno1bd9d952020-11-13 15:56:51 +00002134 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002135 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002136 vnfr_update[
2137 vnfr_update_text + ".mac-address"
2138 ] = increment_ip_mac(
2139 vnfcp_inst_param.get("mac-address"),
2140 vdur.get("count-index", 0),
2141 )
tierno1bd9d952020-11-13 15:56:51 +00002142 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002143 break
2144
tiernocc103432018-10-19 14:10:35 +02002145 vnfr_update["vim-account-id"] = vim_account
2146 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2147
David Garciaecb41322021-03-31 19:10:46 +02002148 if vca_id:
2149 vnfr_update["vca-id"] = vca_id
2150 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2151
tiernocc103432018-10-19 14:10:35 +02002152 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002153 ifaces_forcing_vim_network = self._look_for_pdu(
2154 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2155 )
tiernocc103432018-10-19 14:10:35 +02002156
tierno9cb7d672019-10-30 12:13:48 +00002157 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002158 ifaces_forcing_vim_network += self._look_for_k8scluster(
2159 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2160 )
tierno9cb7d672019-10-30 12:13:48 +00002161 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002162 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002163 rollback.append(
2164 {
2165 "topic": "vnfrs",
2166 "_id": vnfr["_id"],
2167 "operation": "set",
2168 "content": vnfr_update_rollback,
2169 }
2170 )
tierno36ec8602018-11-02 17:27:11 +01002171
2172 # Update indada in case pdu forces to use a concrete vim-network-name
2173 # TODO check if user has already insert a vim-network-name and raises an error
2174 if not ifaces_forcing_vim_network:
2175 continue
2176 for iface_info in ifaces_forcing_vim_network:
2177 if iface_info.get("ns-vld-id"):
2178 if "vld" not in indata:
2179 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002180 indata["vld"].append(
2181 {
2182 key: iface_info[key]
2183 for key in ("name", "vim-network-name", "vim-network-id")
2184 if iface_info.get(key)
2185 }
2186 )
tierno36ec8602018-11-02 17:27:11 +01002187
2188 elif iface_info.get("vnf-vld-id"):
2189 if "vnf" not in indata:
2190 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002191 indata["vnf"].append(
2192 {
2193 "member-vnf-index": member_vnf_index,
2194 "internal-vld": [
2195 {
2196 key: iface_info[key]
2197 for key in (
2198 "name",
2199 "vim-network-name",
2200 "vim-network-id",
2201 )
2202 if iface_info.get(key)
2203 }
2204 ],
2205 }
2206 )
tierno36ec8602018-11-02 17:27:11 +01002207
2208 @staticmethod
2209 def _create_nslcmop(nsr_id, operation, params):
2210 """
2211 Creates a ns-lcm-opp content to be stored at database.
2212 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002213 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002214 :param params: user parameters for the operation
2215 :return: dictionary following SOL005 format
2216 """
tiernob24258a2018-10-04 18:39:49 +02002217 now = time()
2218 _id = str(uuid4())
2219 nslcmop = {
2220 "id": _id,
2221 "_id": _id,
2222 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002223 "queuePosition": None,
2224 "stage": None,
2225 "errorMessage": None,
2226 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002227 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002228 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002229 "lcmOperationType": operation,
2230 "startTime": now,
2231 "isAutomaticInvocation": False,
2232 "operationParams": params,
2233 "isCancelPending": False,
2234 "links": {
2235 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002236 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002237 },
tiernob24258a2018-10-04 18:39:49 +02002238 }
2239 return nslcmop
2240
magnussonlf318b302020-01-20 18:38:18 +01002241 def _get_enabled_vims(self, session):
2242 """
2243 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2244 :param session: current session with user information
2245 """
2246 db_filter = self._get_project_filter(session)
2247 db_filter["_admin.operationalState"] = "ENABLED"
2248 vims = self.db.get_list("vim_accounts", db_filter)
2249 vimAccounts = []
2250 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002251 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002252 return vimAccounts
2253
garciadeblas4568a372021-03-24 09:19:48 +01002254 def new(
2255 self,
2256 rollback,
2257 session,
2258 indata=None,
2259 kwargs=None,
2260 headers=None,
2261 slice_object=False,
2262 ):
tiernob24258a2018-10-04 18:39:49 +02002263 """
2264 Performs a new operation over a ns
2265 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002266 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002267 :param indata: descriptor with the parameters of the operation. It must contains among others
2268 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002269 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002270 :param kwargs: used to override the indata descriptor
2271 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002272 :return: id of the nslcmops
2273 """
garciadeblas4568a372021-03-24 09:19:48 +01002274
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002275 def check_if_nsr_is_not_slice_member(session, nsr_id):
2276 nsis = None
2277 db_filter = self._get_project_filter(session)
2278 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002279 nsis = self.db.get_one(
2280 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2281 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002282 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002283 raise EngineException(
2284 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2285 nsr_id, nsis["_id"]
2286 ),
2287 http_code=HTTPStatus.CONFLICT,
2288 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002289
tiernob24258a2018-10-04 18:39:49 +02002290 try:
2291 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002292 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002293 operation = indata["lcmOperationType"]
2294 nsInstanceId = indata["nsInstanceId"]
2295
2296 validate_input(indata, self.operation_schema[operation])
2297 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002298 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002299 _filter["_id"] = nsInstanceId
2300 nsr = self.db.get_one("nsrs", _filter)
2301
2302 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002303 if operation == "terminate" and slice_object is False:
2304 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002305 if (
2306 not nsr["_admin"].get("nsState")
2307 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2308 ):
tiernob24258a2018-10-04 18:39:49 +02002309 if operation == "terminate" and indata.get("autoremove"):
2310 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002311 return (
2312 None,
2313 None,
2314 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002315 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002316 raise EngineException(
2317 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2318 nsInstanceId, operation
2319 ),
2320 HTTPStatus.CONFLICT,
2321 )
tiernob24258a2018-10-04 18:39:49 +02002322 else:
tierno65ca36d2019-02-12 19:27:52 +01002323 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002324 raise EngineException(
2325 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2326 nsInstanceId, operation
2327 ),
2328 HTTPStatus.CONFLICT,
2329 )
tiernob24258a2018-10-04 18:39:49 +02002330 self._check_ns_operation(session, nsr, operation, indata)
garciadeblasf2af4a12023-01-24 16:56:54 +01002331 if indata.get("primitive_params"):
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002332 indata["primitive_params"] = json.dumps(indata["primitive_params"])
garciadeblasf2af4a12023-01-24 16:56:54 +01002333 elif indata.get("additionalParamsForVnf"):
2334 indata["additionalParamsForVnf"] = json.dumps(
2335 indata["additionalParamsForVnf"]
2336 )
tierno36ec8602018-11-02 17:27:11 +01002337
tiernocc103432018-10-19 14:10:35 +02002338 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002339 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002340 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302341 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2342 nsr_update = {}
2343 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2344 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2345 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2346 ns_request = nsr["instantiate_params"]
garciadeblasf2af4a12023-01-24 16:56:54 +01002347 vnfr = self.db.get_one(
2348 "vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]}
2349 )
elumalai8bf978e2022-05-26 15:32:06 +05302350 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2351 vnfr_vnfd_revision = vnfr.get("revision", 1)
2352 if latest_vnfd_revision != vnfr_vnfd_revision:
2353 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
garciadeblasf2af4a12023-01-24 16:56:54 +01002354 old_db_vnfd = self.db.get_one(
2355 "vnfds_revisions", {"_id": old_vnfd_id}
2356 )
elumalai8bf978e2022-05-26 15:32:06 +05302357 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2358 new_sw_version = vnfd.get("software-version", "1.0")
2359 if new_sw_version != old_sw_version:
2360 vnf_index = vnfr["member-vnf-index-ref"]
2361 self.logger.info("nsr {}".format(nsr))
2362 for vdu in vnfd["vdu"]:
vegall18101ea2023-03-06 13:49:21 +00002363 self.nsrtopic._add_shared_volumes_to_nsr(
2364 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2365 )
garciadeblasf2af4a12023-01-24 16:56:54 +01002366 self.nsrtopic._add_flavor_to_nsr(
2367 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2368 )
elumalai8bf978e2022-05-26 15:32:06 +05302369 sw_image_id = vdu.get("sw-image-desc")
2370 if sw_image_id:
garciadeblasf2af4a12023-01-24 16:56:54 +01002371 image_data = self.nsrtopic._get_image_data_from_vnfd(
2372 vnfd, sw_image_id
2373 )
elumalai8bf978e2022-05-26 15:32:06 +05302374 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2375 for alt_image in vdu.get("alternative-sw-image-desc", ()):
garciadeblasf2af4a12023-01-24 16:56:54 +01002376 image_data = self.nsrtopic._get_image_data_from_vnfd(
2377 vnfd, alt_image
2378 )
elumalai8bf978e2022-05-26 15:32:06 +05302379 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2380 nsr_update["image"] = nsr["image"]
2381 nsr_update["flavor"] = nsr["flavor"]
vegall18101ea2023-03-06 13:49:21 +00002382 nsr_update["shared-volumes"] = nsr["shared-volumes"]
elumalai8bf978e2022-05-26 15:32:06 +05302383 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
garciadeblasf2af4a12023-01-24 16:56:54 +01002384 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(
2385 nsd, ns_request, session
2386 )
2387 vnfr_descriptor = (
2388 self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2389 nsd,
2390 vnfd,
2391 vnfd_id,
2392 vnf_index,
2393 nsr,
2394 ns_request,
2395 ns_k8s_namespace,
2396 latest_vnfd_revision,
2397 )
elumalai8bf978e2022-05-26 15:32:06 +05302398 )
2399 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002400 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002401 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002402 self.format_on_new(
2403 nslcmop_desc, session["project_id"], make_public=session["public"]
2404 )
magnussonlf318b302020-01-20 18:38:18 +01002405 if indata.get("placement-engine"):
2406 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002407 nslcmop_desc["operationParams"][
2408 "validVimAccounts"
2409 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002410 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002411 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002412 if not slice_object:
2413 self.msg.write("ns", operation, nslcmop_desc)
garciadeblas04865402024-07-12 14:44:11 +02002414 return _id, None
tiernobdebce92019-07-01 15:36:49 +00002415 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002416 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2417 # except DbException as e:
2418 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2419
Gabriel Cuba84a60df2023-10-30 14:01:54 -05002420 def cancel(self, rollback, session, indata=None, kwargs=None, headers=None):
2421 validate_input(indata, self.operation_schema["cancel"])
2422 # Override descriptor with query string kwargs
2423 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
2424 nsLcmOpOccId = indata["nsLcmOpOccId"]
2425 cancelMode = indata["cancelMode"]
2426 # get nslcmop from nsLcmOpOccId
2427 _filter = BaseTopic._get_project_filter(session)
2428 _filter["_id"] = nsLcmOpOccId
2429 nslcmop = self.db.get_one("nslcmops", _filter)
2430 # Fail is this is not an ongoing nslcmop
2431 if nslcmop.get("operationState") not in [
2432 "STARTING",
2433 "PROCESSING",
2434 "ROLLING_BACK",
2435 ]:
2436 raise EngineException(
2437 "Operation is not in STARTING, PROCESSING or ROLLING_BACK state",
2438 http_code=HTTPStatus.CONFLICT,
2439 )
2440 nsInstanceId = nslcmop["nsInstanceId"]
2441 update_dict = {
2442 "isCancelPending": True,
2443 "cancelMode": cancelMode,
2444 }
2445 self.db.set_one(
2446 "nslcmops", q_filter=_filter, update_dict=update_dict, fail_on_empty=False
2447 )
2448 data = {
2449 "_id": nsLcmOpOccId,
2450 "nsInstanceId": nsInstanceId,
2451 "cancelMode": cancelMode,
2452 }
2453 self.msg.write("nslcmops", "cancel", data)
2454
tiernobee3bad2019-12-05 12:26:01 +00002455 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002456 raise EngineException(
2457 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2458 )
tiernob24258a2018-10-04 18:39:49 +02002459
tierno65ca36d2019-02-12 19:27:52 +01002460 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002461 raise EngineException(
2462 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2463 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002464
2465
2466class NsiTopic(BaseTopic):
2467 topic = "nsis"
2468 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002469 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002470
delacruzramo32bab472019-09-13 12:24:22 +02002471 def __init__(self, db, fs, msg, auth):
2472 BaseTopic.__init__(self, db, fs, msg, auth)
2473 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002474
Felipe Vicensc37b3842019-01-12 12:24:42 +01002475 @staticmethod
2476 def _format_ns_request(ns_request):
2477 formated_request = copy(ns_request)
2478 # TODO: Add request params
2479 return formated_request
2480
2481 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002482 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002483 """
2484 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002485 :param slice_request: User instantiation additional parameters
2486 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002487 """
tiernofd160572019-01-21 10:41:37 +00002488 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2489 if additional_params:
2490 for k, v in additional_params.items():
2491 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002492 raise EngineException(
2493 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2494 k
2495 )
2496 )
tiernofd160572019-01-21 10:41:37 +00002497 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002498 raise EngineException(
2499 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2500 k
2501 )
2502 )
tiernofd160572019-01-21 10:41:37 +00002503 if isinstance(v, (dict, tuple, list)):
2504 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002505 return additional_params
2506
tiernob4844ab2019-05-23 08:42:12 +00002507 def check_conflict_on_del(self, session, _id, db_content):
2508 """
2509 Check that NSI is not instantiated
2510 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2511 :param _id: nsi internal id
2512 :param db_content: The database content of the _id
2513 :return: None or raises EngineException with the conflict
2514 """
tierno65ca36d2019-02-12 19:27:52 +01002515 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002516 return
tiernob4844ab2019-05-23 08:42:12 +00002517 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002518 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002519 raise EngineException(
2520 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2521 "Launch 'terminate' operation first; or force deletion".format(_id),
2522 http_code=HTTPStatus.CONFLICT,
2523 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002524
tiernobee3bad2019-12-05 12:26:01 +00002525 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002526 """
tiernob4844ab2019-05-23 08:42:12 +00002527 Deletes associated nsilcmops from database. Deletes associated filesystem.
2528 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002529 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002530 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002531 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002532 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002533 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002534 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002535
Felipe Vicens09e65422019-01-22 15:06:46 +01002536 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002537 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002538 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2539 nsr_id = nsrs_detailed_item["nsrId"]
2540 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002541 _filter = {
2542 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2543 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2544 "_id.ne": nsir["_id"],
2545 }
2546 nsi = self.db.get_one(
2547 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2548 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002549 if nsi: # last one using nsr
2550 continue
2551 try:
garciadeblas4568a372021-03-24 09:19:48 +01002552 self.nsrTopic.delete(
2553 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2554 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002555 except (DbException, EngineException) as e:
2556 if e.http_code == HTTPStatus.NOT_FOUND:
2557 pass
2558 else:
2559 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002560
tiernob4844ab2019-05-23 08:42:12 +00002561 # delete related nsilcmops database entries
2562 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002563
tiernob4844ab2019-05-23 08:42:12 +00002564 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002565 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002566 if nsir_admin and nsir_admin.get("nst-id"):
2567 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002568 nsis_list = self.db.get_one(
2569 "nsis",
2570 {"nst-id": nsir_admin["nst-id"]},
2571 fail_on_empty=False,
2572 fail_on_more=False,
2573 )
tiernob4844ab2019-05-23 08:42:12 +00002574 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002575 self.db.set_one(
2576 "nsts",
2577 {"_id": nsir_admin["nst-id"]},
2578 {"_admin.usageState": "NOT_IN_USE"},
2579 )
tiernob4844ab2019-05-23 08:42:12 +00002580
tierno65ca36d2019-02-12 19:27:52 +01002581 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002582 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002583 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002584 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002585 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002586 :param indata: params to be used for the nsir
2587 :param kwargs: used to override the indata descriptor
2588 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002589 :return: the _id of nsi descriptor created at database
2590 """
2591
garciadeblasf2af4a12023-01-24 16:56:54 +01002592 step = "checking quotas" # first step must be defined outside try
Felipe Vicensb57758d2018-10-16 16:00:20 +02002593 try:
delacruzramo32bab472019-09-13 12:24:22 +02002594 self.check_quota(session)
2595
tierno99d4b172019-07-02 09:28:40 +00002596 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002597 slice_request = self._remove_envelop(indata)
2598 # Override descriptor with query string kwargs
2599 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002600 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002601
Felipe Vicensb57758d2018-10-16 16:00:20 +02002602 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002603 step = "getting nstd id='{}' from database".format(
2604 slice_request.get("nstId")
2605 )
tiernob4844ab2019-05-23 08:42:12 +00002606 _filter = self._get_project_filter(session)
2607 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002608 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002609 # check NST is not disabled
2610 step = "checking NST operationalState"
2611 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002612 raise EngineException(
2613 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2614 "instance".format(slice_request["nstId"]),
2615 http_code=HTTPStatus.CONFLICT,
2616 )
tiernob4844ab2019-05-23 08:42:12 +00002617 del _filter["_id"]
2618
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002619 # check NSD is not disabled
2620 step = "checking operationalState"
2621 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002622 raise EngineException(
2623 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2624 "a network slice".format(slice_request["nstId"]),
2625 http_code=HTTPStatus.CONFLICT,
2626 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002627
Felipe Vicens07f31722018-10-29 15:16:44 +01002628 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002629 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002630 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002631 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002632
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002633 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002634 nsi_descriptor = {
2635 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002636 "name": slice_request["nsiName"],
2637 "description": slice_request.get("nsiDescription", ""),
2638 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002639 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002640 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002641 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002642 "nsr-ref-list": [],
2643 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002644 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002645 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002646 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002647
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002648 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002649 self.format_on_new(
2650 nsi_descriptor, session["project_id"], make_public=session["public"]
2651 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002652 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2653 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002654 nsi_descriptor["_admin"]["deployed"] = {}
2655 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2656 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2657
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002658 # Creating netslice-vld for the RO.
2659 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002660
2661 # Building the vlds list to be deployed
2662 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002663 nsi_vlds = []
2664
2665 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2666 # Getting template Instantiation parameters from NST
2667 nsi_vld = deepcopy(netslice_vlds)
2668 nsi_vld["shared-nsrs-list"] = []
2669 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2670 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002671
2672 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002673 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002674 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002675 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002676
Felipe Vicens09e65422019-01-22 15:06:46 +01002677 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002678 for member_ns in nstd["netslice-subnet"]:
2679 nsd_id = member_ns["nsd-ref"]
2680 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002681 member_ns["nsd-ref"], member_ns["id"]
2682 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002683 if nsd_id not in needed_nsds:
2684 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002685 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002686 nsd = self.db.get_one(
2687 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2688 )
tiernob4844ab2019-05-23 08:42:12 +00002689 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002690 nsd.pop("_admin")
2691 needed_nsds[nsd_id] = nsd
2692 else:
2693 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002694 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2695 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002696
Felipe Vicensb57758d2018-10-16 16:00:20 +02002697 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002698 member_ns["nsd-ref"], member_ns["id"]
2699 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002700
Felipe Vicens07f31722018-10-29 15:16:44 +01002701 # creates Network Services records (NSRs)
2702 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002703 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002704 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002705 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002706 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002707 # Check if the netslice-subnet is shared and if it is share if the nss exists
2708 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002709 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002710 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002711 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002712 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2713 "nsd-ref"
2714 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002715 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002716 nsi = self.db.get_one(
2717 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2718 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002719 if nsi and service.get("is-shared-nss"):
2720 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2721 for nsrs_detailed_item in nsrs_detailed_list:
2722 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002723 if nsrs_detailed_item["nss-id"] == service["id"]:
2724 _id_nsr = nsrs_detailed_item["nsrId"]
2725 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002726 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2727 if netslice_subnet["nss-id"] == service["id"]:
2728 indata_ns = netslice_subnet
2729 break
2730 else:
2731 indata_ns = {}
2732 if service.get("instantiation-parameters"):
2733 indata_ns = deepcopy(service["instantiation-parameters"])
2734 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002735
Felipe Vicens09e65422019-01-22 15:06:46 +01002736 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002737 indata_ns["nsName"] = (
2738 slice_request.get("nsiName") + "." + service["id"]
2739 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002740 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2741 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002742 if slice_request.get("ssh_keys"):
2743 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002744
Felipe Vicens09e65422019-01-22 15:06:46 +01002745 if ns_params:
2746 for ns_param in ns_params:
2747 if ns_param.get("id") == service["id"]:
2748 copy_ns_param = deepcopy(ns_param)
2749 del copy_ns_param["id"]
2750 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002751 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002752
2753 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002754 _id_nsr, _ = self.nsrTopic.new(
2755 rollback, session, indata_ns, kwargs, headers
2756 )
2757 nsrs_item = {
2758 "nsrId": _id_nsr,
2759 "shared": service.get("is-shared-nss"),
2760 "nsd-id": service["nsd-ref"],
2761 "nss-id": service["id"],
2762 "nslcmop_instantiate": None,
2763 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002764 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002765 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002766 nsi_netslice_subnet.append(indata_ns)
2767 nsr_ref = {"nsr-ref": _id_nsr}
2768 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002769
2770 # Adding the nsrs list to the nsi
2771 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002772 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002773 self.db.set_one(
2774 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2775 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002776
Felipe Vicens07f31722018-10-29 15:16:44 +01002777 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002778 self.db.create("nsis", nsi_descriptor)
2779 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002780 return nsi_id, None
garciadeblasf2af4a12023-01-24 16:56:54 +01002781 except ValidationError as e:
2782 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
garciadeblas4568a372021-03-24 09:19:48 +01002783 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2784 self.logger.exception(
2785 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2786 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002787 raise EngineException("Error {}: {}".format(step, e))
Felipe Vicensb57758d2018-10-16 16:00:20 +02002788
tierno65ca36d2019-02-12 19:27:52 +01002789 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002790 raise EngineException(
2791 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2792 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002793
2794
2795class NsiLcmOpTopic(BaseTopic):
2796 topic = "nsilcmops"
2797 topic_msg = "nsi"
2798 operation_schema = { # mapping between operation and jsonschema to validate
2799 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002800 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002801 }
garciadeblas4568a372021-03-24 09:19:48 +01002802
delacruzramo32bab472019-09-13 12:24:22 +02002803 def __init__(self, db, fs, msg, auth):
2804 BaseTopic.__init__(self, db, fs, msg, auth)
2805 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002806
2807 def _check_nsi_operation(self, session, nsir, operation, indata):
2808 """
2809 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002810 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002811 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2812 :param indata: descriptor with the parameters of the operation
2813 :return: None
2814 """
2815 nsds = {}
2816 nstd = nsir["network-slice-template"]
2817
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002818 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002819 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002820 for netslice_subnet in nstd["netslice-subnet"]:
2821 if nstId == netslice_subnet["id"]:
2822 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002823 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002824 _filter = self._get_project_filter(session)
2825 _filter["id"] = nsd_id
2826 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002827 return nsds[nsd_id]
2828 else:
garciadeblas4568a372021-03-24 09:19:48 +01002829 raise EngineException(
2830 "Invalid parameter nstId='{}' is not one of the "
2831 "nst:netslice-subnet".format(nstId)
2832 )
2833
Felipe Vicens07f31722018-10-29 15:16:44 +01002834 if operation == "instantiate":
2835 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002836 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002837 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002838
2839 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2840 now = time()
2841 _id = str(uuid4())
2842 nsilcmop = {
2843 "id": _id,
2844 "_id": _id,
2845 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2846 "statusEnteredTime": now,
2847 "netsliceInstanceId": netsliceInstanceId,
2848 "lcmOperationType": operation,
2849 "startTime": now,
2850 "isAutomaticInvocation": False,
2851 "operationParams": params,
2852 "isCancelPending": False,
2853 "links": {
2854 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002855 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2856 + netsliceInstanceId,
2857 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002858 }
2859 return nsilcmop
2860
Felipe Vicens09e65422019-01-22 15:06:46 +01002861 def add_shared_nsr_2vld(self, nsir, nsr_item):
2862 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2863 if nst_sb_item.get("is-shared-nss"):
2864 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2865 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2866 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002867 for admin_vld_nss_cp_ref_item in admin_vld_item[
2868 "nss-connection-point-ref"
2869 ]:
2870 if (
2871 admin_subnet_item["nss-id"]
2872 == admin_vld_nss_cp_ref_item["nss-ref"]
2873 ):
2874 if (
2875 not nsr_item["nsrId"]
2876 in admin_vld_item["shared-nsrs-list"]
2877 ):
2878 admin_vld_item["shared-nsrs-list"].append(
2879 nsr_item["nsrId"]
2880 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002881 break
2882 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002883 self.db.set_one(
2884 "nsis",
2885 {"_id": nsir["_id"]},
2886 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2887 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002888
tierno65ca36d2019-02-12 19:27:52 +01002889 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002890 """
2891 Performs a new operation over a ns
2892 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002893 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002894 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002895 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002896 operation: it can be: instantiate, terminate, action, TODO: update, heal
2897 :param kwargs: used to override the indata descriptor
2898 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002899 :return: id of the nslcmops
2900 """
2901 try:
2902 # Override descriptor with query string kwargs
2903 self._update_input_with_kwargs(indata, kwargs)
2904 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002905 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002906 validate_input(indata, self.operation_schema[operation])
2907
Felipe Vicens126af572019-06-05 19:13:04 +02002908 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002909 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002910 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002911 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002912 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002913 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002914
2915 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002916 if (
2917 not nsir["_admin"].get("nsiState")
2918 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2919 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002920 if operation == "terminate" and indata.get("autoremove"):
2921 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002922 return (
2923 None,
2924 None,
2925 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002926 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002927 raise EngineException(
2928 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2929 netsliceInstanceId, operation
2930 ),
2931 HTTPStatus.CONFLICT,
2932 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002933 else:
tierno65ca36d2019-02-12 19:27:52 +01002934 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002935 raise EngineException(
2936 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2937 netsliceInstanceId, operation
2938 ),
2939 HTTPStatus.CONFLICT,
2940 )
2941
Felipe Vicens07f31722018-10-29 15:16:44 +01002942 # Creating all the NS_operation (nslcmop)
2943 # Get service list from db
2944 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2945 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002946 # nslcmops_item = None
2947 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002948 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002949 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002950 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002951 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002952 _filter[
2953 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2954 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002955 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002956 nsi = self.db.get_one(
2957 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2958 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002959 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002960 _update = {
2961 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2962 index
2963 ): None
2964 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002965 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002966 if (
2967 nsi
2968 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002969 continue # do not create nsilcmop
2970 else: # instantiate
2971 # looks the first nsi fulfilling the conditions but not being the current NSIR
2972 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002973 nsi_nsr_item = next(
2974 n
2975 for n in nsi["_admin"]["nsrs-detailed-list"]
2976 if n["nsrId"] == nsr_id
2977 and n["shared"]
2978 and n["nslcmop_instantiate"]
2979 )
tierno40f742b2020-06-23 15:25:26 +00002980 self.add_shared_nsr_2vld(nsir, nsr_item)
2981 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002982 _update = {
2983 "_admin.nsrs-detailed-list.{}".format(
2984 index
2985 ): nsi_nsr_item
2986 }
tierno40f742b2020-06-23 15:25:26 +00002987 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2988 # continue to not create nslcmop since nsrs is shared and nsrs was created
2989 continue
2990 else:
2991 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002992
tierno40f742b2020-06-23 15:25:26 +00002993 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002994 try:
tierno0b8752f2020-05-12 09:42:02 +00002995 indata_ns = {
2996 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002997 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002998 # Including netslice_id in the ns instantiate Operation
2999 "netsliceInstanceId": netsliceInstanceId,
3000 }
3001 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00003002 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00003003 indata_ns.update(service["instantiate_params"])
3004
tierno99d4b172019-07-02 09:28:40 +00003005 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01003006 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01003007 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
3008 rollback, session, indata_ns, None, headers, slice_object=True
3009 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003010 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00003011 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01003012 _update = {
3013 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3014 index
3015 ): nslcmop
3016 }
tierno40f742b2020-06-23 15:25:26 +00003017 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01003018 except (DbException, EngineException) as e:
3019 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01003020 self.logger.info(
3021 logging_prefix
3022 + "skipping NS={} because not found".format(nsr_id)
3023 )
Felipe Vicens09e65422019-01-22 15:06:46 +01003024 pass
3025 else:
3026 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01003027
3028 # Creates nsilcmop
3029 indata["nslcmops_ids"] = nslcmops
3030 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01003031
garciadeblas4568a372021-03-24 09:19:48 +01003032 nsilcmop_desc = self._create_nsilcmop(
3033 session, netsliceInstanceId, operation, indata
3034 )
3035 self.format_on_new(
3036 nsilcmop_desc, session["project_id"], make_public=session["public"]
3037 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003038 _id = self.db.create("nsilcmops", nsilcmop_desc)
3039 rollback.append({"topic": "nsilcmops", "_id": _id})
3040 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00003041 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01003042 except ValidationError as e:
3043 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01003044
tiernobee3bad2019-12-05 12:26:01 +00003045 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01003046 raise EngineException(
3047 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3048 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003049
tierno65ca36d2019-02-12 19:27:52 +01003050 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01003051 raise EngineException(
3052 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3053 )