blob: 13ca960b2c93abab816956b57709abb5a8142a6b [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
vegall18101ea2023-03-06 13:49:21 +0000443 def _add_shared_volumes_to_nsr(
444 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
445 ):
446 svsd = []
447 for vsd in vnfd.get("virtual-storage-desc", ()):
448 if vsd.get("vdu-storage-requirements"):
449 if (
450 vsd.get("vdu-storage-requirements")[0].get("key") == "multiattach"
451 and vsd.get("vdu-storage-requirements")[0].get("value") == "True"
452 ):
vegallf976a3a2023-06-02 21:25:32 +0000453 # Avoid setting the volume name multiple times
454 if not match(f"shared-.*-{vnfd['id']}", vsd["id"]):
vegall18101ea2023-03-06 13:49:21 +0000455 vsd["id"] = f"shared-{vsd['id']}-{vnfd['id']}"
456 svsd.append(vsd)
457 if svsd:
458 nsr_descriptor["shared-volumes"] = svsd
459
garciadeblasf2af4a12023-01-24 16:56:54 +0100460 def _add_flavor_to_nsr(
461 self, vdu, vnfd, nsr_descriptor, member_vnf_index, revision=None
462 ):
elumalai6c5ea6b2022-04-25 22:27:59 +0530463 flavor_data = {}
464 guest_epa = {}
465 # Find this vdu compute and storage descriptors
466 vdu_virtual_compute = {}
467 vdu_virtual_storage = {}
468 for vcd in vnfd.get("virtual-compute-desc", ()):
469 if vcd.get("id") == vdu.get("virtual-compute-desc"):
470 vdu_virtual_compute = vcd
471 for vsd in vnfd.get("virtual-storage-desc", ()):
472 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
473 vdu_virtual_storage = vsd
474 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblasf2af4a12023-01-24 16:56:54 +0100475 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
elumalai6c5ea6b2022-04-25 22:27:59 +0530476 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
477 "num-virtual-cpu"
478 ]
479 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
480 flavor_data["memory-mb"] = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100481 float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
elumalai6c5ea6b2022-04-25 22:27:59 +0530482 )
483 if vdu_virtual_storage.get("size-of-storage"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100484 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530485 # Get this vdu EPA info for guest_epa
486 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100487 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530488 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
489 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
490 if vcpu_pinning.get("thread-policy"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100491 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530492 if vcpu_pinning.get("policy"):
493 cpu_policy = (
garciadeblasf2af4a12023-01-24 16:56:54 +0100494 "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
elumalai6c5ea6b2022-04-25 22:27:59 +0530495 )
496 guest_epa["cpu-pinning-policy"] = cpu_policy
497 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100498 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
499 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
500 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"][
501 "mempage-size"
elumalai6c5ea6b2022-04-25 22:27:59 +0530502 ]
garciadeblasf2af4a12023-01-24 16:56:54 +0100503 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
504 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"][
505 "numa-node-policy"
506 ]
elumalai6c5ea6b2022-04-25 22:27:59 +0530507 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblasf2af4a12023-01-24 16:56:54 +0100508 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
elumalai6c5ea6b2022-04-25 22:27:59 +0530509
510 if guest_epa:
511 flavor_data["guest-epa"] = guest_epa
512
elumalai99078a92022-07-05 17:53:59 +0530513 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +0100514 flavor_data["name"] = (
515 vdu["id"][:56] + "-" + member_vnf_index + "-" + str(revision) + "-flv"
516 )
elumalai6c5ea6b2022-04-25 22:27:59 +0530517 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
518 nsr_descriptor["flavor"].append(flavor_data)
519
bravofe76b8822021-02-26 16:57:52 -0300520 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300521 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100522 additional_params, _ = self._format_additional_params(
523 ns_request, descriptor=nsd
524 )
garciaale7cbd03c2020-11-27 10:38:35 -0300525
526 nsr_descriptor = {
527 "name": ns_request["nsName"],
528 "name-ref": ns_request["nsName"],
529 "short-name": ns_request["nsName"],
530 "admin-status": "ENABLED",
531 "nsState": "NOT_INSTANTIATED",
532 "currentOperation": "IDLE",
533 "currentOperationID": None,
534 "errorDescription": None,
535 "errorDetail": None,
536 "deploymentStatus": None,
537 "configurationStatus": None,
538 "vcaStatus": None,
539 "nsd": {k: v for k, v in nsd.items()},
540 "datacenter": ns_request["vimAccountId"],
541 "resource-orchestrator": "osmopenmano",
542 "description": ns_request.get("nsDescription", ""),
543 "constituent-vnfr-ref": [],
544 "operational-status": "init", # typedef ns-operational-
545 "config-status": "init", # typedef config-states
546 "detailed-status": "scheduled",
547 "orchestration-progress": {},
548 "create-time": now,
549 "nsd-name-ref": nsd["name"],
550 "operational-events": [], # "id", "timestamp", "description", "event",
551 "nsd-ref": nsd["id"],
552 "nsd-id": nsd["_id"],
553 "vnfd-id": [],
554 "instantiate_params": self._format_ns_request(ns_request),
555 "additionalParamsForNs": additional_params,
556 "ns-instance-config-ref": nsr_id,
557 "id": nsr_id,
558 "_id": nsr_id,
559 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
560 "flavor": [],
561 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100562 "affinity-or-anti-affinity-group": [],
vegall18101ea2023-03-06 13:49:21 +0000563 "shared-volumes": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300564 }
beierlmbc5a5242022-05-17 21:25:29 -0400565 if "revision" in nsd["_admin"]:
566 nsr_descriptor["revision"] = nsd["_admin"]["revision"]
567
garciaale7cbd03c2020-11-27 10:38:35 -0300568 ns_request["nsr_id"] = nsr_id
569 if ns_request and ns_request.get("config-units"):
570 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300571 # Create vld
572 if nsd.get("virtual-link-desc"):
573 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
574 # Fill each vld with vnfd-connection-point-ref data
575 # TODO: Change for multiple df support
576 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
577 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
578 for vnf_profile in vnf_profiles:
579 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
580 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100581 all_vld_connection_point_data[
582 vlc.get("virtual-link-profile-id")
583 ].append(
584 {
585 "member-vnf-index-ref": cpd.get(
586 "constituent-base-element-id"
587 ),
588 "vnfd-connection-point-ref": cpd.get(
589 "constituent-cpd-id"
590 ),
591 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
592 }
593 )
garciaale7cbd03c2020-11-27 10:38:35 -0300594
bravofe76b8822021-02-26 16:57:52 -0300595 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400596 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300597
598 for vdu in vnfd.get("vdu", ()):
elumalai99078a92022-07-05 17:53:59 +0530599 member_vnf_index = vnf_profile.get("id")
600 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor, member_vnf_index)
vegall18101ea2023-03-06 13:49:21 +0000601 self._add_shared_volumes_to_nsr(
602 vdu, vnfd, nsr_descriptor, member_vnf_index
603 )
garciaale7cbd03c2020-11-27 10:38:35 -0300604 sw_image_id = vdu.get("sw-image-desc")
605 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000606 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
607 self._add_image_to_nsr(nsr_descriptor, image_data)
608
609 # also add alternative images to the list of images
610 for alt_image in vdu.get("alternative-sw-image-desc", ()):
611 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
612 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300613
Alexis Romero03fb5842022-03-11 15:53:40 +0100614 # Add Affinity or Anti-affinity group information to NSR
615 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200616 affinity_group_prefix_name = "{}-{}".format(
617 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
618 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100619
620 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200621 affinity_group_data = {}
622 for affinity_group in vdu_profile.get(
623 "affinity-or-anti-affinity-group", ()
624 ):
625 affinity_group_data = (
626 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
627 vnfd, affinity_group["id"]
628 )
629 )
630 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
631 self._add_affinity_or_anti_affinity_group_to_nsr(
632 nsr_descriptor,
633 affinity_group_data,
634 affinity_group_prefix_name,
635 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100636
garciaale7cbd03c2020-11-27 10:38:35 -0300637 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100638 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
639 vld.get("id"), []
640 )
garciaale7cbd03c2020-11-27 10:38:35 -0300641 vld["name"] = vld["id"]
642 nsr_descriptor["vld"] = nsr_vld
garciaale7cbd03c2020-11-27 10:38:35 -0300643 return nsr_descriptor
644
Alexis Romeroee31f532022-04-26 19:10:21 +0200645 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
646 self, vnfd, affinity_group_id
647 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100648 """
649 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
650 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200651 affinity_group = utils.find_in_list(
652 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
653 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100654 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200655 affinity_group_data = {}
656 if affinity_group:
657 if affinity_group.get("id"):
658 affinity_group_data["ag-id"] = affinity_group["id"]
659 if affinity_group.get("type"):
660 affinity_group_data["type"] = affinity_group["type"]
661 if affinity_group.get("scope"):
662 affinity_group_data["scope"] = affinity_group["scope"]
663 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100664
Alexis Romeroee31f532022-04-26 19:10:21 +0200665 def _add_affinity_or_anti_affinity_group_to_nsr(
666 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
667 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100668 """
669 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
670 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200671 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100672 (
673 f
674 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200675 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100676 ),
677 None,
678 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200679 if not affinity_group:
680 affinity_group_data["id"] = str(
681 len(nsr_descriptor["affinity-or-anti-affinity-group"])
682 )
683 affinity_group_data["name"] = "{}-{}".format(
684 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
685 )
686 nsr_descriptor["affinity-or-anti-affinity-group"].append(
687 affinity_group_data
688 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100689
lloretgalleg28c13b62021-02-08 11:48:48 +0000690 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100691 sw_image_desc = utils.find_in_list(
692 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
693 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000694 image_data = {}
695 if sw_image_desc.get("image"):
696 image_data["image"] = sw_image_desc["image"]
697 if sw_image_desc.get("checksum"):
698 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
699 if sw_image_desc.get("vim-type"):
700 image_data["vim-type"] = sw_image_desc["vim-type"]
701 return image_data
702
703 def _add_image_to_nsr(self, nsr_descriptor, image_data):
704 """
705 Adds image to nsr checking first it is not already added
706 """
garciadeblas4568a372021-03-24 09:19:48 +0100707 img = next(
708 (
709 f
710 for f in nsr_descriptor["image"]
711 if all(f.get(k) == image_data[k] for k in image_data)
712 ),
713 None,
714 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000715 if not img:
716 image_data["id"] = str(len(nsr_descriptor["image"]))
717 nsr_descriptor["image"].append(image_data)
718
garciadeblas4568a372021-03-24 09:19:48 +0100719 def _create_vnfr_descriptor_from_vnfd(
720 self,
721 nsd,
722 vnfd,
723 vnfd_id,
724 vnf_index,
725 nsr_descriptor,
726 ns_request,
727 ns_k8s_namespace,
elumalai99078a92022-07-05 17:53:59 +0530728 revision=None,
garciadeblas4568a372021-03-24 09:19:48 +0100729 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300730 vnfr_id = str(uuid4())
731 nsr_id = nsr_descriptor["id"]
732 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100733 additional_params, vnf_params = self._format_additional_params(
734 ns_request, vnf_index, descriptor=vnfd
735 )
garciaale7cbd03c2020-11-27 10:38:35 -0300736
737 vnfr_descriptor = {
738 "id": vnfr_id,
739 "_id": vnfr_id,
740 "nsr-id-ref": nsr_id,
741 "member-vnf-index-ref": vnf_index,
742 "additionalParamsForVnf": additional_params,
743 "created-time": now,
744 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
745 "vnfd-ref": vnfd_id,
746 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
747 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200748 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300749 "vdur": [],
750 "connection-point": [],
751 "ip-address": None, # mgmt-interface filled by LCM
752 }
beierlmcee2ebf2022-03-29 17:42:48 -0400753
754 # Revision backwards compatility. Only specify the revision in the record if
755 # the original VNFD has a revision.
756 if "revision" in vnfd:
757 vnfr_descriptor["revision"] = vnfd["revision"]
758
garciaale7cbd03c2020-11-27 10:38:35 -0300759 vnf_k8s_namespace = ns_k8s_namespace
760 if vnf_params:
761 if vnf_params.get("k8s-namespace"):
762 vnf_k8s_namespace = vnf_params["k8s-namespace"]
763 if vnf_params.get("config-units"):
764 vnfr_descriptor["config-units"] = vnf_params["config-units"]
765
766 # Create vld
767 if vnfd.get("int-virtual-link-desc"):
768 vnfr_descriptor["vld"] = []
769 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
770 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
771
772 for cp in vnfd.get("ext-cpd", ()):
773 vnf_cp = {
774 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100775 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
776 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300777 "id": cp.get("id"),
778 # "ip-address", "mac-address" # filled by LCM
779 # vim-id # TODO it would be nice having a vim port id
780 }
781 vnfr_descriptor["connection-point"].append(vnf_cp)
782
783 # Create k8s-cluster information
784 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
785 if vnfd.get("k8s-cluster"):
786 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
787 all_k8s_cluster_nets_cpds = {}
788 for cpd in get_iterable(vnfd.get("ext-cpd")):
789 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100790 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
791 "id"
792 )
garciaale7cbd03c2020-11-27 10:38:35 -0300793 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
794 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100795 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
796 net.get("id")
797 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300798
799 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300800 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100801 additional_params, kdu_params = self._format_additional_params(
802 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
803 )
garciaale7cbd03c2020-11-27 10:38:35 -0300804 kdu_k8s_namespace = vnf_k8s_namespace
805 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
806 if kdu_params and kdu_params.get("k8s-namespace"):
807 kdu_k8s_namespace = kdu_params["k8s-namespace"]
808
romeromonserbfebfc02021-05-28 10:51:35 +0200809 kdu_deployment_name = ""
810 if kdu_params and kdu_params.get("kdu-deployment-name"):
811 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
812
garciaale7cbd03c2020-11-27 10:38:35 -0300813 kdur = {
814 "additionalParams": additional_params,
815 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200816 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000817 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300818 # TODO "name": "" Name of the VDU in the VIM
819 "ip-address": None, # mgmt-interface filled by LCM
820 "k8s-cluster": {},
821 }
822 if kdu_params and kdu_params.get("config-units"):
823 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000824 if kdu.get("helm-version"):
825 kdur["helm-version"] = kdu["helm-version"]
826 for k8s_type in ("helm-chart", "juju-bundle"):
827 if kdu.get(k8s_type):
828 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300829 if not vnfr_descriptor.get("kdur"):
830 vnfr_descriptor["kdur"] = []
831 vnfr_descriptor["kdur"].append(kdur)
832
833 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300834
garciaale7cbd03c2020-11-27 10:38:35 -0300835 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300836 vdu_mgmt_cp = []
837 try:
garciadeblas4568a372021-03-24 09:19:48 +0100838 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
839 "operate-vnf-op-config"
840 ]["day1-2"]
841 vdu_config = utils.find_in_list(
842 configs, lambda config: config["id"] == vdu["id"]
843 )
bravoff3c39552021-02-24 17:22:24 -0300844 except Exception:
845 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400846
847 try:
848 vdu_instantiation_level = utils.find_in_list(
849 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100850 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400851 )
852 except Exception:
853 vdu_instantiation_level = None
854
bravoff3c39552021-02-24 17:22:24 -0300855 if vdu_config:
856 external_connection_ee = utils.filter_in_list(
857 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100858 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300859 )
860 for ee in external_connection_ee:
861 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
862
garciaale7cbd03c2020-11-27 10:38:35 -0300863 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100864 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
865 )
bravof65e22e52021-11-10 17:58:58 -0300866
867 try:
868 vdu_virtual_storage_descriptors = utils.filter_in_list(
869 vnfd.get("virtual-storage-desc", []),
garciadeblasf2af4a12023-01-24 16:56:54 +0100870 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"],
bravof65e22e52021-11-10 17:58:58 -0300871 )
872 except Exception:
873 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300874 vdur = {
875 "vdu-id-ref": vdu["id"],
876 # TODO "name": "" Name of the VDU in the VIM
877 "ip-address": None, # mgmt-interface filled by LCM
878 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
879 "internal-connection-point": [],
880 "interfaces": [],
881 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100882 "vdu-name": vdu["name"],
garciadeblasf2af4a12023-01-24 16:56:54 +0100883 "virtual-storages": vdu_virtual_storage_descriptors,
garciaale7cbd03c2020-11-27 10:38:35 -0300884 }
885 if vdu_params and vdu_params.get("config-units"):
886 vdur["config-units"] = vdu_params["config-units"]
887 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100888 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
889 "boot-data-drive"
890 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300891 if vdu.get("pdu-type"):
892 vdur["pdu-type"] = vdu["pdu-type"]
893 vdur["name"] = vdu["pdu-type"]
894 # TODO volumes: name, volume-id
895 for icp in vdu.get("int-cpd", ()):
896 vdu_icp = {
897 "id": icp["id"],
898 "connection-point-id": icp["id"],
899 "name": icp.get("id"),
900 }
bravof35766442021-02-04 14:58:04 -0300901
garciaale7cbd03c2020-11-27 10:38:35 -0300902 vdur["internal-connection-point"].append(vdu_icp)
903
904 for iface in icp.get("virtual-network-interface-requirement", ()):
aticigc9c03392022-06-16 01:39:44 +0300905 # Name, mac-address and interface position is taken from VNFD
906 # and included into VNFR. By this way RO can process this information
907 # while creating the VDU.
Gulsum Atici9af2a472023-03-28 17:50:48 +0300908 iface_fields = ("name", "mac-address", "position", "ip-address")
garciadeblas4568a372021-03-24 09:19:48 +0100909 vdu_iface = {
910 x: iface[x] for x in iface_fields if iface.get(x) is not None
911 }
garciaale7cbd03c2020-11-27 10:38:35 -0300912
913 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100914 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100915 vdu_iface["port-security-enabled"] = icp[
916 "port-security-enabled"
917 ]
sousaedu003844e2021-03-02 00:19:15 +0100918
919 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100920 vdu_iface["port-security-disable-strategy"] = icp[
921 "port-security-disable-strategy"
922 ]
sousaedu003844e2021-03-02 00:19:15 +0100923
garciaale7cbd03c2020-11-27 10:38:35 -0300924 for ext_cp in vnfd.get("ext-cpd", ()):
925 if not ext_cp.get("int-cpd"):
926 continue
927 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
928 continue
929 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100930 vdu_iface["external-connection-point-ref"] = ext_cp.get(
931 "id"
932 )
sousaedu003844e2021-03-02 00:19:15 +0100933
934 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100935 vdu_iface["port-security-enabled"] = ext_cp[
936 "port-security-enabled"
937 ]
sousaedu003844e2021-03-02 00:19:15 +0100938
939 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100940 vdu_iface["port-security-disable-strategy"] = ext_cp[
941 "port-security-disable-strategy"
942 ]
sousaedu003844e2021-03-02 00:19:15 +0100943
garciaale7cbd03c2020-11-27 10:38:35 -0300944 break
945
garciadeblas4568a372021-03-24 09:19:48 +0100946 if (
947 vnfd_mgmt_cp
948 and vdu_iface.get("external-connection-point-ref")
949 == vnfd_mgmt_cp
950 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300951 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300952 vdu_iface["mgmt-interface"] = True
953
954 for ecp in vdu_mgmt_cp:
955 if vdu_iface.get("external-connection-point-ref") == ecp:
956 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300957
958 if iface.get("virtual-interface"):
959 vdu_iface.update(deepcopy(iface["virtual-interface"]))
960
961 # look for network where this interface is connected
962 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
963 if iface_ext_cp:
964 # TODO: Change for multiple df support
965 for df in get_iterable(nsd.get("df")):
966 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100967 for vlc_index, vlc in enumerate(
968 get_iterable(
969 vnf_profile.get("virtual-link-connectivity")
970 )
971 ):
972 for cpd in get_iterable(
973 vlc.get("constituent-cpd-id")
974 ):
975 if (
976 cpd.get("constituent-cpd-id")
977 == iface_ext_cp
Pedro Escaleira4606e4a2023-05-31 14:32:17 +0100978 ) and vnf_profile.get("id") == vnf_index:
garciadeblas4568a372021-03-24 09:19:48 +0100979 vdu_iface["ns-vld-id"] = vlc.get(
980 "virtual-link-profile-id"
981 )
garciadeblas61c95912021-02-12 11:23:50 +0000982 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100983 if vdu_iface.get("type") in (
984 "SR-IOV",
985 "PCI-PASSTHROUGH",
986 ):
987 nsr_descriptor["vld"][vlc_index][
988 "pci-interfaces"
989 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300990 break
991 elif vdu_iface.get("internal-connection-point-ref"):
992 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000993 # TODO: store fixed IP address in the record (if it exists in the ICP)
994 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
995 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100996 ivld_index = utils.find_index_in_list(
997 vnfd.get("int-virtual-link-desc", ()),
998 lambda ivld: ivld["id"]
999 == icp.get("int-virtual-link-desc"),
1000 )
garciadeblas61c95912021-02-12 11:23:50 +00001001 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -03001002
1003 vdur["interfaces"].append(vdu_iface)
1004
1005 if vdu.get("sw-image-desc"):
1006 sw_image = utils.find_in_list(
1007 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001008 lambda image: image["id"] == vdu.get("sw-image-desc"),
1009 )
garciaale7cbd03c2020-11-27 10:38:35 -03001010 nsr_sw_image_data = utils.find_in_list(
1011 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001012 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -03001013 )
1014 vdur["ns-image-id"] = nsr_sw_image_data["id"]
1015
lloretgalleg28c13b62021-02-08 11:48:48 +00001016 if vdu.get("alternative-sw-image-desc"):
1017 alt_image_ids = []
1018 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1019 sw_image = utils.find_in_list(
1020 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001021 lambda image: image["id"] == alt_image_id,
1022 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001023 nsr_sw_image_data = utils.find_in_list(
1024 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001025 lambda nsr_image: (
1026 nsr_image.get("image") == sw_image.get("image")
1027 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001028 )
1029 alt_image_ids.append(nsr_sw_image_data["id"])
1030 vdur["alt-image-ids"] = alt_image_ids
1031
elumalai99078a92022-07-05 17:53:59 +05301032 revision = revision if revision is not None else 1
garciadeblasf2af4a12023-01-24 16:56:54 +01001033 flavor_data_name = (
1034 vdu["id"][:56] + "-" + vnf_index + "-" + str(revision) + "-flv"
1035 )
garciaale7cbd03c2020-11-27 10:38:35 -03001036 nsr_flavor_desc = utils.find_in_list(
1037 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001038 lambda flavor: flavor["name"] == flavor_data_name,
1039 )
garciaale7cbd03c2020-11-27 10:38:35 -03001040
1041 if nsr_flavor_desc:
1042 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1043
vegall18101ea2023-03-06 13:49:21 +00001044 # Adding Shared Volume information to vdur
1045 if vdur.get("virtual-storages"):
1046 nsr_sv = []
1047 for vsd in vdur["virtual-storages"]:
1048 if vsd.get("vdu-storage-requirements"):
1049 if (
1050 vsd["vdu-storage-requirements"][0].get("key")
1051 == "multiattach"
1052 and vsd["vdu-storage-requirements"][0].get("value")
1053 == "True"
1054 ):
1055 nsr_sv.append(vsd["id"])
1056 if nsr_sv:
1057 vdur["shared-volumes-id"] = nsr_sv
1058
Alexis Romero03fb5842022-03-11 15:53:40 +01001059 # Adding Affinity groups information to vdur
1060 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001061 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001062 vnfd.get("df")[0]["vdu-profile"],
1063 lambda a_vdu: a_vdu["id"] == vdu["id"],
1064 )
1065 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001066 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001067
Alexis Romeroee31f532022-04-26 19:10:21 +02001068 if vdu_profile_affinity_group:
1069 affinity_group_ids = []
1070 for affinity_group in vdu_profile_affinity_group.get(
1071 "affinity-or-anti-affinity-group", ()
1072 ):
1073 vdu_affinity_group = utils.find_in_list(
1074 vdu_profile_affinity_group.get(
1075 "affinity-or-anti-affinity-group", ()
1076 ),
1077 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001078 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001079 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001080 nsr_descriptor["affinity-or-anti-affinity-group"],
1081 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001082 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1083 and nsr_ag.get("member-vnf-index")
1084 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001085 ),
1086 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001087 # Update Affinity Group VIM name if VDU instantiation parameter is present
1088 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1089 vnf_params_affinity_group = utils.find_in_list(
1090 vnf_params["affinity-or-anti-affinity-group"],
1091 lambda vnfp_ag: (
1092 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1093 ),
1094 )
1095 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1096 nsr_affinity_group[
1097 "vim-affinity-group-id"
1098 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1099 affinity_group_ids.append(nsr_affinity_group["id"])
1100 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001101
bravof4ca51522021-04-22 10:03:02 -04001102 if vdu_instantiation_level:
1103 count = vdu_instantiation_level.get("number-of-instances")
1104 else:
1105 count = 1
1106
garciaale7cbd03c2020-11-27 10:38:35 -03001107 for index in range(0, count):
1108 vdur = deepcopy(vdur)
1109 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001110 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001111 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001112 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001113 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1114
1115 vdur["_id"] = str(uuid4())
1116 vdur["id"] = vdur["_id"]
1117 vdur["count-index"] = index
1118 vnfr_descriptor["vdur"].append(vdur)
garciaale7cbd03c2020-11-27 10:38:35 -03001119 return vnfr_descriptor
1120
K Sai Kiran57589552021-01-27 21:38:34 +05301121 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1122 """
1123 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1124 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1125 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1126 :param ns_instance_content: ns instance content
1127 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1128 :return: None
1129 """
garciadeblasf2af4a12023-01-24 16:56:54 +01001130 time_now, time_delta = (
1131 time(),
1132 time() - ns_instance_content["_admin"]["modified"],
1133 )
1134 force_refresh = (
1135 isinstance(filter_q, dict) and filter_q.get("vcaStatusRefresh") == "true"
1136 )
K Sai Kiran57589552021-01-27 21:38:34 +05301137 threshold_reached = time_delta > 120
1138 if force_refresh or threshold_reached:
1139 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1140 ns_instance_content["_admin"]["modified"] = time_now
1141 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1142 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
garciadeblasf2af4a12023-01-24 16:56:54 +01001143 self.format_on_new(
1144 nslcmop_desc, session["project_id"], make_public=session["public"]
1145 )
K Sai Kiran57589552021-01-27 21:38:34 +05301146 nslcmop_desc["_admin"].pop("nsState")
1147 self.msg.write("ns", operation, nslcmop_desc)
1148 return
1149
1150 def show(self, session, _id, filter_q=None, api_req=False):
1151 """
1152 Get complete information on an ns instance.
1153 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1154 :param _id: string, ns instance id
1155 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1156 :param api_req: True if this call is serving an external API request. False if serving internal request.
1157 :return: dictionary, raise exception if not found.
1158 """
1159 ns_instance_content = super().show(session, _id, api_req)
1160 self.vca_status_refresh(session, ns_instance_content, filter_q)
1161 return ns_instance_content
1162
tierno65ca36d2019-02-12 19:27:52 +01001163 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001164 raise EngineException(
1165 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1166 )
tiernob24258a2018-10-04 18:39:49 +02001167
1168
1169class VnfrTopic(BaseTopic):
1170 topic = "vnfrs"
1171 topic_msg = None
1172
delacruzramo32bab472019-09-13 12:24:22 +02001173 def __init__(self, db, fs, msg, auth):
1174 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001175
tiernobee3bad2019-12-05 12:26:01 +00001176 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001177 raise EngineException(
1178 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1179 )
tiernob24258a2018-10-04 18:39:49 +02001180
tierno65ca36d2019-02-12 19:27:52 +01001181 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001182 raise EngineException(
1183 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1184 )
tiernob24258a2018-10-04 18:39:49 +02001185
tierno65ca36d2019-02-12 19:27:52 +01001186 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001187 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001188 raise EngineException(
1189 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1190 )
tiernob24258a2018-10-04 18:39:49 +02001191
1192
1193class NsLcmOpTopic(BaseTopic):
1194 topic = "nslcmops"
1195 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001196 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001197 "instantiate": ns_instantiate,
1198 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001199 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001200 "scale": ns_scale,
garciadeblas0964edf2022-02-11 00:43:44 +01001201 "heal": ns_heal,
tierno1c38f2f2020-03-24 11:51:39 +00001202 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301203 "migrate": ns_migrate,
govindarajul519da482022-04-29 19:05:22 +05301204 "verticalscale": ns_verticalscale,
tiernob24258a2018-10-04 18:39:49 +02001205 }
1206
delacruzramo32bab472019-09-13 12:24:22 +02001207 def __init__(self, db, fs, msg, auth):
1208 BaseTopic.__init__(self, db, fs, msg, auth)
elumalai6c5ea6b2022-04-25 22:27:59 +05301209 self.nsrtopic = NsrTopic(db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001210
tiernob24258a2018-10-04 18:39:49 +02001211 def _check_ns_operation(self, session, nsr, operation, indata):
1212 """
1213 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001214 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
garciadeblas0964edf2022-02-11 00:43:44 +01001215 :param operation: it can be: instantiate, terminate, action, update, heal
tiernob24258a2018-10-04 18:39:49 +02001216 :param indata: descriptor with the parameters of the operation
1217 :return: None
1218 """
garciaale7cbd03c2020-11-27 10:38:35 -03001219 if operation == "action":
1220 self._check_action_ns_operation(indata, nsr)
1221 elif operation == "scale":
1222 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001223 elif operation == "update":
1224 self._check_update_ns_operation(indata, nsr)
garciadeblas0964edf2022-02-11 00:43:44 +01001225 elif operation == "heal":
1226 self._check_heal_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001227 elif operation == "instantiate":
1228 self._check_instantiate_ns_operation(indata, nsr, session)
1229
1230 def _check_action_ns_operation(self, indata, nsr):
1231 nsd = nsr["nsd"]
1232 # check vnf_member_index
1233 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001234 indata["member_vnf_index"] = indata.pop(
1235 "vnf_member_index"
1236 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001237 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001238 vnfd = self._get_vnfd_from_vnf_member_index(
1239 indata["member_vnf_index"], nsr["_id"]
1240 )
bravof41a52052021-02-17 18:08:01 -03001241 try:
garciadeblas4568a372021-03-24 09:19:48 +01001242 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1243 "operate-vnf-op-config"
1244 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001245 except Exception:
1246 configs = []
1247
garciaale7cbd03c2020-11-27 10:38:35 -03001248 if indata.get("vdu_id"):
1249 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001250 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001251 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001252 )
garciaale7cbd03c2020-11-27 10:38:35 -03001253 elif indata.get("kdu_name"):
1254 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001255 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001256 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001257 )
garciaale7cbd03c2020-11-27 10:38:35 -03001258 else:
bravof41a52052021-02-17 18:08:01 -03001259 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001260 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001261 )
1262 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001263 descriptor_configuration = descriptor_configuration.get(
1264 "config-primitive"
1265 )
garciaale7cbd03c2020-11-27 10:38:35 -03001266 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001267 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1268 "config-primitive"
1269 )
garciaale7cbd03c2020-11-27 10:38:35 -03001270
1271 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001272 if indata.get("kdu_name") and indata["primitive"] in (
1273 "upgrade",
1274 "rollback",
1275 "status",
1276 "inspect",
1277 "readme",
1278 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001279 # TODO should be checked that rollback only can contains revsision_numbe????
1280 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001281 raise EngineException(
1282 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1283 indata["primitive"]
1284 )
1285 )
garciaale7cbd03c2020-11-27 10:38:35 -03001286 return
1287 # if not, check primitive
1288 for config_primitive in get_iterable(descriptor_configuration):
1289 if indata["primitive"] == config_primitive["name"]:
1290 # check needed primitive_params are provided
1291 if indata.get("primitive_params"):
1292 in_primitive_params_copy = copy(indata["primitive_params"])
1293 else:
1294 in_primitive_params_copy = {}
1295 for paramd in get_iterable(config_primitive.get("parameter")):
1296 if paramd["name"] in in_primitive_params_copy:
1297 del in_primitive_params_copy[paramd["name"]]
1298 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001299 raise EngineException(
1300 "Needed parameter {} not provided for primitive '{}'".format(
1301 paramd["name"], indata["primitive"]
1302 )
1303 )
garciaale7cbd03c2020-11-27 10:38:35 -03001304 # check no extra primitive params are provided
1305 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001306 raise EngineException(
1307 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1308 list(in_primitive_params_copy.keys()), indata["primitive"]
1309 )
1310 )
garciaale7cbd03c2020-11-27 10:38:35 -03001311 break
1312 else:
garciadeblas4568a372021-03-24 09:19:48 +01001313 raise EngineException(
1314 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1315 indata["primitive"]
1316 )
1317 )
garciaale7cbd03c2020-11-27 10:38:35 -03001318
aticig544a2ae2022-04-05 09:00:17 +03001319 def _check_update_ns_operation(self, indata, nsr) -> None:
1320 """Validates the ns-update request according to updateType
1321
1322 If updateType is CHANGE_VNFPKG:
1323 - it checks the vnfInstanceId, whether it's available under ns instance
1324 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1325 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301326 If updateType is REMOVE_VNF:
1327 - it checks if the vnfInstanceId is available in the ns instance
1328 - Otherwise exception will be raised.
aticig544a2ae2022-04-05 09:00:17 +03001329
1330 Args:
1331 indata: includes updateType such as CHANGE_VNFPKG,
1332 nsr: network service record
1333
1334 Raises:
1335 EngineException:
1336 a meaningful error if given update parameters are not proper such as
1337 "Error in validating ns-update request: <ID> does not match
1338 with the vnfd-id of vnfinstance
1339 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1340
1341 """
1342 try:
1343 if indata["updateType"] == "CHANGE_VNFPKG":
1344 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1345 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1346 ns_instance_id = indata["nsInstanceId"]
1347 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1348
1349 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
aticig544a2ae2022-04-05 09:00:17 +03001350 raise EngineException(
1351 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1352 f"belong to NS {ns_instance_id}",
1353 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1354 )
1355
1356 # Getting vnfrs through the ns_instance_id
1357 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1358 constituent_vnfd_id = next(
1359 (
1360 vnfr["vnfd-id"]
1361 for vnfr in vnfrs
1362 if vnfr["id"] == vnf_instance_id
1363 ),
1364 None,
1365 )
1366
1367 # Check the given vnfd-id belongs to given vnf instance
1368 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
aticig544a2ae2022-04-05 09:00:17 +03001369 raise EngineException(
1370 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1371 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1372 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1373 )
1374
1375 # Validating the ns update timeout
1376 if (
1377 indata.get("timeout_ns_update")
1378 and indata["timeout_ns_update"] < 300
1379 ):
1380 raise EngineException(
1381 "Error in validating ns-update request: {} second is not enough "
1382 "to upgrade the VNF instance: {}".format(
1383 indata["timeout_ns_update"], vnf_instance_id
1384 ),
1385 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1386 )
elumalai6380e7c2022-04-28 00:15:59 +05301387 elif indata["updateType"] == "REMOVE_VNF":
1388 vnf_instance_id = indata["removeVnfInstanceId"]
1389 ns_instance_id = indata["nsInstanceId"]
1390 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1391 raise EngineException(
1392 "Invalid VNF Instance Id. '{}' is not "
1393 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1394 )
aticig544a2ae2022-04-05 09:00:17 +03001395
1396 except (
1397 DbException,
1398 AttributeError,
1399 IndexError,
1400 KeyError,
1401 ValueError,
1402 ) as e:
1403 raise type(e)(
1404 "Ns update request could not be processed with error: {}.".format(e)
1405 )
1406
garciaale7cbd03c2020-11-27 10:38:35 -03001407 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001408 vnfd = self._get_vnfd_from_vnf_member_index(
1409 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1410 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001411 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001412 if (
1413 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1414 == scaling_aspect["id"]
1415 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001416 break
1417 else:
garciadeblas4568a372021-03-24 09:19:48 +01001418 raise EngineException(
1419 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1420 "present at vnfd:scaling-aspect".format(
1421 indata["scaleVnfData"]["scaleByStepData"][
1422 "scaling-group-descriptor"
1423 ]
1424 )
1425 )
garciaale7cbd03c2020-11-27 10:38:35 -03001426
garciadeblas0964edf2022-02-11 00:43:44 +01001427 def _check_heal_ns_operation(self, indata, nsr):
jeganc1bf1562023-11-13 05:01:53 +00001428 try:
1429 for data in indata.get("healVnfData"):
1430 vnf_id = data.get("vnfInstanceId")
1431 vnf = self.db.get_one("vnfrs", {"_id": vnf_id})
1432 vnfd_member_vnf_index = vnf.get("member-vnf-index-ref")
1433 vnfd = self._get_vnfd_from_vnf_member_index(
1434 vnfd_member_vnf_index, nsr["_id"]
1435 )
1436 if data.get("additionalParams"):
1437 vdu_id = data["additionalParams"].get("vdu")
1438 if vdu_id:
1439 for index in range(len(vdu_id)):
1440 vdu = vdu_id[index].get("vdu-id")
1441 self._check_valid_vdu(vnfd, vdu)
1442 except (DbException, AttributeError, IndexError, KeyError, ValueError) as e:
1443 raise type(e)(
1444 "Ns healing request could not be processed with error: {}.".format(e)
1445 )
garciadeblas0964edf2022-02-11 00:43:44 +01001446
garciaale7cbd03c2020-11-27 10:38:35 -03001447 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001448 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001449 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001450 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001451 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001452 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1453 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1454 for in_vnf in get_iterable(indata.get("vnf")):
1455 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001456 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001457 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001458 else:
garciadeblas4568a372021-03-24 09:19:48 +01001459 vnfd = self._get_vnfd_from_vnf_member_index(
1460 member_vnf_index, nsr["_id"]
1461 )
1462 vnf_member_index_to_vnfd[
1463 member_vnf_index
1464 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001465 self._check_vnf_instantiation_params(in_vnf, vnfd)
1466 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001467 self._check_valid_vim_account(
1468 in_vnf["vimAccountId"], vim_accounts, session
1469 )
tierno260dd6f2019-09-02 10:48:56 +00001470
garciaale7cbd03c2020-11-27 10:38:35 -03001471 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001472 self._check_valid_wim_account(
1473 in_vld.get("wimAccountId"), wim_accounts, session
1474 )
garciaale7cbd03c2020-11-27 10:38:35 -03001475 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1476 if in_vld["name"] == vldd["id"]:
1477 break
tierno9cb7d672019-10-30 12:13:48 +00001478 else:
garciadeblas4568a372021-03-24 09:19:48 +01001479 raise EngineException(
1480 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1481 in_vld["name"]
1482 )
1483 )
tierno9cb7d672019-10-30 12:13:48 +00001484
garciaale7cbd03c2020-11-27 10:38:35 -03001485 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1486 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001487 vnfr = self.db.get_one(
1488 "vnfrs",
1489 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1490 fail_on_empty=False,
1491 )
garciaale7cbd03c2020-11-27 10:38:35 -03001492 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001493 raise EngineException(
1494 "Invalid parameter member_vnf_index='{}' is not one of the "
1495 "nsd:constituent-vnfd".format(member_vnf_index)
1496 )
beierlmcee2ebf2022-03-29 17:42:48 -04001497
garciadeblasf2af4a12023-01-24 16:56:54 +01001498 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
beierlmcee2ebf2022-03-29 17:42:48 -04001499 if "revision" in vnfr:
1500 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
garciadeblasf2af4a12023-01-24 16:56:54 +01001501 vnfd = self.db.get_one(
1502 "vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False
1503 )
beierlmcee2ebf2022-03-29 17:42:48 -04001504 else:
garciadeblasf2af4a12023-01-24 16:56:54 +01001505 vnfd = self.db.get_one(
1506 "vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False
1507 )
beierlmcee2ebf2022-03-29 17:42:48 -04001508
garciaale7cbd03c2020-11-27 10:38:35 -03001509 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001510 raise EngineException(
1511 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1512 vnfr["vnfd-id"]
1513 )
1514 )
garciaale7cbd03c2020-11-27 10:38:35 -03001515 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001516
garciaale7cbd03c2020-11-27 10:38:35 -03001517 def _check_valid_vdu(self, vnfd, vdu_id):
1518 for vdud in get_iterable(vnfd.get("vdu")):
1519 if vdud["id"] == vdu_id:
1520 return vdud
1521 else:
garciadeblas4568a372021-03-24 09:19:48 +01001522 raise EngineException(
1523 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1524 vdu_id
1525 )
1526 )
garciaale7cbd03c2020-11-27 10:38:35 -03001527
1528 def _check_valid_kdu(self, vnfd, kdu_name):
1529 for kdud in get_iterable(vnfd.get("kdu")):
1530 if kdud["name"] == kdu_name:
1531 return kdud
1532 else:
garciadeblas4568a372021-03-24 09:19:48 +01001533 raise EngineException(
1534 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1535 kdu_name
1536 )
1537 )
garciaale7cbd03c2020-11-27 10:38:35 -03001538
1539 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1540 for in_vdu in get_iterable(in_vnf.get("vdu")):
1541 for vdu in get_iterable(vnfd.get("vdu")):
1542 if in_vdu["id"] == vdu["id"]:
1543 for volume in get_iterable(in_vdu.get("volume")):
1544 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
aticigd7753fc2022-05-18 18:55:23 +03001545 if volumed == volume["name"]:
garciaale7cbd03c2020-11-27 10:38:35 -03001546 break
1547 else:
garciadeblas4568a372021-03-24 09:19:48 +01001548 raise EngineException(
1549 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1550 "volume:name='{}' is not present at "
1551 "vnfd:vdu:virtual-storage-desc list".format(
1552 in_vnf["member-vnf-index"],
1553 in_vdu["id"],
1554 volume["id"],
1555 )
1556 )
garciaale7cbd03c2020-11-27 10:38:35 -03001557
1558 vdu_if_names = set()
1559 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001560 for iface in get_iterable(
1561 cpd.get("virtual-network-interface-requirement")
1562 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001563 vdu_if_names.add(iface.get("name"))
1564
aticigd7753fc2022-05-18 18:55:23 +03001565 for in_iface in get_iterable(in_vdu.get("interface")):
garciaale7cbd03c2020-11-27 10:38:35 -03001566 if in_iface["name"] in vdu_if_names:
1567 break
1568 else:
garciadeblas4568a372021-03-24 09:19:48 +01001569 raise EngineException(
1570 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1571 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1572 in_vnf["member-vnf-index"],
1573 in_vdu["id"],
1574 in_iface["name"],
1575 )
1576 )
garciaale7cbd03c2020-11-27 10:38:35 -03001577 break
1578
1579 else:
garciadeblas4568a372021-03-24 09:19:48 +01001580 raise EngineException(
1581 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1582 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1583 )
garciaale7cbd03c2020-11-27 10:38:35 -03001584
garciadeblas4568a372021-03-24 09:19:48 +01001585 vnfd_ivlds_cpds = {
1586 ivld.get("id"): set()
1587 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1588 }
Gulsum Atici9af2a472023-03-28 17:50:48 +03001589 for vdu in vnfd.get("vdu", {}):
1590 for cpd in vdu.get("int-cpd", {}):
garciaale7cbd03c2020-11-27 10:38:35 -03001591 if cpd.get("int-virtual-link-desc"):
1592 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1593
1594 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1595 if in_ivld.get("name") in vnfd_ivlds_cpds:
1596 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1597 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001598 break
tiernob24258a2018-10-04 18:39:49 +02001599 else:
garciadeblas4568a372021-03-24 09:19:48 +01001600 raise EngineException(
1601 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1602 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1603 "vnfd:internal-vld:name/id:internal-connection-point".format(
1604 in_vnf["member-vnf-index"],
1605 in_ivld["name"],
1606 in_icp["id-ref"],
1607 )
1608 )
tiernob24258a2018-10-04 18:39:49 +02001609 else:
garciadeblas4568a372021-03-24 09:19:48 +01001610 raise EngineException(
1611 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1612 " is not present at vnfd '{}'".format(
1613 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1614 )
1615 )
tiernob24258a2018-10-04 18:39:49 +02001616
garciaale7cbd03c2020-11-27 10:38:35 -03001617 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1618 if vim_account in vim_accounts:
1619 return
1620 try:
1621 db_filter = self._get_project_filter(session)
1622 db_filter["_id"] = vim_account
1623 self.db.get_one("vim_accounts", db_filter)
1624 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001625 raise EngineException(
1626 "Invalid vimAccountId='{}' not present for the project".format(
1627 vim_account
1628 )
1629 )
garciaale7cbd03c2020-11-27 10:38:35 -03001630 vim_accounts.append(vim_account)
1631
David Garcia98de2982021-10-13 17:14:01 +02001632 def _get_vim_account(self, vim_id: str, session):
1633 try:
1634 db_filter = self._get_project_filter(session)
1635 db_filter["_id"] = vim_id
1636 return self.db.get_one("vim_accounts", db_filter)
1637 except Exception:
1638 raise EngineException(
garciadeblasf2af4a12023-01-24 16:56:54 +01001639 "Invalid vimAccountId='{}' not present for the project".format(vim_id)
David Garcia98de2982021-10-13 17:14:01 +02001640 )
1641
garciaale7cbd03c2020-11-27 10:38:35 -03001642 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1643 if not isinstance(wim_account, str):
1644 return
1645 if wim_account in wim_accounts:
1646 return
1647 try:
gifrerenom44f5ec12022-03-07 16:57:25 +00001648 db_filter = self._get_project_filter(session)
garciaale7cbd03c2020-11-27 10:38:35 -03001649 db_filter["_id"] = wim_account
1650 self.db.get_one("wim_accounts", db_filter)
1651 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001652 raise EngineException(
1653 "Invalid wimAccountId='{}' not present for the project".format(
1654 wim_account
1655 )
1656 )
garciaale7cbd03c2020-11-27 10:38:35 -03001657 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001658
garciadeblas4568a372021-03-24 09:19:48 +01001659 def _look_for_pdu(
1660 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1661 ):
tiernocc103432018-10-19 14:10:35 +02001662 """
tierno36ec8602018-11-02 17:27:11 +01001663 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1664 (ip_address, ...) information.
1665 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001666 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001667 :param rollback: list with the database modifications to rollback if needed
1668 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1669 :param vim_account: vim_account where this vnfr should be deployed
1670 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1671 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1672 of the changed vnfr is needed
1673
1674 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1675 "vim-network-name": used at VIM
1676 "name": interface name
1677 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1678 "ns-vld-id": NSD vld where this interface is connected.
1679 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 +02001680 """
tierno36ec8602018-11-02 17:27:11 +01001681
1682 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001683 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1684 if not vdur.get("pdu-type"):
1685 continue
1686 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001687 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001688 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001689 pdu_filter["type"] = pdu_type
1690 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001691 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001692 # TODO feature 1417: "shared": True,
1693
1694 available_pdus = self.db.get_list("pdus", pdu_filter)
1695 for pdu in available_pdus:
1696 # step 1 check if this pdu contains needed interfaces:
1697 match_interfaces = True
1698 for vdur_interface in vdur["interfaces"]:
1699 for pdu_interface in pdu["interfaces"]:
1700 if pdu_interface["name"] == vdur_interface["name"]:
1701 # TODO feature 1417: match per mgmt type
1702 break
1703 else: # no interface found for name
1704 match_interfaces = False
1705 break
1706 if match_interfaces:
1707 break
1708 else:
1709 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001710 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001711 "names".format(
1712 pdu_type,
1713 vim_account,
1714 vnfr["member-vnf-index-ref"],
1715 vdur["vdu-id-ref"],
1716 )
1717 )
tiernocc103432018-10-19 14:10:35 +02001718
1719 # step 2. Update pdu
1720 rollback_pdu = {
1721 "_admin.usageState": pdu["_admin"]["usageState"],
1722 "_admin.usage.vnfr_id": None,
1723 "_admin.usage.nsr_id": None,
1724 "_admin.usage.vdur": None,
1725 }
garciadeblas4568a372021-03-24 09:19:48 +01001726 self.db.set_one(
1727 "pdus",
1728 {"_id": pdu["_id"]},
1729 {
1730 "_admin.usageState": "IN_USE",
1731 "_admin.usage": {
1732 "vnfr_id": vnfr["_id"],
1733 "nsr_id": vnfr["nsr-id-ref"],
1734 "vdur": vdur["vdu-id-ref"],
1735 },
1736 },
1737 )
1738 rollback.append(
1739 {
1740 "topic": "pdus",
1741 "_id": pdu["_id"],
1742 "operation": "set",
1743 "content": rollback_pdu,
1744 }
1745 )
tiernocc103432018-10-19 14:10:35 +02001746
1747 # step 3. Fill vnfr info by filling vdur
1748 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001749 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001750 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1751 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1752 for pdu_interface in pdu["interfaces"]:
1753 if pdu_interface["name"] == vdur_interface["name"]:
1754 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1755 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001756 if k in (
1757 "ip-address",
1758 "mac-address",
1759 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001760 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001761 vnfr_update_rollback[
1762 iface_text + ".{}".format(k)
1763 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001764 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001765 if vdur_interface.get(
1766 "mgmt-interface"
1767 ) or vdur_interface.get("mgmt-vnf"):
1768 vnfr_update_rollback[
1769 vdu_text + ".ip-address"
1770 ] = vdur.get("ip-address")
1771 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1772 "ip-address"
1773 ]
tierno36ec8602018-11-02 17:27:11 +01001774 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001775 vnfr_update_rollback["ip-address"] = vnfr.get(
1776 "ip-address"
1777 )
tierno36ec8602018-11-02 17:27:11 +01001778 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001779 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1780 "ip-address"
1781 ]
1782 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1783 "vim-network-id"
1784 ):
1785 ifaces_forcing_vim_network.append(
1786 {
1787 "name": vdur_interface.get("vnf-vld-id")
1788 or vdur_interface.get("ns-vld-id"),
1789 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1790 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1791 }
1792 )
gcalvino17d5b732018-12-17 16:26:21 +01001793 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001794 ifaces_forcing_vim_network[-1][
1795 "vim-network-id"
1796 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001797 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001798 ifaces_forcing_vim_network[-1][
1799 "vim-network-name"
1800 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001801 break
1802
tierno36ec8602018-11-02 17:27:11 +01001803 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001804
garciadeblas4568a372021-03-24 09:19:48 +01001805 def _look_for_k8scluster(
1806 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1807 ):
tierno9cb7d672019-10-30 12:13:48 +00001808 """
1809 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1810 Fills vnfr.kdur with the selected k8scluster
1811
1812 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1813 :param rollback: list with the database modifications to rollback if needed
1814 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1815 :param vim_account: vim_account where this vnfr should be deployed
1816 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1817 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1818 of the changed vnfr is needed
1819
1820 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1821 "vim-network-name": used at VIM
1822 "name": interface name
1823 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1824 "ns-vld-id": NSD vld where this interface is connected.
1825 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1826 """
1827
1828 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001829 if not vnfr.get("kdur"):
1830 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001831
tiernoc67b0e92019-11-05 12:45:29 +00001832 kdu_filter = self._get_project_filter(session)
1833 kdu_filter["vim_account"] = vim_account
1834 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1835 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1836
1837 k8s_requirements = {} # just for logging
1838 for k8scluster in available_k8sclusters:
1839 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001840 break
tiernoc67b0e92019-11-05 12:45:29 +00001841 # restrict by cni
1842 if vnfr["k8s-cluster"].get("cni"):
1843 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001844 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1845 k8scluster.get("cni", ())
1846 ):
tiernoc67b0e92019-11-05 12:45:29 +00001847 continue
1848 # restrict by version
1849 if vnfr["k8s-cluster"].get("version"):
1850 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1851 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1852 continue
1853 # restrict by number of networks
1854 if vnfr["k8s-cluster"].get("nets"):
1855 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001856 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1857 vnfr["k8s-cluster"]["nets"]
1858 ):
tiernoc67b0e92019-11-05 12:45:29 +00001859 continue
1860 break
1861 else:
garciadeblas4568a372021-03-24 09:19:48 +01001862 raise EngineException(
1863 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1864 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1865 )
1866 )
tierno9cb7d672019-10-30 12:13:48 +00001867
tiernoc67b0e92019-11-05 12:45:29 +00001868 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001869 # step 3. Fill vnfr info by filling kdur
1870 kdu_text = "kdur.{}.".format(kdur_index)
1871 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1872 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1873
tiernoc67b0e92019-11-05 12:45:29 +00001874 # step 4. Check VIM networks that forces the selected k8s_cluster
1875 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1876 k8scluster_net_list = list(k8scluster.get("nets").keys())
1877 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1878 # get a network from k8s_cluster nets. If name matches use this, if not use other
1879 if kdur_net["id"] in k8scluster_net_list: # name matches
1880 vim_net = k8scluster["nets"][kdur_net["id"]]
1881 k8scluster_net_list.remove(kdur_net["id"])
1882 else:
1883 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1884 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001885 vnfr_update_rollback[
1886 "k8s-cluster.nets.{}.vim_net".format(net_index)
1887 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001888 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001889 if vim_net and (
1890 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1891 ):
1892 ifaces_forcing_vim_network.append(
1893 {
1894 "name": kdur_net.get("vnf-vld-id")
1895 or kdur_net.get("ns-vld-id"),
1896 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1897 "ns-vld-id": kdur_net.get("ns-vld-id"),
1898 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1899 }
1900 )
tiernoc67b0e92019-11-05 12:45:29 +00001901 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001902 return ifaces_forcing_vim_network
1903
Gulsum Aticie395aa42021-11-10 20:59:06 +03001904 def _update_vnfrs_from_nsd(self, nsr):
garciadeblasf2af4a12023-01-24 16:56:54 +01001905 step = "Getting vnf_profiles from nsd" # first step must be defined outside try
Gulsum Aticie395aa42021-11-10 20:59:06 +03001906 try:
1907 nsr_id = nsr["_id"]
1908 nsd = nsr["nsd"]
1909
Gulsum Aticie395aa42021-11-10 20:59:06 +03001910 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1911 vld_fixed_ip_connection_point_data = {}
1912
1913 step = "Getting ip-address info from vnf_profile if it exists"
1914 for vnfp in vnf_profiles:
1915 # Checking ip-address info from nsd.vnf_profile and storing
1916 for vlc in vnfp.get("virtual-link-connectivity", ()):
1917 for cpd in vlc.get("constituent-cpd-id", ()):
1918 if cpd.get("ip-address"):
1919 step = "Storing ip-address info"
garciadeblasf2af4a12023-01-24 16:56:54 +01001920 vld_fixed_ip_connection_point_data.update(
1921 {
1922 vlc.get("virtual-link-profile-id")
1923 + "."
1924 + cpd.get("constituent-base-element-id"): {
1925 "vnfd-connection-point-ref": cpd.get(
1926 "constituent-cpd-id"
1927 ),
1928 "ip-address": cpd.get("ip-address"),
1929 }
1930 }
1931 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001932
1933 # Inserting ip address to vnfr
1934 if len(vld_fixed_ip_connection_point_data) > 0:
1935 step = "Getting vnfrs"
1936 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1937 for item in vld_fixed_ip_connection_point_data.keys():
1938 step = "Filtering vnfrs"
garciadeblasf2af4a12023-01-24 16:56:54 +01001939 vnfr = next(
1940 filter(
1941 lambda vnfr: vnfr["member-vnf-index-ref"]
1942 == item.split(".")[1],
1943 vnfrs,
1944 ),
1945 None,
1946 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001947 if vnfr:
1948 vnfr_update = {}
1949 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1950 for iface_index, iface in enumerate(vdur["interfaces"]):
1951 step = "Looking for matched interface"
1952 if (
garciadeblasf2af4a12023-01-24 16:56:54 +01001953 iface.get("external-connection-point-ref")
1954 == vld_fixed_ip_connection_point_data[item].get(
1955 "vnfd-connection-point-ref"
1956 )
1957 and iface.get("ns-vld-id") == item.split(".")[0]
Gulsum Aticie395aa42021-11-10 20:59:06 +03001958 ):
1959 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1960 vdur_index, iface_index
1961 )
1962 step = "Storing info in order to update vnfr"
1963 vnfr_update[
1964 vnfr_update_text + ".ip-address"
garciadeblasf2af4a12023-01-24 16:56:54 +01001965 ] = increment_ip_mac(
1966 vld_fixed_ip_connection_point_data[item].get(
1967 "ip-address"
1968 ),
1969 vdur.get("count-index", 0),
1970 )
Gulsum Aticie395aa42021-11-10 20:59:06 +03001971 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1972
1973 step = "updating vnfr at database"
1974 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1975 except (
garciadeblasf2af4a12023-01-24 16:56:54 +01001976 ValidationError,
1977 EngineException,
1978 DbException,
1979 MsgException,
1980 FsException,
Gulsum Aticie395aa42021-11-10 20:59:06 +03001981 ) as e:
1982 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1983
tiernocc103432018-10-19 14:10:35 +02001984 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001985 # get vnfr
1986 nsr_id = nsr["_id"]
1987 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1988
1989 for vnfr in vnfrs:
1990 vnfr_update = {}
1991 vnfr_update_rollback = {}
1992 member_vnf_index = vnfr["member-vnf-index-ref"]
1993 # update vim-account-id
1994
1995 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02001996 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001997 # check instantiate parameters
1998 for vnf_inst_params in get_iterable(indata.get("vnf")):
1999 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
2000 continue
2001 if vnf_inst_params.get("vimAccountId"):
2002 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02002003 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02002004
tiernocddb07d2020-10-06 08:28:00 +00002005 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
2006 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
2007 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2008 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
2009 continue
garciadeblas4568a372021-03-24 09:19:48 +01002010 for iface_inst_param in get_iterable(
2011 vdu_inst_param.get("interface")
2012 ):
2013 iface_index, _ = next(
2014 i
2015 for i in enumerate(vdur["interfaces"])
2016 if i[1]["name"] == iface_inst_param["name"]
2017 )
2018 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2019 vdur_index, iface_index
2020 )
tiernocddb07d2020-10-06 08:28:00 +00002021 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002022 vnfr_update[
2023 vnfr_update_text + ".ip-address"
2024 ] = increment_ip_mac(
2025 iface_inst_param.get("ip-address"),
2026 vdur.get("count-index", 0),
2027 )
tierno1bd9d952020-11-13 15:56:51 +00002028 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002029 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002030 vnfr_update[
2031 vnfr_update_text + ".mac-address"
2032 ] = increment_ip_mac(
2033 iface_inst_param.get("mac-address"),
2034 vdur.get("count-index", 0),
2035 )
tierno1bd9d952020-11-13 15:56:51 +00002036 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03002037 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01002038 vnfr_update[
2039 vnfr_update_text + ".floating-ip-required"
2040 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002041 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2042 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01002043 for ivld_inst_param in get_iterable(
2044 vnf_inst_params.get("internal-vld")
2045 ):
2046 for icp_inst_param in get_iterable(
2047 ivld_inst_param.get("internal-connection-point")
2048 ):
tiernocddb07d2020-10-06 08:28:00 +00002049 # look for iface
2050 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2051 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002052 if (
2053 iface.get("internal-connection-point-ref")
2054 == icp_inst_param["id-ref"]
2055 ):
2056 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2057 vdur_index, iface_index
2058 )
tiernocddb07d2020-10-06 08:28:00 +00002059 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002060 vnfr_update[
2061 vnfr_update_text + ".ip-address"
2062 ] = increment_ip_mac(
2063 icp_inst_param.get("ip-address"),
2064 vdur.get("count-index", 0),
2065 )
2066 vnfr_update[
2067 vnfr_update_text + ".fixed-ip"
2068 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002069 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002070 vnfr_update[
2071 vnfr_update_text + ".mac-address"
2072 ] = increment_ip_mac(
2073 icp_inst_param.get("mac-address"),
2074 vdur.get("count-index", 0),
2075 )
2076 vnfr_update[
2077 vnfr_update_text + ".fixed-mac"
2078 ] = True
tiernocddb07d2020-10-06 08:28:00 +00002079 break
2080 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2081 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01002082 for vnfcp_inst_param in get_iterable(
2083 vld_inst_param.get("vnfd-connection-point-ref")
2084 ):
tiernocddb07d2020-10-06 08:28:00 +00002085 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2086 continue
2087 # look for iface
2088 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2089 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002090 if (
2091 iface.get("external-connection-point-ref")
2092 == vnfcp_inst_param["vnfd-connection-point-ref"]
2093 ):
2094 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2095 vdur_index, iface_index
2096 )
tiernocddb07d2020-10-06 08:28:00 +00002097 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002098 vnfr_update[
2099 vnfr_update_text + ".ip-address"
2100 ] = increment_ip_mac(
2101 vnfcp_inst_param.get("ip-address"),
2102 vdur.get("count-index", 0),
2103 )
tierno1bd9d952020-11-13 15:56:51 +00002104 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002105 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002106 vnfr_update[
2107 vnfr_update_text + ".mac-address"
2108 ] = increment_ip_mac(
2109 vnfcp_inst_param.get("mac-address"),
2110 vdur.get("count-index", 0),
2111 )
tierno1bd9d952020-11-13 15:56:51 +00002112 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002113 break
2114
tiernocc103432018-10-19 14:10:35 +02002115 vnfr_update["vim-account-id"] = vim_account
2116 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2117
David Garciaecb41322021-03-31 19:10:46 +02002118 if vca_id:
2119 vnfr_update["vca-id"] = vca_id
2120 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2121
tiernocc103432018-10-19 14:10:35 +02002122 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002123 ifaces_forcing_vim_network = self._look_for_pdu(
2124 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2125 )
tiernocc103432018-10-19 14:10:35 +02002126
tierno9cb7d672019-10-30 12:13:48 +00002127 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002128 ifaces_forcing_vim_network += self._look_for_k8scluster(
2129 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2130 )
tierno9cb7d672019-10-30 12:13:48 +00002131 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002132 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002133 rollback.append(
2134 {
2135 "topic": "vnfrs",
2136 "_id": vnfr["_id"],
2137 "operation": "set",
2138 "content": vnfr_update_rollback,
2139 }
2140 )
tierno36ec8602018-11-02 17:27:11 +01002141
2142 # Update indada in case pdu forces to use a concrete vim-network-name
2143 # TODO check if user has already insert a vim-network-name and raises an error
2144 if not ifaces_forcing_vim_network:
2145 continue
2146 for iface_info in ifaces_forcing_vim_network:
2147 if iface_info.get("ns-vld-id"):
2148 if "vld" not in indata:
2149 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002150 indata["vld"].append(
2151 {
2152 key: iface_info[key]
2153 for key in ("name", "vim-network-name", "vim-network-id")
2154 if iface_info.get(key)
2155 }
2156 )
tierno36ec8602018-11-02 17:27:11 +01002157
2158 elif iface_info.get("vnf-vld-id"):
2159 if "vnf" not in indata:
2160 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002161 indata["vnf"].append(
2162 {
2163 "member-vnf-index": member_vnf_index,
2164 "internal-vld": [
2165 {
2166 key: iface_info[key]
2167 for key in (
2168 "name",
2169 "vim-network-name",
2170 "vim-network-id",
2171 )
2172 if iface_info.get(key)
2173 }
2174 ],
2175 }
2176 )
tierno36ec8602018-11-02 17:27:11 +01002177
2178 @staticmethod
2179 def _create_nslcmop(nsr_id, operation, params):
2180 """
2181 Creates a ns-lcm-opp content to be stored at database.
2182 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002183 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002184 :param params: user parameters for the operation
2185 :return: dictionary following SOL005 format
2186 """
tiernob24258a2018-10-04 18:39:49 +02002187 now = time()
2188 _id = str(uuid4())
2189 nslcmop = {
2190 "id": _id,
2191 "_id": _id,
2192 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002193 "queuePosition": None,
2194 "stage": None,
2195 "errorMessage": None,
2196 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002197 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002198 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002199 "lcmOperationType": operation,
2200 "startTime": now,
2201 "isAutomaticInvocation": False,
2202 "operationParams": params,
2203 "isCancelPending": False,
2204 "links": {
2205 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002206 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002207 },
tiernob24258a2018-10-04 18:39:49 +02002208 }
2209 return nslcmop
2210
magnussonlf318b302020-01-20 18:38:18 +01002211 def _get_enabled_vims(self, session):
2212 """
2213 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2214 :param session: current session with user information
2215 """
2216 db_filter = self._get_project_filter(session)
2217 db_filter["_admin.operationalState"] = "ENABLED"
2218 vims = self.db.get_list("vim_accounts", db_filter)
2219 vimAccounts = []
2220 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002221 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002222 return vimAccounts
2223
garciadeblas4568a372021-03-24 09:19:48 +01002224 def new(
2225 self,
2226 rollback,
2227 session,
2228 indata=None,
2229 kwargs=None,
2230 headers=None,
2231 slice_object=False,
2232 ):
tiernob24258a2018-10-04 18:39:49 +02002233 """
2234 Performs a new operation over a ns
2235 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002236 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002237 :param indata: descriptor with the parameters of the operation. It must contains among others
2238 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002239 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002240 :param kwargs: used to override the indata descriptor
2241 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002242 :return: id of the nslcmops
2243 """
garciadeblas4568a372021-03-24 09:19:48 +01002244
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002245 def check_if_nsr_is_not_slice_member(session, nsr_id):
2246 nsis = None
2247 db_filter = self._get_project_filter(session)
2248 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002249 nsis = self.db.get_one(
2250 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2251 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002252 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002253 raise EngineException(
2254 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2255 nsr_id, nsis["_id"]
2256 ),
2257 http_code=HTTPStatus.CONFLICT,
2258 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002259
tiernob24258a2018-10-04 18:39:49 +02002260 try:
2261 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002262 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002263 operation = indata["lcmOperationType"]
2264 nsInstanceId = indata["nsInstanceId"]
2265
2266 validate_input(indata, self.operation_schema[operation])
2267 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002268 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002269 _filter["_id"] = nsInstanceId
2270 nsr = self.db.get_one("nsrs", _filter)
2271
2272 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002273 if operation == "terminate" and slice_object is False:
2274 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002275 if (
2276 not nsr["_admin"].get("nsState")
2277 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2278 ):
tiernob24258a2018-10-04 18:39:49 +02002279 if operation == "terminate" and indata.get("autoremove"):
2280 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002281 return (
2282 None,
2283 None,
2284 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002285 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002286 raise EngineException(
2287 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2288 nsInstanceId, operation
2289 ),
2290 HTTPStatus.CONFLICT,
2291 )
tiernob24258a2018-10-04 18:39:49 +02002292 else:
tierno65ca36d2019-02-12 19:27:52 +01002293 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002294 raise EngineException(
2295 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2296 nsInstanceId, operation
2297 ),
2298 HTTPStatus.CONFLICT,
2299 )
tiernob24258a2018-10-04 18:39:49 +02002300 self._check_ns_operation(session, nsr, operation, indata)
garciadeblasf2af4a12023-01-24 16:56:54 +01002301 if indata.get("primitive_params"):
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002302 indata["primitive_params"] = json.dumps(indata["primitive_params"])
garciadeblasf2af4a12023-01-24 16:56:54 +01002303 elif indata.get("additionalParamsForVnf"):
2304 indata["additionalParamsForVnf"] = json.dumps(
2305 indata["additionalParamsForVnf"]
2306 )
tierno36ec8602018-11-02 17:27:11 +01002307
tiernocc103432018-10-19 14:10:35 +02002308 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002309 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002310 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302311 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2312 nsr_update = {}
2313 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2314 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2315 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2316 ns_request = nsr["instantiate_params"]
garciadeblasf2af4a12023-01-24 16:56:54 +01002317 vnfr = self.db.get_one(
2318 "vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]}
2319 )
elumalai8bf978e2022-05-26 15:32:06 +05302320 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2321 vnfr_vnfd_revision = vnfr.get("revision", 1)
2322 if latest_vnfd_revision != vnfr_vnfd_revision:
2323 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
garciadeblasf2af4a12023-01-24 16:56:54 +01002324 old_db_vnfd = self.db.get_one(
2325 "vnfds_revisions", {"_id": old_vnfd_id}
2326 )
elumalai8bf978e2022-05-26 15:32:06 +05302327 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2328 new_sw_version = vnfd.get("software-version", "1.0")
2329 if new_sw_version != old_sw_version:
2330 vnf_index = vnfr["member-vnf-index-ref"]
2331 self.logger.info("nsr {}".format(nsr))
2332 for vdu in vnfd["vdu"]:
vegall18101ea2023-03-06 13:49:21 +00002333 self.nsrtopic._add_shared_volumes_to_nsr(
2334 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2335 )
garciadeblasf2af4a12023-01-24 16:56:54 +01002336 self.nsrtopic._add_flavor_to_nsr(
2337 vdu, vnfd, nsr, vnf_index, latest_vnfd_revision
2338 )
elumalai8bf978e2022-05-26 15:32:06 +05302339 sw_image_id = vdu.get("sw-image-desc")
2340 if sw_image_id:
garciadeblasf2af4a12023-01-24 16:56:54 +01002341 image_data = self.nsrtopic._get_image_data_from_vnfd(
2342 vnfd, sw_image_id
2343 )
elumalai8bf978e2022-05-26 15:32:06 +05302344 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2345 for alt_image in vdu.get("alternative-sw-image-desc", ()):
garciadeblasf2af4a12023-01-24 16:56:54 +01002346 image_data = self.nsrtopic._get_image_data_from_vnfd(
2347 vnfd, alt_image
2348 )
elumalai8bf978e2022-05-26 15:32:06 +05302349 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2350 nsr_update["image"] = nsr["image"]
2351 nsr_update["flavor"] = nsr["flavor"]
vegall18101ea2023-03-06 13:49:21 +00002352 nsr_update["shared-volumes"] = nsr["shared-volumes"]
elumalai8bf978e2022-05-26 15:32:06 +05302353 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
garciadeblasf2af4a12023-01-24 16:56:54 +01002354 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(
2355 nsd, ns_request, session
2356 )
2357 vnfr_descriptor = (
2358 self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2359 nsd,
2360 vnfd,
2361 vnfd_id,
2362 vnf_index,
2363 nsr,
2364 ns_request,
2365 ns_k8s_namespace,
2366 latest_vnfd_revision,
2367 )
elumalai8bf978e2022-05-26 15:32:06 +05302368 )
elumalai3f63ed52023-11-14 15:06:38 +05302369 self._update_vnfrs_from_nsd(nsr)
2370 vnfr_new = self.db.get_one(
2371 "vnfrs",
2372 {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]},
2373 )
2374 fixed_ip_dict = {}
2375 for vdu_record in vnfr_new.get("vdur"):
2376 if vdu_record.get("count-index") == 0:
2377 for interface in vdu_record.get("interfaces"):
2378 if (
2379 interface.get("external-connection-point-ref")
2380 and interface.get("fixed-ip") is True
2381 ):
2382 fixed_ip_dict[
2383 vdu_record.get("vdu-id-ref")
2384 ] = interface.get("ip-address")
2385 for new_vdu in vnfr_descriptor.get("vdur"):
2386 if fixed_ip_dict.get(new_vdu.get("vdu-id-ref")):
2387 for new_interface in new_vdu.get("interfaces"):
2388 if new_interface.get(
2389 "external-connection-point-ref"
2390 ):
2391 new_interface["ip-address"] = fixed_ip_dict.get(
2392 new_vdu.get("vdu-id-ref")
2393 )
2394 new_interface["fixed-ip"] = True
elumalai8bf978e2022-05-26 15:32:06 +05302395 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002396 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002397 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002398 self.format_on_new(
2399 nslcmop_desc, session["project_id"], make_public=session["public"]
2400 )
magnussonlf318b302020-01-20 18:38:18 +01002401 if indata.get("placement-engine"):
2402 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002403 nslcmop_desc["operationParams"][
2404 "validVimAccounts"
2405 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002406 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002407 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002408 if not slice_object:
2409 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002410 return _id, None
2411 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002412 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2413 # except DbException as e:
2414 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2415
tiernobee3bad2019-12-05 12:26:01 +00002416 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002417 raise EngineException(
2418 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2419 )
tiernob24258a2018-10-04 18:39:49 +02002420
tierno65ca36d2019-02-12 19:27:52 +01002421 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002422 raise EngineException(
2423 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2424 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002425
2426
2427class NsiTopic(BaseTopic):
2428 topic = "nsis"
2429 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002430 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002431
delacruzramo32bab472019-09-13 12:24:22 +02002432 def __init__(self, db, fs, msg, auth):
2433 BaseTopic.__init__(self, db, fs, msg, auth)
2434 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002435
Felipe Vicensc37b3842019-01-12 12:24:42 +01002436 @staticmethod
2437 def _format_ns_request(ns_request):
2438 formated_request = copy(ns_request)
2439 # TODO: Add request params
2440 return formated_request
2441
2442 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002443 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002444 """
2445 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002446 :param slice_request: User instantiation additional parameters
2447 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002448 """
tiernofd160572019-01-21 10:41:37 +00002449 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2450 if additional_params:
2451 for k, v in additional_params.items():
2452 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002453 raise EngineException(
2454 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2455 k
2456 )
2457 )
tiernofd160572019-01-21 10:41:37 +00002458 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002459 raise EngineException(
2460 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2461 k
2462 )
2463 )
tiernofd160572019-01-21 10:41:37 +00002464 if isinstance(v, (dict, tuple, list)):
2465 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002466 return additional_params
2467
tiernob4844ab2019-05-23 08:42:12 +00002468 def check_conflict_on_del(self, session, _id, db_content):
2469 """
2470 Check that NSI is not instantiated
2471 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2472 :param _id: nsi internal id
2473 :param db_content: The database content of the _id
2474 :return: None or raises EngineException with the conflict
2475 """
tierno65ca36d2019-02-12 19:27:52 +01002476 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002477 return
tiernob4844ab2019-05-23 08:42:12 +00002478 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002479 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002480 raise EngineException(
2481 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2482 "Launch 'terminate' operation first; or force deletion".format(_id),
2483 http_code=HTTPStatus.CONFLICT,
2484 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002485
tiernobee3bad2019-12-05 12:26:01 +00002486 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002487 """
tiernob4844ab2019-05-23 08:42:12 +00002488 Deletes associated nsilcmops from database. Deletes associated filesystem.
2489 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002490 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002491 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002492 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002493 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002494 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002495 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002496
Felipe Vicens09e65422019-01-22 15:06:46 +01002497 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002498 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002499 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2500 nsr_id = nsrs_detailed_item["nsrId"]
2501 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002502 _filter = {
2503 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2504 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2505 "_id.ne": nsir["_id"],
2506 }
2507 nsi = self.db.get_one(
2508 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2509 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002510 if nsi: # last one using nsr
2511 continue
2512 try:
garciadeblas4568a372021-03-24 09:19:48 +01002513 self.nsrTopic.delete(
2514 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2515 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002516 except (DbException, EngineException) as e:
2517 if e.http_code == HTTPStatus.NOT_FOUND:
2518 pass
2519 else:
2520 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002521
tiernob4844ab2019-05-23 08:42:12 +00002522 # delete related nsilcmops database entries
2523 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002524
tiernob4844ab2019-05-23 08:42:12 +00002525 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002526 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002527 if nsir_admin and nsir_admin.get("nst-id"):
2528 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002529 nsis_list = self.db.get_one(
2530 "nsis",
2531 {"nst-id": nsir_admin["nst-id"]},
2532 fail_on_empty=False,
2533 fail_on_more=False,
2534 )
tiernob4844ab2019-05-23 08:42:12 +00002535 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002536 self.db.set_one(
2537 "nsts",
2538 {"_id": nsir_admin["nst-id"]},
2539 {"_admin.usageState": "NOT_IN_USE"},
2540 )
tiernob4844ab2019-05-23 08:42:12 +00002541
tierno65ca36d2019-02-12 19:27:52 +01002542 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002543 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002544 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002545 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002546 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002547 :param indata: params to be used for the nsir
2548 :param kwargs: used to override the indata descriptor
2549 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002550 :return: the _id of nsi descriptor created at database
2551 """
2552
garciadeblasf2af4a12023-01-24 16:56:54 +01002553 step = "checking quotas" # first step must be defined outside try
Felipe Vicensb57758d2018-10-16 16:00:20 +02002554 try:
delacruzramo32bab472019-09-13 12:24:22 +02002555 self.check_quota(session)
2556
tierno99d4b172019-07-02 09:28:40 +00002557 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002558 slice_request = self._remove_envelop(indata)
2559 # Override descriptor with query string kwargs
2560 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002561 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002562
Felipe Vicensb57758d2018-10-16 16:00:20 +02002563 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002564 step = "getting nstd id='{}' from database".format(
2565 slice_request.get("nstId")
2566 )
tiernob4844ab2019-05-23 08:42:12 +00002567 _filter = self._get_project_filter(session)
2568 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002569 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002570 # check NST is not disabled
2571 step = "checking NST operationalState"
2572 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002573 raise EngineException(
2574 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2575 "instance".format(slice_request["nstId"]),
2576 http_code=HTTPStatus.CONFLICT,
2577 )
tiernob4844ab2019-05-23 08:42:12 +00002578 del _filter["_id"]
2579
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002580 # check NSD is not disabled
2581 step = "checking operationalState"
2582 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002583 raise EngineException(
2584 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2585 "a network slice".format(slice_request["nstId"]),
2586 http_code=HTTPStatus.CONFLICT,
2587 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002588
Felipe Vicens07f31722018-10-29 15:16:44 +01002589 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002590 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002591 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002592 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002593
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002594 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002595 nsi_descriptor = {
2596 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002597 "name": slice_request["nsiName"],
2598 "description": slice_request.get("nsiDescription", ""),
2599 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002600 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002601 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002602 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002603 "nsr-ref-list": [],
2604 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002605 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002606 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002607 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002608
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002609 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002610 self.format_on_new(
2611 nsi_descriptor, session["project_id"], make_public=session["public"]
2612 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002613 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2614 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002615 nsi_descriptor["_admin"]["deployed"] = {}
2616 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2617 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2618
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002619 # Creating netslice-vld for the RO.
2620 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002621
2622 # Building the vlds list to be deployed
2623 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002624 nsi_vlds = []
2625
2626 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2627 # Getting template Instantiation parameters from NST
2628 nsi_vld = deepcopy(netslice_vlds)
2629 nsi_vld["shared-nsrs-list"] = []
2630 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2631 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002632
2633 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002634 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002635 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002636 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002637
Felipe Vicens09e65422019-01-22 15:06:46 +01002638 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002639 for member_ns in nstd["netslice-subnet"]:
2640 nsd_id = member_ns["nsd-ref"]
2641 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002642 member_ns["nsd-ref"], member_ns["id"]
2643 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002644 if nsd_id not in needed_nsds:
2645 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002646 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002647 nsd = self.db.get_one(
2648 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2649 )
tiernob4844ab2019-05-23 08:42:12 +00002650 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002651 nsd.pop("_admin")
2652 needed_nsds[nsd_id] = nsd
2653 else:
2654 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002655 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2656 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002657
Felipe Vicensb57758d2018-10-16 16:00:20 +02002658 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002659 member_ns["nsd-ref"], member_ns["id"]
2660 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002661
Felipe Vicens07f31722018-10-29 15:16:44 +01002662 # creates Network Services records (NSRs)
2663 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002664 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002665 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002666 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002667 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002668 # Check if the netslice-subnet is shared and if it is share if the nss exists
2669 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002670 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002671 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002672 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002673 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2674 "nsd-ref"
2675 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002676 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002677 nsi = self.db.get_one(
2678 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2679 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002680 if nsi and service.get("is-shared-nss"):
2681 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2682 for nsrs_detailed_item in nsrs_detailed_list:
2683 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002684 if nsrs_detailed_item["nss-id"] == service["id"]:
2685 _id_nsr = nsrs_detailed_item["nsrId"]
2686 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002687 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2688 if netslice_subnet["nss-id"] == service["id"]:
2689 indata_ns = netslice_subnet
2690 break
2691 else:
2692 indata_ns = {}
2693 if service.get("instantiation-parameters"):
2694 indata_ns = deepcopy(service["instantiation-parameters"])
2695 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002696
Felipe Vicens09e65422019-01-22 15:06:46 +01002697 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002698 indata_ns["nsName"] = (
2699 slice_request.get("nsiName") + "." + service["id"]
2700 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002701 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2702 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002703 if slice_request.get("ssh_keys"):
2704 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002705
Felipe Vicens09e65422019-01-22 15:06:46 +01002706 if ns_params:
2707 for ns_param in ns_params:
2708 if ns_param.get("id") == service["id"]:
2709 copy_ns_param = deepcopy(ns_param)
2710 del copy_ns_param["id"]
2711 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002712 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002713
2714 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002715 _id_nsr, _ = self.nsrTopic.new(
2716 rollback, session, indata_ns, kwargs, headers
2717 )
2718 nsrs_item = {
2719 "nsrId": _id_nsr,
2720 "shared": service.get("is-shared-nss"),
2721 "nsd-id": service["nsd-ref"],
2722 "nss-id": service["id"],
2723 "nslcmop_instantiate": None,
2724 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002725 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002726 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002727 nsi_netslice_subnet.append(indata_ns)
2728 nsr_ref = {"nsr-ref": _id_nsr}
2729 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002730
2731 # Adding the nsrs list to the nsi
2732 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002733 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002734 self.db.set_one(
2735 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2736 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002737
Felipe Vicens07f31722018-10-29 15:16:44 +01002738 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002739 self.db.create("nsis", nsi_descriptor)
2740 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002741 return nsi_id, None
garciadeblasf2af4a12023-01-24 16:56:54 +01002742 except ValidationError as e:
2743 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
garciadeblas4568a372021-03-24 09:19:48 +01002744 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2745 self.logger.exception(
2746 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2747 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002748 raise EngineException("Error {}: {}".format(step, e))
Felipe Vicensb57758d2018-10-16 16:00:20 +02002749
tierno65ca36d2019-02-12 19:27:52 +01002750 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002751 raise EngineException(
2752 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2753 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002754
2755
2756class NsiLcmOpTopic(BaseTopic):
2757 topic = "nsilcmops"
2758 topic_msg = "nsi"
2759 operation_schema = { # mapping between operation and jsonschema to validate
2760 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002761 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002762 }
garciadeblas4568a372021-03-24 09:19:48 +01002763
delacruzramo32bab472019-09-13 12:24:22 +02002764 def __init__(self, db, fs, msg, auth):
2765 BaseTopic.__init__(self, db, fs, msg, auth)
2766 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002767
2768 def _check_nsi_operation(self, session, nsir, operation, indata):
2769 """
2770 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002771 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002772 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2773 :param indata: descriptor with the parameters of the operation
2774 :return: None
2775 """
2776 nsds = {}
2777 nstd = nsir["network-slice-template"]
2778
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002779 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002780 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002781 for netslice_subnet in nstd["netslice-subnet"]:
2782 if nstId == netslice_subnet["id"]:
2783 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002784 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002785 _filter = self._get_project_filter(session)
2786 _filter["id"] = nsd_id
2787 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002788 return nsds[nsd_id]
2789 else:
garciadeblas4568a372021-03-24 09:19:48 +01002790 raise EngineException(
2791 "Invalid parameter nstId='{}' is not one of the "
2792 "nst:netslice-subnet".format(nstId)
2793 )
2794
Felipe Vicens07f31722018-10-29 15:16:44 +01002795 if operation == "instantiate":
2796 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002797 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002798 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002799
2800 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2801 now = time()
2802 _id = str(uuid4())
2803 nsilcmop = {
2804 "id": _id,
2805 "_id": _id,
2806 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2807 "statusEnteredTime": now,
2808 "netsliceInstanceId": netsliceInstanceId,
2809 "lcmOperationType": operation,
2810 "startTime": now,
2811 "isAutomaticInvocation": False,
2812 "operationParams": params,
2813 "isCancelPending": False,
2814 "links": {
2815 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002816 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2817 + netsliceInstanceId,
2818 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002819 }
2820 return nsilcmop
2821
Felipe Vicens09e65422019-01-22 15:06:46 +01002822 def add_shared_nsr_2vld(self, nsir, nsr_item):
2823 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2824 if nst_sb_item.get("is-shared-nss"):
2825 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2826 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2827 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002828 for admin_vld_nss_cp_ref_item in admin_vld_item[
2829 "nss-connection-point-ref"
2830 ]:
2831 if (
2832 admin_subnet_item["nss-id"]
2833 == admin_vld_nss_cp_ref_item["nss-ref"]
2834 ):
2835 if (
2836 not nsr_item["nsrId"]
2837 in admin_vld_item["shared-nsrs-list"]
2838 ):
2839 admin_vld_item["shared-nsrs-list"].append(
2840 nsr_item["nsrId"]
2841 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002842 break
2843 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002844 self.db.set_one(
2845 "nsis",
2846 {"_id": nsir["_id"]},
2847 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2848 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002849
tierno65ca36d2019-02-12 19:27:52 +01002850 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002851 """
2852 Performs a new operation over a ns
2853 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002854 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002855 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002856 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002857 operation: it can be: instantiate, terminate, action, TODO: update, heal
2858 :param kwargs: used to override the indata descriptor
2859 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002860 :return: id of the nslcmops
2861 """
2862 try:
2863 # Override descriptor with query string kwargs
2864 self._update_input_with_kwargs(indata, kwargs)
2865 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002866 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002867 validate_input(indata, self.operation_schema[operation])
2868
Felipe Vicens126af572019-06-05 19:13:04 +02002869 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002870 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002871 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002872 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002873 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002874 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002875
2876 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002877 if (
2878 not nsir["_admin"].get("nsiState")
2879 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2880 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002881 if operation == "terminate" and indata.get("autoremove"):
2882 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002883 return (
2884 None,
2885 None,
2886 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002887 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002888 raise EngineException(
2889 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2890 netsliceInstanceId, operation
2891 ),
2892 HTTPStatus.CONFLICT,
2893 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002894 else:
tierno65ca36d2019-02-12 19:27:52 +01002895 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002896 raise EngineException(
2897 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2898 netsliceInstanceId, operation
2899 ),
2900 HTTPStatus.CONFLICT,
2901 )
2902
Felipe Vicens07f31722018-10-29 15:16:44 +01002903 # Creating all the NS_operation (nslcmop)
2904 # Get service list from db
2905 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2906 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002907 # nslcmops_item = None
2908 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002909 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002910 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002911 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002912 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002913 _filter[
2914 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2915 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002916 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002917 nsi = self.db.get_one(
2918 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2919 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002920 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002921 _update = {
2922 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2923 index
2924 ): None
2925 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002926 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002927 if (
2928 nsi
2929 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002930 continue # do not create nsilcmop
2931 else: # instantiate
2932 # looks the first nsi fulfilling the conditions but not being the current NSIR
2933 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002934 nsi_nsr_item = next(
2935 n
2936 for n in nsi["_admin"]["nsrs-detailed-list"]
2937 if n["nsrId"] == nsr_id
2938 and n["shared"]
2939 and n["nslcmop_instantiate"]
2940 )
tierno40f742b2020-06-23 15:25:26 +00002941 self.add_shared_nsr_2vld(nsir, nsr_item)
2942 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002943 _update = {
2944 "_admin.nsrs-detailed-list.{}".format(
2945 index
2946 ): nsi_nsr_item
2947 }
tierno40f742b2020-06-23 15:25:26 +00002948 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2949 # continue to not create nslcmop since nsrs is shared and nsrs was created
2950 continue
2951 else:
2952 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002953
tierno40f742b2020-06-23 15:25:26 +00002954 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002955 try:
tierno0b8752f2020-05-12 09:42:02 +00002956 indata_ns = {
2957 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002958 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002959 # Including netslice_id in the ns instantiate Operation
2960 "netsliceInstanceId": netsliceInstanceId,
2961 }
2962 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002963 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002964 indata_ns.update(service["instantiate_params"])
2965
tierno99d4b172019-07-02 09:28:40 +00002966 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002967 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002968 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2969 rollback, session, indata_ns, None, headers, slice_object=True
2970 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002971 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002972 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002973 _update = {
2974 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2975 index
2976 ): nslcmop
2977 }
tierno40f742b2020-06-23 15:25:26 +00002978 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002979 except (DbException, EngineException) as e:
2980 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002981 self.logger.info(
2982 logging_prefix
2983 + "skipping NS={} because not found".format(nsr_id)
2984 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002985 pass
2986 else:
2987 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002988
2989 # Creates nsilcmop
2990 indata["nslcmops_ids"] = nslcmops
2991 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002992
garciadeblas4568a372021-03-24 09:19:48 +01002993 nsilcmop_desc = self._create_nsilcmop(
2994 session, netsliceInstanceId, operation, indata
2995 )
2996 self.format_on_new(
2997 nsilcmop_desc, session["project_id"], make_public=session["public"]
2998 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002999 _id = self.db.create("nsilcmops", nsilcmop_desc)
3000 rollback.append({"topic": "nsilcmops", "_id": _id})
3001 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00003002 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01003003 except ValidationError as e:
3004 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01003005
tiernobee3bad2019-12-05 12:26:01 +00003006 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01003007 raise EngineException(
3008 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3009 )
Felipe Vicens07f31722018-10-29 15:16:44 +01003010
tierno65ca36d2019-02-12 19:27:52 +01003011 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01003012 raise EngineException(
3013 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
3014 )