blob: d7f826f191f7edafbacf5b8c824356391282c27d [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernob24258a2018-10-04 18:39:49 +020016# import logging
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +010017import json
tiernob24258a2018-10-04 18:39:49 +020018from uuid import uuid4
19from http import HTTPStatus
20from time import time
tiernocc103432018-10-19 14:10:35 +020021from copy import copy, deepcopy
garciadeblas4568a372021-03-24 09:19:48 +010022from osm_nbi.validation import (
23 validate_input,
24 ValidationError,
25 ns_instantiate,
26 ns_terminate,
27 ns_action,
28 ns_scale,
aticig544a2ae2022-04-05 09:00:17 +030029 ns_update,
garciadeblas0964edf2022-02-11 00:43:44 +010030 ns_heal,
garciadeblas4568a372021-03-24 09:19:48 +010031 nsi_instantiate,
elumalai8e3806c2022-04-28 17:26:24 +053032 ns_migrate,
govindarajul519da482022-04-29 19:05:22 +053033 ns_verticalscale,
garciadeblas4568a372021-03-24 09:19:48 +010034)
35from osm_nbi.base_topic import (
36 BaseTopic,
37 EngineException,
38 get_iterable,
39 deep_get,
40 increment_ip_mac,
aticig2b5e1232022-08-10 17:30:12 +030041 update_descriptor_usage_state,
garciadeblas4568a372021-03-24 09:19:48 +010042)
tiernobee085c2018-12-12 17:03:04 +000043from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010044from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000045from osm_common.msgbase import MsgException
46from osm_common.fsbase import FsException
garciaale7cbd03c2020-11-27 10:38:35 -030047from osm_nbi import utils
garciadeblas4568a372021-03-24 09:19:48 +010048from re import (
49 match,
50) # For checking that additional parameter names are valid Jinja2 identifiers
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
garciadeblasf2af4a12023-01-24 16:56:54 +0100443 def _add_flavor_to_nsr(
444 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
445 ):
elumalai6c5ea6b2022-04-25 22:27:59 +0530446 flavor_data = {}
447 guest_epa = {}
448 # Find this vdu compute and storage descriptors
449 vdu_virtual_compute = {}
450 vdu_virtual_storage = {}
451 for vcd in vnfd.get("virtual-compute-desc", ()):
452 if vcd.get("id") == vdu.get("virtual-compute-desc"):
453 vdu_virtual_compute = vcd
454 for vsd in vnfd.get("virtual-storage-desc", ()):
455 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
456 vdu_virtual_storage = vsd
457 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblasf2af4a12023-01-24 16:56:54 +0100458 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
elumalai6c5ea6b2022-04-25 22:27:59 +0530459 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
460 "num-virtual-cpu"
461 ]
462 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
463 flavor_data["memory-mb"] = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100464 float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
elumalai6c5ea6b2022-04-25 22:27:59 +0530465 )
466 if vdu_virtual_storage.get("size-of-storage"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100467 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530468 # Get this vdu EPA info for guest_epa
469 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100470 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530471 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
472 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
473 if vcpu_pinning.get("thread-policy"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100474 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530475 if vcpu_pinning.get("policy"):
476 cpu_policy = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100477 "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
elumalai6c5ea6b2022-04-25 22:27:59 +0530478 )
479 guest_epa["cpu-pinning-policy"] = cpu_policy
480 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100481 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
482 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
483 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"][
484 "mempage-size"
elumalai6c5ea6b2022-04-25 22:27:59 +0530485 ]
garciadeblasf2af4a12023-01-24 16:56:54 +0100486 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
487 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"][
488 "numa-node-policy"
489 ]
elumalai6c5ea6b2022-04-25 22:27:59 +0530490 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100491 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530492
493 if guest_epa:
494 flavor_data["guest-epa"] = guest_epa
495
elumalai99078a92022-07-05 17:53:59 +0530496 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +0100497 flavor_data["name"] = (
498 vdu["id"][:56] + "-" + member_vnf_index + "-" + str(revision) + "-flv"
499 )
elumalai6c5ea6b2022-04-25 22:27:59 +0530500 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
501 nsr_descriptor["flavor"].append(flavor_data)
502
bravofe76b8822021-02-26 16:57:52 -0300503 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300504 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100505 additional_params, _ = self._format_additional_params(
506 ns_request, descriptor=nsd
507 )
garciaale7cbd03c2020-11-27 10:38:35 -0300508
509 nsr_descriptor = {
510 "name": ns_request["nsName"],
511 "name-ref": ns_request["nsName"],
512 "short-name": ns_request["nsName"],
513 "admin-status": "ENABLED",
514 "nsState": "NOT_INSTANTIATED",
515 "currentOperation": "IDLE",
516 "currentOperationID": None,
517 "errorDescription": None,
518 "errorDetail": None,
519 "deploymentStatus": None,
520 "configurationStatus": None,
521 "vcaStatus": None,
522 "nsd": {k: v for k, v in nsd.items()},
523 "datacenter": ns_request["vimAccountId"],
524 "resource-orchestrator": "osmopenmano",
525 "description": ns_request.get("nsDescription", ""),
526 "constituent-vnfr-ref": [],
527 "operational-status": "init", # typedef ns-operational-
528 "config-status": "init", # typedef config-states
529 "detailed-status": "scheduled",
530 "orchestration-progress": {},
531 "create-time": now,
532 "nsd-name-ref": nsd["name"],
533 "operational-events": [], # "id", "timestamp", "description", "event",
534 "nsd-ref": nsd["id"],
535 "nsd-id": nsd["_id"],
536 "vnfd-id": [],
537 "instantiate_params": self._format_ns_request(ns_request),
538 "additionalParamsForNs": additional_params,
539 "ns-instance-config-ref": nsr_id,
540 "id": nsr_id,
541 "_id": nsr_id,
542 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
543 "flavor": [],
544 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100545 "affinity-or-anti-affinity-group": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300546 }
beierlmbc5a5242022-05-17 21:25:29 -0400547 if "revision" in nsd["_admin"]:
548 nsr_descriptor["revision"] = nsd["_admin"]["revision"]
549
garciaale7cbd03c2020-11-27 10:38:35 -0300550 ns_request["nsr_id"] = nsr_id
551 if ns_request and ns_request.get("config-units"):
552 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300553 # Create vld
554 if nsd.get("virtual-link-desc"):
555 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
556 # Fill each vld with vnfd-connection-point-ref data
557 # TODO: Change for multiple df support
558 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
559 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
560 for vnf_profile in vnf_profiles:
561 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
562 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100563 all_vld_connection_point_data[
564 vlc.get("virtual-link-profile-id")
565 ].append(
566 {
567 "member-vnf-index-ref": cpd.get(
568 "constituent-base-element-id"
569 ),
570 "vnfd-connection-point-ref": cpd.get(
571 "constituent-cpd-id"
572 ),
573 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
574 }
575 )
garciaale7cbd03c2020-11-27 10:38:35 -0300576
bravofe76b8822021-02-26 16:57:52 -0300577 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400578 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300579
580 for vdu in vnfd.get("vdu", ()):
elumalai99078a92022-07-05 17:53:59 +0530581 member_vnf_index = vnf_profile.get("id")
582 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor, member_vnf_index)
garciaale7cbd03c2020-11-27 10:38:35 -0300583 sw_image_id = vdu.get("sw-image-desc")
584 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000585 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
586 self._add_image_to_nsr(nsr_descriptor, image_data)
587
588 # also add alternative images to the list of images
589 for alt_image in vdu.get("alternative-sw-image-desc", ()):
590 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
591 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300592
Alexis Romero03fb5842022-03-11 15:53:40 +0100593 # Add Affinity or Anti-affinity group information to NSR
594 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200595 affinity_group_prefix_name = "{}-{}".format(
596 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
597 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100598
599 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200600 affinity_group_data = {}
601 for affinity_group in vdu_profile.get(
602 "affinity-or-anti-affinity-group", ()
603 ):
604 affinity_group_data = (
605 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
606 vnfd, affinity_group["id"]
607 )
608 )
609 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
610 self._add_affinity_or_anti_affinity_group_to_nsr(
611 nsr_descriptor,
612 affinity_group_data,
613 affinity_group_prefix_name,
614 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100615
garciaale7cbd03c2020-11-27 10:38:35 -0300616 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100617 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
618 vld.get("id"), []
619 )
garciaale7cbd03c2020-11-27 10:38:35 -0300620 vld["name"] = vld["id"]
621 nsr_descriptor["vld"] = nsr_vld
622
623 return nsr_descriptor
624
Alexis Romeroee31f532022-04-26 19:10:21 +0200625 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
626 self, vnfd, affinity_group_id
627 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100628 """
629 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
630 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200631 affinity_group = utils.find_in_list(
632 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
633 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100634 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200635 affinity_group_data = {}
636 if affinity_group:
637 if affinity_group.get("id"):
638 affinity_group_data["ag-id"] = affinity_group["id"]
639 if affinity_group.get("type"):
640 affinity_group_data["type"] = affinity_group["type"]
641 if affinity_group.get("scope"):
642 affinity_group_data["scope"] = affinity_group["scope"]
643 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100644
Alexis Romeroee31f532022-04-26 19:10:21 +0200645 def _add_affinity_or_anti_affinity_group_to_nsr(
646 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
647 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100648 """
649 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
650 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200651 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100652 (
653 f
654 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200655 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100656 ),
657 None,
658 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200659 if not affinity_group:
660 affinity_group_data["id"] = str(
661 len(nsr_descriptor["affinity-or-anti-affinity-group"])
662 )
663 affinity_group_data["name"] = "{}-{}".format(
664 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
665 )
666 nsr_descriptor["affinity-or-anti-affinity-group"].append(
667 affinity_group_data
668 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100669
lloretgalleg28c13b62021-02-08 11:48:48 +0000670 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100671 sw_image_desc = utils.find_in_list(
672 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
673 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000674 image_data = {}
675 if sw_image_desc.get("image"):
676 image_data["image"] = sw_image_desc["image"]
677 if sw_image_desc.get("checksum"):
678 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
679 if sw_image_desc.get("vim-type"):
680 image_data["vim-type"] = sw_image_desc["vim-type"]
681 return image_data
682
683 def _add_image_to_nsr(self, nsr_descriptor, image_data):
684 """
685 Adds image to nsr checking first it is not already added
686 """
garciadeblas4568a372021-03-24 09:19:48 +0100687 img = next(
688 (
689 f
690 for f in nsr_descriptor["image"]
691 if all(f.get(k) == image_data[k] for k in image_data)
692 ),
693 None,
694 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000695 if not img:
696 image_data["id"] = str(len(nsr_descriptor["image"]))
697 nsr_descriptor["image"].append(image_data)
698
garciadeblas4568a372021-03-24 09:19:48 +0100699 def _create_vnfr_descriptor_from_vnfd(
700 self,
701 nsd,
702 vnfd,
703 vnfd_id,
704 vnf_index,
705 nsr_descriptor,
706 ns_request,
707 ns_k8s_namespace,
elumalai99078a92022-07-05 17:53:59 +0530708 revision=None,
garciadeblas4568a372021-03-24 09:19:48 +0100709 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300710 vnfr_id = str(uuid4())
711 nsr_id = nsr_descriptor["id"]
712 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100713 additional_params, vnf_params = self._format_additional_params(
714 ns_request, vnf_index, descriptor=vnfd
715 )
garciaale7cbd03c2020-11-27 10:38:35 -0300716
717 vnfr_descriptor = {
718 "id": vnfr_id,
719 "_id": vnfr_id,
720 "nsr-id-ref": nsr_id,
721 "member-vnf-index-ref": vnf_index,
722 "additionalParamsForVnf": additional_params,
723 "created-time": now,
724 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
725 "vnfd-ref": vnfd_id,
726 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
727 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200728 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300729 "vdur": [],
730 "connection-point": [],
731 "ip-address": None, # mgmt-interface filled by LCM
732 }
beierlmcee2ebf2022-03-29 17:42:48 -0400733
734 # Revision backwards compatility. Only specify the revision in the record if
735 # the original VNFD has a revision.
736 if "revision" in vnfd:
737 vnfr_descriptor["revision"] = vnfd["revision"]
738
garciaale7cbd03c2020-11-27 10:38:35 -0300739 vnf_k8s_namespace = ns_k8s_namespace
740 if vnf_params:
741 if vnf_params.get("k8s-namespace"):
742 vnf_k8s_namespace = vnf_params["k8s-namespace"]
743 if vnf_params.get("config-units"):
744 vnfr_descriptor["config-units"] = vnf_params["config-units"]
745
746 # Create vld
747 if vnfd.get("int-virtual-link-desc"):
748 vnfr_descriptor["vld"] = []
749 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
750 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
751
752 for cp in vnfd.get("ext-cpd", ()):
753 vnf_cp = {
754 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100755 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
756 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300757 "id": cp.get("id"),
758 # "ip-address", "mac-address" # filled by LCM
759 # vim-id # TODO it would be nice having a vim port id
760 }
761 vnfr_descriptor["connection-point"].append(vnf_cp)
762
763 # Create k8s-cluster information
764 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
765 if vnfd.get("k8s-cluster"):
766 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
767 all_k8s_cluster_nets_cpds = {}
768 for cpd in get_iterable(vnfd.get("ext-cpd")):
769 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100770 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
771 "id"
772 )
garciaale7cbd03c2020-11-27 10:38:35 -0300773 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
774 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100775 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
776 net.get("id")
777 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300778
779 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300780 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100781 additional_params, kdu_params = self._format_additional_params(
782 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
783 )
garciaale7cbd03c2020-11-27 10:38:35 -0300784 kdu_k8s_namespace = vnf_k8s_namespace
785 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
786 if kdu_params and kdu_params.get("k8s-namespace"):
787 kdu_k8s_namespace = kdu_params["k8s-namespace"]
788
romeromonserbfebfc02021-05-28 10:51:35 +0200789 kdu_deployment_name = ""
790 if kdu_params and kdu_params.get("kdu-deployment-name"):
791 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
792
garciaale7cbd03c2020-11-27 10:38:35 -0300793 kdur = {
794 "additionalParams": additional_params,
795 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200796 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000797 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300798 # TODO "name": "" Name of the VDU in the VIM
799 "ip-address": None, # mgmt-interface filled by LCM
800 "k8s-cluster": {},
801 }
802 if kdu_params and kdu_params.get("config-units"):
803 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000804 if kdu.get("helm-version"):
805 kdur["helm-version"] = kdu["helm-version"]
806 for k8s_type in ("helm-chart", "juju-bundle"):
807 if kdu.get(k8s_type):
808 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300809 if not vnfr_descriptor.get("kdur"):
810 vnfr_descriptor["kdur"] = []
811 vnfr_descriptor["kdur"].append(kdur)
812
813 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300814
garciaale7cbd03c2020-11-27 10:38:35 -0300815 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300816 vdu_mgmt_cp = []
817 try:
garciadeblas4568a372021-03-24 09:19:48 +0100818 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
819 "operate-vnf-op-config"
820 ]["day1-2"]
821 vdu_config = utils.find_in_list(
822 configs, lambda config: config["id"] == vdu["id"]
823 )
bravoff3c39552021-02-24 17:22:24 -0300824 except Exception:
825 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400826
827 try:
828 vdu_instantiation_level = utils.find_in_list(
829 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100830 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400831 )
832 except Exception:
833 vdu_instantiation_level = None
834
bravoff3c39552021-02-24 17:22:24 -0300835 if vdu_config:
836 external_connection_ee = utils.filter_in_list(
837 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100838 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300839 )
840 for ee in external_connection_ee:
841 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
842
garciaale7cbd03c2020-11-27 10:38:35 -0300843 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100844 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
845 )
bravof65e22e52021-11-10 17:58:58 -0300846
847 try:
848 vdu_virtual_storage_descriptors = utils.filter_in_list(
849 vnfd.get("virtual-storage-desc", []),
garciadeblasf2af4a12023-01-24 16:56:54 +0100850 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"],
bravof65e22e52021-11-10 17:58:58 -0300851 )
852 except Exception:
853 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300854 vdur = {
855 "vdu-id-ref": vdu["id"],
856 # TODO "name": "" Name of the VDU in the VIM
857 "ip-address": None, # mgmt-interface filled by LCM
858 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
859 "internal-connection-point": [],
860 "interfaces": [],
861 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100862 "vdu-name": vdu["name"],
garciadeblasf2af4a12023-01-24 16:56:54 +0100863 "virtual-storages": vdu_virtual_storage_descriptors,
garciaale7cbd03c2020-11-27 10:38:35 -0300864 }
865 if vdu_params and vdu_params.get("config-units"):
866 vdur["config-units"] = vdu_params["config-units"]
867 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100868 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
869 "boot-data-drive"
870 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300871 if vdu.get("pdu-type"):
872 vdur["pdu-type"] = vdu["pdu-type"]
873 vdur["name"] = vdu["pdu-type"]
874 # TODO volumes: name, volume-id
875 for icp in vdu.get("int-cpd", ()):
876 vdu_icp = {
877 "id": icp["id"],
878 "connection-point-id": icp["id"],
879 "name": icp.get("id"),
880 }
bravof35766442021-02-04 14:58:04 -0300881
garciaale7cbd03c2020-11-27 10:38:35 -0300882 vdur["internal-connection-point"].append(vdu_icp)
883
884 for iface in icp.get("virtual-network-interface-requirement", ()):
aticigc9c03392022-06-16 01:39:44 +0300885 # Name, mac-address and interface position is taken from VNFD
886 # and included into VNFR. By this way RO can process this information
887 # while creating the VDU.
Gulsum Atici9af2a472023-03-28 17:50:48 +0300888 iface_fields = ("name", "mac-address", "position", "ip-address")
garciadeblas4568a372021-03-24 09:19:48 +0100889 vdu_iface = {
890 x: iface[x] for x in iface_fields if iface.get(x) is not None
891 }
garciaale7cbd03c2020-11-27 10:38:35 -0300892
893 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100894 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100895 vdu_iface["port-security-enabled"] = icp[
896 "port-security-enabled"
897 ]
sousaedu003844e2021-03-02 00:19:15 +0100898
899 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100900 vdu_iface["port-security-disable-strategy"] = icp[
901 "port-security-disable-strategy"
902 ]
sousaedu003844e2021-03-02 00:19:15 +0100903
garciaale7cbd03c2020-11-27 10:38:35 -0300904 for ext_cp in vnfd.get("ext-cpd", ()):
905 if not ext_cp.get("int-cpd"):
906 continue
907 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
908 continue
909 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100910 vdu_iface["external-connection-point-ref"] = ext_cp.get(
911 "id"
912 )
sousaedu003844e2021-03-02 00:19:15 +0100913
914 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100915 vdu_iface["port-security-enabled"] = ext_cp[
916 "port-security-enabled"
917 ]
sousaedu003844e2021-03-02 00:19:15 +0100918
919 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100920 vdu_iface["port-security-disable-strategy"] = ext_cp[
921 "port-security-disable-strategy"
922 ]
sousaedu003844e2021-03-02 00:19:15 +0100923
garciaale7cbd03c2020-11-27 10:38:35 -0300924 break
925
garciadeblas4568a372021-03-24 09:19:48 +0100926 if (
927 vnfd_mgmt_cp
928 and vdu_iface.get("external-connection-point-ref")
929 == vnfd_mgmt_cp
930 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300931 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300932 vdu_iface["mgmt-interface"] = True
933
934 for ecp in vdu_mgmt_cp:
935 if vdu_iface.get("external-connection-point-ref") == ecp:
936 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300937
938 if iface.get("virtual-interface"):
939 vdu_iface.update(deepcopy(iface["virtual-interface"]))
940
941 # look for network where this interface is connected
942 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
943 if iface_ext_cp:
944 # TODO: Change for multiple df support
945 for df in get_iterable(nsd.get("df")):
946 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100947 for vlc_index, vlc in enumerate(
948 get_iterable(
949 vnf_profile.get("virtual-link-connectivity")
950 )
951 ):
952 for cpd in get_iterable(
953 vlc.get("constituent-cpd-id")
954 ):
955 if (
956 cpd.get("constituent-cpd-id")
957 == iface_ext_cp
958 ):
959 vdu_iface["ns-vld-id"] = vlc.get(
960 "virtual-link-profile-id"
961 )
garciadeblas61c95912021-02-12 11:23:50 +0000962 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100963 if vdu_iface.get("type") in (
964 "SR-IOV",
965 "PCI-PASSTHROUGH",
966 ):
967 nsr_descriptor["vld"][vlc_index][
968 "pci-interfaces"
969 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300970 break
971 elif vdu_iface.get("internal-connection-point-ref"):
972 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000973 # TODO: store fixed IP address in the record (if it exists in the ICP)
974 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
975 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100976 ivld_index = utils.find_index_in_list(
977 vnfd.get("int-virtual-link-desc", ()),
978 lambda ivld: ivld["id"]
979 == icp.get("int-virtual-link-desc"),
980 )
garciadeblas61c95912021-02-12 11:23:50 +0000981 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300982
983 vdur["interfaces"].append(vdu_iface)
984
985 if vdu.get("sw-image-desc"):
986 sw_image = utils.find_in_list(
987 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100988 lambda image: image["id"] == vdu.get("sw-image-desc"),
989 )
garciaale7cbd03c2020-11-27 10:38:35 -0300990 nsr_sw_image_data = utils.find_in_list(
991 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100992 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300993 )
994 vdur["ns-image-id"] = nsr_sw_image_data["id"]
995
lloretgalleg28c13b62021-02-08 11:48:48 +0000996 if vdu.get("alternative-sw-image-desc"):
997 alt_image_ids = []
998 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
999 sw_image = utils.find_in_list(
1000 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001001 lambda image: image["id"] == alt_image_id,
1002 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001003 nsr_sw_image_data = utils.find_in_list(
1004 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001005 lambda nsr_image: (
1006 nsr_image.get("image") == sw_image.get("image")
1007 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001008 )
1009 alt_image_ids.append(nsr_sw_image_data["id"])
1010 vdur["alt-image-ids"] = alt_image_ids
1011
elumalai99078a92022-07-05 17:53:59 +05301012 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +01001013 flavor_data_name = (
1014 vdu["id"][:56] + "-" + vnf_index + "-" + str(revision) + "-flv"
1015 )
garciaale7cbd03c2020-11-27 10:38:35 -03001016 nsr_flavor_desc = utils.find_in_list(
1017 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001018 lambda flavor: flavor["name"] == flavor_data_name,
1019 )
garciaale7cbd03c2020-11-27 10:38:35 -03001020
1021 if nsr_flavor_desc:
1022 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1023
Alexis Romero03fb5842022-03-11 15:53:40 +01001024 # Adding Affinity groups information to vdur
1025 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001026 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001027 vnfd.get("df")[0]["vdu-profile"],
1028 lambda a_vdu: a_vdu["id"] == vdu["id"],
1029 )
1030 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001031 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001032
Alexis Romeroee31f532022-04-26 19:10:21 +02001033 if vdu_profile_affinity_group:
1034 affinity_group_ids = []
1035 for affinity_group in vdu_profile_affinity_group.get(
1036 "affinity-or-anti-affinity-group", ()
1037 ):
1038 vdu_affinity_group = utils.find_in_list(
1039 vdu_profile_affinity_group.get(
1040 "affinity-or-anti-affinity-group", ()
1041 ),
1042 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001043 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001044 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001045 nsr_descriptor["affinity-or-anti-affinity-group"],
1046 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001047 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1048 and nsr_ag.get("member-vnf-index")
1049 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001050 ),
1051 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001052 # Update Affinity Group VIM name if VDU instantiation parameter is present
1053 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1054 vnf_params_affinity_group = utils.find_in_list(
1055 vnf_params["affinity-or-anti-affinity-group"],
1056 lambda vnfp_ag: (
1057 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1058 ),
1059 )
1060 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1061 nsr_affinity_group[
1062 "vim-affinity-group-id"
1063 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1064 affinity_group_ids.append(nsr_affinity_group["id"])
1065 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001066
bravof4ca51522021-04-22 10:03:02 -04001067 if vdu_instantiation_level:
1068 count = vdu_instantiation_level.get("number-of-instances")
1069 else:
1070 count = 1
1071
garciaale7cbd03c2020-11-27 10:38:35 -03001072 for index in range(0, count):
1073 vdur = deepcopy(vdur)
1074 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001075 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001076 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001077 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001078 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1079
1080 vdur["_id"] = str(uuid4())
1081 vdur["id"] = vdur["_id"]
1082 vdur["count-index"] = index
1083 vnfr_descriptor["vdur"].append(vdur)
1084
1085 return vnfr_descriptor
1086
K Sai Kiran57589552021-01-27 21:38:34 +05301087 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1088 """
1089 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1090 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1091 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1092 :param ns_instance_content: ns instance content
1093 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1094 :return: None
1095 """
garciadeblasf2af4a12023-01-24 16:56:54 +01001096 time_now, time_delta = (
1097 time(),
1098 time() - ns_instance_content["_admin"]["modified"],
1099 )
1100 force_refresh = (
1101 isinstance(filter_q, dict) and filter_q.get("vcaStatusRefresh") == "true"
1102 )
K Sai Kiran57589552021-01-27 21:38:34 +05301103 threshold_reached = time_delta > 120
1104 if force_refresh or threshold_reached:
1105 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1106 ns_instance_content["_admin"]["modified"] = time_now
1107 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1108 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
garciadeblasf2af4a12023-01-24 16:56:54 +01001109 self.format_on_new(
1110 nslcmop_desc, session["project_id"], make_public=session["public"]
1111 )
K Sai Kiran57589552021-01-27 21:38:34 +05301112 nslcmop_desc["_admin"].pop("nsState")
1113 self.msg.write("ns", operation, nslcmop_desc)
1114 return
1115
1116 def show(self, session, _id, filter_q=None, api_req=False):
1117 """
1118 Get complete information on an ns instance.
1119 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1120 :param _id: string, ns instance id
1121 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1122 :param api_req: True if this call is serving an external API request. False if serving internal request.
1123 :return: dictionary, raise exception if not found.
1124 """
1125 ns_instance_content = super().show(session, _id, api_req)
1126 self.vca_status_refresh(session, ns_instance_content, filter_q)
1127 return ns_instance_content
1128
tierno65ca36d2019-02-12 19:27:52 +01001129 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001130 raise EngineException(
1131 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1132 )
tiernob24258a2018-10-04 18:39:49 +02001133
1134
1135class VnfrTopic(BaseTopic):
1136 topic = "vnfrs"
1137 topic_msg = None
1138
delacruzramo32bab472019-09-13 12:24:22 +02001139 def __init__(self, db, fs, msg, auth):
1140 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001141
tiernobee3bad2019-12-05 12:26:01 +00001142 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001143 raise EngineException(
1144 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1145 )
tiernob24258a2018-10-04 18:39:49 +02001146
tierno65ca36d2019-02-12 19:27:52 +01001147 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001148 raise EngineException(
1149 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1150 )
tiernob24258a2018-10-04 18:39:49 +02001151
tierno65ca36d2019-02-12 19:27:52 +01001152 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001153 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001154 raise EngineException(
1155 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1156 )
tiernob24258a2018-10-04 18:39:49 +02001157
1158
1159class NsLcmOpTopic(BaseTopic):
1160 topic = "nslcmops"
1161 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001162 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001163 "instantiate": ns_instantiate,
1164 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001165 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001166 "scale": ns_scale,
garciadeblas0964edf2022-02-11 00:43:44 +01001167 "heal": ns_heal,
tierno1c38f2f2020-03-24 11:51:39 +00001168 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301169 "migrate": ns_migrate,
govindarajul519da482022-04-29 19:05:22 +05301170 "verticalscale": ns_verticalscale,
tiernob24258a2018-10-04 18:39:49 +02001171 }
1172
delacruzramo32bab472019-09-13 12:24:22 +02001173 def __init__(self, db, fs, msg, auth):
1174 BaseTopic.__init__(self, db, fs, msg, auth)
elumalai6c5ea6b2022-04-25 22:27:59 +05301175 self.nsrtopic = NsrTopic(db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001176
tiernob24258a2018-10-04 18:39:49 +02001177 def _check_ns_operation(self, session, nsr, operation, indata):
1178 """
1179 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001180 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
garciadeblas0964edf2022-02-11 00:43:44 +01001181 :param operation: it can be: instantiate, terminate, action, update, heal
tiernob24258a2018-10-04 18:39:49 +02001182 :param indata: descriptor with the parameters of the operation
1183 :return: None
1184 """
garciaale7cbd03c2020-11-27 10:38:35 -03001185 if operation == "action":
1186 self._check_action_ns_operation(indata, nsr)
1187 elif operation == "scale":
1188 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001189 elif operation == "update":
1190 self._check_update_ns_operation(indata, nsr)
garciadeblas0964edf2022-02-11 00:43:44 +01001191 elif operation == "heal":
1192 self._check_heal_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001193 elif operation == "instantiate":
1194 self._check_instantiate_ns_operation(indata, nsr, session)
1195
1196 def _check_action_ns_operation(self, indata, nsr):
1197 nsd = nsr["nsd"]
1198 # check vnf_member_index
1199 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001200 indata["member_vnf_index"] = indata.pop(
1201 "vnf_member_index"
1202 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001203 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001204 vnfd = self._get_vnfd_from_vnf_member_index(
1205 indata["member_vnf_index"], nsr["_id"]
1206 )
bravof41a52052021-02-17 18:08:01 -03001207 try:
garciadeblas4568a372021-03-24 09:19:48 +01001208 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1209 "operate-vnf-op-config"
1210 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001211 except Exception:
1212 configs = []
1213
garciaale7cbd03c2020-11-27 10:38:35 -03001214 if indata.get("vdu_id"):
1215 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001216 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001217 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001218 )
garciaale7cbd03c2020-11-27 10:38:35 -03001219 elif indata.get("kdu_name"):
1220 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001221 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001222 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001223 )
garciaale7cbd03c2020-11-27 10:38:35 -03001224 else:
bravof41a52052021-02-17 18:08:01 -03001225 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001226 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001227 )
1228 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001229 descriptor_configuration = descriptor_configuration.get(
1230 "config-primitive"
1231 )
garciaale7cbd03c2020-11-27 10:38:35 -03001232 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001233 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1234 "config-primitive"
1235 )
garciaale7cbd03c2020-11-27 10:38:35 -03001236
1237 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001238 if indata.get("kdu_name") and indata["primitive"] in (
1239 "upgrade",
1240 "rollback",
1241 "status",
1242 "inspect",
1243 "readme",
1244 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001245 # TODO should be checked that rollback only can contains revsision_numbe????
1246 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001247 raise EngineException(
1248 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1249 indata["primitive"]
1250 )
1251 )
garciaale7cbd03c2020-11-27 10:38:35 -03001252 return
1253 # if not, check primitive
1254 for config_primitive in get_iterable(descriptor_configuration):
1255 if indata["primitive"] == config_primitive["name"]:
1256 # check needed primitive_params are provided
1257 if indata.get("primitive_params"):
1258 in_primitive_params_copy = copy(indata["primitive_params"])
1259 else:
1260 in_primitive_params_copy = {}
1261 for paramd in get_iterable(config_primitive.get("parameter")):
1262 if paramd["name"] in in_primitive_params_copy:
1263 del in_primitive_params_copy[paramd["name"]]
1264 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001265 raise EngineException(
1266 "Needed parameter {} not provided for primitive '{}'".format(
1267 paramd["name"], indata["primitive"]
1268 )
1269 )
garciaale7cbd03c2020-11-27 10:38:35 -03001270 # check no extra primitive params are provided
1271 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001272 raise EngineException(
1273 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1274 list(in_primitive_params_copy.keys()), indata["primitive"]
1275 )
1276 )
garciaale7cbd03c2020-11-27 10:38:35 -03001277 break
1278 else:
garciadeblas4568a372021-03-24 09:19:48 +01001279 raise EngineException(
1280 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1281 indata["primitive"]
1282 )
1283 )
garciaale7cbd03c2020-11-27 10:38:35 -03001284
aticig544a2ae2022-04-05 09:00:17 +03001285 def _check_update_ns_operation(self, indata, nsr) -> None:
1286 """Validates the ns-update request according to updateType
1287
1288 If updateType is CHANGE_VNFPKG:
1289 - it checks the vnfInstanceId, whether it's available under ns instance
1290 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1291 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301292 If updateType is REMOVE_VNF:
1293 - it checks if the vnfInstanceId is available in the ns instance
1294 - Otherwise exception will be raised.
aticig544a2ae2022-04-05 09:00:17 +03001295
1296 Args:
1297 indata: includes updateType such as CHANGE_VNFPKG,
1298 nsr: network service record
1299
1300 Raises:
1301 EngineException:
1302 a meaningful error if given update parameters are not proper such as
1303 "Error in validating ns-update request: <ID> does not match
1304 with the vnfd-id of vnfinstance
1305 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1306
1307 """
1308 try:
1309 if indata["updateType"] == "CHANGE_VNFPKG":
1310 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1311 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1312 ns_instance_id = indata["nsInstanceId"]
1313 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1314
1315 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
aticig544a2ae2022-04-05 09:00:17 +03001316 raise EngineException(
1317 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1318 f"belong to NS {ns_instance_id}",
1319 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1320 )
1321
1322 # Getting vnfrs through the ns_instance_id
1323 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1324 constituent_vnfd_id = next(
1325 (
1326 vnfr["vnfd-id"]
1327 for vnfr in vnfrs
1328 if vnfr["id"] == vnf_instance_id
1329 ),
1330 None,
1331 )
1332
1333 # Check the given vnfd-id belongs to given vnf instance
1334 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
aticig544a2ae2022-04-05 09:00:17 +03001335 raise EngineException(
1336 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1337 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1338 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1339 )
1340
1341 # Validating the ns update timeout
1342 if (
1343 indata.get("timeout_ns_update")
1344 and indata["timeout_ns_update"] < 300
1345 ):
1346 raise EngineException(
1347 "Error in validating ns-update request: {} second is not enough "
1348 "to upgrade the VNF instance: {}".format(
1349 indata["timeout_ns_update"], vnf_instance_id
1350 ),
1351 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1352 )
elumalai6380e7c2022-04-28 00:15:59 +05301353 elif indata["updateType"] == "REMOVE_VNF":
1354 vnf_instance_id = indata["removeVnfInstanceId"]
1355 ns_instance_id = indata["nsInstanceId"]
1356 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1357 raise EngineException(
1358 "Invalid VNF Instance Id. '{}' is not "
1359 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1360 )
aticig544a2ae2022-04-05 09:00:17 +03001361
1362 except (
1363 DbException,
1364 AttributeError,
1365 IndexError,
1366 KeyError,
1367 ValueError,
1368 ) as e:
1369 raise type(e)(
1370 "Ns update request could not be processed with error: {}.".format(e)
1371 )
1372
garciaale7cbd03c2020-11-27 10:38:35 -03001373 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001374 vnfd = self._get_vnfd_from_vnf_member_index(
1375 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1376 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001377 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001378 if (
1379 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1380 == scaling_aspect["id"]
1381 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001382 break
1383 else:
garciadeblas4568a372021-03-24 09:19:48 +01001384 raise EngineException(
1385 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1386 "present at vnfd:scaling-aspect".format(
1387 indata["scaleVnfData"]["scaleByStepData"][
1388 "scaling-group-descriptor"
1389 ]
1390 )
1391 )
garciaale7cbd03c2020-11-27 10:38:35 -03001392
garciadeblas0964edf2022-02-11 00:43:44 +01001393 def _check_heal_ns_operation(self, indata, nsr):
1394 return
1395
garciaale7cbd03c2020-11-27 10:38:35 -03001396 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001397 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001398 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001399 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001400 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001401 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1402 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1403 for in_vnf in get_iterable(indata.get("vnf")):
1404 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001405 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001406 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001407 else:
garciadeblas4568a372021-03-24 09:19:48 +01001408 vnfd = self._get_vnfd_from_vnf_member_index(
1409 member_vnf_index, nsr["_id"]
1410 )
1411 vnf_member_index_to_vnfd[
1412 member_vnf_index
1413 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001414 self._check_vnf_instantiation_params(in_vnf, vnfd)
1415 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001416 self._check_valid_vim_account(
1417 in_vnf["vimAccountId"], vim_accounts, session
1418 )
tierno260dd6f2019-09-02 10:48:56 +00001419
garciaale7cbd03c2020-11-27 10:38:35 -03001420 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001421 self._check_valid_wim_account(
1422 in_vld.get("wimAccountId"), wim_accounts, session
1423 )
garciaale7cbd03c2020-11-27 10:38:35 -03001424 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1425 if in_vld["name"] == vldd["id"]:
1426 break
tierno9cb7d672019-10-30 12:13:48 +00001427 else:
garciadeblas4568a372021-03-24 09:19:48 +01001428 raise EngineException(
1429 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1430 in_vld["name"]
1431 )
1432 )
tierno9cb7d672019-10-30 12:13:48 +00001433
garciaale7cbd03c2020-11-27 10:38:35 -03001434 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1435 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001436 vnfr = self.db.get_one(
1437 "vnfrs",
1438 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1439 fail_on_empty=False,
1440 )
garciaale7cbd03c2020-11-27 10:38:35 -03001441 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001442 raise EngineException(
1443 "Invalid parameter member_vnf_index='{}' is not one of the "
1444 "nsd:constituent-vnfd".format(member_vnf_index)
1445 )
beierlmcee2ebf2022-03-29 17:42:48 -04001446
garciadeblasf2af4a12023-01-24 16:56:54 +01001447 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
beierlmcee2ebf2022-03-29 17:42:48 -04001448 if "revision" in vnfr:
1449 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
garciadeblasf2af4a12023-01-24 16:56:54 +01001450 vnfd = self.db.get_one(
1451 "vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False
1452 )
beierlmcee2ebf2022-03-29 17:42:48 -04001453 else:
garciadeblasf2af4a12023-01-24 16:56:54 +01001454 vnfd = self.db.get_one(
1455 "vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False
1456 )
beierlmcee2ebf2022-03-29 17:42:48 -04001457
garciaale7cbd03c2020-11-27 10:38:35 -03001458 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001459 raise EngineException(
1460 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1461 vnfr["vnfd-id"]
1462 )
1463 )
garciaale7cbd03c2020-11-27 10:38:35 -03001464 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001465
garciaale7cbd03c2020-11-27 10:38:35 -03001466 def _check_valid_vdu(self, vnfd, vdu_id):
1467 for vdud in get_iterable(vnfd.get("vdu")):
1468 if vdud["id"] == vdu_id:
1469 return vdud
1470 else:
garciadeblas4568a372021-03-24 09:19:48 +01001471 raise EngineException(
1472 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1473 vdu_id
1474 )
1475 )
garciaale7cbd03c2020-11-27 10:38:35 -03001476
1477 def _check_valid_kdu(self, vnfd, kdu_name):
1478 for kdud in get_iterable(vnfd.get("kdu")):
1479 if kdud["name"] == kdu_name:
1480 return kdud
1481 else:
garciadeblas4568a372021-03-24 09:19:48 +01001482 raise EngineException(
1483 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1484 kdu_name
1485 )
1486 )
garciaale7cbd03c2020-11-27 10:38:35 -03001487
1488 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1489 for in_vdu in get_iterable(in_vnf.get("vdu")):
1490 for vdu in get_iterable(vnfd.get("vdu")):
1491 if in_vdu["id"] == vdu["id"]:
1492 for volume in get_iterable(in_vdu.get("volume")):
1493 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
aticigd7753fc2022-05-18 18:55:23 +03001494 if volumed == volume["name"]:
garciaale7cbd03c2020-11-27 10:38:35 -03001495 break
1496 else:
garciadeblas4568a372021-03-24 09:19:48 +01001497 raise EngineException(
1498 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1499 "volume:name='{}' is not present at "
1500 "vnfd:vdu:virtual-storage-desc list".format(
1501 in_vnf["member-vnf-index"],
1502 in_vdu["id"],
1503 volume["id"],
1504 )
1505 )
garciaale7cbd03c2020-11-27 10:38:35 -03001506
1507 vdu_if_names = set()
1508 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001509 for iface in get_iterable(
1510 cpd.get("virtual-network-interface-requirement")
1511 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001512 vdu_if_names.add(iface.get("name"))
1513
aticigd7753fc2022-05-18 18:55:23 +03001514 for in_iface in get_iterable(in_vdu.get("interface")):
garciaale7cbd03c2020-11-27 10:38:35 -03001515 if in_iface["name"] in vdu_if_names:
1516 break
1517 else:
garciadeblas4568a372021-03-24 09:19:48 +01001518 raise EngineException(
1519 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1520 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1521 in_vnf["member-vnf-index"],
1522 in_vdu["id"],
1523 in_iface["name"],
1524 )
1525 )
garciaale7cbd03c2020-11-27 10:38:35 -03001526 break
1527
1528 else:
garciadeblas4568a372021-03-24 09:19:48 +01001529 raise EngineException(
1530 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1531 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1532 )
garciaale7cbd03c2020-11-27 10:38:35 -03001533
garciadeblas4568a372021-03-24 09:19:48 +01001534 vnfd_ivlds_cpds = {
1535 ivld.get("id"): set()
1536 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1537 }
Gulsum Atici9af2a472023-03-28 17:50:48 +03001538 for vdu in vnfd.get("vdu", {}):
1539 for cpd in vdu.get("int-cpd", {}):
garciaale7cbd03c2020-11-27 10:38:35 -03001540 if cpd.get("int-virtual-link-desc"):
1541 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1542
1543 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1544 if in_ivld.get("name") in vnfd_ivlds_cpds:
1545 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1546 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001547 break
tiernob24258a2018-10-04 18:39:49 +02001548 else:
garciadeblas4568a372021-03-24 09:19:48 +01001549 raise EngineException(
1550 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1551 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1552 "vnfd:internal-vld:name/id:internal-connection-point".format(
1553 in_vnf["member-vnf-index"],
1554 in_ivld["name"],
1555 in_icp["id-ref"],
1556 )
1557 )
tiernob24258a2018-10-04 18:39:49 +02001558 else:
garciadeblas4568a372021-03-24 09:19:48 +01001559 raise EngineException(
1560 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1561 " is not present at vnfd '{}'".format(
1562 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1563 )
1564 )
tiernob24258a2018-10-04 18:39:49 +02001565
garciaale7cbd03c2020-11-27 10:38:35 -03001566 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1567 if vim_account in vim_accounts:
1568 return
1569 try:
1570 db_filter = self._get_project_filter(session)
1571 db_filter["_id"] = vim_account
1572 self.db.get_one("vim_accounts", db_filter)
1573 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001574 raise EngineException(
1575 "Invalid vimAccountId='{}' not present for the project".format(
1576 vim_account
1577 )
1578 )
garciaale7cbd03c2020-11-27 10:38:35 -03001579 vim_accounts.append(vim_account)
1580
David Garcia98de2982021-10-13 17:14:01 +02001581 def _get_vim_account(self, vim_id: str, session):
1582 try:
1583 db_filter = self._get_project_filter(session)
1584 db_filter["_id"] = vim_id
1585 return self.db.get_one("vim_accounts", db_filter)
1586 except Exception:
1587 raise EngineException(
garciadeblasf2af4a12023-01-24 16:56:54 +01001588 "Invalid vimAccountId='{}' not present for the project".format(vim_id)
David Garcia98de2982021-10-13 17:14:01 +02001589 )
1590
garciaale7cbd03c2020-11-27 10:38:35 -03001591 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1592 if not isinstance(wim_account, str):
1593 return
1594 if wim_account in wim_accounts:
1595 return
1596 try:
gifrerenom44f5ec12022-03-07 16:57:25 +00001597 db_filter = self._get_project_filter(session)
garciaale7cbd03c2020-11-27 10:38:35 -03001598 db_filter["_id"] = wim_account
1599 self.db.get_one("wim_accounts", db_filter)
1600 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001601 raise EngineException(
1602 "Invalid wimAccountId='{}' not present for the project".format(
1603 wim_account
1604 )
1605 )
garciaale7cbd03c2020-11-27 10:38:35 -03001606 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001607
garciadeblas4568a372021-03-24 09:19:48 +01001608 def _look_for_pdu(
1609 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1610 ):
tiernocc103432018-10-19 14:10:35 +02001611 """
tierno36ec8602018-11-02 17:27:11 +01001612 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1613 (ip_address, ...) information.
1614 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001615 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001616 :param rollback: list with the database modifications to rollback if needed
1617 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1618 :param vim_account: vim_account where this vnfr should be deployed
1619 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1620 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1621 of the changed vnfr is needed
1622
1623 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1624 "vim-network-name": used at VIM
1625 "name": interface name
1626 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1627 "ns-vld-id": NSD vld where this interface is connected.
1628 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 +02001629 """
tierno36ec8602018-11-02 17:27:11 +01001630
1631 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001632 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1633 if not vdur.get("pdu-type"):
1634 continue
1635 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001636 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001637 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001638 pdu_filter["type"] = pdu_type
1639 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001640 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001641 # TODO feature 1417: "shared": True,
1642
1643 available_pdus = self.db.get_list("pdus", pdu_filter)
1644 for pdu in available_pdus:
1645 # step 1 check if this pdu contains needed interfaces:
1646 match_interfaces = True
1647 for vdur_interface in vdur["interfaces"]:
1648 for pdu_interface in pdu["interfaces"]:
1649 if pdu_interface["name"] == vdur_interface["name"]:
1650 # TODO feature 1417: match per mgmt type
1651 break
1652 else: # no interface found for name
1653 match_interfaces = False
1654 break
1655 if match_interfaces:
1656 break
1657 else:
1658 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001659 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001660 "names".format(
1661 pdu_type,
1662 vim_account,
1663 vnfr["member-vnf-index-ref"],
1664 vdur["vdu-id-ref"],
1665 )
1666 )
tiernocc103432018-10-19 14:10:35 +02001667
1668 # step 2. Update pdu
1669 rollback_pdu = {
1670 "_admin.usageState": pdu["_admin"]["usageState"],
1671 "_admin.usage.vnfr_id": None,
1672 "_admin.usage.nsr_id": None,
1673 "_admin.usage.vdur": None,
1674 }
garciadeblas4568a372021-03-24 09:19:48 +01001675 self.db.set_one(
1676 "pdus",
1677 {"_id": pdu["_id"]},
1678 {
1679 "_admin.usageState": "IN_USE",
1680 "_admin.usage": {
1681 "vnfr_id": vnfr["_id"],
1682 "nsr_id": vnfr["nsr-id-ref"],
1683 "vdur": vdur["vdu-id-ref"],
1684 },
1685 },
1686 )
1687 rollback.append(
1688 {
1689 "topic": "pdus",
1690 "_id": pdu["_id"],
1691 "operation": "set",
1692 "content": rollback_pdu,
1693 }
1694 )
tiernocc103432018-10-19 14:10:35 +02001695
1696 # step 3. Fill vnfr info by filling vdur
1697 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001698 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001699 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1700 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1701 for pdu_interface in pdu["interfaces"]:
1702 if pdu_interface["name"] == vdur_interface["name"]:
1703 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1704 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001705 if k in (
1706 "ip-address",
1707 "mac-address",
1708 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001709 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001710 vnfr_update_rollback[
1711 iface_text + ".{}".format(k)
1712 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001713 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001714 if vdur_interface.get(
1715 "mgmt-interface"
1716 ) or vdur_interface.get("mgmt-vnf"):
1717 vnfr_update_rollback[
1718 vdu_text + ".ip-address"
1719 ] = vdur.get("ip-address")
1720 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1721 "ip-address"
1722 ]
tierno36ec8602018-11-02 17:27:11 +01001723 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001724 vnfr_update_rollback["ip-address"] = vnfr.get(
1725 "ip-address"
1726 )
tierno36ec8602018-11-02 17:27:11 +01001727 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001728 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1729 "ip-address"
1730 ]
1731 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1732 "vim-network-id"
1733 ):
1734 ifaces_forcing_vim_network.append(
1735 {
1736 "name": vdur_interface.get("vnf-vld-id")
1737 or vdur_interface.get("ns-vld-id"),
1738 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1739 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1740 }
1741 )
gcalvino17d5b732018-12-17 16:26:21 +01001742 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001743 ifaces_forcing_vim_network[-1][
1744 "vim-network-id"
1745 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001746 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001747 ifaces_forcing_vim_network[-1][
1748 "vim-network-name"
1749 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001750 break
1751
tierno36ec8602018-11-02 17:27:11 +01001752 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001753
garciadeblas4568a372021-03-24 09:19:48 +01001754 def _look_for_k8scluster(
1755 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1756 ):
tierno9cb7d672019-10-30 12:13:48 +00001757 """
1758 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1759 Fills vnfr.kdur with the selected k8scluster
1760
1761 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1762 :param rollback: list with the database modifications to rollback if needed
1763 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1764 :param vim_account: vim_account where this vnfr should be deployed
1765 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1766 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1767 of the changed vnfr is needed
1768
1769 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1770 "vim-network-name": used at VIM
1771 "name": interface name
1772 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1773 "ns-vld-id": NSD vld where this interface is connected.
1774 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1775 """
1776
1777 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001778 if not vnfr.get("kdur"):
1779 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001780
tiernoc67b0e92019-11-05 12:45:29 +00001781 kdu_filter = self._get_project_filter(session)
1782 kdu_filter["vim_account"] = vim_account
1783 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1784 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1785
1786 k8s_requirements = {} # just for logging
1787 for k8scluster in available_k8sclusters:
1788 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001789 break
tiernoc67b0e92019-11-05 12:45:29 +00001790 # restrict by cni
1791 if vnfr["k8s-cluster"].get("cni"):
1792 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001793 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1794 k8scluster.get("cni", ())
1795 ):
tiernoc67b0e92019-11-05 12:45:29 +00001796 continue
1797 # restrict by version
1798 if vnfr["k8s-cluster"].get("version"):
1799 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1800 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1801 continue
1802 # restrict by number of networks
1803 if vnfr["k8s-cluster"].get("nets"):
1804 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001805 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1806 vnfr["k8s-cluster"]["nets"]
1807 ):
tiernoc67b0e92019-11-05 12:45:29 +00001808 continue
1809 break
1810 else:
garciadeblas4568a372021-03-24 09:19:48 +01001811 raise EngineException(
1812 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1813 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1814 )
1815 )
tierno9cb7d672019-10-30 12:13:48 +00001816
tiernoc67b0e92019-11-05 12:45:29 +00001817 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001818 # step 3. Fill vnfr info by filling kdur
1819 kdu_text = "kdur.{}.".format(kdur_index)
1820 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1821 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1822
tiernoc67b0e92019-11-05 12:45:29 +00001823 # step 4. Check VIM networks that forces the selected k8s_cluster
1824 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1825 k8scluster_net_list = list(k8scluster.get("nets").keys())
1826 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1827 # get a network from k8s_cluster nets. If name matches use this, if not use other
1828 if kdur_net["id"] in k8scluster_net_list: # name matches
1829 vim_net = k8scluster["nets"][kdur_net["id"]]
1830 k8scluster_net_list.remove(kdur_net["id"])
1831 else:
1832 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1833 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001834 vnfr_update_rollback[
1835 "k8s-cluster.nets.{}.vim_net".format(net_index)
1836 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001837 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001838 if vim_net and (
1839 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1840 ):
1841 ifaces_forcing_vim_network.append(
1842 {
1843 "name": kdur_net.get("vnf-vld-id")
1844 or kdur_net.get("ns-vld-id"),
1845 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1846 "ns-vld-id": kdur_net.get("ns-vld-id"),
1847 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1848 }
1849 )
tiernoc67b0e92019-11-05 12:45:29 +00001850 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001851 return ifaces_forcing_vim_network
1852
Gulsum Aticie395aa42021-11-10 20:59:06 +03001853 def _update_vnfrs_from_nsd(self, nsr):
garciadeblasf2af4a12023-01-24 16:56:54 +01001854 step = "Getting vnf_profiles from nsd" # first step must be defined outside try
Gulsum Aticie395aa42021-11-10 20:59:06 +03001855 try:
1856 nsr_id = nsr["_id"]
1857 nsd = nsr["nsd"]
1858
Gulsum Aticie395aa42021-11-10 20:59:06 +03001859 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1860 vld_fixed_ip_connection_point_data = {}
1861
1862 step = "Getting ip-address info from vnf_profile if it exists"
1863 for vnfp in vnf_profiles:
1864 # Checking ip-address info from nsd.vnf_profile and storing
1865 for vlc in vnfp.get("virtual-link-connectivity", ()):
1866 for cpd in vlc.get("constituent-cpd-id", ()):
1867 if cpd.get("ip-address"):
1868 step = "Storing ip-address info"
garciadeblasf2af4a12023-01-24 16:56:54 +01001869 vld_fixed_ip_connection_point_data.update(
1870 {
1871 vlc.get("virtual-link-profile-id")
1872 + "."
1873 + cpd.get("constituent-base-element-id"): {
1874 "vnfd-connection-point-ref": cpd.get(
1875 "constituent-cpd-id"
1876 ),
1877 "ip-address": cpd.get("ip-address"),
1878 }
1879 }
1880 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001881
1882 # Inserting ip address to vnfr
1883 if len(vld_fixed_ip_connection_point_data) > 0:
1884 step = "Getting vnfrs"
1885 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1886 for item in vld_fixed_ip_connection_point_data.keys():
1887 step = "Filtering vnfrs"
garciadeblasf2af4a12023-01-24 16:56:54 +01001888 vnfr = next(
1889 filter(
1890 lambda vnfr: vnfr["member-vnf-index-ref"]
1891 == item.split(".")[1],
1892 vnfrs,
1893 ),
1894 None,
1895 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001896 if vnfr:
1897 vnfr_update = {}
1898 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1899 for iface_index, iface in enumerate(vdur["interfaces"]):
1900 step = "Looking for matched interface"
1901 if (
garciadeblasf2af4a12023-01-24 16:56:54 +01001902 iface.get("external-connection-point-ref")
1903 == vld_fixed_ip_connection_point_data[item].get(
1904 "vnfd-connection-point-ref"
1905 )
1906 and iface.get("ns-vld-id") == item.split(".")[0]
Gulsum Aticie395aa42021-11-10 20:59:06 +03001907 ):
1908 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1909 vdur_index, iface_index
1910 )
1911 step = "Storing info in order to update vnfr"
1912 vnfr_update[
1913 vnfr_update_text + ".ip-address"
garciadeblasf2af4a12023-01-24 16:56:54 +01001914 ] = increment_ip_mac(
1915 vld_fixed_ip_connection_point_data[item].get(
1916 "ip-address"
1917 ),
1918 vdur.get("count-index", 0),
1919 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001920 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1921
1922 step = "updating vnfr at database"
1923 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1924 except (
garciadeblasf2af4a12023-01-24 16:56:54 +01001925 ValidationError,
1926 EngineException,
1927 DbException,
1928 MsgException,
1929 FsException,
Gulsum Aticie395aa42021-11-10 20:59:06 +03001930 ) as e:
1931 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1932
tiernocc103432018-10-19 14:10:35 +02001933 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001934 # get vnfr
1935 nsr_id = nsr["_id"]
1936 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1937
1938 for vnfr in vnfrs:
1939 vnfr_update = {}
1940 vnfr_update_rollback = {}
1941 member_vnf_index = vnfr["member-vnf-index-ref"]
1942 # update vim-account-id
1943
1944 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02001945 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001946 # check instantiate parameters
1947 for vnf_inst_params in get_iterable(indata.get("vnf")):
1948 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1949 continue
1950 if vnf_inst_params.get("vimAccountId"):
1951 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02001952 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001953
tiernocddb07d2020-10-06 08:28:00 +00001954 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1955 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1956 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1957 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1958 continue
garciadeblas4568a372021-03-24 09:19:48 +01001959 for iface_inst_param in get_iterable(
1960 vdu_inst_param.get("interface")
1961 ):
1962 iface_index, _ = next(
1963 i
1964 for i in enumerate(vdur["interfaces"])
1965 if i[1]["name"] == iface_inst_param["name"]
1966 )
1967 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1968 vdur_index, iface_index
1969 )
tiernocddb07d2020-10-06 08:28:00 +00001970 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001971 vnfr_update[
1972 vnfr_update_text + ".ip-address"
1973 ] = increment_ip_mac(
1974 iface_inst_param.get("ip-address"),
1975 vdur.get("count-index", 0),
1976 )
tierno1bd9d952020-11-13 15:56:51 +00001977 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001978 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001979 vnfr_update[
1980 vnfr_update_text + ".mac-address"
1981 ] = increment_ip_mac(
1982 iface_inst_param.get("mac-address"),
1983 vdur.get("count-index", 0),
1984 )
tierno1bd9d952020-11-13 15:56:51 +00001985 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001986 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001987 vnfr_update[
1988 vnfr_update_text + ".floating-ip-required"
1989 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001990 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1991 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001992 for ivld_inst_param in get_iterable(
1993 vnf_inst_params.get("internal-vld")
1994 ):
1995 for icp_inst_param in get_iterable(
1996 ivld_inst_param.get("internal-connection-point")
1997 ):
tiernocddb07d2020-10-06 08:28:00 +00001998 # look for iface
1999 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2000 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002001 if (
2002 iface.get("internal-connection-point-ref")
2003 == icp_inst_param["id-ref"]
2004 ):
2005 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2006 vdur_index, iface_index
2007 )
tiernocddb07d2020-10-06 08:28:00 +00002008 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002009 vnfr_update[
2010 vnfr_update_text + ".ip-address"
2011 ] = increment_ip_mac(
2012 icp_inst_param.get("ip-address"),
2013 vdur.get("count-index", 0),
2014 )
2015 vnfr_update[
2016 vnfr_update_text + ".fixed-ip"
2017 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002018 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002019 vnfr_update[
2020 vnfr_update_text + ".mac-address"
2021 ] = increment_ip_mac(
2022 icp_inst_param.get("mac-address"),
2023 vdur.get("count-index", 0),
2024 )
2025 vnfr_update[
2026 vnfr_update_text + ".fixed-mac"
2027 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002028 break
2029 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2030 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01002031 for vnfcp_inst_param in get_iterable(
2032 vld_inst_param.get("vnfd-connection-point-ref")
2033 ):
tiernocddb07d2020-10-06 08:28:00 +00002034 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2035 continue
2036 # look for iface
2037 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2038 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002039 if (
2040 iface.get("external-connection-point-ref")
2041 == vnfcp_inst_param["vnfd-connection-point-ref"]
2042 ):
2043 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2044 vdur_index, iface_index
2045 )
tiernocddb07d2020-10-06 08:28:00 +00002046 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002047 vnfr_update[
2048 vnfr_update_text + ".ip-address"
2049 ] = increment_ip_mac(
2050 vnfcp_inst_param.get("ip-address"),
2051 vdur.get("count-index", 0),
2052 )
tierno1bd9d952020-11-13 15:56:51 +00002053 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002054 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002055 vnfr_update[
2056 vnfr_update_text + ".mac-address"
2057 ] = increment_ip_mac(
2058 vnfcp_inst_param.get("mac-address"),
2059 vdur.get("count-index", 0),
2060 )
tierno1bd9d952020-11-13 15:56:51 +00002061 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002062 break
2063
tiernocc103432018-10-19 14:10:35 +02002064 vnfr_update["vim-account-id"] = vim_account
2065 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2066
David Garciaecb41322021-03-31 19:10:46 +02002067 if vca_id:
2068 vnfr_update["vca-id"] = vca_id
2069 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2070
tiernocc103432018-10-19 14:10:35 +02002071 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002072 ifaces_forcing_vim_network = self._look_for_pdu(
2073 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2074 )
tiernocc103432018-10-19 14:10:35 +02002075
tierno9cb7d672019-10-30 12:13:48 +00002076 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002077 ifaces_forcing_vim_network += self._look_for_k8scluster(
2078 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2079 )
tierno9cb7d672019-10-30 12:13:48 +00002080 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002081 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002082 rollback.append(
2083 {
2084 "topic": "vnfrs",
2085 "_id": vnfr["_id"],
2086 "operation": "set",
2087 "content": vnfr_update_rollback,
2088 }
2089 )
tierno36ec8602018-11-02 17:27:11 +01002090
2091 # Update indada in case pdu forces to use a concrete vim-network-name
2092 # TODO check if user has already insert a vim-network-name and raises an error
2093 if not ifaces_forcing_vim_network:
2094 continue
2095 for iface_info in ifaces_forcing_vim_network:
2096 if iface_info.get("ns-vld-id"):
2097 if "vld" not in indata:
2098 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002099 indata["vld"].append(
2100 {
2101 key: iface_info[key]
2102 for key in ("name", "vim-network-name", "vim-network-id")
2103 if iface_info.get(key)
2104 }
2105 )
tierno36ec8602018-11-02 17:27:11 +01002106
2107 elif iface_info.get("vnf-vld-id"):
2108 if "vnf" not in indata:
2109 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002110 indata["vnf"].append(
2111 {
2112 "member-vnf-index": member_vnf_index,
2113 "internal-vld": [
2114 {
2115 key: iface_info[key]
2116 for key in (
2117 "name",
2118 "vim-network-name",
2119 "vim-network-id",
2120 )
2121 if iface_info.get(key)
2122 }
2123 ],
2124 }
2125 )
tierno36ec8602018-11-02 17:27:11 +01002126
2127 @staticmethod
2128 def _create_nslcmop(nsr_id, operation, params):
2129 """
2130 Creates a ns-lcm-opp content to be stored at database.
2131 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002132 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002133 :param params: user parameters for the operation
2134 :return: dictionary following SOL005 format
2135 """
tiernob24258a2018-10-04 18:39:49 +02002136 now = time()
2137 _id = str(uuid4())
2138 nslcmop = {
2139 "id": _id,
2140 "_id": _id,
2141 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002142 "queuePosition": None,
2143 "stage": None,
2144 "errorMessage": None,
2145 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002146 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002147 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002148 "lcmOperationType": operation,
2149 "startTime": now,
2150 "isAutomaticInvocation": False,
2151 "operationParams": params,
2152 "isCancelPending": False,
2153 "links": {
2154 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002155 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002156 },
tiernob24258a2018-10-04 18:39:49 +02002157 }
2158 return nslcmop
2159
magnussonlf318b302020-01-20 18:38:18 +01002160 def _get_enabled_vims(self, session):
2161 """
2162 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2163 :param session: current session with user information
2164 """
2165 db_filter = self._get_project_filter(session)
2166 db_filter["_admin.operationalState"] = "ENABLED"
2167 vims = self.db.get_list("vim_accounts", db_filter)
2168 vimAccounts = []
2169 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002170 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002171 return vimAccounts
2172
garciadeblas4568a372021-03-24 09:19:48 +01002173 def new(
2174 self,
2175 rollback,
2176 session,
2177 indata=None,
2178 kwargs=None,
2179 headers=None,
2180 slice_object=False,
2181 ):
tiernob24258a2018-10-04 18:39:49 +02002182 """
2183 Performs a new operation over a ns
2184 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002185 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002186 :param indata: descriptor with the parameters of the operation. It must contains among others
2187 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002188 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002189 :param kwargs: used to override the indata descriptor
2190 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002191 :return: id of the nslcmops
2192 """
garciadeblas4568a372021-03-24 09:19:48 +01002193
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002194 def check_if_nsr_is_not_slice_member(session, nsr_id):
2195 nsis = None
2196 db_filter = self._get_project_filter(session)
2197 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002198 nsis = self.db.get_one(
2199 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2200 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002201 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002202 raise EngineException(
2203 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2204 nsr_id, nsis["_id"]
2205 ),
2206 http_code=HTTPStatus.CONFLICT,
2207 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002208
tiernob24258a2018-10-04 18:39:49 +02002209 try:
2210 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002211 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002212 operation = indata["lcmOperationType"]
2213 nsInstanceId = indata["nsInstanceId"]
2214
2215 validate_input(indata, self.operation_schema[operation])
2216 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002217 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002218 _filter["_id"] = nsInstanceId
2219 nsr = self.db.get_one("nsrs", _filter)
2220
2221 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002222 if operation == "terminate" and slice_object is False:
2223 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002224 if (
2225 not nsr["_admin"].get("nsState")
2226 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2227 ):
tiernob24258a2018-10-04 18:39:49 +02002228 if operation == "terminate" and indata.get("autoremove"):
2229 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002230 return (
2231 None,
2232 None,
2233 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002234 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002235 raise EngineException(
2236 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2237 nsInstanceId, operation
2238 ),
2239 HTTPStatus.CONFLICT,
2240 )
tiernob24258a2018-10-04 18:39:49 +02002241 else:
tierno65ca36d2019-02-12 19:27:52 +01002242 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002243 raise EngineException(
2244 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2245 nsInstanceId, operation
2246 ),
2247 HTTPStatus.CONFLICT,
2248 )
tiernob24258a2018-10-04 18:39:49 +02002249 self._check_ns_operation(session, nsr, operation, indata)
garciadeblasf2af4a12023-01-24 16:56:54 +01002250 if indata.get("primitive_params"):
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002251 indata["primitive_params"] = json.dumps(indata["primitive_params"])
garciadeblasf2af4a12023-01-24 16:56:54 +01002252 elif indata.get("additionalParamsForVnf"):
2253 indata["additionalParamsForVnf"] = json.dumps(
2254 indata["additionalParamsForVnf"]
2255 )
tierno36ec8602018-11-02 17:27:11 +01002256
tiernocc103432018-10-19 14:10:35 +02002257 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002258 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002259 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302260 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2261 nsr_update = {}
2262 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2263 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2264 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2265 ns_request = nsr["instantiate_params"]
garciadeblasf2af4a12023-01-24 16:56:54 +01002266 vnfr = self.db.get_one(
2267 "vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]}
2268 )
elumalai8bf978e2022-05-26 15:32:06 +05302269 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2270 vnfr_vnfd_revision = vnfr.get("revision", 1)
2271 if latest_vnfd_revision != vnfr_vnfd_revision:
2272 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
garciadeblasf2af4a12023-01-24 16:56:54 +01002273 old_db_vnfd = self.db.get_one(
2274 "vnfds_revisions", {"_id": old_vnfd_id}
2275 )
elumalai8bf978e2022-05-26 15:32:06 +05302276 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2277 new_sw_version = vnfd.get("software-version", "1.0")
2278 if new_sw_version != old_sw_version:
2279 vnf_index = vnfr["member-vnf-index-ref"]
2280 self.logger.info("nsr {}".format(nsr))
2281 for vdu in vnfd["vdu"]:
garciadeblasf2af4a12023-01-24 16:56:54 +01002282 self.nsrtopic._add_flavor_to_nsr(
2283 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2284 )
elumalai8bf978e2022-05-26 15:32:06 +05302285 sw_image_id = vdu.get("sw-image-desc")
2286 if sw_image_id:
garciadeblasf2af4a12023-01-24 16:56:54 +01002287 image_data = self.nsrtopic._get_image_data_from_vnfd(
2288 vnfd, sw_image_id
2289 )
elumalai8bf978e2022-05-26 15:32:06 +05302290 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2291 for alt_image in vdu.get("alternative-sw-image-desc", ()):
garciadeblasf2af4a12023-01-24 16:56:54 +01002292 image_data = self.nsrtopic._get_image_data_from_vnfd(
2293 vnfd, alt_image
2294 )
elumalai8bf978e2022-05-26 15:32:06 +05302295 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2296 nsr_update["image"] = nsr["image"]
2297 nsr_update["flavor"] = nsr["flavor"]
2298 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
garciadeblasf2af4a12023-01-24 16:56:54 +01002299 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(
2300 nsd, ns_request, session
2301 )
2302 vnfr_descriptor = (
2303 self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2304 nsd,
2305 vnfd,
2306 vnfd_id,
2307 vnf_index,
2308 nsr,
2309 ns_request,
2310 ns_k8s_namespace,
2311 latest_vnfd_revision,
2312 )
elumalai8bf978e2022-05-26 15:32:06 +05302313 )
2314 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002315 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002316 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002317 self.format_on_new(
2318 nslcmop_desc, session["project_id"], make_public=session["public"]
2319 )
magnussonlf318b302020-01-20 18:38:18 +01002320 if indata.get("placement-engine"):
2321 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002322 nslcmop_desc["operationParams"][
2323 "validVimAccounts"
2324 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002325 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002326 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002327 if not slice_object:
2328 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002329 return _id, None
2330 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002331 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2332 # except DbException as e:
2333 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2334
tiernobee3bad2019-12-05 12:26:01 +00002335 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002336 raise EngineException(
2337 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2338 )
tiernob24258a2018-10-04 18:39:49 +02002339
tierno65ca36d2019-02-12 19:27:52 +01002340 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002341 raise EngineException(
2342 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2343 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002344
2345
2346class NsiTopic(BaseTopic):
2347 topic = "nsis"
2348 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002349 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002350
delacruzramo32bab472019-09-13 12:24:22 +02002351 def __init__(self, db, fs, msg, auth):
2352 BaseTopic.__init__(self, db, fs, msg, auth)
2353 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002354
Felipe Vicensc37b3842019-01-12 12:24:42 +01002355 @staticmethod
2356 def _format_ns_request(ns_request):
2357 formated_request = copy(ns_request)
2358 # TODO: Add request params
2359 return formated_request
2360
2361 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002362 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002363 """
2364 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002365 :param slice_request: User instantiation additional parameters
2366 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002367 """
tiernofd160572019-01-21 10:41:37 +00002368 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2369 if additional_params:
2370 for k, v in additional_params.items():
2371 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002372 raise EngineException(
2373 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2374 k
2375 )
2376 )
tiernofd160572019-01-21 10:41:37 +00002377 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002378 raise EngineException(
2379 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2380 k
2381 )
2382 )
tiernofd160572019-01-21 10:41:37 +00002383 if isinstance(v, (dict, tuple, list)):
2384 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002385 return additional_params
2386
tiernob4844ab2019-05-23 08:42:12 +00002387 def check_conflict_on_del(self, session, _id, db_content):
2388 """
2389 Check that NSI is not instantiated
2390 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2391 :param _id: nsi internal id
2392 :param db_content: The database content of the _id
2393 :return: None or raises EngineException with the conflict
2394 """
tierno65ca36d2019-02-12 19:27:52 +01002395 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002396 return
tiernob4844ab2019-05-23 08:42:12 +00002397 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002398 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002399 raise EngineException(
2400 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2401 "Launch 'terminate' operation first; or force deletion".format(_id),
2402 http_code=HTTPStatus.CONFLICT,
2403 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002404
tiernobee3bad2019-12-05 12:26:01 +00002405 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002406 """
tiernob4844ab2019-05-23 08:42:12 +00002407 Deletes associated nsilcmops from database. Deletes associated filesystem.
2408 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002409 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002410 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002411 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002412 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002413 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002414 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002415
Felipe Vicens09e65422019-01-22 15:06:46 +01002416 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002417 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002418 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2419 nsr_id = nsrs_detailed_item["nsrId"]
2420 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002421 _filter = {
2422 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2423 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2424 "_id.ne": nsir["_id"],
2425 }
2426 nsi = self.db.get_one(
2427 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2428 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002429 if nsi: # last one using nsr
2430 continue
2431 try:
garciadeblas4568a372021-03-24 09:19:48 +01002432 self.nsrTopic.delete(
2433 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2434 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002435 except (DbException, EngineException) as e:
2436 if e.http_code == HTTPStatus.NOT_FOUND:
2437 pass
2438 else:
2439 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002440
tiernob4844ab2019-05-23 08:42:12 +00002441 # delete related nsilcmops database entries
2442 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002443
tiernob4844ab2019-05-23 08:42:12 +00002444 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002445 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002446 if nsir_admin and nsir_admin.get("nst-id"):
2447 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002448 nsis_list = self.db.get_one(
2449 "nsis",
2450 {"nst-id": nsir_admin["nst-id"]},
2451 fail_on_empty=False,
2452 fail_on_more=False,
2453 )
tiernob4844ab2019-05-23 08:42:12 +00002454 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002455 self.db.set_one(
2456 "nsts",
2457 {"_id": nsir_admin["nst-id"]},
2458 {"_admin.usageState": "NOT_IN_USE"},
2459 )
tiernob4844ab2019-05-23 08:42:12 +00002460
tierno65ca36d2019-02-12 19:27:52 +01002461 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002462 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002463 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002464 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002465 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002466 :param indata: params to be used for the nsir
2467 :param kwargs: used to override the indata descriptor
2468 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002469 :return: the _id of nsi descriptor created at database
2470 """
2471
garciadeblasf2af4a12023-01-24 16:56:54 +01002472 step = "checking quotas" # first step must be defined outside try
Felipe Vicensb57758d2018-10-16 16:00:20 +02002473 try:
delacruzramo32bab472019-09-13 12:24:22 +02002474 self.check_quota(session)
2475
tierno99d4b172019-07-02 09:28:40 +00002476 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002477 slice_request = self._remove_envelop(indata)
2478 # Override descriptor with query string kwargs
2479 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002480 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002481
Felipe Vicensb57758d2018-10-16 16:00:20 +02002482 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002483 step = "getting nstd id='{}' from database".format(
2484 slice_request.get("nstId")
2485 )
tiernob4844ab2019-05-23 08:42:12 +00002486 _filter = self._get_project_filter(session)
2487 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002488 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002489 # check NST is not disabled
2490 step = "checking NST operationalState"
2491 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002492 raise EngineException(
2493 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2494 "instance".format(slice_request["nstId"]),
2495 http_code=HTTPStatus.CONFLICT,
2496 )
tiernob4844ab2019-05-23 08:42:12 +00002497 del _filter["_id"]
2498
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002499 # check NSD is not disabled
2500 step = "checking operationalState"
2501 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002502 raise EngineException(
2503 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2504 "a network slice".format(slice_request["nstId"]),
2505 http_code=HTTPStatus.CONFLICT,
2506 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002507
Felipe Vicens07f31722018-10-29 15:16:44 +01002508 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002509 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002510 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002511 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002512
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002513 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002514 nsi_descriptor = {
2515 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002516 "name": slice_request["nsiName"],
2517 "description": slice_request.get("nsiDescription", ""),
2518 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002519 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002520 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002521 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002522 "nsr-ref-list": [],
2523 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002524 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002525 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002526 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002527
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002528 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002529 self.format_on_new(
2530 nsi_descriptor, session["project_id"], make_public=session["public"]
2531 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002532 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2533 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002534 nsi_descriptor["_admin"]["deployed"] = {}
2535 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2536 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2537
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002538 # Creating netslice-vld for the RO.
2539 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002540
2541 # Building the vlds list to be deployed
2542 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002543 nsi_vlds = []
2544
2545 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2546 # Getting template Instantiation parameters from NST
2547 nsi_vld = deepcopy(netslice_vlds)
2548 nsi_vld["shared-nsrs-list"] = []
2549 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2550 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002551
2552 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002553 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002554 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002555 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002556
Felipe Vicens09e65422019-01-22 15:06:46 +01002557 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002558 for member_ns in nstd["netslice-subnet"]:
2559 nsd_id = member_ns["nsd-ref"]
2560 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002561 member_ns["nsd-ref"], member_ns["id"]
2562 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002563 if nsd_id not in needed_nsds:
2564 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002565 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002566 nsd = self.db.get_one(
2567 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2568 )
tiernob4844ab2019-05-23 08:42:12 +00002569 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002570 nsd.pop("_admin")
2571 needed_nsds[nsd_id] = nsd
2572 else:
2573 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002574 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2575 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002576
Felipe Vicensb57758d2018-10-16 16:00:20 +02002577 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002578 member_ns["nsd-ref"], member_ns["id"]
2579 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002580
Felipe Vicens07f31722018-10-29 15:16:44 +01002581 # creates Network Services records (NSRs)
2582 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002583 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002584 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002585 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002586 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002587 # Check if the netslice-subnet is shared and if it is share if the nss exists
2588 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002589 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002590 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002591 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002592 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2593 "nsd-ref"
2594 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002595 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002596 nsi = self.db.get_one(
2597 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2598 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002599 if nsi and service.get("is-shared-nss"):
2600 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2601 for nsrs_detailed_item in nsrs_detailed_list:
2602 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002603 if nsrs_detailed_item["nss-id"] == service["id"]:
2604 _id_nsr = nsrs_detailed_item["nsrId"]
2605 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002606 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2607 if netslice_subnet["nss-id"] == service["id"]:
2608 indata_ns = netslice_subnet
2609 break
2610 else:
2611 indata_ns = {}
2612 if service.get("instantiation-parameters"):
2613 indata_ns = deepcopy(service["instantiation-parameters"])
2614 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002615
Felipe Vicens09e65422019-01-22 15:06:46 +01002616 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002617 indata_ns["nsName"] = (
2618 slice_request.get("nsiName") + "." + service["id"]
2619 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002620 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2621 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002622 if slice_request.get("ssh_keys"):
2623 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002624
Felipe Vicens09e65422019-01-22 15:06:46 +01002625 if ns_params:
2626 for ns_param in ns_params:
2627 if ns_param.get("id") == service["id"]:
2628 copy_ns_param = deepcopy(ns_param)
2629 del copy_ns_param["id"]
2630 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002631 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002632
2633 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002634 _id_nsr, _ = self.nsrTopic.new(
2635 rollback, session, indata_ns, kwargs, headers
2636 )
2637 nsrs_item = {
2638 "nsrId": _id_nsr,
2639 "shared": service.get("is-shared-nss"),
2640 "nsd-id": service["nsd-ref"],
2641 "nss-id": service["id"],
2642 "nslcmop_instantiate": None,
2643 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002644 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002645 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002646 nsi_netslice_subnet.append(indata_ns)
2647 nsr_ref = {"nsr-ref": _id_nsr}
2648 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002649
2650 # Adding the nsrs list to the nsi
2651 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002652 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002653 self.db.set_one(
2654 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2655 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002656
Felipe Vicens07f31722018-10-29 15:16:44 +01002657 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002658 self.db.create("nsis", nsi_descriptor)
2659 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002660 return nsi_id, None
garciadeblasf2af4a12023-01-24 16:56:54 +01002661 except ValidationError as e:
2662 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
garciadeblas4568a372021-03-24 09:19:48 +01002663 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2664 self.logger.exception(
2665 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2666 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002667 raise EngineException("Error {}: {}".format(step, e))
Felipe Vicensb57758d2018-10-16 16:00:20 +02002668
tierno65ca36d2019-02-12 19:27:52 +01002669 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002670 raise EngineException(
2671 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2672 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002673
2674
2675class NsiLcmOpTopic(BaseTopic):
2676 topic = "nsilcmops"
2677 topic_msg = "nsi"
2678 operation_schema = { # mapping between operation and jsonschema to validate
2679 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002680 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002681 }
garciadeblas4568a372021-03-24 09:19:48 +01002682
delacruzramo32bab472019-09-13 12:24:22 +02002683 def __init__(self, db, fs, msg, auth):
2684 BaseTopic.__init__(self, db, fs, msg, auth)
2685 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002686
2687 def _check_nsi_operation(self, session, nsir, operation, indata):
2688 """
2689 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002690 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002691 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2692 :param indata: descriptor with the parameters of the operation
2693 :return: None
2694 """
2695 nsds = {}
2696 nstd = nsir["network-slice-template"]
2697
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002698 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002699 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002700 for netslice_subnet in nstd["netslice-subnet"]:
2701 if nstId == netslice_subnet["id"]:
2702 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002703 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002704 _filter = self._get_project_filter(session)
2705 _filter["id"] = nsd_id
2706 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002707 return nsds[nsd_id]
2708 else:
garciadeblas4568a372021-03-24 09:19:48 +01002709 raise EngineException(
2710 "Invalid parameter nstId='{}' is not one of the "
2711 "nst:netslice-subnet".format(nstId)
2712 )
2713
Felipe Vicens07f31722018-10-29 15:16:44 +01002714 if operation == "instantiate":
2715 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002716 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002717 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002718
2719 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2720 now = time()
2721 _id = str(uuid4())
2722 nsilcmop = {
2723 "id": _id,
2724 "_id": _id,
2725 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2726 "statusEnteredTime": now,
2727 "netsliceInstanceId": netsliceInstanceId,
2728 "lcmOperationType": operation,
2729 "startTime": now,
2730 "isAutomaticInvocation": False,
2731 "operationParams": params,
2732 "isCancelPending": False,
2733 "links": {
2734 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002735 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2736 + netsliceInstanceId,
2737 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002738 }
2739 return nsilcmop
2740
Felipe Vicens09e65422019-01-22 15:06:46 +01002741 def add_shared_nsr_2vld(self, nsir, nsr_item):
2742 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2743 if nst_sb_item.get("is-shared-nss"):
2744 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2745 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2746 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002747 for admin_vld_nss_cp_ref_item in admin_vld_item[
2748 "nss-connection-point-ref"
2749 ]:
2750 if (
2751 admin_subnet_item["nss-id"]
2752 == admin_vld_nss_cp_ref_item["nss-ref"]
2753 ):
2754 if (
2755 not nsr_item["nsrId"]
2756 in admin_vld_item["shared-nsrs-list"]
2757 ):
2758 admin_vld_item["shared-nsrs-list"].append(
2759 nsr_item["nsrId"]
2760 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002761 break
2762 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002763 self.db.set_one(
2764 "nsis",
2765 {"_id": nsir["_id"]},
2766 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2767 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002768
tierno65ca36d2019-02-12 19:27:52 +01002769 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002770 """
2771 Performs a new operation over a ns
2772 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002773 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002774 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002775 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002776 operation: it can be: instantiate, terminate, action, TODO: update, heal
2777 :param kwargs: used to override the indata descriptor
2778 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002779 :return: id of the nslcmops
2780 """
2781 try:
2782 # Override descriptor with query string kwargs
2783 self._update_input_with_kwargs(indata, kwargs)
2784 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002785 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002786 validate_input(indata, self.operation_schema[operation])
2787
Felipe Vicens126af572019-06-05 19:13:04 +02002788 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002789 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002790 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002791 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002792 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002793 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002794
2795 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002796 if (
2797 not nsir["_admin"].get("nsiState")
2798 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2799 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002800 if operation == "terminate" and indata.get("autoremove"):
2801 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002802 return (
2803 None,
2804 None,
2805 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002806 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002807 raise EngineException(
2808 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2809 netsliceInstanceId, operation
2810 ),
2811 HTTPStatus.CONFLICT,
2812 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002813 else:
tierno65ca36d2019-02-12 19:27:52 +01002814 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002815 raise EngineException(
2816 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2817 netsliceInstanceId, operation
2818 ),
2819 HTTPStatus.CONFLICT,
2820 )
2821
Felipe Vicens07f31722018-10-29 15:16:44 +01002822 # Creating all the NS_operation (nslcmop)
2823 # Get service list from db
2824 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2825 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002826 # nslcmops_item = None
2827 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002828 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002829 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002830 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002831 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002832 _filter[
2833 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2834 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002835 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002836 nsi = self.db.get_one(
2837 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2838 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002839 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002840 _update = {
2841 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2842 index
2843 ): None
2844 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002845 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002846 if (
2847 nsi
2848 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002849 continue # do not create nsilcmop
2850 else: # instantiate
2851 # looks the first nsi fulfilling the conditions but not being the current NSIR
2852 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002853 nsi_nsr_item = next(
2854 n
2855 for n in nsi["_admin"]["nsrs-detailed-list"]
2856 if n["nsrId"] == nsr_id
2857 and n["shared"]
2858 and n["nslcmop_instantiate"]
2859 )
tierno40f742b2020-06-23 15:25:26 +00002860 self.add_shared_nsr_2vld(nsir, nsr_item)
2861 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002862 _update = {
2863 "_admin.nsrs-detailed-list.{}".format(
2864 index
2865 ): nsi_nsr_item
2866 }
tierno40f742b2020-06-23 15:25:26 +00002867 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2868 # continue to not create nslcmop since nsrs is shared and nsrs was created
2869 continue
2870 else:
2871 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002872
tierno40f742b2020-06-23 15:25:26 +00002873 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002874 try:
tierno0b8752f2020-05-12 09:42:02 +00002875 indata_ns = {
2876 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002877 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002878 # Including netslice_id in the ns instantiate Operation
2879 "netsliceInstanceId": netsliceInstanceId,
2880 }
2881 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002882 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002883 indata_ns.update(service["instantiate_params"])
2884
tierno99d4b172019-07-02 09:28:40 +00002885 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002886 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002887 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2888 rollback, session, indata_ns, None, headers, slice_object=True
2889 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002890 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002891 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002892 _update = {
2893 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2894 index
2895 ): nslcmop
2896 }
tierno40f742b2020-06-23 15:25:26 +00002897 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002898 except (DbException, EngineException) as e:
2899 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002900 self.logger.info(
2901 logging_prefix
2902 + "skipping NS={} because not found".format(nsr_id)
2903 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002904 pass
2905 else:
2906 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002907
2908 # Creates nsilcmop
2909 indata["nslcmops_ids"] = nslcmops
2910 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002911
garciadeblas4568a372021-03-24 09:19:48 +01002912 nsilcmop_desc = self._create_nsilcmop(
2913 session, netsliceInstanceId, operation, indata
2914 )
2915 self.format_on_new(
2916 nsilcmop_desc, session["project_id"], make_public=session["public"]
2917 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002918 _id = self.db.create("nsilcmops", nsilcmop_desc)
2919 rollback.append({"topic": "nsilcmops", "_id": _id})
2920 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002921 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002922 except ValidationError as e:
2923 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002924
tiernobee3bad2019-12-05 12:26:01 +00002925 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002926 raise EngineException(
2927 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2928 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002929
tierno65ca36d2019-02-12 19:27:52 +01002930 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002931 raise EngineException(
2932 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2933 )