blob: aac0b0b0afe34193a059b4f14116bd1522b3069b [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,
garciadeblas4568a372021-03-24 09:19:48 +010030 nsi_instantiate,
elumalai8e3806c2022-04-28 17:26:24 +053031 ns_migrate,
garciadeblas4568a372021-03-24 09:19:48 +010032)
33from osm_nbi.base_topic import (
34 BaseTopic,
35 EngineException,
36 get_iterable,
37 deep_get,
38 increment_ip_mac,
39)
tiernobee085c2018-12-12 17:03:04 +000040from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010041from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000042from osm_common.msgbase import MsgException
43from osm_common.fsbase import FsException
garciaale7cbd03c2020-11-27 10:38:35 -030044from osm_nbi import utils
garciadeblas4568a372021-03-24 09:19:48 +010045from re import (
46 match,
47) # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020048
49__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
50
51
52class NsrTopic(BaseTopic):
53 topic = "nsrs"
54 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000055 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000056 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020057
delacruzramo32bab472019-09-13 12:24:22 +020058 def __init__(self, db, fs, msg, auth):
59 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020060
61 def _check_descriptor_dependencies(self, session, descriptor):
62 """
63 Check that the dependent descriptors exist on a new descriptor or edition
64 :param session: client session information
65 :param descriptor: descriptor to be inserted or edit
66 :return: None or raises exception
67 """
68 if not descriptor.get("nsdId"):
69 return
70 nsd_id = descriptor["nsdId"]
71 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
garciadeblas4568a372021-03-24 09:19:48 +010072 raise EngineException(
73 "Descriptor error at nsdId='{}' references a non exist nsd".format(
74 nsd_id
75 ),
76 http_code=HTTPStatus.CONFLICT,
77 )
tiernob24258a2018-10-04 18:39:49 +020078
79 @staticmethod
80 def format_on_new(content, project_id=None, make_public=False):
81 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
82 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000083 return None
tiernob24258a2018-10-04 18:39:49 +020084
tiernob4844ab2019-05-23 08:42:12 +000085 def check_conflict_on_del(self, session, _id, db_content):
86 """
87 Check that NSR is not instantiated
88 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
89 :param _id: nsr internal id
90 :param db_content: The database content of the nsr
91 :return: None or raises EngineException with the conflict
92 """
tierno65ca36d2019-02-12 19:27:52 +010093 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020094 return
tiernob4844ab2019-05-23 08:42:12 +000095 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020096 if nsr["_admin"].get("nsState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +010097 raise EngineException(
98 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
99 "Launch 'terminate' operation first; or force deletion".format(_id),
100 http_code=HTTPStatus.CONFLICT,
101 )
tiernob24258a2018-10-04 18:39:49 +0200102
tiernobee3bad2019-12-05 12:26:01 +0000103 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +0000104 """
105 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
106 Set usageState of pdu, vnfd, nsd
107 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
108 :param _id: server internal id
109 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +0000110 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +0000111 :return: None if ok or raises EngineException with the problem
112 """
tiernobee085c2018-12-12 17:03:04 +0000113 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +0200114 self.db.del_list("nslcmops", {"nsInstanceId": _id})
115 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +0000116
tiernob24258a2018-10-04 18:39:49 +0200117 # set all used pdus as free
garciadeblas4568a372021-03-24 09:19:48 +0100118 self.db.set_list(
119 "pdus",
120 {"_admin.usage.nsr_id": _id},
121 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
122 )
tiernob24258a2018-10-04 18:39:49 +0200123
tiernob4844ab2019-05-23 08:42:12 +0000124 # Set NSD usageState
125 nsr = db_content
126 used_nsd_id = nsr.get("nsd-id")
127 if used_nsd_id:
128 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100129 nsrs_list = self.db.get_one(
130 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
131 )
tiernob4844ab2019-05-23 08:42:12 +0000132 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100133 self.db.set_one(
134 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
135 )
tiernob4844ab2019-05-23 08:42:12 +0000136
137 # Set VNFD usageState
138 used_vnfd_id_list = nsr.get("vnfd-id")
139 if used_vnfd_id_list:
140 for used_vnfd_id in used_vnfd_id_list:
141 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100142 nsrs_list = self.db.get_one(
143 "nsrs",
144 {"vnfd-id": used_vnfd_id},
145 fail_on_empty=False,
146 fail_on_more=False,
147 )
tiernob4844ab2019-05-23 08:42:12 +0000148 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100149 self.db.set_one(
150 "vnfds",
151 {"_id": used_vnfd_id},
152 {"_admin.usageState": "NOT_IN_USE"},
153 )
tiernob4844ab2019-05-23 08:42:12 +0000154
tiernof0441ea2020-05-26 15:39:18 +0000155 # delete extra ro_nsrs used for internal RO module
156 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
157
tiernobee085c2018-12-12 17:03:04 +0000158 @staticmethod
159 def _format_ns_request(ns_request):
160 formated_request = copy(ns_request)
161 formated_request.pop("additionalParamsForNs", None)
162 formated_request.pop("additionalParamsForVnf", None)
163 return formated_request
164
165 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +0100166 def _format_additional_params(
167 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
168 ):
tiernobee085c2018-12-12 17:03:04 +0000169 """
170 Get and format user additional params for NS or VNF
171 :param ns_request: User instantiation additional parameters
172 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
173 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000174 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000175 """
176 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000177 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000178 if not member_vnf_index:
179 additional_params = copy(ns_request.get("additionalParamsForNs"))
180 where_ = "additionalParamsForNs"
181 elif ns_request.get("additionalParamsForVnf"):
garciadeblas4568a372021-03-24 09:19:48 +0100182 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
183 member_vnf_index
184 )
185 item = next(
186 (
187 x
188 for x in ns_request["additionalParamsForVnf"]
189 if x["member-vnf-index"] == member_vnf_index
190 ),
191 None,
192 )
tierno714954e2019-11-29 13:43:26 +0000193 if item:
tierno54db2e42020-04-06 15:29:42 +0000194 if not vdu_id and not kdu_name:
195 other_params = item
tierno714954e2019-11-29 13:43:26 +0000196 additional_params = copy(item.get("additionalParams")) or {}
197 if vdu_id and item.get("additionalParamsForVdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100198 item_vdu = next(
199 (
200 x
201 for x in item["additionalParamsForVdu"]
202 if x["vdu_id"] == vdu_id
203 ),
204 None,
205 )
tiernobce98f02020-04-17 11:27:47 +0000206 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000207 if item_vdu and item_vdu.get("additionalParams"):
208 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000209 additional_params = item_vdu["additionalParams"]
210 if kdu_name:
211 additional_params = {}
212 if item.get("additionalParamsForKdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100213 item_kdu = next(
214 (
215 x
216 for x in item["additionalParamsForKdu"]
217 if x["kdu_name"] == kdu_name
218 ),
219 None,
220 )
tiernobce98f02020-04-17 11:27:47 +0000221 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000222 if item_kdu and item_kdu.get("additionalParams"):
garciadeblas4568a372021-03-24 09:19:48 +0100223 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
224 kdu_name
225 )
tiernob091dc12019-12-02 15:53:25 +0000226 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000227
tiernobee085c2018-12-12 17:03:04 +0000228 if additional_params:
229 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000230 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
garciadeblas4568a372021-03-24 09:19:48 +0100231 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
232 raise EngineException(
233 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
234 "and underscores, and cannot start with a digit".format(
235 where_, k
236 )
237 )
delacruzramo36ffe552019-05-03 14:52:37 +0200238 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000239 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +0100240 raise EngineException(
241 "Invalid param at {}:{}. Only string keys are allowed".format(
242 where_, k
243 )
244 )
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100245 if "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +0100246 raise EngineException(
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100247 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
garciadeblas4568a372021-03-24 09:19:48 +0100248 where_, k
249 )
250 )
tiernobee085c2018-12-12 17:03:04 +0000251 if isinstance(v, (dict, tuple, list)):
252 additional_params[k] = "!!yaml " + safe_dump(v)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100253 if kdu_name:
254 additional_params = json.dumps(additional_params)
tiernobee085c2018-12-12 17:03:04 +0000255
256 if descriptor:
bravof41a52052021-02-17 18:08:01 -0300257 for df in descriptor.get("df", []):
258 # check that enough parameters are supplied for the initial-config-primitive
259 # TODO: check for cloud-init
260 if member_vnf_index:
garciaale7cbd03c2020-11-27 10:38:35 -0300261 initial_primitives = []
garciadeblas4568a372021-03-24 09:19:48 +0100262 if (
263 "lcm-operations-configuration" in df
264 and "operate-vnf-op-config"
265 in df["lcm-operations-configuration"]
266 ):
267 for config in df["lcm-operations-configuration"][
268 "operate-vnf-op-config"
269 ].get("day1-2", []):
270 for primitive in get_iterable(
271 config.get("initial-config-primitive")
272 ):
bravof41a52052021-02-17 18:08:01 -0300273 initial_primitives.append(primitive)
274 else:
garciadeblas4568a372021-03-24 09:19:48 +0100275 initial_primitives = deep_get(
276 descriptor, ("ns-configuration", "initial-config-primitive")
277 )
tiernobee085c2018-12-12 17:03:04 +0000278
bravof41a52052021-02-17 18:08:01 -0300279 for initial_primitive in get_iterable(initial_primitives):
280 for param in get_iterable(initial_primitive.get("parameter")):
garciadeblas4568a372021-03-24 09:19:48 +0100281 if param["value"].startswith("<") and param["value"].endswith(
282 ">"
283 ):
284 if param["value"] in (
285 "<rw_mgmt_ip>",
286 "<VDU_SCALE_INFO>",
287 "<ns_config_info>",
288 ):
bravof41a52052021-02-17 18:08:01 -0300289 continue
garciadeblas4568a372021-03-24 09:19:48 +0100290 if (
291 not additional_params
292 or param["value"][1:-1] not in additional_params
293 ):
294 raise EngineException(
295 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
296 "initial-config-primitive[name={}] not supplied".format(
297 param["value"],
298 descriptor["id"],
299 initial_primitive["name"],
300 )
301 )
tierno714954e2019-11-29 13:43:26 +0000302
tierno54db2e42020-04-06 15:29:42 +0000303 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000304
tierno65ca36d2019-02-12 19:27:52 +0100305 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200306 """
307 Creates a new nsr into database. It also creates needed vnfrs
308 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100309 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200310 :param indata: params to be used for the nsr
311 :param kwargs: used to override the indata descriptor
312 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000313 :return: the _id of nsr descriptor created at database. Or an exception of type
314 EngineException, ValidationError, DbException, FsException, MsgException.
315 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200316 """
tiernob24258a2018-10-04 18:39:49 +0200317 try:
delacruzramo32bab472019-09-13 12:24:22 +0200318 step = "checking quotas"
319 self.check_quota(session)
320
tierno99d4b172019-07-02 09:28:40 +0000321 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200322 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200323 self._update_input_with_kwargs(ns_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -0300324 ns_request = self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200325
tiernob24258a2018-10-04 18:39:49 +0200326 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale7cbd03c2020-11-27 10:38:35 -0300327 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
328 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200329
Frank Bryden3c64ab62020-07-21 14:25:32 +0000330 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300331 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000332
tiernob24258a2018-10-04 18:39:49 +0200333 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300334 nsr_id = str(uuid4())
garciadeblas4568a372021-03-24 09:19:48 +0100335 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
336 nsd, ns_request, nsr_id, session
337 )
tierno54db2e42020-04-06 15:29:42 +0000338
garciaale7cbd03c2020-11-27 10:38:35 -0300339 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200340 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300341 # TODO: Change for multiple df support
K Sai Kiranbb006022021-05-20 11:09:49 +0530342 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
garciaale7cbd03c2020-11-27 10:38:35 -0300343 for vnfp in vnf_profiles:
344 vnfd_id = vnfp.get("vnfd-id")
345 vnf_index = vnfp.get("id")
garciadeblas4568a372021-03-24 09:19:48 +0100346 step = (
347 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
348 vnfd_id, vnf_index
349 )
350 )
tiernob24258a2018-10-04 18:39:49 +0200351 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300352 vnfd = self._get_vnfd_from_db(vnfd_id, session)
beierlmcee2ebf2022-03-29 17:42:48 -0400353 if "revision" in vnfd["_admin"]:
354 vnfd["revision"] = vnfd["_admin"]["revision"]
355 vnfd.pop("_admin")
tiernob24258a2018-10-04 18:39:49 +0200356 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000357 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200358 else:
359 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100360
garciadeblas4568a372021-03-24 09:19:48 +0100361 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
362 vnfd_id, vnf_index
363 )
364 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
365 nsd,
366 vnfd,
367 vnfd_id,
368 vnf_index,
369 nsr_descriptor,
370 ns_request,
371 ns_k8s_namespace,
372 )
tierno36ec8602018-11-02 17:27:11 +0100373
garciadeblas4568a372021-03-24 09:19:48 +0100374 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
375 vnfd_id, vnf_index
376 )
garciaale7cbd03c2020-11-27 10:38:35 -0300377 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
378 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
tiernob24258a2018-10-04 18:39:49 +0200379
380 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300381 self._add_nsr_to_db(nsr_descriptor, rollback, session)
tiernobee085c2018-12-12 17:03:04 +0000382
383 step = "creating nsr temporal folder"
384 self.fs.mkdir(nsr_id)
385
tiernobdebce92019-07-01 15:36:49 +0000386 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100387 except (
388 ValidationError,
389 EngineException,
390 DbException,
391 MsgException,
392 FsException,
393 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000394 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200395
garciaale7cbd03c2020-11-27 10:38:35 -0300396 def _get_nsd_from_db(self, nsd_id, session):
397 _filter = self._get_project_filter(session)
398 _filter["_id"] = nsd_id
399 return self.db.get_one("nsds", _filter)
400
401 def _get_vnfd_from_db(self, vnfd_id, session):
402 _filter = self._get_project_filter(session)
403 _filter["id"] = vnfd_id
404 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
garciaale7cbd03c2020-11-27 10:38:35 -0300405 return vnfd
406
407 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100408 self.format_on_new(
409 nsr_descriptor, session["project_id"], make_public=session["public"]
410 )
garciaale7cbd03c2020-11-27 10:38:35 -0300411 self.db.create("nsrs", nsr_descriptor)
412 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
413
414 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100415 self.format_on_new(
416 vnfr_descriptor, session["project_id"], make_public=session["public"]
417 )
garciaale7cbd03c2020-11-27 10:38:35 -0300418 self.db.create("vnfrs", vnfr_descriptor)
419 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
420
421 def _check_nsd_operational_state(self, nsd, ns_request):
422 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100423 raise EngineException(
424 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
425 "a network service".format(ns_request["nsdId"]),
426 http_code=HTTPStatus.CONFLICT,
427 )
garciaale7cbd03c2020-11-27 10:38:35 -0300428
429 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100430 additional_params, _ = self._format_additional_params(
431 ns_request, descriptor=nsd
432 )
garciaale7cbd03c2020-11-27 10:38:35 -0300433 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
434 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
435 if ns_request and ns_request.get("k8s-namespace"):
436 ns_k8s_namespace = ns_request["k8s-namespace"]
437 if additional_params and additional_params.get("k8s-namespace"):
438 ns_k8s_namespace = additional_params["k8s-namespace"]
439
440 return ns_k8s_namespace
441
elumalai6c5ea6b2022-04-25 22:27:59 +0530442 def _add_flavor_to_nsr(self, vdu, vnfd, nsr_descriptor):
443 flavor_data = {}
444 guest_epa = {}
445 # Find this vdu compute and storage descriptors
446 vdu_virtual_compute = {}
447 vdu_virtual_storage = {}
448 for vcd in vnfd.get("virtual-compute-desc", ()):
449 if vcd.get("id") == vdu.get("virtual-compute-desc"):
450 vdu_virtual_compute = vcd
451 for vsd in vnfd.get("virtual-storage-desc", ()):
452 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
453 vdu_virtual_storage = vsd
454 # Get this vdu vcpus, memory and storage info for flavor_data
455 if vdu_virtual_compute.get("virtual-cpu", {}).get(
456 "num-virtual-cpu"
457 ):
458 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
459 "num-virtual-cpu"
460 ]
461 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
462 flavor_data["memory-mb"] = (
463 float(vdu_virtual_compute["virtual-memory"]["size"])
464 * 1024.0
465 )
466 if vdu_virtual_storage.get("size-of-storage"):
467 flavor_data["storage-gb"] = vdu_virtual_storage[
468 "size-of-storage"
469 ]
470 # Get this vdu EPA info for guest_epa
471 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
472 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
473 "cpu-quota"
474 ]
475 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
476 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
477 if vcpu_pinning.get("thread-policy"):
478 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
479 "thread-policy"
480 ]
481 if vcpu_pinning.get("policy"):
482 cpu_policy = (
483 "SHARED"
484 if vcpu_pinning["policy"] == "dynamic"
485 else "DEDICATED"
486 )
487 guest_epa["cpu-pinning-policy"] = cpu_policy
488 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
489 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
490 "mem-quota"
491 ]
492 if vdu_virtual_compute.get("virtual-memory", {}).get(
493 "mempage-size"
494 ):
495 guest_epa["mempage-size"] = vdu_virtual_compute[
496 "virtual-memory"
497 ]["mempage-size"]
498 if vdu_virtual_compute.get("virtual-memory", {}).get(
499 "numa-node-policy"
500 ):
501 guest_epa["numa-node-policy"] = vdu_virtual_compute[
502 "virtual-memory"
503 ]["numa-node-policy"]
504 if vdu_virtual_storage.get("disk-io-quota"):
505 guest_epa["disk-io-quota"] = vdu_virtual_storage[
506 "disk-io-quota"
507 ]
508
509 if guest_epa:
510 flavor_data["guest-epa"] = guest_epa
511
512 flavor_data["name"] = vdu["id"][:56] + "-flv"
513 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
514 nsr_descriptor["flavor"].append(flavor_data)
515
bravofe76b8822021-02-26 16:57:52 -0300516 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300517 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100518 additional_params, _ = self._format_additional_params(
519 ns_request, descriptor=nsd
520 )
garciaale7cbd03c2020-11-27 10:38:35 -0300521
522 nsr_descriptor = {
523 "name": ns_request["nsName"],
524 "name-ref": ns_request["nsName"],
525 "short-name": ns_request["nsName"],
526 "admin-status": "ENABLED",
527 "nsState": "NOT_INSTANTIATED",
528 "currentOperation": "IDLE",
529 "currentOperationID": None,
530 "errorDescription": None,
531 "errorDetail": None,
532 "deploymentStatus": None,
533 "configurationStatus": None,
534 "vcaStatus": None,
535 "nsd": {k: v for k, v in nsd.items()},
536 "datacenter": ns_request["vimAccountId"],
537 "resource-orchestrator": "osmopenmano",
538 "description": ns_request.get("nsDescription", ""),
539 "constituent-vnfr-ref": [],
540 "operational-status": "init", # typedef ns-operational-
541 "config-status": "init", # typedef config-states
542 "detailed-status": "scheduled",
543 "orchestration-progress": {},
544 "create-time": now,
545 "nsd-name-ref": nsd["name"],
546 "operational-events": [], # "id", "timestamp", "description", "event",
547 "nsd-ref": nsd["id"],
548 "nsd-id": nsd["_id"],
549 "vnfd-id": [],
550 "instantiate_params": self._format_ns_request(ns_request),
551 "additionalParamsForNs": additional_params,
552 "ns-instance-config-ref": nsr_id,
553 "id": nsr_id,
554 "_id": nsr_id,
555 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
556 "flavor": [],
557 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100558 "affinity-or-anti-affinity-group": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300559 }
560 ns_request["nsr_id"] = nsr_id
561 if ns_request and ns_request.get("config-units"):
562 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300563 # Create vld
564 if nsd.get("virtual-link-desc"):
565 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
566 # Fill each vld with vnfd-connection-point-ref data
567 # TODO: Change for multiple df support
568 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
569 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
570 for vnf_profile in vnf_profiles:
571 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
572 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100573 all_vld_connection_point_data[
574 vlc.get("virtual-link-profile-id")
575 ].append(
576 {
577 "member-vnf-index-ref": cpd.get(
578 "constituent-base-element-id"
579 ),
580 "vnfd-connection-point-ref": cpd.get(
581 "constituent-cpd-id"
582 ),
583 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
584 }
585 )
garciaale7cbd03c2020-11-27 10:38:35 -0300586
bravofe76b8822021-02-26 16:57:52 -0300587 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400588 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300589
590 for vdu in vnfd.get("vdu", ()):
elumalai6c5ea6b2022-04-25 22:27:59 +0530591 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor)
garciaale7cbd03c2020-11-27 10:38:35 -0300592 sw_image_id = vdu.get("sw-image-desc")
593 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000594 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
595 self._add_image_to_nsr(nsr_descriptor, image_data)
596
597 # also add alternative images to the list of images
598 for alt_image in vdu.get("alternative-sw-image-desc", ()):
599 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
600 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300601
Alexis Romero03fb5842022-03-11 15:53:40 +0100602 # Add Affinity or Anti-affinity group information to NSR
603 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200604 affinity_group_prefix_name = "{}-{}".format(
605 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
606 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100607
608 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200609 affinity_group_data = {}
610 for affinity_group in vdu_profile.get(
611 "affinity-or-anti-affinity-group", ()
612 ):
613 affinity_group_data = (
614 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
615 vnfd, affinity_group["id"]
616 )
617 )
618 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
619 self._add_affinity_or_anti_affinity_group_to_nsr(
620 nsr_descriptor,
621 affinity_group_data,
622 affinity_group_prefix_name,
623 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100624
garciaale7cbd03c2020-11-27 10:38:35 -0300625 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100626 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
627 vld.get("id"), []
628 )
garciaale7cbd03c2020-11-27 10:38:35 -0300629 vld["name"] = vld["id"]
630 nsr_descriptor["vld"] = nsr_vld
631
632 return nsr_descriptor
633
Alexis Romeroee31f532022-04-26 19:10:21 +0200634 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
635 self, vnfd, affinity_group_id
636 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100637 """
638 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
639 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200640 affinity_group = utils.find_in_list(
641 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
642 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100643 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200644 affinity_group_data = {}
645 if affinity_group:
646 if affinity_group.get("id"):
647 affinity_group_data["ag-id"] = affinity_group["id"]
648 if affinity_group.get("type"):
649 affinity_group_data["type"] = affinity_group["type"]
650 if affinity_group.get("scope"):
651 affinity_group_data["scope"] = affinity_group["scope"]
652 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100653
Alexis Romeroee31f532022-04-26 19:10:21 +0200654 def _add_affinity_or_anti_affinity_group_to_nsr(
655 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
656 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100657 """
658 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
659 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200660 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100661 (
662 f
663 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200664 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100665 ),
666 None,
667 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200668 if not affinity_group:
669 affinity_group_data["id"] = str(
670 len(nsr_descriptor["affinity-or-anti-affinity-group"])
671 )
672 affinity_group_data["name"] = "{}-{}".format(
673 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
674 )
675 nsr_descriptor["affinity-or-anti-affinity-group"].append(
676 affinity_group_data
677 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100678
lloretgalleg28c13b62021-02-08 11:48:48 +0000679 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100680 sw_image_desc = utils.find_in_list(
681 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
682 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000683 image_data = {}
684 if sw_image_desc.get("image"):
685 image_data["image"] = sw_image_desc["image"]
686 if sw_image_desc.get("checksum"):
687 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
688 if sw_image_desc.get("vim-type"):
689 image_data["vim-type"] = sw_image_desc["vim-type"]
690 return image_data
691
692 def _add_image_to_nsr(self, nsr_descriptor, image_data):
693 """
694 Adds image to nsr checking first it is not already added
695 """
garciadeblas4568a372021-03-24 09:19:48 +0100696 img = next(
697 (
698 f
699 for f in nsr_descriptor["image"]
700 if all(f.get(k) == image_data[k] for k in image_data)
701 ),
702 None,
703 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000704 if not img:
705 image_data["id"] = str(len(nsr_descriptor["image"]))
706 nsr_descriptor["image"].append(image_data)
707
garciadeblas4568a372021-03-24 09:19:48 +0100708 def _create_vnfr_descriptor_from_vnfd(
709 self,
710 nsd,
711 vnfd,
712 vnfd_id,
713 vnf_index,
714 nsr_descriptor,
715 ns_request,
716 ns_k8s_namespace,
717 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300718 vnfr_id = str(uuid4())
719 nsr_id = nsr_descriptor["id"]
720 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100721 additional_params, vnf_params = self._format_additional_params(
722 ns_request, vnf_index, descriptor=vnfd
723 )
garciaale7cbd03c2020-11-27 10:38:35 -0300724
725 vnfr_descriptor = {
726 "id": vnfr_id,
727 "_id": vnfr_id,
728 "nsr-id-ref": nsr_id,
729 "member-vnf-index-ref": vnf_index,
730 "additionalParamsForVnf": additional_params,
731 "created-time": now,
732 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
733 "vnfd-ref": vnfd_id,
734 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
735 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200736 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300737 "vdur": [],
738 "connection-point": [],
739 "ip-address": None, # mgmt-interface filled by LCM
740 }
beierlmcee2ebf2022-03-29 17:42:48 -0400741
742 # Revision backwards compatility. Only specify the revision in the record if
743 # the original VNFD has a revision.
744 if "revision" in vnfd:
745 vnfr_descriptor["revision"] = vnfd["revision"]
746
747
garciaale7cbd03c2020-11-27 10:38:35 -0300748 vnf_k8s_namespace = ns_k8s_namespace
749 if vnf_params:
750 if vnf_params.get("k8s-namespace"):
751 vnf_k8s_namespace = vnf_params["k8s-namespace"]
752 if vnf_params.get("config-units"):
753 vnfr_descriptor["config-units"] = vnf_params["config-units"]
754
755 # Create vld
756 if vnfd.get("int-virtual-link-desc"):
757 vnfr_descriptor["vld"] = []
758 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
759 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
760
761 for cp in vnfd.get("ext-cpd", ()):
762 vnf_cp = {
763 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100764 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
765 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300766 "id": cp.get("id"),
767 # "ip-address", "mac-address" # filled by LCM
768 # vim-id # TODO it would be nice having a vim port id
769 }
770 vnfr_descriptor["connection-point"].append(vnf_cp)
771
772 # Create k8s-cluster information
773 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
774 if vnfd.get("k8s-cluster"):
775 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
776 all_k8s_cluster_nets_cpds = {}
777 for cpd in get_iterable(vnfd.get("ext-cpd")):
778 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100779 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
780 "id"
781 )
garciaale7cbd03c2020-11-27 10:38:35 -0300782 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
783 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100784 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
785 net.get("id")
786 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300787
788 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300789 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100790 additional_params, kdu_params = self._format_additional_params(
791 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
792 )
garciaale7cbd03c2020-11-27 10:38:35 -0300793 kdu_k8s_namespace = vnf_k8s_namespace
794 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
795 if kdu_params and kdu_params.get("k8s-namespace"):
796 kdu_k8s_namespace = kdu_params["k8s-namespace"]
797
romeromonserbfebfc02021-05-28 10:51:35 +0200798 kdu_deployment_name = ""
799 if kdu_params and kdu_params.get("kdu-deployment-name"):
800 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
801
garciaale7cbd03c2020-11-27 10:38:35 -0300802 kdur = {
803 "additionalParams": additional_params,
804 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200805 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000806 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300807 # TODO "name": "" Name of the VDU in the VIM
808 "ip-address": None, # mgmt-interface filled by LCM
809 "k8s-cluster": {},
810 }
811 if kdu_params and kdu_params.get("config-units"):
812 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000813 if kdu.get("helm-version"):
814 kdur["helm-version"] = kdu["helm-version"]
815 for k8s_type in ("helm-chart", "juju-bundle"):
816 if kdu.get(k8s_type):
817 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300818 if not vnfr_descriptor.get("kdur"):
819 vnfr_descriptor["kdur"] = []
820 vnfr_descriptor["kdur"].append(kdur)
821
822 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300823
garciaale7cbd03c2020-11-27 10:38:35 -0300824 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300825 vdu_mgmt_cp = []
826 try:
garciadeblas4568a372021-03-24 09:19:48 +0100827 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
828 "operate-vnf-op-config"
829 ]["day1-2"]
830 vdu_config = utils.find_in_list(
831 configs, lambda config: config["id"] == vdu["id"]
832 )
bravoff3c39552021-02-24 17:22:24 -0300833 except Exception:
834 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400835
836 try:
837 vdu_instantiation_level = utils.find_in_list(
838 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100839 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400840 )
841 except Exception:
842 vdu_instantiation_level = None
843
bravoff3c39552021-02-24 17:22:24 -0300844 if vdu_config:
845 external_connection_ee = utils.filter_in_list(
846 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100847 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300848 )
849 for ee in external_connection_ee:
850 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
851
garciaale7cbd03c2020-11-27 10:38:35 -0300852 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100853 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
854 )
bravof65e22e52021-11-10 17:58:58 -0300855
856 try:
857 vdu_virtual_storage_descriptors = utils.filter_in_list(
858 vnfd.get("virtual-storage-desc", []),
859 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
860 )
861 except Exception:
862 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300863 vdur = {
864 "vdu-id-ref": vdu["id"],
865 # TODO "name": "" Name of the VDU in the VIM
866 "ip-address": None, # mgmt-interface filled by LCM
867 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
868 "internal-connection-point": [],
869 "interfaces": [],
870 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100871 "vdu-name": vdu["name"],
bravof65e22e52021-11-10 17:58:58 -0300872 "virtual-storages": vdu_virtual_storage_descriptors
garciaale7cbd03c2020-11-27 10:38:35 -0300873 }
874 if vdu_params and vdu_params.get("config-units"):
875 vdur["config-units"] = vdu_params["config-units"]
876 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100877 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
878 "boot-data-drive"
879 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300880 if vdu.get("pdu-type"):
881 vdur["pdu-type"] = vdu["pdu-type"]
882 vdur["name"] = vdu["pdu-type"]
883 # TODO volumes: name, volume-id
884 for icp in vdu.get("int-cpd", ()):
885 vdu_icp = {
886 "id": icp["id"],
887 "connection-point-id": icp["id"],
888 "name": icp.get("id"),
889 }
bravof35766442021-02-04 14:58:04 -0300890
garciaale7cbd03c2020-11-27 10:38:35 -0300891 vdur["internal-connection-point"].append(vdu_icp)
892
893 for iface in icp.get("virtual-network-interface-requirement", ()):
894 iface_fields = ("name", "mac-address")
garciadeblas4568a372021-03-24 09:19:48 +0100895 vdu_iface = {
896 x: iface[x] for x in iface_fields if iface.get(x) is not None
897 }
garciaale7cbd03c2020-11-27 10:38:35 -0300898
899 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100900 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100901 vdu_iface["port-security-enabled"] = icp[
902 "port-security-enabled"
903 ]
sousaedu003844e2021-03-02 00:19:15 +0100904
905 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100906 vdu_iface["port-security-disable-strategy"] = icp[
907 "port-security-disable-strategy"
908 ]
sousaedu003844e2021-03-02 00:19:15 +0100909
garciaale7cbd03c2020-11-27 10:38:35 -0300910 for ext_cp in vnfd.get("ext-cpd", ()):
911 if not ext_cp.get("int-cpd"):
912 continue
913 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
914 continue
915 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100916 vdu_iface["external-connection-point-ref"] = ext_cp.get(
917 "id"
918 )
sousaedu003844e2021-03-02 00:19:15 +0100919
920 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100921 vdu_iface["port-security-enabled"] = ext_cp[
922 "port-security-enabled"
923 ]
sousaedu003844e2021-03-02 00:19:15 +0100924
925 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100926 vdu_iface["port-security-disable-strategy"] = ext_cp[
927 "port-security-disable-strategy"
928 ]
sousaedu003844e2021-03-02 00:19:15 +0100929
garciaale7cbd03c2020-11-27 10:38:35 -0300930 break
931
garciadeblas4568a372021-03-24 09:19:48 +0100932 if (
933 vnfd_mgmt_cp
934 and vdu_iface.get("external-connection-point-ref")
935 == vnfd_mgmt_cp
936 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300937 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300938 vdu_iface["mgmt-interface"] = True
939
940 for ecp in vdu_mgmt_cp:
941 if vdu_iface.get("external-connection-point-ref") == ecp:
942 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300943
944 if iface.get("virtual-interface"):
945 vdu_iface.update(deepcopy(iface["virtual-interface"]))
946
947 # look for network where this interface is connected
948 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
949 if iface_ext_cp:
950 # TODO: Change for multiple df support
951 for df in get_iterable(nsd.get("df")):
952 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100953 for vlc_index, vlc in enumerate(
954 get_iterable(
955 vnf_profile.get("virtual-link-connectivity")
956 )
957 ):
958 for cpd in get_iterable(
959 vlc.get("constituent-cpd-id")
960 ):
961 if (
962 cpd.get("constituent-cpd-id")
963 == iface_ext_cp
964 ):
965 vdu_iface["ns-vld-id"] = vlc.get(
966 "virtual-link-profile-id"
967 )
garciadeblas61c95912021-02-12 11:23:50 +0000968 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100969 if vdu_iface.get("type") in (
970 "SR-IOV",
971 "PCI-PASSTHROUGH",
972 ):
973 nsr_descriptor["vld"][vlc_index][
974 "pci-interfaces"
975 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300976 break
977 elif vdu_iface.get("internal-connection-point-ref"):
978 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000979 # TODO: store fixed IP address in the record (if it exists in the ICP)
980 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
981 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100982 ivld_index = utils.find_index_in_list(
983 vnfd.get("int-virtual-link-desc", ()),
984 lambda ivld: ivld["id"]
985 == icp.get("int-virtual-link-desc"),
986 )
garciadeblas61c95912021-02-12 11:23:50 +0000987 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300988
989 vdur["interfaces"].append(vdu_iface)
990
991 if vdu.get("sw-image-desc"):
992 sw_image = utils.find_in_list(
993 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100994 lambda image: image["id"] == vdu.get("sw-image-desc"),
995 )
garciaale7cbd03c2020-11-27 10:38:35 -0300996 nsr_sw_image_data = utils.find_in_list(
997 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100998 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300999 )
1000 vdur["ns-image-id"] = nsr_sw_image_data["id"]
1001
lloretgalleg28c13b62021-02-08 11:48:48 +00001002 if vdu.get("alternative-sw-image-desc"):
1003 alt_image_ids = []
1004 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1005 sw_image = utils.find_in_list(
1006 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001007 lambda image: image["id"] == alt_image_id,
1008 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001009 nsr_sw_image_data = utils.find_in_list(
1010 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001011 lambda nsr_image: (
1012 nsr_image.get("image") == sw_image.get("image")
1013 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001014 )
1015 alt_image_ids.append(nsr_sw_image_data["id"])
1016 vdur["alt-image-ids"] = alt_image_ids
1017
garciaale7cbd03c2020-11-27 10:38:35 -03001018 flavor_data_name = vdu["id"][:56] + "-flv"
1019 nsr_flavor_desc = utils.find_in_list(
1020 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001021 lambda flavor: flavor["name"] == flavor_data_name,
1022 )
garciaale7cbd03c2020-11-27 10:38:35 -03001023
1024 if nsr_flavor_desc:
1025 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1026
Alexis Romero03fb5842022-03-11 15:53:40 +01001027 # Adding Affinity groups information to vdur
1028 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001029 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001030 vnfd.get("df")[0]["vdu-profile"],
1031 lambda a_vdu: a_vdu["id"] == vdu["id"],
1032 )
1033 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001034 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001035
Alexis Romeroee31f532022-04-26 19:10:21 +02001036 if vdu_profile_affinity_group:
1037 affinity_group_ids = []
1038 for affinity_group in vdu_profile_affinity_group.get(
1039 "affinity-or-anti-affinity-group", ()
1040 ):
1041 vdu_affinity_group = utils.find_in_list(
1042 vdu_profile_affinity_group.get(
1043 "affinity-or-anti-affinity-group", ()
1044 ),
1045 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001046 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001047 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001048 nsr_descriptor["affinity-or-anti-affinity-group"],
1049 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001050 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1051 and nsr_ag.get("member-vnf-index")
1052 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001053 ),
1054 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001055 # Update Affinity Group VIM name if VDU instantiation parameter is present
1056 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1057 vnf_params_affinity_group = utils.find_in_list(
1058 vnf_params["affinity-or-anti-affinity-group"],
1059 lambda vnfp_ag: (
1060 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1061 ),
1062 )
1063 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1064 nsr_affinity_group[
1065 "vim-affinity-group-id"
1066 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1067 affinity_group_ids.append(nsr_affinity_group["id"])
1068 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001069
bravof4ca51522021-04-22 10:03:02 -04001070 if vdu_instantiation_level:
1071 count = vdu_instantiation_level.get("number-of-instances")
1072 else:
1073 count = 1
1074
garciaale7cbd03c2020-11-27 10:38:35 -03001075 for index in range(0, count):
1076 vdur = deepcopy(vdur)
1077 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001078 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001079 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001080 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001081 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1082
1083 vdur["_id"] = str(uuid4())
1084 vdur["id"] = vdur["_id"]
1085 vdur["count-index"] = index
1086 vnfr_descriptor["vdur"].append(vdur)
1087
1088 return vnfr_descriptor
1089
K Sai Kiran57589552021-01-27 21:38:34 +05301090 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1091 """
1092 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1093 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1094 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1095 :param ns_instance_content: ns instance content
1096 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1097 :return: None
1098 """
1099 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
1100 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
1101 threshold_reached = time_delta > 120
1102 if force_refresh or threshold_reached:
1103 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1104 ns_instance_content["_admin"]["modified"] = time_now
1105 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1106 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
1107 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1108 nslcmop_desc["_admin"].pop("nsState")
1109 self.msg.write("ns", operation, nslcmop_desc)
1110 return
1111
1112 def show(self, session, _id, filter_q=None, api_req=False):
1113 """
1114 Get complete information on an ns instance.
1115 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1116 :param _id: string, ns instance id
1117 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1118 :param api_req: True if this call is serving an external API request. False if serving internal request.
1119 :return: dictionary, raise exception if not found.
1120 """
1121 ns_instance_content = super().show(session, _id, api_req)
1122 self.vca_status_refresh(session, ns_instance_content, filter_q)
1123 return ns_instance_content
1124
tierno65ca36d2019-02-12 19:27:52 +01001125 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001126 raise EngineException(
1127 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1128 )
tiernob24258a2018-10-04 18:39:49 +02001129
1130
1131class VnfrTopic(BaseTopic):
1132 topic = "vnfrs"
1133 topic_msg = None
1134
delacruzramo32bab472019-09-13 12:24:22 +02001135 def __init__(self, db, fs, msg, auth):
1136 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001137
tiernobee3bad2019-12-05 12:26:01 +00001138 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001139 raise EngineException(
1140 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1141 )
tiernob24258a2018-10-04 18:39:49 +02001142
tierno65ca36d2019-02-12 19:27:52 +01001143 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001144 raise EngineException(
1145 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1146 )
tiernob24258a2018-10-04 18:39:49 +02001147
tierno65ca36d2019-02-12 19:27:52 +01001148 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001149 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001150 raise EngineException(
1151 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1152 )
tiernob24258a2018-10-04 18:39:49 +02001153
1154
1155class NsLcmOpTopic(BaseTopic):
1156 topic = "nslcmops"
1157 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001158 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001159 "instantiate": ns_instantiate,
1160 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001161 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001162 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +00001163 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301164 "migrate": ns_migrate,
tiernob24258a2018-10-04 18:39:49 +02001165 }
1166
delacruzramo32bab472019-09-13 12:24:22 +02001167 def __init__(self, db, fs, msg, auth):
1168 BaseTopic.__init__(self, db, fs, msg, auth)
elumalai6c5ea6b2022-04-25 22:27:59 +05301169 self.nsrtopic = NsrTopic(db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001170
tiernob24258a2018-10-04 18:39:49 +02001171 def _check_ns_operation(self, session, nsr, operation, indata):
1172 """
1173 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001174 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
aticig544a2ae2022-04-05 09:00:17 +03001175 :param operation: it can be: instantiate, terminate, action, update. TODO: heal
tiernob24258a2018-10-04 18:39:49 +02001176 :param indata: descriptor with the parameters of the operation
1177 :return: None
1178 """
garciaale7cbd03c2020-11-27 10:38:35 -03001179 if operation == "action":
1180 self._check_action_ns_operation(indata, nsr)
1181 elif operation == "scale":
1182 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001183 elif operation == "update":
1184 self._check_update_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001185 elif operation == "instantiate":
1186 self._check_instantiate_ns_operation(indata, nsr, session)
1187
1188 def _check_action_ns_operation(self, indata, nsr):
1189 nsd = nsr["nsd"]
1190 # check vnf_member_index
1191 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001192 indata["member_vnf_index"] = indata.pop(
1193 "vnf_member_index"
1194 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001195 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001196 vnfd = self._get_vnfd_from_vnf_member_index(
1197 indata["member_vnf_index"], nsr["_id"]
1198 )
bravof41a52052021-02-17 18:08:01 -03001199 try:
garciadeblas4568a372021-03-24 09:19:48 +01001200 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1201 "operate-vnf-op-config"
1202 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001203 except Exception:
1204 configs = []
1205
garciaale7cbd03c2020-11-27 10:38:35 -03001206 if indata.get("vdu_id"):
1207 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001208 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001209 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001210 )
garciaale7cbd03c2020-11-27 10:38:35 -03001211 elif indata.get("kdu_name"):
1212 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001213 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001214 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001215 )
garciaale7cbd03c2020-11-27 10:38:35 -03001216 else:
bravof41a52052021-02-17 18:08:01 -03001217 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001218 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001219 )
1220 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001221 descriptor_configuration = descriptor_configuration.get(
1222 "config-primitive"
1223 )
garciaale7cbd03c2020-11-27 10:38:35 -03001224 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001225 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1226 "config-primitive"
1227 )
garciaale7cbd03c2020-11-27 10:38:35 -03001228
1229 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001230 if indata.get("kdu_name") and indata["primitive"] in (
1231 "upgrade",
1232 "rollback",
1233 "status",
1234 "inspect",
1235 "readme",
1236 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001237 # TODO should be checked that rollback only can contains revsision_numbe????
1238 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001239 raise EngineException(
1240 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1241 indata["primitive"]
1242 )
1243 )
garciaale7cbd03c2020-11-27 10:38:35 -03001244 return
1245 # if not, check primitive
1246 for config_primitive in get_iterable(descriptor_configuration):
1247 if indata["primitive"] == config_primitive["name"]:
1248 # check needed primitive_params are provided
1249 if indata.get("primitive_params"):
1250 in_primitive_params_copy = copy(indata["primitive_params"])
1251 else:
1252 in_primitive_params_copy = {}
1253 for paramd in get_iterable(config_primitive.get("parameter")):
1254 if paramd["name"] in in_primitive_params_copy:
1255 del in_primitive_params_copy[paramd["name"]]
1256 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001257 raise EngineException(
1258 "Needed parameter {} not provided for primitive '{}'".format(
1259 paramd["name"], indata["primitive"]
1260 )
1261 )
garciaale7cbd03c2020-11-27 10:38:35 -03001262 # check no extra primitive params are provided
1263 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001264 raise EngineException(
1265 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1266 list(in_primitive_params_copy.keys()), indata["primitive"]
1267 )
1268 )
garciaale7cbd03c2020-11-27 10:38:35 -03001269 break
1270 else:
garciadeblas4568a372021-03-24 09:19:48 +01001271 raise EngineException(
1272 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1273 indata["primitive"]
1274 )
1275 )
garciaale7cbd03c2020-11-27 10:38:35 -03001276
aticig544a2ae2022-04-05 09:00:17 +03001277 def _check_update_ns_operation(self, indata, nsr) -> None:
1278 """Validates the ns-update request according to updateType
1279
1280 If updateType is CHANGE_VNFPKG:
1281 - it checks the vnfInstanceId, whether it's available under ns instance
1282 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1283 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301284 If updateType is REMOVE_VNF:
1285 - it checks if the vnfInstanceId is available in the ns instance
1286 - Otherwise exception will be raised.
aticig544a2ae2022-04-05 09:00:17 +03001287
1288 Args:
1289 indata: includes updateType such as CHANGE_VNFPKG,
1290 nsr: network service record
1291
1292 Raises:
1293 EngineException:
1294 a meaningful error if given update parameters are not proper such as
1295 "Error in validating ns-update request: <ID> does not match
1296 with the vnfd-id of vnfinstance
1297 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1298
1299 """
1300 try:
1301 if indata["updateType"] == "CHANGE_VNFPKG":
1302 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1303 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1304 ns_instance_id = indata["nsInstanceId"]
1305 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1306
1307 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1308
1309 raise EngineException(
1310 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1311 f"belong to NS {ns_instance_id}",
1312 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1313 )
1314
1315 # Getting vnfrs through the ns_instance_id
1316 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1317 constituent_vnfd_id = next(
1318 (
1319 vnfr["vnfd-id"]
1320 for vnfr in vnfrs
1321 if vnfr["id"] == vnf_instance_id
1322 ),
1323 None,
1324 )
1325
1326 # Check the given vnfd-id belongs to given vnf instance
1327 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
1328
1329 raise EngineException(
1330 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1331 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1332 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1333 )
1334
1335 # Validating the ns update timeout
1336 if (
1337 indata.get("timeout_ns_update")
1338 and indata["timeout_ns_update"] < 300
1339 ):
1340 raise EngineException(
1341 "Error in validating ns-update request: {} second is not enough "
1342 "to upgrade the VNF instance: {}".format(
1343 indata["timeout_ns_update"], vnf_instance_id
1344 ),
1345 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1346 )
elumalai6380e7c2022-04-28 00:15:59 +05301347 elif indata["updateType"] == "REMOVE_VNF":
1348 vnf_instance_id = indata["removeVnfInstanceId"]
1349 ns_instance_id = indata["nsInstanceId"]
1350 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1351 raise EngineException(
1352 "Invalid VNF Instance Id. '{}' is not "
1353 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1354 )
aticig544a2ae2022-04-05 09:00:17 +03001355
1356 except (
1357 DbException,
1358 AttributeError,
1359 IndexError,
1360 KeyError,
1361 ValueError,
1362 ) as e:
1363 raise type(e)(
1364 "Ns update request could not be processed with error: {}.".format(e)
1365 )
1366
garciaale7cbd03c2020-11-27 10:38:35 -03001367 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001368 vnfd = self._get_vnfd_from_vnf_member_index(
1369 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1370 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001371 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001372 if (
1373 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1374 == scaling_aspect["id"]
1375 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001376 break
1377 else:
garciadeblas4568a372021-03-24 09:19:48 +01001378 raise EngineException(
1379 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1380 "present at vnfd:scaling-aspect".format(
1381 indata["scaleVnfData"]["scaleByStepData"][
1382 "scaling-group-descriptor"
1383 ]
1384 )
1385 )
garciaale7cbd03c2020-11-27 10:38:35 -03001386
1387 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001388 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001389 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001390 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001391 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001392 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1393 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1394 for in_vnf in get_iterable(indata.get("vnf")):
1395 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001396 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001397 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001398 else:
garciadeblas4568a372021-03-24 09:19:48 +01001399 vnfd = self._get_vnfd_from_vnf_member_index(
1400 member_vnf_index, nsr["_id"]
1401 )
1402 vnf_member_index_to_vnfd[
1403 member_vnf_index
1404 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001405 self._check_vnf_instantiation_params(in_vnf, vnfd)
1406 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001407 self._check_valid_vim_account(
1408 in_vnf["vimAccountId"], vim_accounts, session
1409 )
tierno260dd6f2019-09-02 10:48:56 +00001410
garciaale7cbd03c2020-11-27 10:38:35 -03001411 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001412 self._check_valid_wim_account(
1413 in_vld.get("wimAccountId"), wim_accounts, session
1414 )
garciaale7cbd03c2020-11-27 10:38:35 -03001415 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1416 if in_vld["name"] == vldd["id"]:
1417 break
tierno9cb7d672019-10-30 12:13:48 +00001418 else:
garciadeblas4568a372021-03-24 09:19:48 +01001419 raise EngineException(
1420 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1421 in_vld["name"]
1422 )
1423 )
tierno9cb7d672019-10-30 12:13:48 +00001424
garciaale7cbd03c2020-11-27 10:38:35 -03001425 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1426 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001427 vnfr = self.db.get_one(
1428 "vnfrs",
1429 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1430 fail_on_empty=False,
1431 )
garciaale7cbd03c2020-11-27 10:38:35 -03001432 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001433 raise EngineException(
1434 "Invalid parameter member_vnf_index='{}' is not one of the "
1435 "nsd:constituent-vnfd".format(member_vnf_index)
1436 )
beierlmcee2ebf2022-03-29 17:42:48 -04001437
1438 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1439 if "revision" in vnfr:
1440 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
1441 vnfd = self.db.get_one("vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False)
1442 else:
1443 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1444
garciaale7cbd03c2020-11-27 10:38:35 -03001445 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001446 raise EngineException(
1447 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1448 vnfr["vnfd-id"]
1449 )
1450 )
garciaale7cbd03c2020-11-27 10:38:35 -03001451 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001452
garciaale7cbd03c2020-11-27 10:38:35 -03001453 def _check_valid_vdu(self, vnfd, vdu_id):
1454 for vdud in get_iterable(vnfd.get("vdu")):
1455 if vdud["id"] == vdu_id:
1456 return vdud
1457 else:
garciadeblas4568a372021-03-24 09:19:48 +01001458 raise EngineException(
1459 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1460 vdu_id
1461 )
1462 )
garciaale7cbd03c2020-11-27 10:38:35 -03001463
1464 def _check_valid_kdu(self, vnfd, kdu_name):
1465 for kdud in get_iterable(vnfd.get("kdu")):
1466 if kdud["name"] == kdu_name:
1467 return kdud
1468 else:
garciadeblas4568a372021-03-24 09:19:48 +01001469 raise EngineException(
1470 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1471 kdu_name
1472 )
1473 )
garciaale7cbd03c2020-11-27 10:38:35 -03001474
1475 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1476 for in_vdu in get_iterable(in_vnf.get("vdu")):
1477 for vdu in get_iterable(vnfd.get("vdu")):
1478 if in_vdu["id"] == vdu["id"]:
1479 for volume in get_iterable(in_vdu.get("volume")):
1480 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1481 if volumed["id"] == volume["name"]:
1482 break
1483 else:
garciadeblas4568a372021-03-24 09:19:48 +01001484 raise EngineException(
1485 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1486 "volume:name='{}' is not present at "
1487 "vnfd:vdu:virtual-storage-desc list".format(
1488 in_vnf["member-vnf-index"],
1489 in_vdu["id"],
1490 volume["id"],
1491 )
1492 )
garciaale7cbd03c2020-11-27 10:38:35 -03001493
1494 vdu_if_names = set()
1495 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001496 for iface in get_iterable(
1497 cpd.get("virtual-network-interface-requirement")
1498 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001499 vdu_if_names.add(iface.get("name"))
1500
1501 for in_iface in get_iterable(in_vdu["interface"]):
1502 if in_iface["name"] in vdu_if_names:
1503 break
1504 else:
garciadeblas4568a372021-03-24 09:19:48 +01001505 raise EngineException(
1506 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1507 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1508 in_vnf["member-vnf-index"],
1509 in_vdu["id"],
1510 in_iface["name"],
1511 )
1512 )
garciaale7cbd03c2020-11-27 10:38:35 -03001513 break
1514
1515 else:
garciadeblas4568a372021-03-24 09:19:48 +01001516 raise EngineException(
1517 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1518 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1519 )
garciaale7cbd03c2020-11-27 10:38:35 -03001520
garciadeblas4568a372021-03-24 09:19:48 +01001521 vnfd_ivlds_cpds = {
1522 ivld.get("id"): set()
1523 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1524 }
garciaale7cbd03c2020-11-27 10:38:35 -03001525 for vdu in get_iterable(vnfd.get("vdu")):
1526 for cpd in get_iterable(vnfd.get("int-cpd")):
1527 if cpd.get("int-virtual-link-desc"):
1528 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1529
1530 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1531 if in_ivld.get("name") in vnfd_ivlds_cpds:
1532 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1533 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001534 break
tiernob24258a2018-10-04 18:39:49 +02001535 else:
garciadeblas4568a372021-03-24 09:19:48 +01001536 raise EngineException(
1537 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1538 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1539 "vnfd:internal-vld:name/id:internal-connection-point".format(
1540 in_vnf["member-vnf-index"],
1541 in_ivld["name"],
1542 in_icp["id-ref"],
1543 )
1544 )
tiernob24258a2018-10-04 18:39:49 +02001545 else:
garciadeblas4568a372021-03-24 09:19:48 +01001546 raise EngineException(
1547 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1548 " is not present at vnfd '{}'".format(
1549 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1550 )
1551 )
tiernob24258a2018-10-04 18:39:49 +02001552
garciaale7cbd03c2020-11-27 10:38:35 -03001553 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1554 if vim_account in vim_accounts:
1555 return
1556 try:
1557 db_filter = self._get_project_filter(session)
1558 db_filter["_id"] = vim_account
1559 self.db.get_one("vim_accounts", db_filter)
1560 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001561 raise EngineException(
1562 "Invalid vimAccountId='{}' not present for the project".format(
1563 vim_account
1564 )
1565 )
garciaale7cbd03c2020-11-27 10:38:35 -03001566 vim_accounts.append(vim_account)
1567
David Garcia98de2982021-10-13 17:14:01 +02001568 def _get_vim_account(self, vim_id: str, session):
1569 try:
1570 db_filter = self._get_project_filter(session)
1571 db_filter["_id"] = vim_id
1572 return self.db.get_one("vim_accounts", db_filter)
1573 except Exception:
1574 raise EngineException(
1575 "Invalid vimAccountId='{}' not present for the project".format(
1576 vim_id
1577 )
1578 )
1579
garciaale7cbd03c2020-11-27 10:38:35 -03001580 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1581 if not isinstance(wim_account, str):
1582 return
1583 if wim_account in wim_accounts:
1584 return
1585 try:
1586 db_filter = self._get_project_filter(session, write=False, show_all=True)
1587 db_filter["_id"] = wim_account
1588 self.db.get_one("wim_accounts", db_filter)
1589 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001590 raise EngineException(
1591 "Invalid wimAccountId='{}' not present for the project".format(
1592 wim_account
1593 )
1594 )
garciaale7cbd03c2020-11-27 10:38:35 -03001595 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001596
garciadeblas4568a372021-03-24 09:19:48 +01001597 def _look_for_pdu(
1598 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1599 ):
tiernocc103432018-10-19 14:10:35 +02001600 """
tierno36ec8602018-11-02 17:27:11 +01001601 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1602 (ip_address, ...) information.
1603 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001604 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001605 :param rollback: list with the database modifications to rollback if needed
1606 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1607 :param vim_account: vim_account where this vnfr should be deployed
1608 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1609 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1610 of the changed vnfr is needed
1611
1612 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1613 "vim-network-name": used at VIM
1614 "name": interface name
1615 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1616 "ns-vld-id": NSD vld where this interface is connected.
1617 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 +02001618 """
tierno36ec8602018-11-02 17:27:11 +01001619
1620 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001621 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1622 if not vdur.get("pdu-type"):
1623 continue
1624 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001625 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001626 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001627 pdu_filter["type"] = pdu_type
1628 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001629 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001630 # TODO feature 1417: "shared": True,
1631
1632 available_pdus = self.db.get_list("pdus", pdu_filter)
1633 for pdu in available_pdus:
1634 # step 1 check if this pdu contains needed interfaces:
1635 match_interfaces = True
1636 for vdur_interface in vdur["interfaces"]:
1637 for pdu_interface in pdu["interfaces"]:
1638 if pdu_interface["name"] == vdur_interface["name"]:
1639 # TODO feature 1417: match per mgmt type
1640 break
1641 else: # no interface found for name
1642 match_interfaces = False
1643 break
1644 if match_interfaces:
1645 break
1646 else:
1647 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001648 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001649 "names".format(
1650 pdu_type,
1651 vim_account,
1652 vnfr["member-vnf-index-ref"],
1653 vdur["vdu-id-ref"],
1654 )
1655 )
tiernocc103432018-10-19 14:10:35 +02001656
1657 # step 2. Update pdu
1658 rollback_pdu = {
1659 "_admin.usageState": pdu["_admin"]["usageState"],
1660 "_admin.usage.vnfr_id": None,
1661 "_admin.usage.nsr_id": None,
1662 "_admin.usage.vdur": None,
1663 }
garciadeblas4568a372021-03-24 09:19:48 +01001664 self.db.set_one(
1665 "pdus",
1666 {"_id": pdu["_id"]},
1667 {
1668 "_admin.usageState": "IN_USE",
1669 "_admin.usage": {
1670 "vnfr_id": vnfr["_id"],
1671 "nsr_id": vnfr["nsr-id-ref"],
1672 "vdur": vdur["vdu-id-ref"],
1673 },
1674 },
1675 )
1676 rollback.append(
1677 {
1678 "topic": "pdus",
1679 "_id": pdu["_id"],
1680 "operation": "set",
1681 "content": rollback_pdu,
1682 }
1683 )
tiernocc103432018-10-19 14:10:35 +02001684
1685 # step 3. Fill vnfr info by filling vdur
1686 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001687 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001688 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1689 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1690 for pdu_interface in pdu["interfaces"]:
1691 if pdu_interface["name"] == vdur_interface["name"]:
1692 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1693 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001694 if k in (
1695 "ip-address",
1696 "mac-address",
1697 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001698 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001699 vnfr_update_rollback[
1700 iface_text + ".{}".format(k)
1701 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001702 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001703 if vdur_interface.get(
1704 "mgmt-interface"
1705 ) or vdur_interface.get("mgmt-vnf"):
1706 vnfr_update_rollback[
1707 vdu_text + ".ip-address"
1708 ] = vdur.get("ip-address")
1709 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1710 "ip-address"
1711 ]
tierno36ec8602018-11-02 17:27:11 +01001712 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001713 vnfr_update_rollback["ip-address"] = vnfr.get(
1714 "ip-address"
1715 )
tierno36ec8602018-11-02 17:27:11 +01001716 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001717 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1718 "ip-address"
1719 ]
1720 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1721 "vim-network-id"
1722 ):
1723 ifaces_forcing_vim_network.append(
1724 {
1725 "name": vdur_interface.get("vnf-vld-id")
1726 or vdur_interface.get("ns-vld-id"),
1727 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1728 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1729 }
1730 )
gcalvino17d5b732018-12-17 16:26:21 +01001731 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001732 ifaces_forcing_vim_network[-1][
1733 "vim-network-id"
1734 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001735 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001736 ifaces_forcing_vim_network[-1][
1737 "vim-network-name"
1738 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001739 break
1740
tierno36ec8602018-11-02 17:27:11 +01001741 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001742
garciadeblas4568a372021-03-24 09:19:48 +01001743 def _look_for_k8scluster(
1744 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1745 ):
tierno9cb7d672019-10-30 12:13:48 +00001746 """
1747 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1748 Fills vnfr.kdur with the selected k8scluster
1749
1750 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1751 :param rollback: list with the database modifications to rollback if needed
1752 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1753 :param vim_account: vim_account where this vnfr should be deployed
1754 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1755 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1756 of the changed vnfr is needed
1757
1758 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1759 "vim-network-name": used at VIM
1760 "name": interface name
1761 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1762 "ns-vld-id": NSD vld where this interface is connected.
1763 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1764 """
1765
1766 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001767 if not vnfr.get("kdur"):
1768 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001769
tiernoc67b0e92019-11-05 12:45:29 +00001770 kdu_filter = self._get_project_filter(session)
1771 kdu_filter["vim_account"] = vim_account
1772 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1773 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1774
1775 k8s_requirements = {} # just for logging
1776 for k8scluster in available_k8sclusters:
1777 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001778 break
tiernoc67b0e92019-11-05 12:45:29 +00001779 # restrict by cni
1780 if vnfr["k8s-cluster"].get("cni"):
1781 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001782 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1783 k8scluster.get("cni", ())
1784 ):
tiernoc67b0e92019-11-05 12:45:29 +00001785 continue
1786 # restrict by version
1787 if vnfr["k8s-cluster"].get("version"):
1788 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1789 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1790 continue
1791 # restrict by number of networks
1792 if vnfr["k8s-cluster"].get("nets"):
1793 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001794 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1795 vnfr["k8s-cluster"]["nets"]
1796 ):
tiernoc67b0e92019-11-05 12:45:29 +00001797 continue
1798 break
1799 else:
garciadeblas4568a372021-03-24 09:19:48 +01001800 raise EngineException(
1801 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1802 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1803 )
1804 )
tierno9cb7d672019-10-30 12:13:48 +00001805
tiernoc67b0e92019-11-05 12:45:29 +00001806 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001807 # step 3. Fill vnfr info by filling kdur
1808 kdu_text = "kdur.{}.".format(kdur_index)
1809 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1810 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1811
tiernoc67b0e92019-11-05 12:45:29 +00001812 # step 4. Check VIM networks that forces the selected k8s_cluster
1813 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1814 k8scluster_net_list = list(k8scluster.get("nets").keys())
1815 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1816 # get a network from k8s_cluster nets. If name matches use this, if not use other
1817 if kdur_net["id"] in k8scluster_net_list: # name matches
1818 vim_net = k8scluster["nets"][kdur_net["id"]]
1819 k8scluster_net_list.remove(kdur_net["id"])
1820 else:
1821 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1822 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001823 vnfr_update_rollback[
1824 "k8s-cluster.nets.{}.vim_net".format(net_index)
1825 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001826 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001827 if vim_net and (
1828 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1829 ):
1830 ifaces_forcing_vim_network.append(
1831 {
1832 "name": kdur_net.get("vnf-vld-id")
1833 or kdur_net.get("ns-vld-id"),
1834 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1835 "ns-vld-id": kdur_net.get("ns-vld-id"),
1836 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1837 }
1838 )
tiernoc67b0e92019-11-05 12:45:29 +00001839 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001840 return ifaces_forcing_vim_network
1841
Gulsum Aticie395aa42021-11-10 20:59:06 +03001842 def _update_vnfrs_from_nsd(self, nsr):
1843 try:
1844 nsr_id = nsr["_id"]
1845 nsd = nsr["nsd"]
1846
1847 step = "Getting vnf_profiles from nsd"
1848 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1849 vld_fixed_ip_connection_point_data = {}
1850
1851 step = "Getting ip-address info from vnf_profile if it exists"
1852 for vnfp in vnf_profiles:
1853 # Checking ip-address info from nsd.vnf_profile and storing
1854 for vlc in vnfp.get("virtual-link-connectivity", ()):
1855 for cpd in vlc.get("constituent-cpd-id", ()):
1856 if cpd.get("ip-address"):
1857 step = "Storing ip-address info"
1858 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1859 "vnfd-connection-point-ref": cpd.get(
1860 "constituent-cpd-id"),
1861 "ip-address": cpd.get(
1862 "ip-address")}})
1863
1864 # Inserting ip address to vnfr
1865 if len(vld_fixed_ip_connection_point_data) > 0:
1866 step = "Getting vnfrs"
1867 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1868 for item in vld_fixed_ip_connection_point_data.keys():
1869 step = "Filtering vnfrs"
1870 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1871 if vnfr:
1872 vnfr_update = {}
1873 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1874 for iface_index, iface in enumerate(vdur["interfaces"]):
1875 step = "Looking for matched interface"
1876 if (
1877 iface.get("external-connection-point-ref")
1878 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1879 iface.get("ns-vld-id") == item.split('.')[0]
1880
1881 ):
1882 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1883 vdur_index, iface_index
1884 )
1885 step = "Storing info in order to update vnfr"
1886 vnfr_update[
1887 vnfr_update_text + ".ip-address"
1888 ] = increment_ip_mac(
1889 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1890 vdur.get("count-index", 0), )
1891 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1892
1893 step = "updating vnfr at database"
1894 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1895 except (
1896 ValidationError,
1897 EngineException,
1898 DbException,
1899 MsgException,
1900 FsException,
1901 ) as e:
1902 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1903
tiernocc103432018-10-19 14:10:35 +02001904 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001905 # get vnfr
1906 nsr_id = nsr["_id"]
1907 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1908
1909 for vnfr in vnfrs:
1910 vnfr_update = {}
1911 vnfr_update_rollback = {}
1912 member_vnf_index = vnfr["member-vnf-index-ref"]
1913 # update vim-account-id
1914
1915 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02001916 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001917 # check instantiate parameters
1918 for vnf_inst_params in get_iterable(indata.get("vnf")):
1919 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1920 continue
1921 if vnf_inst_params.get("vimAccountId"):
1922 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02001923 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001924
tiernocddb07d2020-10-06 08:28:00 +00001925 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1926 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1927 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1928 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1929 continue
garciadeblas4568a372021-03-24 09:19:48 +01001930 for iface_inst_param in get_iterable(
1931 vdu_inst_param.get("interface")
1932 ):
1933 iface_index, _ = next(
1934 i
1935 for i in enumerate(vdur["interfaces"])
1936 if i[1]["name"] == iface_inst_param["name"]
1937 )
1938 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1939 vdur_index, iface_index
1940 )
tiernocddb07d2020-10-06 08:28:00 +00001941 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001942 vnfr_update[
1943 vnfr_update_text + ".ip-address"
1944 ] = increment_ip_mac(
1945 iface_inst_param.get("ip-address"),
1946 vdur.get("count-index", 0),
1947 )
tierno1bd9d952020-11-13 15:56:51 +00001948 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001949 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001950 vnfr_update[
1951 vnfr_update_text + ".mac-address"
1952 ] = increment_ip_mac(
1953 iface_inst_param.get("mac-address"),
1954 vdur.get("count-index", 0),
1955 )
tierno1bd9d952020-11-13 15:56:51 +00001956 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001957 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001958 vnfr_update[
1959 vnfr_update_text + ".floating-ip-required"
1960 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001961 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1962 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001963 for ivld_inst_param in get_iterable(
1964 vnf_inst_params.get("internal-vld")
1965 ):
1966 for icp_inst_param in get_iterable(
1967 ivld_inst_param.get("internal-connection-point")
1968 ):
tiernocddb07d2020-10-06 08:28:00 +00001969 # look for iface
1970 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1971 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001972 if (
1973 iface.get("internal-connection-point-ref")
1974 == icp_inst_param["id-ref"]
1975 ):
1976 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1977 vdur_index, iface_index
1978 )
tiernocddb07d2020-10-06 08:28:00 +00001979 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001980 vnfr_update[
1981 vnfr_update_text + ".ip-address"
1982 ] = increment_ip_mac(
1983 icp_inst_param.get("ip-address"),
1984 vdur.get("count-index", 0),
1985 )
1986 vnfr_update[
1987 vnfr_update_text + ".fixed-ip"
1988 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001989 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001990 vnfr_update[
1991 vnfr_update_text + ".mac-address"
1992 ] = increment_ip_mac(
1993 icp_inst_param.get("mac-address"),
1994 vdur.get("count-index", 0),
1995 )
1996 vnfr_update[
1997 vnfr_update_text + ".fixed-mac"
1998 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001999 break
2000 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2001 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01002002 for vnfcp_inst_param in get_iterable(
2003 vld_inst_param.get("vnfd-connection-point-ref")
2004 ):
tiernocddb07d2020-10-06 08:28:00 +00002005 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2006 continue
2007 # look for iface
2008 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2009 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002010 if (
2011 iface.get("external-connection-point-ref")
2012 == vnfcp_inst_param["vnfd-connection-point-ref"]
2013 ):
2014 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2015 vdur_index, iface_index
2016 )
tiernocddb07d2020-10-06 08:28:00 +00002017 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002018 vnfr_update[
2019 vnfr_update_text + ".ip-address"
2020 ] = increment_ip_mac(
2021 vnfcp_inst_param.get("ip-address"),
2022 vdur.get("count-index", 0),
2023 )
tierno1bd9d952020-11-13 15:56:51 +00002024 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002025 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002026 vnfr_update[
2027 vnfr_update_text + ".mac-address"
2028 ] = increment_ip_mac(
2029 vnfcp_inst_param.get("mac-address"),
2030 vdur.get("count-index", 0),
2031 )
tierno1bd9d952020-11-13 15:56:51 +00002032 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002033 break
2034
tiernocc103432018-10-19 14:10:35 +02002035 vnfr_update["vim-account-id"] = vim_account
2036 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2037
David Garciaecb41322021-03-31 19:10:46 +02002038 if vca_id:
2039 vnfr_update["vca-id"] = vca_id
2040 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2041
tiernocc103432018-10-19 14:10:35 +02002042 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002043 ifaces_forcing_vim_network = self._look_for_pdu(
2044 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2045 )
tiernocc103432018-10-19 14:10:35 +02002046
tierno9cb7d672019-10-30 12:13:48 +00002047 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002048 ifaces_forcing_vim_network += self._look_for_k8scluster(
2049 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2050 )
tierno9cb7d672019-10-30 12:13:48 +00002051 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002052 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002053 rollback.append(
2054 {
2055 "topic": "vnfrs",
2056 "_id": vnfr["_id"],
2057 "operation": "set",
2058 "content": vnfr_update_rollback,
2059 }
2060 )
tierno36ec8602018-11-02 17:27:11 +01002061
2062 # Update indada in case pdu forces to use a concrete vim-network-name
2063 # TODO check if user has already insert a vim-network-name and raises an error
2064 if not ifaces_forcing_vim_network:
2065 continue
2066 for iface_info in ifaces_forcing_vim_network:
2067 if iface_info.get("ns-vld-id"):
2068 if "vld" not in indata:
2069 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002070 indata["vld"].append(
2071 {
2072 key: iface_info[key]
2073 for key in ("name", "vim-network-name", "vim-network-id")
2074 if iface_info.get(key)
2075 }
2076 )
tierno36ec8602018-11-02 17:27:11 +01002077
2078 elif iface_info.get("vnf-vld-id"):
2079 if "vnf" not in indata:
2080 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002081 indata["vnf"].append(
2082 {
2083 "member-vnf-index": member_vnf_index,
2084 "internal-vld": [
2085 {
2086 key: iface_info[key]
2087 for key in (
2088 "name",
2089 "vim-network-name",
2090 "vim-network-id",
2091 )
2092 if iface_info.get(key)
2093 }
2094 ],
2095 }
2096 )
tierno36ec8602018-11-02 17:27:11 +01002097
2098 @staticmethod
2099 def _create_nslcmop(nsr_id, operation, params):
2100 """
2101 Creates a ns-lcm-opp content to be stored at database.
2102 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002103 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002104 :param params: user parameters for the operation
2105 :return: dictionary following SOL005 format
2106 """
tiernob24258a2018-10-04 18:39:49 +02002107 now = time()
2108 _id = str(uuid4())
2109 nslcmop = {
2110 "id": _id,
2111 "_id": _id,
2112 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002113 "queuePosition": None,
2114 "stage": None,
2115 "errorMessage": None,
2116 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002117 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002118 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002119 "lcmOperationType": operation,
2120 "startTime": now,
2121 "isAutomaticInvocation": False,
2122 "operationParams": params,
2123 "isCancelPending": False,
2124 "links": {
2125 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002126 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002127 },
tiernob24258a2018-10-04 18:39:49 +02002128 }
2129 return nslcmop
2130
magnussonlf318b302020-01-20 18:38:18 +01002131 def _get_enabled_vims(self, session):
2132 """
2133 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2134 :param session: current session with user information
2135 """
2136 db_filter = self._get_project_filter(session)
2137 db_filter["_admin.operationalState"] = "ENABLED"
2138 vims = self.db.get_list("vim_accounts", db_filter)
2139 vimAccounts = []
2140 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002141 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002142 return vimAccounts
2143
garciadeblas4568a372021-03-24 09:19:48 +01002144 def new(
2145 self,
2146 rollback,
2147 session,
2148 indata=None,
2149 kwargs=None,
2150 headers=None,
2151 slice_object=False,
2152 ):
tiernob24258a2018-10-04 18:39:49 +02002153 """
2154 Performs a new operation over a ns
2155 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002156 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002157 :param indata: descriptor with the parameters of the operation. It must contains among others
2158 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002159 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002160 :param kwargs: used to override the indata descriptor
2161 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002162 :return: id of the nslcmops
2163 """
garciadeblas4568a372021-03-24 09:19:48 +01002164
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002165 def check_if_nsr_is_not_slice_member(session, nsr_id):
2166 nsis = None
2167 db_filter = self._get_project_filter(session)
2168 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002169 nsis = self.db.get_one(
2170 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2171 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002172 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002173 raise EngineException(
2174 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2175 nsr_id, nsis["_id"]
2176 ),
2177 http_code=HTTPStatus.CONFLICT,
2178 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002179
tiernob24258a2018-10-04 18:39:49 +02002180 try:
2181 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002182 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002183 operation = indata["lcmOperationType"]
2184 nsInstanceId = indata["nsInstanceId"]
2185
2186 validate_input(indata, self.operation_schema[operation])
2187 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002188 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002189 _filter["_id"] = nsInstanceId
2190 nsr = self.db.get_one("nsrs", _filter)
2191
2192 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002193 if operation == "terminate" and slice_object is False:
2194 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002195 if (
2196 not nsr["_admin"].get("nsState")
2197 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2198 ):
tiernob24258a2018-10-04 18:39:49 +02002199 if operation == "terminate" and indata.get("autoremove"):
2200 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002201 return (
2202 None,
2203 None,
2204 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002205 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002206 raise EngineException(
2207 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2208 nsInstanceId, operation
2209 ),
2210 HTTPStatus.CONFLICT,
2211 )
tiernob24258a2018-10-04 18:39:49 +02002212 else:
tierno65ca36d2019-02-12 19:27:52 +01002213 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002214 raise EngineException(
2215 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2216 nsInstanceId, operation
2217 ),
2218 HTTPStatus.CONFLICT,
2219 )
tiernob24258a2018-10-04 18:39:49 +02002220 self._check_ns_operation(session, nsr, operation, indata)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002221 if (indata.get("primitive_params")):
2222 indata["primitive_params"] = json.dumps(indata["primitive_params"])
2223 elif (indata.get("additionalParamsForVnf")):
2224 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
tierno36ec8602018-11-02 17:27:11 +01002225
tiernocc103432018-10-19 14:10:35 +02002226 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002227 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002228 self._update_vnfrs(session, rollback, nsr, indata)
elumalai6c5ea6b2022-04-25 22:27:59 +05302229 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2230 nsr_update = {}
2231 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2232 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2233 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2234 ns_request = nsr["instantiate_params"]
2235 vnfr = self.db.get_one("vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]})
elumalai8bf978e2022-05-26 15:32:06 +05302236 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2237 vnfr_vnfd_revision = vnfr.get("revision", 1)
2238 if latest_vnfd_revision != vnfr_vnfd_revision:
2239 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
2240 old_db_vnfd = self.db.get_one("vnfds_revisions", {"_id": old_vnfd_id})
2241 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2242 new_sw_version = vnfd.get("software-version", "1.0")
2243 if new_sw_version != old_sw_version:
2244 vnf_index = vnfr["member-vnf-index-ref"]
2245 self.logger.info("nsr {}".format(nsr))
2246 for vdu in vnfd["vdu"]:
2247 self.nsrtopic._add_flavor_to_nsr(vdu, vnfd, nsr)
2248 sw_image_id = vdu.get("sw-image-desc")
2249 if sw_image_id:
2250 image_data = self.nsrtopic._get_image_data_from_vnfd(vnfd, sw_image_id)
2251 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2252 for alt_image in vdu.get("alternative-sw-image-desc", ()):
2253 image_data = self.nsrtopic._get_image_data_from_vnfd(vnfd, alt_image)
2254 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2255 nsr_update["image"] = nsr["image"]
2256 nsr_update["flavor"] = nsr["flavor"]
2257 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
2258 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(nsd, ns_request, session)
2259 vnfr_descriptor = self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2260 nsd,
2261 vnfd,
2262 vnfd_id,
2263 vnf_index,
2264 nsr,
2265 ns_request,
2266 ns_k8s_namespace,
2267 )
2268 indata["newVdur"] = vnfr_descriptor["vdur"]
tierno36ec8602018-11-02 17:27:11 +01002269 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002270 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002271 self.format_on_new(
2272 nslcmop_desc, session["project_id"], make_public=session["public"]
2273 )
magnussonlf318b302020-01-20 18:38:18 +01002274 if indata.get("placement-engine"):
2275 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002276 nslcmop_desc["operationParams"][
2277 "validVimAccounts"
2278 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002279 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002280 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002281 if not slice_object:
2282 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002283 return _id, None
2284 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002285 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2286 # except DbException as e:
2287 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2288
tiernobee3bad2019-12-05 12:26:01 +00002289 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002290 raise EngineException(
2291 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2292 )
tiernob24258a2018-10-04 18:39:49 +02002293
tierno65ca36d2019-02-12 19:27:52 +01002294 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002295 raise EngineException(
2296 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2297 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002298
2299
2300class NsiTopic(BaseTopic):
2301 topic = "nsis"
2302 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002303 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002304
delacruzramo32bab472019-09-13 12:24:22 +02002305 def __init__(self, db, fs, msg, auth):
2306 BaseTopic.__init__(self, db, fs, msg, auth)
2307 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002308
Felipe Vicensc37b3842019-01-12 12:24:42 +01002309 @staticmethod
2310 def _format_ns_request(ns_request):
2311 formated_request = copy(ns_request)
2312 # TODO: Add request params
2313 return formated_request
2314
2315 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002316 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002317 """
2318 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002319 :param slice_request: User instantiation additional parameters
2320 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002321 """
tiernofd160572019-01-21 10:41:37 +00002322 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2323 if additional_params:
2324 for k, v in additional_params.items():
2325 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002326 raise EngineException(
2327 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2328 k
2329 )
2330 )
tiernofd160572019-01-21 10:41:37 +00002331 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002332 raise EngineException(
2333 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2334 k
2335 )
2336 )
tiernofd160572019-01-21 10:41:37 +00002337 if isinstance(v, (dict, tuple, list)):
2338 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002339 return additional_params
2340
Felipe Vicensb57758d2018-10-16 16:00:20 +02002341 def _check_descriptor_dependencies(self, session, descriptor):
2342 """
2343 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01002344 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002345 :param descriptor: descriptor to be inserted or edit
2346 :return: None or raises exception
2347 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002348 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002349 return
Felipe Vicens07f31722018-10-29 15:16:44 +01002350 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002351 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
garciadeblas4568a372021-03-24 09:19:48 +01002352 raise EngineException(
2353 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2354 nstd_id
2355 ),
2356 http_code=HTTPStatus.CONFLICT,
2357 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002358
tiernob4844ab2019-05-23 08:42:12 +00002359 def check_conflict_on_del(self, session, _id, db_content):
2360 """
2361 Check that NSI is not instantiated
2362 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2363 :param _id: nsi internal id
2364 :param db_content: The database content of the _id
2365 :return: None or raises EngineException with the conflict
2366 """
tierno65ca36d2019-02-12 19:27:52 +01002367 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002368 return
tiernob4844ab2019-05-23 08:42:12 +00002369 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002370 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002371 raise EngineException(
2372 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2373 "Launch 'terminate' operation first; or force deletion".format(_id),
2374 http_code=HTTPStatus.CONFLICT,
2375 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002376
tiernobee3bad2019-12-05 12:26:01 +00002377 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002378 """
tiernob4844ab2019-05-23 08:42:12 +00002379 Deletes associated nsilcmops from database. Deletes associated filesystem.
2380 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002381 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002382 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002383 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002384 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002385 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002386 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002387
Felipe Vicens09e65422019-01-22 15:06:46 +01002388 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002389 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002390 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2391 nsr_id = nsrs_detailed_item["nsrId"]
2392 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002393 _filter = {
2394 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2395 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2396 "_id.ne": nsir["_id"],
2397 }
2398 nsi = self.db.get_one(
2399 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2400 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002401 if nsi: # last one using nsr
2402 continue
2403 try:
garciadeblas4568a372021-03-24 09:19:48 +01002404 self.nsrTopic.delete(
2405 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2406 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002407 except (DbException, EngineException) as e:
2408 if e.http_code == HTTPStatus.NOT_FOUND:
2409 pass
2410 else:
2411 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002412
tiernob4844ab2019-05-23 08:42:12 +00002413 # delete related nsilcmops database entries
2414 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002415
tiernob4844ab2019-05-23 08:42:12 +00002416 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002417 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002418 if nsir_admin and nsir_admin.get("nst-id"):
2419 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002420 nsis_list = self.db.get_one(
2421 "nsis",
2422 {"nst-id": nsir_admin["nst-id"]},
2423 fail_on_empty=False,
2424 fail_on_more=False,
2425 )
tiernob4844ab2019-05-23 08:42:12 +00002426 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002427 self.db.set_one(
2428 "nsts",
2429 {"_id": nsir_admin["nst-id"]},
2430 {"_admin.usageState": "NOT_IN_USE"},
2431 )
tiernob4844ab2019-05-23 08:42:12 +00002432
tierno65ca36d2019-02-12 19:27:52 +01002433 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002434 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002435 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002436 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002437 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002438 :param indata: params to be used for the nsir
2439 :param kwargs: used to override the indata descriptor
2440 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002441 :return: the _id of nsi descriptor created at database
2442 """
2443
2444 try:
delacruzramo32bab472019-09-13 12:24:22 +02002445 step = "checking quotas"
2446 self.check_quota(session)
2447
tierno99d4b172019-07-02 09:28:40 +00002448 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002449 slice_request = self._remove_envelop(indata)
2450 # Override descriptor with query string kwargs
2451 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002452 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002453
Felipe Vicensb57758d2018-10-16 16:00:20 +02002454 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002455 step = "getting nstd id='{}' from database".format(
2456 slice_request.get("nstId")
2457 )
tiernob4844ab2019-05-23 08:42:12 +00002458 _filter = self._get_project_filter(session)
2459 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002460 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002461 # check NST is not disabled
2462 step = "checking NST operationalState"
2463 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002464 raise EngineException(
2465 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2466 "instance".format(slice_request["nstId"]),
2467 http_code=HTTPStatus.CONFLICT,
2468 )
tiernob4844ab2019-05-23 08:42:12 +00002469 del _filter["_id"]
2470
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002471 # check NSD is not disabled
2472 step = "checking operationalState"
2473 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002474 raise EngineException(
2475 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2476 "a network slice".format(slice_request["nstId"]),
2477 http_code=HTTPStatus.CONFLICT,
2478 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002479
Felipe Vicens07f31722018-10-29 15:16:44 +01002480 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002481 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002482 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002483 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002484
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002485 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002486 nsi_descriptor = {
2487 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002488 "name": slice_request["nsiName"],
2489 "description": slice_request.get("nsiDescription", ""),
2490 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002491 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002492 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002493 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002494 "nsr-ref-list": [],
2495 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002496 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002497 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002498 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002499
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002500 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002501 self.format_on_new(
2502 nsi_descriptor, session["project_id"], make_public=session["public"]
2503 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002504 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2505 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002506 nsi_descriptor["_admin"]["deployed"] = {}
2507 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2508 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2509
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002510 # Creating netslice-vld for the RO.
2511 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002512
2513 # Building the vlds list to be deployed
2514 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002515 nsi_vlds = []
2516
2517 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2518 # Getting template Instantiation parameters from NST
2519 nsi_vld = deepcopy(netslice_vlds)
2520 nsi_vld["shared-nsrs-list"] = []
2521 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2522 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002523
2524 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002525 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002526 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002527 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002528
Felipe Vicens09e65422019-01-22 15:06:46 +01002529 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002530 for member_ns in nstd["netslice-subnet"]:
2531 nsd_id = member_ns["nsd-ref"]
2532 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002533 member_ns["nsd-ref"], member_ns["id"]
2534 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002535 if nsd_id not in needed_nsds:
2536 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002537 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002538 nsd = self.db.get_one(
2539 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2540 )
tiernob4844ab2019-05-23 08:42:12 +00002541 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002542 nsd.pop("_admin")
2543 needed_nsds[nsd_id] = nsd
2544 else:
2545 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002546 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2547 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002548
Felipe Vicensb57758d2018-10-16 16:00:20 +02002549 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002550 member_ns["nsd-ref"], member_ns["id"]
2551 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002552
Felipe Vicens07f31722018-10-29 15:16:44 +01002553 # creates Network Services records (NSRs)
2554 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002555 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002556 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002557 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002558 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002559 # Check if the netslice-subnet is shared and if it is share if the nss exists
2560 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002561 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002562 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002563 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002564 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2565 "nsd-ref"
2566 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002567 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002568 nsi = self.db.get_one(
2569 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2570 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002571 if nsi and service.get("is-shared-nss"):
2572 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2573 for nsrs_detailed_item in nsrs_detailed_list:
2574 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002575 if nsrs_detailed_item["nss-id"] == service["id"]:
2576 _id_nsr = nsrs_detailed_item["nsrId"]
2577 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002578 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2579 if netslice_subnet["nss-id"] == service["id"]:
2580 indata_ns = netslice_subnet
2581 break
2582 else:
2583 indata_ns = {}
2584 if service.get("instantiation-parameters"):
2585 indata_ns = deepcopy(service["instantiation-parameters"])
2586 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002587
Felipe Vicens09e65422019-01-22 15:06:46 +01002588 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002589 indata_ns["nsName"] = (
2590 slice_request.get("nsiName") + "." + service["id"]
2591 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002592 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2593 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002594 if slice_request.get("ssh_keys"):
2595 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002596
Felipe Vicens09e65422019-01-22 15:06:46 +01002597 if ns_params:
2598 for ns_param in ns_params:
2599 if ns_param.get("id") == service["id"]:
2600 copy_ns_param = deepcopy(ns_param)
2601 del copy_ns_param["id"]
2602 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002603 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002604
2605 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002606 _id_nsr, _ = self.nsrTopic.new(
2607 rollback, session, indata_ns, kwargs, headers
2608 )
2609 nsrs_item = {
2610 "nsrId": _id_nsr,
2611 "shared": service.get("is-shared-nss"),
2612 "nsd-id": service["nsd-ref"],
2613 "nss-id": service["id"],
2614 "nslcmop_instantiate": None,
2615 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002616 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002617 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002618 nsi_netslice_subnet.append(indata_ns)
2619 nsr_ref = {"nsr-ref": _id_nsr}
2620 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002621
2622 # Adding the nsrs list to the nsi
2623 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002624 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002625 self.db.set_one(
2626 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2627 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002628
Felipe Vicens07f31722018-10-29 15:16:44 +01002629 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002630 self.db.create("nsis", nsi_descriptor)
2631 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002632 return nsi_id, None
garciadeblas4568a372021-03-24 09:19:48 +01002633 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2634 self.logger.exception(
2635 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2636 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002637 raise EngineException("Error {}: {}".format(step, e))
2638 except ValidationError as e:
2639 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2640
tierno65ca36d2019-02-12 19:27:52 +01002641 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002642 raise EngineException(
2643 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2644 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002645
2646
2647class NsiLcmOpTopic(BaseTopic):
2648 topic = "nsilcmops"
2649 topic_msg = "nsi"
2650 operation_schema = { # mapping between operation and jsonschema to validate
2651 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002652 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002653 }
garciadeblas4568a372021-03-24 09:19:48 +01002654
delacruzramo32bab472019-09-13 12:24:22 +02002655 def __init__(self, db, fs, msg, auth):
2656 BaseTopic.__init__(self, db, fs, msg, auth)
2657 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002658
2659 def _check_nsi_operation(self, session, nsir, operation, indata):
2660 """
2661 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002662 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002663 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2664 :param indata: descriptor with the parameters of the operation
2665 :return: None
2666 """
2667 nsds = {}
2668 nstd = nsir["network-slice-template"]
2669
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002670 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002671 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002672 for netslice_subnet in nstd["netslice-subnet"]:
2673 if nstId == netslice_subnet["id"]:
2674 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002675 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002676 _filter = self._get_project_filter(session)
2677 _filter["id"] = nsd_id
2678 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002679 return nsds[nsd_id]
2680 else:
garciadeblas4568a372021-03-24 09:19:48 +01002681 raise EngineException(
2682 "Invalid parameter nstId='{}' is not one of the "
2683 "nst:netslice-subnet".format(nstId)
2684 )
2685
Felipe Vicens07f31722018-10-29 15:16:44 +01002686 if operation == "instantiate":
2687 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002688 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002689 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002690
2691 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2692 now = time()
2693 _id = str(uuid4())
2694 nsilcmop = {
2695 "id": _id,
2696 "_id": _id,
2697 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2698 "statusEnteredTime": now,
2699 "netsliceInstanceId": netsliceInstanceId,
2700 "lcmOperationType": operation,
2701 "startTime": now,
2702 "isAutomaticInvocation": False,
2703 "operationParams": params,
2704 "isCancelPending": False,
2705 "links": {
2706 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002707 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2708 + netsliceInstanceId,
2709 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002710 }
2711 return nsilcmop
2712
Felipe Vicens09e65422019-01-22 15:06:46 +01002713 def add_shared_nsr_2vld(self, nsir, nsr_item):
2714 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2715 if nst_sb_item.get("is-shared-nss"):
2716 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2717 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2718 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002719 for admin_vld_nss_cp_ref_item in admin_vld_item[
2720 "nss-connection-point-ref"
2721 ]:
2722 if (
2723 admin_subnet_item["nss-id"]
2724 == admin_vld_nss_cp_ref_item["nss-ref"]
2725 ):
2726 if (
2727 not nsr_item["nsrId"]
2728 in admin_vld_item["shared-nsrs-list"]
2729 ):
2730 admin_vld_item["shared-nsrs-list"].append(
2731 nsr_item["nsrId"]
2732 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002733 break
2734 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002735 self.db.set_one(
2736 "nsis",
2737 {"_id": nsir["_id"]},
2738 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2739 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002740
tierno65ca36d2019-02-12 19:27:52 +01002741 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002742 """
2743 Performs a new operation over a ns
2744 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002745 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002746 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002747 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002748 operation: it can be: instantiate, terminate, action, TODO: update, heal
2749 :param kwargs: used to override the indata descriptor
2750 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002751 :return: id of the nslcmops
2752 """
2753 try:
2754 # Override descriptor with query string kwargs
2755 self._update_input_with_kwargs(indata, kwargs)
2756 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002757 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002758 validate_input(indata, self.operation_schema[operation])
2759
Felipe Vicens126af572019-06-05 19:13:04 +02002760 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002761 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002762 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002763 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002764 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002765 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002766
2767 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002768 if (
2769 not nsir["_admin"].get("nsiState")
2770 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2771 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002772 if operation == "terminate" and indata.get("autoremove"):
2773 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002774 return (
2775 None,
2776 None,
2777 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002778 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002779 raise EngineException(
2780 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2781 netsliceInstanceId, operation
2782 ),
2783 HTTPStatus.CONFLICT,
2784 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002785 else:
tierno65ca36d2019-02-12 19:27:52 +01002786 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002787 raise EngineException(
2788 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2789 netsliceInstanceId, operation
2790 ),
2791 HTTPStatus.CONFLICT,
2792 )
2793
Felipe Vicens07f31722018-10-29 15:16:44 +01002794 # Creating all the NS_operation (nslcmop)
2795 # Get service list from db
2796 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2797 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002798 # nslcmops_item = None
2799 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002800 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002801 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002802 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002803 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002804 _filter[
2805 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2806 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002807 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002808 nsi = self.db.get_one(
2809 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2810 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002811 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002812 _update = {
2813 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2814 index
2815 ): None
2816 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002817 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002818 if (
2819 nsi
2820 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002821 continue # do not create nsilcmop
2822 else: # instantiate
2823 # looks the first nsi fulfilling the conditions but not being the current NSIR
2824 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002825 nsi_nsr_item = next(
2826 n
2827 for n in nsi["_admin"]["nsrs-detailed-list"]
2828 if n["nsrId"] == nsr_id
2829 and n["shared"]
2830 and n["nslcmop_instantiate"]
2831 )
tierno40f742b2020-06-23 15:25:26 +00002832 self.add_shared_nsr_2vld(nsir, nsr_item)
2833 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002834 _update = {
2835 "_admin.nsrs-detailed-list.{}".format(
2836 index
2837 ): nsi_nsr_item
2838 }
tierno40f742b2020-06-23 15:25:26 +00002839 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2840 # continue to not create nslcmop since nsrs is shared and nsrs was created
2841 continue
2842 else:
2843 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002844
tierno40f742b2020-06-23 15:25:26 +00002845 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002846 try:
tierno0b8752f2020-05-12 09:42:02 +00002847 indata_ns = {
2848 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002849 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002850 # Including netslice_id in the ns instantiate Operation
2851 "netsliceInstanceId": netsliceInstanceId,
2852 }
2853 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002854 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002855 indata_ns.update(service["instantiate_params"])
2856
tierno99d4b172019-07-02 09:28:40 +00002857 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002858 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002859 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2860 rollback, session, indata_ns, None, headers, slice_object=True
2861 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002862 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002863 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002864 _update = {
2865 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2866 index
2867 ): nslcmop
2868 }
tierno40f742b2020-06-23 15:25:26 +00002869 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002870 except (DbException, EngineException) as e:
2871 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002872 self.logger.info(
2873 logging_prefix
2874 + "skipping NS={} because not found".format(nsr_id)
2875 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002876 pass
2877 else:
2878 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002879
2880 # Creates nsilcmop
2881 indata["nslcmops_ids"] = nslcmops
2882 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002883
garciadeblas4568a372021-03-24 09:19:48 +01002884 nsilcmop_desc = self._create_nsilcmop(
2885 session, netsliceInstanceId, operation, indata
2886 )
2887 self.format_on_new(
2888 nsilcmop_desc, session["project_id"], make_public=session["public"]
2889 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002890 _id = self.db.create("nsilcmops", nsilcmop_desc)
2891 rollback.append({"topic": "nsilcmops", "_id": _id})
2892 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002893 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002894 except ValidationError as e:
2895 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002896
tiernobee3bad2019-12-05 12:26:01 +00002897 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002898 raise EngineException(
2899 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2900 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002901
tierno65ca36d2019-02-12 19:27:52 +01002902 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002903 raise EngineException(
2904 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2905 )