blob: 2df6a7d15b93bf78a26fd84f74c0672b93e1a440 [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
bravofe76b8822021-02-26 16:57:52 -0300442 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300443 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100444 additional_params, _ = self._format_additional_params(
445 ns_request, descriptor=nsd
446 )
garciaale7cbd03c2020-11-27 10:38:35 -0300447
448 nsr_descriptor = {
449 "name": ns_request["nsName"],
450 "name-ref": ns_request["nsName"],
451 "short-name": ns_request["nsName"],
452 "admin-status": "ENABLED",
453 "nsState": "NOT_INSTANTIATED",
454 "currentOperation": "IDLE",
455 "currentOperationID": None,
456 "errorDescription": None,
457 "errorDetail": None,
458 "deploymentStatus": None,
459 "configurationStatus": None,
460 "vcaStatus": None,
461 "nsd": {k: v for k, v in nsd.items()},
462 "datacenter": ns_request["vimAccountId"],
463 "resource-orchestrator": "osmopenmano",
464 "description": ns_request.get("nsDescription", ""),
465 "constituent-vnfr-ref": [],
466 "operational-status": "init", # typedef ns-operational-
467 "config-status": "init", # typedef config-states
468 "detailed-status": "scheduled",
469 "orchestration-progress": {},
470 "create-time": now,
471 "nsd-name-ref": nsd["name"],
472 "operational-events": [], # "id", "timestamp", "description", "event",
473 "nsd-ref": nsd["id"],
474 "nsd-id": nsd["_id"],
475 "vnfd-id": [],
476 "instantiate_params": self._format_ns_request(ns_request),
477 "additionalParamsForNs": additional_params,
478 "ns-instance-config-ref": nsr_id,
479 "id": nsr_id,
480 "_id": nsr_id,
481 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
482 "flavor": [],
483 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100484 "affinity-or-anti-affinity-group": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300485 }
486 ns_request["nsr_id"] = nsr_id
487 if ns_request and ns_request.get("config-units"):
488 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300489 # Create vld
490 if nsd.get("virtual-link-desc"):
491 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
492 # Fill each vld with vnfd-connection-point-ref data
493 # TODO: Change for multiple df support
494 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
495 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
496 for vnf_profile in vnf_profiles:
497 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
498 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100499 all_vld_connection_point_data[
500 vlc.get("virtual-link-profile-id")
501 ].append(
502 {
503 "member-vnf-index-ref": cpd.get(
504 "constituent-base-element-id"
505 ),
506 "vnfd-connection-point-ref": cpd.get(
507 "constituent-cpd-id"
508 ),
509 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
510 }
511 )
garciaale7cbd03c2020-11-27 10:38:35 -0300512
bravofe76b8822021-02-26 16:57:52 -0300513 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400514 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300515
516 for vdu in vnfd.get("vdu", ()):
517 flavor_data = {}
518 guest_epa = {}
519 # Find this vdu compute and storage descriptors
520 vdu_virtual_compute = {}
521 vdu_virtual_storage = {}
522 for vcd in vnfd.get("virtual-compute-desc", ()):
523 if vcd.get("id") == vdu.get("virtual-compute-desc"):
524 vdu_virtual_compute = vcd
525 for vsd in vnfd.get("virtual-storage-desc", ()):
526 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
527 vdu_virtual_storage = vsd
528 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblas4568a372021-03-24 09:19:48 +0100529 if vdu_virtual_compute.get("virtual-cpu", {}).get(
530 "num-virtual-cpu"
531 ):
532 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
533 "num-virtual-cpu"
534 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300535 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
garciadeblas4568a372021-03-24 09:19:48 +0100536 flavor_data["memory-mb"] = (
537 float(vdu_virtual_compute["virtual-memory"]["size"])
538 * 1024.0
539 )
garciaale7cbd03c2020-11-27 10:38:35 -0300540 if vdu_virtual_storage.get("size-of-storage"):
garciadeblas4568a372021-03-24 09:19:48 +0100541 flavor_data["storage-gb"] = vdu_virtual_storage[
542 "size-of-storage"
543 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300544 # Get this vdu EPA info for guest_epa
545 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100546 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
547 "cpu-quota"
548 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300549 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
550 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
551 if vcpu_pinning.get("thread-policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100552 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
553 "thread-policy"
554 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300555 if vcpu_pinning.get("policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100556 cpu_policy = (
557 "SHARED"
558 if vcpu_pinning["policy"] == "dynamic"
559 else "DEDICATED"
560 )
garciaale7cbd03c2020-11-27 10:38:35 -0300561 guest_epa["cpu-pinning-policy"] = cpu_policy
562 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100563 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
564 "mem-quota"
565 ]
566 if vdu_virtual_compute.get("virtual-memory", {}).get(
567 "mempage-size"
568 ):
569 guest_epa["mempage-size"] = vdu_virtual_compute[
570 "virtual-memory"
571 ]["mempage-size"]
572 if vdu_virtual_compute.get("virtual-memory", {}).get(
573 "numa-node-policy"
574 ):
575 guest_epa["numa-node-policy"] = vdu_virtual_compute[
576 "virtual-memory"
577 ]["numa-node-policy"]
garciaale7cbd03c2020-11-27 10:38:35 -0300578 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100579 guest_epa["disk-io-quota"] = vdu_virtual_storage[
580 "disk-io-quota"
581 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300582
583 if guest_epa:
584 flavor_data["guest-epa"] = guest_epa
585
586 flavor_data["name"] = vdu["id"][:56] + "-flv"
587 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
588 nsr_descriptor["flavor"].append(flavor_data)
589
590 sw_image_id = vdu.get("sw-image-desc")
591 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000592 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
593 self._add_image_to_nsr(nsr_descriptor, image_data)
594
595 # also add alternative images to the list of images
596 for alt_image in vdu.get("alternative-sw-image-desc", ()):
597 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
598 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300599
Alexis Romero03fb5842022-03-11 15:53:40 +0100600 # Add Affinity or Anti-affinity group information to NSR
601 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200602 affinity_group_prefix_name = "{}-{}".format(
603 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
604 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100605
606 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200607 affinity_group_data = {}
608 for affinity_group in vdu_profile.get(
609 "affinity-or-anti-affinity-group", ()
610 ):
611 affinity_group_data = (
612 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
613 vnfd, affinity_group["id"]
614 )
615 )
616 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
617 self._add_affinity_or_anti_affinity_group_to_nsr(
618 nsr_descriptor,
619 affinity_group_data,
620 affinity_group_prefix_name,
621 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100622
garciaale7cbd03c2020-11-27 10:38:35 -0300623 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100624 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
625 vld.get("id"), []
626 )
garciaale7cbd03c2020-11-27 10:38:35 -0300627 vld["name"] = vld["id"]
628 nsr_descriptor["vld"] = nsr_vld
629
630 return nsr_descriptor
631
Alexis Romeroee31f532022-04-26 19:10:21 +0200632 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
633 self, vnfd, affinity_group_id
634 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100635 """
636 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
637 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200638 affinity_group = utils.find_in_list(
639 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
640 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100641 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200642 affinity_group_data = {}
643 if affinity_group:
644 if affinity_group.get("id"):
645 affinity_group_data["ag-id"] = affinity_group["id"]
646 if affinity_group.get("type"):
647 affinity_group_data["type"] = affinity_group["type"]
648 if affinity_group.get("scope"):
649 affinity_group_data["scope"] = affinity_group["scope"]
650 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100651
Alexis Romeroee31f532022-04-26 19:10:21 +0200652 def _add_affinity_or_anti_affinity_group_to_nsr(
653 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
654 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100655 """
656 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
657 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200658 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100659 (
660 f
661 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200662 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100663 ),
664 None,
665 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200666 if not affinity_group:
667 affinity_group_data["id"] = str(
668 len(nsr_descriptor["affinity-or-anti-affinity-group"])
669 )
670 affinity_group_data["name"] = "{}-{}".format(
671 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
672 )
673 nsr_descriptor["affinity-or-anti-affinity-group"].append(
674 affinity_group_data
675 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100676
lloretgalleg28c13b62021-02-08 11:48:48 +0000677 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100678 sw_image_desc = utils.find_in_list(
679 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
680 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000681 image_data = {}
682 if sw_image_desc.get("image"):
683 image_data["image"] = sw_image_desc["image"]
684 if sw_image_desc.get("checksum"):
685 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
686 if sw_image_desc.get("vim-type"):
687 image_data["vim-type"] = sw_image_desc["vim-type"]
688 return image_data
689
690 def _add_image_to_nsr(self, nsr_descriptor, image_data):
691 """
692 Adds image to nsr checking first it is not already added
693 """
garciadeblas4568a372021-03-24 09:19:48 +0100694 img = next(
695 (
696 f
697 for f in nsr_descriptor["image"]
698 if all(f.get(k) == image_data[k] for k in image_data)
699 ),
700 None,
701 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000702 if not img:
703 image_data["id"] = str(len(nsr_descriptor["image"]))
704 nsr_descriptor["image"].append(image_data)
705
garciadeblas4568a372021-03-24 09:19:48 +0100706 def _create_vnfr_descriptor_from_vnfd(
707 self,
708 nsd,
709 vnfd,
710 vnfd_id,
711 vnf_index,
712 nsr_descriptor,
713 ns_request,
714 ns_k8s_namespace,
715 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300716 vnfr_id = str(uuid4())
717 nsr_id = nsr_descriptor["id"]
718 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100719 additional_params, vnf_params = self._format_additional_params(
720 ns_request, vnf_index, descriptor=vnfd
721 )
garciaale7cbd03c2020-11-27 10:38:35 -0300722
723 vnfr_descriptor = {
724 "id": vnfr_id,
725 "_id": vnfr_id,
726 "nsr-id-ref": nsr_id,
727 "member-vnf-index-ref": vnf_index,
728 "additionalParamsForVnf": additional_params,
729 "created-time": now,
730 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
731 "vnfd-ref": vnfd_id,
732 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
733 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200734 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300735 "vdur": [],
736 "connection-point": [],
737 "ip-address": None, # mgmt-interface filled by LCM
738 }
beierlmcee2ebf2022-03-29 17:42:48 -0400739
740 # Revision backwards compatility. Only specify the revision in the record if
741 # the original VNFD has a revision.
742 if "revision" in vnfd:
743 vnfr_descriptor["revision"] = vnfd["revision"]
744
745
garciaale7cbd03c2020-11-27 10:38:35 -0300746 vnf_k8s_namespace = ns_k8s_namespace
747 if vnf_params:
748 if vnf_params.get("k8s-namespace"):
749 vnf_k8s_namespace = vnf_params["k8s-namespace"]
750 if vnf_params.get("config-units"):
751 vnfr_descriptor["config-units"] = vnf_params["config-units"]
752
753 # Create vld
754 if vnfd.get("int-virtual-link-desc"):
755 vnfr_descriptor["vld"] = []
756 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
757 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
758
759 for cp in vnfd.get("ext-cpd", ()):
760 vnf_cp = {
761 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100762 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
763 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300764 "id": cp.get("id"),
765 # "ip-address", "mac-address" # filled by LCM
766 # vim-id # TODO it would be nice having a vim port id
767 }
768 vnfr_descriptor["connection-point"].append(vnf_cp)
769
770 # Create k8s-cluster information
771 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
772 if vnfd.get("k8s-cluster"):
773 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
774 all_k8s_cluster_nets_cpds = {}
775 for cpd in get_iterable(vnfd.get("ext-cpd")):
776 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100777 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
778 "id"
779 )
garciaale7cbd03c2020-11-27 10:38:35 -0300780 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
781 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100782 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
783 net.get("id")
784 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300785
786 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300787 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100788 additional_params, kdu_params = self._format_additional_params(
789 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
790 )
garciaale7cbd03c2020-11-27 10:38:35 -0300791 kdu_k8s_namespace = vnf_k8s_namespace
792 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
793 if kdu_params and kdu_params.get("k8s-namespace"):
794 kdu_k8s_namespace = kdu_params["k8s-namespace"]
795
romeromonserbfebfc02021-05-28 10:51:35 +0200796 kdu_deployment_name = ""
797 if kdu_params and kdu_params.get("kdu-deployment-name"):
798 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
799
garciaale7cbd03c2020-11-27 10:38:35 -0300800 kdur = {
801 "additionalParams": additional_params,
802 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200803 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000804 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300805 # TODO "name": "" Name of the VDU in the VIM
806 "ip-address": None, # mgmt-interface filled by LCM
807 "k8s-cluster": {},
808 }
809 if kdu_params and kdu_params.get("config-units"):
810 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000811 if kdu.get("helm-version"):
812 kdur["helm-version"] = kdu["helm-version"]
813 for k8s_type in ("helm-chart", "juju-bundle"):
814 if kdu.get(k8s_type):
815 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300816 if not vnfr_descriptor.get("kdur"):
817 vnfr_descriptor["kdur"] = []
818 vnfr_descriptor["kdur"].append(kdur)
819
820 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300821
garciaale7cbd03c2020-11-27 10:38:35 -0300822 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300823 vdu_mgmt_cp = []
824 try:
garciadeblas4568a372021-03-24 09:19:48 +0100825 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
826 "operate-vnf-op-config"
827 ]["day1-2"]
828 vdu_config = utils.find_in_list(
829 configs, lambda config: config["id"] == vdu["id"]
830 )
bravoff3c39552021-02-24 17:22:24 -0300831 except Exception:
832 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400833
834 try:
835 vdu_instantiation_level = utils.find_in_list(
836 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100837 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400838 )
839 except Exception:
840 vdu_instantiation_level = None
841
bravoff3c39552021-02-24 17:22:24 -0300842 if vdu_config:
843 external_connection_ee = utils.filter_in_list(
844 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100845 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300846 )
847 for ee in external_connection_ee:
848 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
849
garciaale7cbd03c2020-11-27 10:38:35 -0300850 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100851 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
852 )
bravof65e22e52021-11-10 17:58:58 -0300853
854 try:
855 vdu_virtual_storage_descriptors = utils.filter_in_list(
856 vnfd.get("virtual-storage-desc", []),
857 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
858 )
859 except Exception:
860 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300861 vdur = {
862 "vdu-id-ref": vdu["id"],
863 # TODO "name": "" Name of the VDU in the VIM
864 "ip-address": None, # mgmt-interface filled by LCM
865 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
866 "internal-connection-point": [],
867 "interfaces": [],
868 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100869 "vdu-name": vdu["name"],
bravof65e22e52021-11-10 17:58:58 -0300870 "virtual-storages": vdu_virtual_storage_descriptors
garciaale7cbd03c2020-11-27 10:38:35 -0300871 }
872 if vdu_params and vdu_params.get("config-units"):
873 vdur["config-units"] = vdu_params["config-units"]
874 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100875 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
876 "boot-data-drive"
877 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300878 if vdu.get("pdu-type"):
879 vdur["pdu-type"] = vdu["pdu-type"]
880 vdur["name"] = vdu["pdu-type"]
881 # TODO volumes: name, volume-id
882 for icp in vdu.get("int-cpd", ()):
883 vdu_icp = {
884 "id": icp["id"],
885 "connection-point-id": icp["id"],
886 "name": icp.get("id"),
887 }
bravof35766442021-02-04 14:58:04 -0300888
garciaale7cbd03c2020-11-27 10:38:35 -0300889 vdur["internal-connection-point"].append(vdu_icp)
890
891 for iface in icp.get("virtual-network-interface-requirement", ()):
892 iface_fields = ("name", "mac-address")
garciadeblas4568a372021-03-24 09:19:48 +0100893 vdu_iface = {
894 x: iface[x] for x in iface_fields if iface.get(x) is not None
895 }
garciaale7cbd03c2020-11-27 10:38:35 -0300896
897 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100898 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100899 vdu_iface["port-security-enabled"] = icp[
900 "port-security-enabled"
901 ]
sousaedu003844e2021-03-02 00:19:15 +0100902
903 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100904 vdu_iface["port-security-disable-strategy"] = icp[
905 "port-security-disable-strategy"
906 ]
sousaedu003844e2021-03-02 00:19:15 +0100907
garciaale7cbd03c2020-11-27 10:38:35 -0300908 for ext_cp in vnfd.get("ext-cpd", ()):
909 if not ext_cp.get("int-cpd"):
910 continue
911 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
912 continue
913 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100914 vdu_iface["external-connection-point-ref"] = ext_cp.get(
915 "id"
916 )
sousaedu003844e2021-03-02 00:19:15 +0100917
918 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100919 vdu_iface["port-security-enabled"] = ext_cp[
920 "port-security-enabled"
921 ]
sousaedu003844e2021-03-02 00:19:15 +0100922
923 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100924 vdu_iface["port-security-disable-strategy"] = ext_cp[
925 "port-security-disable-strategy"
926 ]
sousaedu003844e2021-03-02 00:19:15 +0100927
garciaale7cbd03c2020-11-27 10:38:35 -0300928 break
929
garciadeblas4568a372021-03-24 09:19:48 +0100930 if (
931 vnfd_mgmt_cp
932 and vdu_iface.get("external-connection-point-ref")
933 == vnfd_mgmt_cp
934 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300935 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300936 vdu_iface["mgmt-interface"] = True
937
938 for ecp in vdu_mgmt_cp:
939 if vdu_iface.get("external-connection-point-ref") == ecp:
940 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300941
942 if iface.get("virtual-interface"):
943 vdu_iface.update(deepcopy(iface["virtual-interface"]))
944
945 # look for network where this interface is connected
946 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
947 if iface_ext_cp:
948 # TODO: Change for multiple df support
949 for df in get_iterable(nsd.get("df")):
950 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100951 for vlc_index, vlc in enumerate(
952 get_iterable(
953 vnf_profile.get("virtual-link-connectivity")
954 )
955 ):
956 for cpd in get_iterable(
957 vlc.get("constituent-cpd-id")
958 ):
959 if (
960 cpd.get("constituent-cpd-id")
961 == iface_ext_cp
962 ):
963 vdu_iface["ns-vld-id"] = vlc.get(
964 "virtual-link-profile-id"
965 )
garciadeblas61c95912021-02-12 11:23:50 +0000966 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100967 if vdu_iface.get("type") in (
968 "SR-IOV",
969 "PCI-PASSTHROUGH",
970 ):
971 nsr_descriptor["vld"][vlc_index][
972 "pci-interfaces"
973 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300974 break
975 elif vdu_iface.get("internal-connection-point-ref"):
976 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000977 # TODO: store fixed IP address in the record (if it exists in the ICP)
978 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
979 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100980 ivld_index = utils.find_index_in_list(
981 vnfd.get("int-virtual-link-desc", ()),
982 lambda ivld: ivld["id"]
983 == icp.get("int-virtual-link-desc"),
984 )
garciadeblas61c95912021-02-12 11:23:50 +0000985 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300986
987 vdur["interfaces"].append(vdu_iface)
988
989 if vdu.get("sw-image-desc"):
990 sw_image = utils.find_in_list(
991 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100992 lambda image: image["id"] == vdu.get("sw-image-desc"),
993 )
garciaale7cbd03c2020-11-27 10:38:35 -0300994 nsr_sw_image_data = utils.find_in_list(
995 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100996 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300997 )
998 vdur["ns-image-id"] = nsr_sw_image_data["id"]
999
lloretgalleg28c13b62021-02-08 11:48:48 +00001000 if vdu.get("alternative-sw-image-desc"):
1001 alt_image_ids = []
1002 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1003 sw_image = utils.find_in_list(
1004 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001005 lambda image: image["id"] == alt_image_id,
1006 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001007 nsr_sw_image_data = utils.find_in_list(
1008 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001009 lambda nsr_image: (
1010 nsr_image.get("image") == sw_image.get("image")
1011 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001012 )
1013 alt_image_ids.append(nsr_sw_image_data["id"])
1014 vdur["alt-image-ids"] = alt_image_ids
1015
garciaale7cbd03c2020-11-27 10:38:35 -03001016 flavor_data_name = vdu["id"][:56] + "-flv"
1017 nsr_flavor_desc = utils.find_in_list(
1018 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001019 lambda flavor: flavor["name"] == flavor_data_name,
1020 )
garciaale7cbd03c2020-11-27 10:38:35 -03001021
1022 if nsr_flavor_desc:
1023 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1024
Alexis Romero03fb5842022-03-11 15:53:40 +01001025 # Adding Affinity groups information to vdur
1026 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001027 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001028 vnfd.get("df")[0]["vdu-profile"],
1029 lambda a_vdu: a_vdu["id"] == vdu["id"],
1030 )
1031 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001032 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001033
Alexis Romeroee31f532022-04-26 19:10:21 +02001034 if vdu_profile_affinity_group:
1035 affinity_group_ids = []
1036 for affinity_group in vdu_profile_affinity_group.get(
1037 "affinity-or-anti-affinity-group", ()
1038 ):
1039 vdu_affinity_group = utils.find_in_list(
1040 vdu_profile_affinity_group.get(
1041 "affinity-or-anti-affinity-group", ()
1042 ),
1043 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001044 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001045 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001046 nsr_descriptor["affinity-or-anti-affinity-group"],
1047 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001048 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1049 and nsr_ag.get("member-vnf-index")
1050 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001051 ),
1052 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001053 # Update Affinity Group VIM name if VDU instantiation parameter is present
1054 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1055 vnf_params_affinity_group = utils.find_in_list(
1056 vnf_params["affinity-or-anti-affinity-group"],
1057 lambda vnfp_ag: (
1058 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1059 ),
1060 )
1061 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1062 nsr_affinity_group[
1063 "vim-affinity-group-id"
1064 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1065 affinity_group_ids.append(nsr_affinity_group["id"])
1066 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001067
bravof4ca51522021-04-22 10:03:02 -04001068 if vdu_instantiation_level:
1069 count = vdu_instantiation_level.get("number-of-instances")
1070 else:
1071 count = 1
1072
garciaale7cbd03c2020-11-27 10:38:35 -03001073 for index in range(0, count):
1074 vdur = deepcopy(vdur)
1075 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001076 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001077 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001078 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001079 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1080
1081 vdur["_id"] = str(uuid4())
1082 vdur["id"] = vdur["_id"]
1083 vdur["count-index"] = index
1084 vnfr_descriptor["vdur"].append(vdur)
1085
1086 return vnfr_descriptor
1087
K Sai Kiran57589552021-01-27 21:38:34 +05301088 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1089 """
1090 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1091 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1092 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1093 :param ns_instance_content: ns instance content
1094 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1095 :return: None
1096 """
1097 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
1098 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
1099 threshold_reached = time_delta > 120
1100 if force_refresh or threshold_reached:
1101 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1102 ns_instance_content["_admin"]["modified"] = time_now
1103 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1104 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
1105 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1106 nslcmop_desc["_admin"].pop("nsState")
1107 self.msg.write("ns", operation, nslcmop_desc)
1108 return
1109
1110 def show(self, session, _id, filter_q=None, api_req=False):
1111 """
1112 Get complete information on an ns instance.
1113 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1114 :param _id: string, ns instance id
1115 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1116 :param api_req: True if this call is serving an external API request. False if serving internal request.
1117 :return: dictionary, raise exception if not found.
1118 """
1119 ns_instance_content = super().show(session, _id, api_req)
1120 self.vca_status_refresh(session, ns_instance_content, filter_q)
1121 return ns_instance_content
1122
tierno65ca36d2019-02-12 19:27:52 +01001123 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001124 raise EngineException(
1125 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1126 )
tiernob24258a2018-10-04 18:39:49 +02001127
1128
1129class VnfrTopic(BaseTopic):
1130 topic = "vnfrs"
1131 topic_msg = None
1132
delacruzramo32bab472019-09-13 12:24:22 +02001133 def __init__(self, db, fs, msg, auth):
1134 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001135
tiernobee3bad2019-12-05 12:26:01 +00001136 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001137 raise EngineException(
1138 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1139 )
tiernob24258a2018-10-04 18:39:49 +02001140
tierno65ca36d2019-02-12 19:27:52 +01001141 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001142 raise EngineException(
1143 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1144 )
tiernob24258a2018-10-04 18:39:49 +02001145
tierno65ca36d2019-02-12 19:27:52 +01001146 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001147 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001148 raise EngineException(
1149 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1150 )
tiernob24258a2018-10-04 18:39:49 +02001151
1152
1153class NsLcmOpTopic(BaseTopic):
1154 topic = "nslcmops"
1155 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001156 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001157 "instantiate": ns_instantiate,
1158 "action": ns_action,
aticig544a2ae2022-04-05 09:00:17 +03001159 "update": ns_update,
tiernob24258a2018-10-04 18:39:49 +02001160 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +00001161 "terminate": ns_terminate,
elumalai8e3806c2022-04-28 17:26:24 +05301162 "migrate": ns_migrate,
tiernob24258a2018-10-04 18:39:49 +02001163 }
1164
delacruzramo32bab472019-09-13 12:24:22 +02001165 def __init__(self, db, fs, msg, auth):
1166 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001167
tiernob24258a2018-10-04 18:39:49 +02001168 def _check_ns_operation(self, session, nsr, operation, indata):
1169 """
1170 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001171 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
aticig544a2ae2022-04-05 09:00:17 +03001172 :param operation: it can be: instantiate, terminate, action, update. TODO: heal
tiernob24258a2018-10-04 18:39:49 +02001173 :param indata: descriptor with the parameters of the operation
1174 :return: None
1175 """
garciaale7cbd03c2020-11-27 10:38:35 -03001176 if operation == "action":
1177 self._check_action_ns_operation(indata, nsr)
1178 elif operation == "scale":
1179 self._check_scale_ns_operation(indata, nsr)
aticig544a2ae2022-04-05 09:00:17 +03001180 elif operation == "update":
1181 self._check_update_ns_operation(indata, nsr)
garciaale7cbd03c2020-11-27 10:38:35 -03001182 elif operation == "instantiate":
1183 self._check_instantiate_ns_operation(indata, nsr, session)
1184
1185 def _check_action_ns_operation(self, indata, nsr):
1186 nsd = nsr["nsd"]
1187 # check vnf_member_index
1188 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001189 indata["member_vnf_index"] = indata.pop(
1190 "vnf_member_index"
1191 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001192 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001193 vnfd = self._get_vnfd_from_vnf_member_index(
1194 indata["member_vnf_index"], nsr["_id"]
1195 )
bravof41a52052021-02-17 18:08:01 -03001196 try:
garciadeblas4568a372021-03-24 09:19:48 +01001197 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1198 "operate-vnf-op-config"
1199 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001200 except Exception:
1201 configs = []
1202
garciaale7cbd03c2020-11-27 10:38:35 -03001203 if indata.get("vdu_id"):
1204 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001205 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001206 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001207 )
garciaale7cbd03c2020-11-27 10:38:35 -03001208 elif indata.get("kdu_name"):
1209 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001210 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001211 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001212 )
garciaale7cbd03c2020-11-27 10:38:35 -03001213 else:
bravof41a52052021-02-17 18:08:01 -03001214 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001215 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001216 )
1217 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001218 descriptor_configuration = descriptor_configuration.get(
1219 "config-primitive"
1220 )
garciaale7cbd03c2020-11-27 10:38:35 -03001221 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001222 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1223 "config-primitive"
1224 )
garciaale7cbd03c2020-11-27 10:38:35 -03001225
1226 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001227 if indata.get("kdu_name") and indata["primitive"] in (
1228 "upgrade",
1229 "rollback",
1230 "status",
1231 "inspect",
1232 "readme",
1233 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001234 # TODO should be checked that rollback only can contains revsision_numbe????
1235 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001236 raise EngineException(
1237 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1238 indata["primitive"]
1239 )
1240 )
garciaale7cbd03c2020-11-27 10:38:35 -03001241 return
1242 # if not, check primitive
1243 for config_primitive in get_iterable(descriptor_configuration):
1244 if indata["primitive"] == config_primitive["name"]:
1245 # check needed primitive_params are provided
1246 if indata.get("primitive_params"):
1247 in_primitive_params_copy = copy(indata["primitive_params"])
1248 else:
1249 in_primitive_params_copy = {}
1250 for paramd in get_iterable(config_primitive.get("parameter")):
1251 if paramd["name"] in in_primitive_params_copy:
1252 del in_primitive_params_copy[paramd["name"]]
1253 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001254 raise EngineException(
1255 "Needed parameter {} not provided for primitive '{}'".format(
1256 paramd["name"], indata["primitive"]
1257 )
1258 )
garciaale7cbd03c2020-11-27 10:38:35 -03001259 # check no extra primitive params are provided
1260 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001261 raise EngineException(
1262 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1263 list(in_primitive_params_copy.keys()), indata["primitive"]
1264 )
1265 )
garciaale7cbd03c2020-11-27 10:38:35 -03001266 break
1267 else:
garciadeblas4568a372021-03-24 09:19:48 +01001268 raise EngineException(
1269 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1270 indata["primitive"]
1271 )
1272 )
garciaale7cbd03c2020-11-27 10:38:35 -03001273
aticig544a2ae2022-04-05 09:00:17 +03001274 def _check_update_ns_operation(self, indata, nsr) -> None:
1275 """Validates the ns-update request according to updateType
1276
1277 If updateType is CHANGE_VNFPKG:
1278 - it checks the vnfInstanceId, whether it's available under ns instance
1279 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1280 Otherwise exception will be raised.
elumalai6380e7c2022-04-28 00:15:59 +05301281 If updateType is REMOVE_VNF:
1282 - it checks if the vnfInstanceId is available in the ns instance
1283 - Otherwise exception will be raised.
aticig544a2ae2022-04-05 09:00:17 +03001284
1285 Args:
1286 indata: includes updateType such as CHANGE_VNFPKG,
1287 nsr: network service record
1288
1289 Raises:
1290 EngineException:
1291 a meaningful error if given update parameters are not proper such as
1292 "Error in validating ns-update request: <ID> does not match
1293 with the vnfd-id of vnfinstance
1294 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1295
1296 """
1297 try:
1298 if indata["updateType"] == "CHANGE_VNFPKG":
1299 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1300 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1301 ns_instance_id = indata["nsInstanceId"]
1302 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1303
1304 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1305
1306 raise EngineException(
1307 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1308 f"belong to NS {ns_instance_id}",
1309 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1310 )
1311
1312 # Getting vnfrs through the ns_instance_id
1313 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1314 constituent_vnfd_id = next(
1315 (
1316 vnfr["vnfd-id"]
1317 for vnfr in vnfrs
1318 if vnfr["id"] == vnf_instance_id
1319 ),
1320 None,
1321 )
1322
1323 # Check the given vnfd-id belongs to given vnf instance
1324 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
1325
1326 raise EngineException(
1327 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1328 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1329 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1330 )
1331
1332 # Validating the ns update timeout
1333 if (
1334 indata.get("timeout_ns_update")
1335 and indata["timeout_ns_update"] < 300
1336 ):
1337 raise EngineException(
1338 "Error in validating ns-update request: {} second is not enough "
1339 "to upgrade the VNF instance: {}".format(
1340 indata["timeout_ns_update"], vnf_instance_id
1341 ),
1342 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1343 )
elumalai6380e7c2022-04-28 00:15:59 +05301344 elif indata["updateType"] == "REMOVE_VNF":
1345 vnf_instance_id = indata["removeVnfInstanceId"]
1346 ns_instance_id = indata["nsInstanceId"]
1347 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1348 raise EngineException(
1349 "Invalid VNF Instance Id. '{}' is not "
1350 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1351 )
aticig544a2ae2022-04-05 09:00:17 +03001352
1353 except (
1354 DbException,
1355 AttributeError,
1356 IndexError,
1357 KeyError,
1358 ValueError,
1359 ) as e:
1360 raise type(e)(
1361 "Ns update request could not be processed with error: {}.".format(e)
1362 )
1363
garciaale7cbd03c2020-11-27 10:38:35 -03001364 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001365 vnfd = self._get_vnfd_from_vnf_member_index(
1366 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1367 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001368 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001369 if (
1370 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1371 == scaling_aspect["id"]
1372 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001373 break
1374 else:
garciadeblas4568a372021-03-24 09:19:48 +01001375 raise EngineException(
1376 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1377 "present at vnfd:scaling-aspect".format(
1378 indata["scaleVnfData"]["scaleByStepData"][
1379 "scaling-group-descriptor"
1380 ]
1381 )
1382 )
garciaale7cbd03c2020-11-27 10:38:35 -03001383
1384 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001385 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001386 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001387 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001388 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001389 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1390 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1391 for in_vnf in get_iterable(indata.get("vnf")):
1392 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001393 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001394 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001395 else:
garciadeblas4568a372021-03-24 09:19:48 +01001396 vnfd = self._get_vnfd_from_vnf_member_index(
1397 member_vnf_index, nsr["_id"]
1398 )
1399 vnf_member_index_to_vnfd[
1400 member_vnf_index
1401 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001402 self._check_vnf_instantiation_params(in_vnf, vnfd)
1403 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001404 self._check_valid_vim_account(
1405 in_vnf["vimAccountId"], vim_accounts, session
1406 )
tierno260dd6f2019-09-02 10:48:56 +00001407
garciaale7cbd03c2020-11-27 10:38:35 -03001408 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001409 self._check_valid_wim_account(
1410 in_vld.get("wimAccountId"), wim_accounts, session
1411 )
garciaale7cbd03c2020-11-27 10:38:35 -03001412 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1413 if in_vld["name"] == vldd["id"]:
1414 break
tierno9cb7d672019-10-30 12:13:48 +00001415 else:
garciadeblas4568a372021-03-24 09:19:48 +01001416 raise EngineException(
1417 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1418 in_vld["name"]
1419 )
1420 )
tierno9cb7d672019-10-30 12:13:48 +00001421
garciaale7cbd03c2020-11-27 10:38:35 -03001422 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1423 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001424 vnfr = self.db.get_one(
1425 "vnfrs",
1426 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1427 fail_on_empty=False,
1428 )
garciaale7cbd03c2020-11-27 10:38:35 -03001429 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001430 raise EngineException(
1431 "Invalid parameter member_vnf_index='{}' is not one of the "
1432 "nsd:constituent-vnfd".format(member_vnf_index)
1433 )
beierlmcee2ebf2022-03-29 17:42:48 -04001434
1435 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1436 if "revision" in vnfr:
1437 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
1438 vnfd = self.db.get_one("vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False)
1439 else:
1440 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1441
garciaale7cbd03c2020-11-27 10:38:35 -03001442 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001443 raise EngineException(
1444 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1445 vnfr["vnfd-id"]
1446 )
1447 )
garciaale7cbd03c2020-11-27 10:38:35 -03001448 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001449
garciaale7cbd03c2020-11-27 10:38:35 -03001450 def _check_valid_vdu(self, vnfd, vdu_id):
1451 for vdud in get_iterable(vnfd.get("vdu")):
1452 if vdud["id"] == vdu_id:
1453 return vdud
1454 else:
garciadeblas4568a372021-03-24 09:19:48 +01001455 raise EngineException(
1456 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1457 vdu_id
1458 )
1459 )
garciaale7cbd03c2020-11-27 10:38:35 -03001460
1461 def _check_valid_kdu(self, vnfd, kdu_name):
1462 for kdud in get_iterable(vnfd.get("kdu")):
1463 if kdud["name"] == kdu_name:
1464 return kdud
1465 else:
garciadeblas4568a372021-03-24 09:19:48 +01001466 raise EngineException(
1467 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1468 kdu_name
1469 )
1470 )
garciaale7cbd03c2020-11-27 10:38:35 -03001471
1472 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1473 for in_vdu in get_iterable(in_vnf.get("vdu")):
1474 for vdu in get_iterable(vnfd.get("vdu")):
1475 if in_vdu["id"] == vdu["id"]:
1476 for volume in get_iterable(in_vdu.get("volume")):
1477 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1478 if volumed["id"] == volume["name"]:
1479 break
1480 else:
garciadeblas4568a372021-03-24 09:19:48 +01001481 raise EngineException(
1482 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1483 "volume:name='{}' is not present at "
1484 "vnfd:vdu:virtual-storage-desc list".format(
1485 in_vnf["member-vnf-index"],
1486 in_vdu["id"],
1487 volume["id"],
1488 )
1489 )
garciaale7cbd03c2020-11-27 10:38:35 -03001490
1491 vdu_if_names = set()
1492 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001493 for iface in get_iterable(
1494 cpd.get("virtual-network-interface-requirement")
1495 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001496 vdu_if_names.add(iface.get("name"))
1497
1498 for in_iface in get_iterable(in_vdu["interface"]):
1499 if in_iface["name"] in vdu_if_names:
1500 break
1501 else:
garciadeblas4568a372021-03-24 09:19:48 +01001502 raise EngineException(
1503 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1504 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1505 in_vnf["member-vnf-index"],
1506 in_vdu["id"],
1507 in_iface["name"],
1508 )
1509 )
garciaale7cbd03c2020-11-27 10:38:35 -03001510 break
1511
1512 else:
garciadeblas4568a372021-03-24 09:19:48 +01001513 raise EngineException(
1514 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1515 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1516 )
garciaale7cbd03c2020-11-27 10:38:35 -03001517
garciadeblas4568a372021-03-24 09:19:48 +01001518 vnfd_ivlds_cpds = {
1519 ivld.get("id"): set()
1520 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1521 }
garciaale7cbd03c2020-11-27 10:38:35 -03001522 for vdu in get_iterable(vnfd.get("vdu")):
1523 for cpd in get_iterable(vnfd.get("int-cpd")):
1524 if cpd.get("int-virtual-link-desc"):
1525 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1526
1527 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1528 if in_ivld.get("name") in vnfd_ivlds_cpds:
1529 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1530 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001531 break
tiernob24258a2018-10-04 18:39:49 +02001532 else:
garciadeblas4568a372021-03-24 09:19:48 +01001533 raise EngineException(
1534 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1535 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1536 "vnfd:internal-vld:name/id:internal-connection-point".format(
1537 in_vnf["member-vnf-index"],
1538 in_ivld["name"],
1539 in_icp["id-ref"],
1540 )
1541 )
tiernob24258a2018-10-04 18:39:49 +02001542 else:
garciadeblas4568a372021-03-24 09:19:48 +01001543 raise EngineException(
1544 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1545 " is not present at vnfd '{}'".format(
1546 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1547 )
1548 )
tiernob24258a2018-10-04 18:39:49 +02001549
garciaale7cbd03c2020-11-27 10:38:35 -03001550 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1551 if vim_account in vim_accounts:
1552 return
1553 try:
1554 db_filter = self._get_project_filter(session)
1555 db_filter["_id"] = vim_account
1556 self.db.get_one("vim_accounts", db_filter)
1557 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001558 raise EngineException(
1559 "Invalid vimAccountId='{}' not present for the project".format(
1560 vim_account
1561 )
1562 )
garciaale7cbd03c2020-11-27 10:38:35 -03001563 vim_accounts.append(vim_account)
1564
David Garcia98de2982021-10-13 17:14:01 +02001565 def _get_vim_account(self, vim_id: str, session):
1566 try:
1567 db_filter = self._get_project_filter(session)
1568 db_filter["_id"] = vim_id
1569 return self.db.get_one("vim_accounts", db_filter)
1570 except Exception:
1571 raise EngineException(
1572 "Invalid vimAccountId='{}' not present for the project".format(
1573 vim_id
1574 )
1575 )
1576
garciaale7cbd03c2020-11-27 10:38:35 -03001577 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1578 if not isinstance(wim_account, str):
1579 return
1580 if wim_account in wim_accounts:
1581 return
1582 try:
1583 db_filter = self._get_project_filter(session, write=False, show_all=True)
1584 db_filter["_id"] = wim_account
1585 self.db.get_one("wim_accounts", db_filter)
1586 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001587 raise EngineException(
1588 "Invalid wimAccountId='{}' not present for the project".format(
1589 wim_account
1590 )
1591 )
garciaale7cbd03c2020-11-27 10:38:35 -03001592 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001593
garciadeblas4568a372021-03-24 09:19:48 +01001594 def _look_for_pdu(
1595 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1596 ):
tiernocc103432018-10-19 14:10:35 +02001597 """
tierno36ec8602018-11-02 17:27:11 +01001598 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1599 (ip_address, ...) information.
1600 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001601 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001602 :param rollback: list with the database modifications to rollback if needed
1603 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1604 :param vim_account: vim_account where this vnfr should be deployed
1605 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1606 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1607 of the changed vnfr is needed
1608
1609 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1610 "vim-network-name": used at VIM
1611 "name": interface name
1612 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1613 "ns-vld-id": NSD vld where this interface is connected.
1614 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 +02001615 """
tierno36ec8602018-11-02 17:27:11 +01001616
1617 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001618 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1619 if not vdur.get("pdu-type"):
1620 continue
1621 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001622 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001623 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001624 pdu_filter["type"] = pdu_type
1625 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001626 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001627 # TODO feature 1417: "shared": True,
1628
1629 available_pdus = self.db.get_list("pdus", pdu_filter)
1630 for pdu in available_pdus:
1631 # step 1 check if this pdu contains needed interfaces:
1632 match_interfaces = True
1633 for vdur_interface in vdur["interfaces"]:
1634 for pdu_interface in pdu["interfaces"]:
1635 if pdu_interface["name"] == vdur_interface["name"]:
1636 # TODO feature 1417: match per mgmt type
1637 break
1638 else: # no interface found for name
1639 match_interfaces = False
1640 break
1641 if match_interfaces:
1642 break
1643 else:
1644 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001645 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001646 "names".format(
1647 pdu_type,
1648 vim_account,
1649 vnfr["member-vnf-index-ref"],
1650 vdur["vdu-id-ref"],
1651 )
1652 )
tiernocc103432018-10-19 14:10:35 +02001653
1654 # step 2. Update pdu
1655 rollback_pdu = {
1656 "_admin.usageState": pdu["_admin"]["usageState"],
1657 "_admin.usage.vnfr_id": None,
1658 "_admin.usage.nsr_id": None,
1659 "_admin.usage.vdur": None,
1660 }
garciadeblas4568a372021-03-24 09:19:48 +01001661 self.db.set_one(
1662 "pdus",
1663 {"_id": pdu["_id"]},
1664 {
1665 "_admin.usageState": "IN_USE",
1666 "_admin.usage": {
1667 "vnfr_id": vnfr["_id"],
1668 "nsr_id": vnfr["nsr-id-ref"],
1669 "vdur": vdur["vdu-id-ref"],
1670 },
1671 },
1672 )
1673 rollback.append(
1674 {
1675 "topic": "pdus",
1676 "_id": pdu["_id"],
1677 "operation": "set",
1678 "content": rollback_pdu,
1679 }
1680 )
tiernocc103432018-10-19 14:10:35 +02001681
1682 # step 3. Fill vnfr info by filling vdur
1683 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001684 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001685 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1686 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1687 for pdu_interface in pdu["interfaces"]:
1688 if pdu_interface["name"] == vdur_interface["name"]:
1689 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1690 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001691 if k in (
1692 "ip-address",
1693 "mac-address",
1694 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001695 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001696 vnfr_update_rollback[
1697 iface_text + ".{}".format(k)
1698 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001699 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001700 if vdur_interface.get(
1701 "mgmt-interface"
1702 ) or vdur_interface.get("mgmt-vnf"):
1703 vnfr_update_rollback[
1704 vdu_text + ".ip-address"
1705 ] = vdur.get("ip-address")
1706 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1707 "ip-address"
1708 ]
tierno36ec8602018-11-02 17:27:11 +01001709 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001710 vnfr_update_rollback["ip-address"] = vnfr.get(
1711 "ip-address"
1712 )
tierno36ec8602018-11-02 17:27:11 +01001713 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001714 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1715 "ip-address"
1716 ]
1717 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1718 "vim-network-id"
1719 ):
1720 ifaces_forcing_vim_network.append(
1721 {
1722 "name": vdur_interface.get("vnf-vld-id")
1723 or vdur_interface.get("ns-vld-id"),
1724 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1725 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1726 }
1727 )
gcalvino17d5b732018-12-17 16:26:21 +01001728 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001729 ifaces_forcing_vim_network[-1][
1730 "vim-network-id"
1731 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001732 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001733 ifaces_forcing_vim_network[-1][
1734 "vim-network-name"
1735 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001736 break
1737
tierno36ec8602018-11-02 17:27:11 +01001738 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001739
garciadeblas4568a372021-03-24 09:19:48 +01001740 def _look_for_k8scluster(
1741 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1742 ):
tierno9cb7d672019-10-30 12:13:48 +00001743 """
1744 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1745 Fills vnfr.kdur with the selected k8scluster
1746
1747 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1748 :param rollback: list with the database modifications to rollback if needed
1749 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1750 :param vim_account: vim_account where this vnfr should be deployed
1751 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1752 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1753 of the changed vnfr is needed
1754
1755 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1756 "vim-network-name": used at VIM
1757 "name": interface name
1758 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1759 "ns-vld-id": NSD vld where this interface is connected.
1760 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1761 """
1762
1763 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001764 if not vnfr.get("kdur"):
1765 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001766
tiernoc67b0e92019-11-05 12:45:29 +00001767 kdu_filter = self._get_project_filter(session)
1768 kdu_filter["vim_account"] = vim_account
1769 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1770 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1771
1772 k8s_requirements = {} # just for logging
1773 for k8scluster in available_k8sclusters:
1774 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001775 break
tiernoc67b0e92019-11-05 12:45:29 +00001776 # restrict by cni
1777 if vnfr["k8s-cluster"].get("cni"):
1778 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001779 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1780 k8scluster.get("cni", ())
1781 ):
tiernoc67b0e92019-11-05 12:45:29 +00001782 continue
1783 # restrict by version
1784 if vnfr["k8s-cluster"].get("version"):
1785 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1786 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1787 continue
1788 # restrict by number of networks
1789 if vnfr["k8s-cluster"].get("nets"):
1790 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001791 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1792 vnfr["k8s-cluster"]["nets"]
1793 ):
tiernoc67b0e92019-11-05 12:45:29 +00001794 continue
1795 break
1796 else:
garciadeblas4568a372021-03-24 09:19:48 +01001797 raise EngineException(
1798 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1799 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1800 )
1801 )
tierno9cb7d672019-10-30 12:13:48 +00001802
tiernoc67b0e92019-11-05 12:45:29 +00001803 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001804 # step 3. Fill vnfr info by filling kdur
1805 kdu_text = "kdur.{}.".format(kdur_index)
1806 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1807 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1808
tiernoc67b0e92019-11-05 12:45:29 +00001809 # step 4. Check VIM networks that forces the selected k8s_cluster
1810 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1811 k8scluster_net_list = list(k8scluster.get("nets").keys())
1812 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1813 # get a network from k8s_cluster nets. If name matches use this, if not use other
1814 if kdur_net["id"] in k8scluster_net_list: # name matches
1815 vim_net = k8scluster["nets"][kdur_net["id"]]
1816 k8scluster_net_list.remove(kdur_net["id"])
1817 else:
1818 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1819 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001820 vnfr_update_rollback[
1821 "k8s-cluster.nets.{}.vim_net".format(net_index)
1822 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001823 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001824 if vim_net and (
1825 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1826 ):
1827 ifaces_forcing_vim_network.append(
1828 {
1829 "name": kdur_net.get("vnf-vld-id")
1830 or kdur_net.get("ns-vld-id"),
1831 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1832 "ns-vld-id": kdur_net.get("ns-vld-id"),
1833 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1834 }
1835 )
tiernoc67b0e92019-11-05 12:45:29 +00001836 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001837 return ifaces_forcing_vim_network
1838
Gulsum Aticie395aa42021-11-10 20:59:06 +03001839 def _update_vnfrs_from_nsd(self, nsr):
1840 try:
1841 nsr_id = nsr["_id"]
1842 nsd = nsr["nsd"]
1843
1844 step = "Getting vnf_profiles from nsd"
1845 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1846 vld_fixed_ip_connection_point_data = {}
1847
1848 step = "Getting ip-address info from vnf_profile if it exists"
1849 for vnfp in vnf_profiles:
1850 # Checking ip-address info from nsd.vnf_profile and storing
1851 for vlc in vnfp.get("virtual-link-connectivity", ()):
1852 for cpd in vlc.get("constituent-cpd-id", ()):
1853 if cpd.get("ip-address"):
1854 step = "Storing ip-address info"
1855 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1856 "vnfd-connection-point-ref": cpd.get(
1857 "constituent-cpd-id"),
1858 "ip-address": cpd.get(
1859 "ip-address")}})
1860
1861 # Inserting ip address to vnfr
1862 if len(vld_fixed_ip_connection_point_data) > 0:
1863 step = "Getting vnfrs"
1864 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1865 for item in vld_fixed_ip_connection_point_data.keys():
1866 step = "Filtering vnfrs"
1867 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1868 if vnfr:
1869 vnfr_update = {}
1870 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1871 for iface_index, iface in enumerate(vdur["interfaces"]):
1872 step = "Looking for matched interface"
1873 if (
1874 iface.get("external-connection-point-ref")
1875 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1876 iface.get("ns-vld-id") == item.split('.')[0]
1877
1878 ):
1879 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1880 vdur_index, iface_index
1881 )
1882 step = "Storing info in order to update vnfr"
1883 vnfr_update[
1884 vnfr_update_text + ".ip-address"
1885 ] = increment_ip_mac(
1886 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1887 vdur.get("count-index", 0), )
1888 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1889
1890 step = "updating vnfr at database"
1891 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1892 except (
1893 ValidationError,
1894 EngineException,
1895 DbException,
1896 MsgException,
1897 FsException,
1898 ) as e:
1899 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1900
tiernocc103432018-10-19 14:10:35 +02001901 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001902 # get vnfr
1903 nsr_id = nsr["_id"]
1904 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1905
1906 for vnfr in vnfrs:
1907 vnfr_update = {}
1908 vnfr_update_rollback = {}
1909 member_vnf_index = vnfr["member-vnf-index-ref"]
1910 # update vim-account-id
1911
1912 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02001913 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001914 # check instantiate parameters
1915 for vnf_inst_params in get_iterable(indata.get("vnf")):
1916 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1917 continue
1918 if vnf_inst_params.get("vimAccountId"):
1919 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02001920 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001921
tiernocddb07d2020-10-06 08:28:00 +00001922 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1923 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1924 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1925 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1926 continue
garciadeblas4568a372021-03-24 09:19:48 +01001927 for iface_inst_param in get_iterable(
1928 vdu_inst_param.get("interface")
1929 ):
1930 iface_index, _ = next(
1931 i
1932 for i in enumerate(vdur["interfaces"])
1933 if i[1]["name"] == iface_inst_param["name"]
1934 )
1935 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1936 vdur_index, iface_index
1937 )
tiernocddb07d2020-10-06 08:28:00 +00001938 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001939 vnfr_update[
1940 vnfr_update_text + ".ip-address"
1941 ] = increment_ip_mac(
1942 iface_inst_param.get("ip-address"),
1943 vdur.get("count-index", 0),
1944 )
tierno1bd9d952020-11-13 15:56:51 +00001945 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001946 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001947 vnfr_update[
1948 vnfr_update_text + ".mac-address"
1949 ] = increment_ip_mac(
1950 iface_inst_param.get("mac-address"),
1951 vdur.get("count-index", 0),
1952 )
tierno1bd9d952020-11-13 15:56:51 +00001953 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001954 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001955 vnfr_update[
1956 vnfr_update_text + ".floating-ip-required"
1957 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001958 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1959 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001960 for ivld_inst_param in get_iterable(
1961 vnf_inst_params.get("internal-vld")
1962 ):
1963 for icp_inst_param in get_iterable(
1964 ivld_inst_param.get("internal-connection-point")
1965 ):
tiernocddb07d2020-10-06 08:28:00 +00001966 # look for iface
1967 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1968 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001969 if (
1970 iface.get("internal-connection-point-ref")
1971 == icp_inst_param["id-ref"]
1972 ):
1973 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1974 vdur_index, iface_index
1975 )
tiernocddb07d2020-10-06 08:28:00 +00001976 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001977 vnfr_update[
1978 vnfr_update_text + ".ip-address"
1979 ] = increment_ip_mac(
1980 icp_inst_param.get("ip-address"),
1981 vdur.get("count-index", 0),
1982 )
1983 vnfr_update[
1984 vnfr_update_text + ".fixed-ip"
1985 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001986 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001987 vnfr_update[
1988 vnfr_update_text + ".mac-address"
1989 ] = increment_ip_mac(
1990 icp_inst_param.get("mac-address"),
1991 vdur.get("count-index", 0),
1992 )
1993 vnfr_update[
1994 vnfr_update_text + ".fixed-mac"
1995 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001996 break
1997 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1998 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001999 for vnfcp_inst_param in get_iterable(
2000 vld_inst_param.get("vnfd-connection-point-ref")
2001 ):
tiernocddb07d2020-10-06 08:28:00 +00002002 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2003 continue
2004 # look for iface
2005 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2006 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01002007 if (
2008 iface.get("external-connection-point-ref")
2009 == vnfcp_inst_param["vnfd-connection-point-ref"]
2010 ):
2011 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2012 vdur_index, iface_index
2013 )
tiernocddb07d2020-10-06 08:28:00 +00002014 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002015 vnfr_update[
2016 vnfr_update_text + ".ip-address"
2017 ] = increment_ip_mac(
2018 vnfcp_inst_param.get("ip-address"),
2019 vdur.get("count-index", 0),
2020 )
tierno1bd9d952020-11-13 15:56:51 +00002021 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00002022 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01002023 vnfr_update[
2024 vnfr_update_text + ".mac-address"
2025 ] = increment_ip_mac(
2026 vnfcp_inst_param.get("mac-address"),
2027 vdur.get("count-index", 0),
2028 )
tierno1bd9d952020-11-13 15:56:51 +00002029 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00002030 break
2031
tiernocc103432018-10-19 14:10:35 +02002032 vnfr_update["vim-account-id"] = vim_account
2033 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2034
David Garciaecb41322021-03-31 19:10:46 +02002035 if vca_id:
2036 vnfr_update["vca-id"] = vca_id
2037 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2038
tiernocc103432018-10-19 14:10:35 +02002039 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01002040 ifaces_forcing_vim_network = self._look_for_pdu(
2041 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2042 )
tiernocc103432018-10-19 14:10:35 +02002043
tierno9cb7d672019-10-30 12:13:48 +00002044 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01002045 ifaces_forcing_vim_network += self._look_for_k8scluster(
2046 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2047 )
tierno9cb7d672019-10-30 12:13:48 +00002048 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01002049 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01002050 rollback.append(
2051 {
2052 "topic": "vnfrs",
2053 "_id": vnfr["_id"],
2054 "operation": "set",
2055 "content": vnfr_update_rollback,
2056 }
2057 )
tierno36ec8602018-11-02 17:27:11 +01002058
2059 # Update indada in case pdu forces to use a concrete vim-network-name
2060 # TODO check if user has already insert a vim-network-name and raises an error
2061 if not ifaces_forcing_vim_network:
2062 continue
2063 for iface_info in ifaces_forcing_vim_network:
2064 if iface_info.get("ns-vld-id"):
2065 if "vld" not in indata:
2066 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002067 indata["vld"].append(
2068 {
2069 key: iface_info[key]
2070 for key in ("name", "vim-network-name", "vim-network-id")
2071 if iface_info.get(key)
2072 }
2073 )
tierno36ec8602018-11-02 17:27:11 +01002074
2075 elif iface_info.get("vnf-vld-id"):
2076 if "vnf" not in indata:
2077 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01002078 indata["vnf"].append(
2079 {
2080 "member-vnf-index": member_vnf_index,
2081 "internal-vld": [
2082 {
2083 key: iface_info[key]
2084 for key in (
2085 "name",
2086 "vim-network-name",
2087 "vim-network-id",
2088 )
2089 if iface_info.get(key)
2090 }
2091 ],
2092 }
2093 )
tierno36ec8602018-11-02 17:27:11 +01002094
2095 @staticmethod
2096 def _create_nslcmop(nsr_id, operation, params):
2097 """
2098 Creates a ns-lcm-opp content to be stored at database.
2099 :param nsr_id: internal id of the instance
aticig544a2ae2022-04-05 09:00:17 +03002100 :param operation: instantiate, terminate, scale, action, update ...
tierno36ec8602018-11-02 17:27:11 +01002101 :param params: user parameters for the operation
2102 :return: dictionary following SOL005 format
2103 """
tiernob24258a2018-10-04 18:39:49 +02002104 now = time()
2105 _id = str(uuid4())
2106 nslcmop = {
2107 "id": _id,
2108 "_id": _id,
2109 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002110 "queuePosition": None,
2111 "stage": None,
2112 "errorMessage": None,
2113 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002114 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002115 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002116 "lcmOperationType": operation,
2117 "startTime": now,
2118 "isAutomaticInvocation": False,
2119 "operationParams": params,
2120 "isCancelPending": False,
2121 "links": {
2122 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002123 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002124 },
tiernob24258a2018-10-04 18:39:49 +02002125 }
2126 return nslcmop
2127
magnussonlf318b302020-01-20 18:38:18 +01002128 def _get_enabled_vims(self, session):
2129 """
2130 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2131 :param session: current session with user information
2132 """
2133 db_filter = self._get_project_filter(session)
2134 db_filter["_admin.operationalState"] = "ENABLED"
2135 vims = self.db.get_list("vim_accounts", db_filter)
2136 vimAccounts = []
2137 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002138 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002139 return vimAccounts
2140
garciadeblas4568a372021-03-24 09:19:48 +01002141 def new(
2142 self,
2143 rollback,
2144 session,
2145 indata=None,
2146 kwargs=None,
2147 headers=None,
2148 slice_object=False,
2149 ):
tiernob24258a2018-10-04 18:39:49 +02002150 """
2151 Performs a new operation over a ns
2152 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002153 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002154 :param indata: descriptor with the parameters of the operation. It must contains among others
2155 nsInstanceId: _id of the nsr to perform the operation
aticig544a2ae2022-04-05 09:00:17 +03002156 operation: it can be: instantiate, terminate, action, update TODO: heal
tiernob24258a2018-10-04 18:39:49 +02002157 :param kwargs: used to override the indata descriptor
2158 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002159 :return: id of the nslcmops
2160 """
garciadeblas4568a372021-03-24 09:19:48 +01002161
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002162 def check_if_nsr_is_not_slice_member(session, nsr_id):
2163 nsis = None
2164 db_filter = self._get_project_filter(session)
2165 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002166 nsis = self.db.get_one(
2167 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2168 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002169 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002170 raise EngineException(
2171 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2172 nsr_id, nsis["_id"]
2173 ),
2174 http_code=HTTPStatus.CONFLICT,
2175 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002176
tiernob24258a2018-10-04 18:39:49 +02002177 try:
2178 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002179 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002180 operation = indata["lcmOperationType"]
2181 nsInstanceId = indata["nsInstanceId"]
2182
2183 validate_input(indata, self.operation_schema[operation])
2184 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002185 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002186 _filter["_id"] = nsInstanceId
2187 nsr = self.db.get_one("nsrs", _filter)
2188
2189 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002190 if operation == "terminate" and slice_object is False:
2191 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002192 if (
2193 not nsr["_admin"].get("nsState")
2194 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2195 ):
tiernob24258a2018-10-04 18:39:49 +02002196 if operation == "terminate" and indata.get("autoremove"):
2197 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002198 return (
2199 None,
2200 None,
2201 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002202 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002203 raise EngineException(
2204 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2205 nsInstanceId, operation
2206 ),
2207 HTTPStatus.CONFLICT,
2208 )
tiernob24258a2018-10-04 18:39:49 +02002209 else:
tierno65ca36d2019-02-12 19:27:52 +01002210 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002211 raise EngineException(
2212 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2213 nsInstanceId, operation
2214 ),
2215 HTTPStatus.CONFLICT,
2216 )
tiernob24258a2018-10-04 18:39:49 +02002217 self._check_ns_operation(session, nsr, operation, indata)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002218 if (indata.get("primitive_params")):
2219 indata["primitive_params"] = json.dumps(indata["primitive_params"])
2220 elif (indata.get("additionalParamsForVnf")):
2221 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
tierno36ec8602018-11-02 17:27:11 +01002222
tiernocc103432018-10-19 14:10:35 +02002223 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002224 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002225 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01002226
2227 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002228 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002229 self.format_on_new(
2230 nslcmop_desc, session["project_id"], make_public=session["public"]
2231 )
magnussonlf318b302020-01-20 18:38:18 +01002232 if indata.get("placement-engine"):
2233 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002234 nslcmop_desc["operationParams"][
2235 "validVimAccounts"
2236 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002237 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002238 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002239 if not slice_object:
2240 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002241 return _id, None
2242 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002243 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2244 # except DbException as e:
2245 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2246
tiernobee3bad2019-12-05 12:26:01 +00002247 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002248 raise EngineException(
2249 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2250 )
tiernob24258a2018-10-04 18:39:49 +02002251
tierno65ca36d2019-02-12 19:27:52 +01002252 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002253 raise EngineException(
2254 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2255 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002256
2257
2258class NsiTopic(BaseTopic):
2259 topic = "nsis"
2260 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002261 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002262
delacruzramo32bab472019-09-13 12:24:22 +02002263 def __init__(self, db, fs, msg, auth):
2264 BaseTopic.__init__(self, db, fs, msg, auth)
2265 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002266
Felipe Vicensc37b3842019-01-12 12:24:42 +01002267 @staticmethod
2268 def _format_ns_request(ns_request):
2269 formated_request = copy(ns_request)
2270 # TODO: Add request params
2271 return formated_request
2272
2273 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002274 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002275 """
2276 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002277 :param slice_request: User instantiation additional parameters
2278 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002279 """
tiernofd160572019-01-21 10:41:37 +00002280 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2281 if additional_params:
2282 for k, v in additional_params.items():
2283 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002284 raise EngineException(
2285 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2286 k
2287 )
2288 )
tiernofd160572019-01-21 10:41:37 +00002289 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002290 raise EngineException(
2291 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2292 k
2293 )
2294 )
tiernofd160572019-01-21 10:41:37 +00002295 if isinstance(v, (dict, tuple, list)):
2296 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002297 return additional_params
2298
Felipe Vicensb57758d2018-10-16 16:00:20 +02002299 def _check_descriptor_dependencies(self, session, descriptor):
2300 """
2301 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01002302 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002303 :param descriptor: descriptor to be inserted or edit
2304 :return: None or raises exception
2305 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002306 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002307 return
Felipe Vicens07f31722018-10-29 15:16:44 +01002308 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002309 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
garciadeblas4568a372021-03-24 09:19:48 +01002310 raise EngineException(
2311 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2312 nstd_id
2313 ),
2314 http_code=HTTPStatus.CONFLICT,
2315 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002316
tiernob4844ab2019-05-23 08:42:12 +00002317 def check_conflict_on_del(self, session, _id, db_content):
2318 """
2319 Check that NSI is not instantiated
2320 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2321 :param _id: nsi internal id
2322 :param db_content: The database content of the _id
2323 :return: None or raises EngineException with the conflict
2324 """
tierno65ca36d2019-02-12 19:27:52 +01002325 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002326 return
tiernob4844ab2019-05-23 08:42:12 +00002327 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002328 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002329 raise EngineException(
2330 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2331 "Launch 'terminate' operation first; or force deletion".format(_id),
2332 http_code=HTTPStatus.CONFLICT,
2333 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002334
tiernobee3bad2019-12-05 12:26:01 +00002335 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002336 """
tiernob4844ab2019-05-23 08:42:12 +00002337 Deletes associated nsilcmops from database. Deletes associated filesystem.
2338 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002339 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002340 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002341 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002342 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002343 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002344 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002345
Felipe Vicens09e65422019-01-22 15:06:46 +01002346 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002347 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002348 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2349 nsr_id = nsrs_detailed_item["nsrId"]
2350 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002351 _filter = {
2352 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2353 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2354 "_id.ne": nsir["_id"],
2355 }
2356 nsi = self.db.get_one(
2357 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2358 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002359 if nsi: # last one using nsr
2360 continue
2361 try:
garciadeblas4568a372021-03-24 09:19:48 +01002362 self.nsrTopic.delete(
2363 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2364 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002365 except (DbException, EngineException) as e:
2366 if e.http_code == HTTPStatus.NOT_FOUND:
2367 pass
2368 else:
2369 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002370
tiernob4844ab2019-05-23 08:42:12 +00002371 # delete related nsilcmops database entries
2372 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002373
tiernob4844ab2019-05-23 08:42:12 +00002374 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002375 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002376 if nsir_admin and nsir_admin.get("nst-id"):
2377 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002378 nsis_list = self.db.get_one(
2379 "nsis",
2380 {"nst-id": nsir_admin["nst-id"]},
2381 fail_on_empty=False,
2382 fail_on_more=False,
2383 )
tiernob4844ab2019-05-23 08:42:12 +00002384 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002385 self.db.set_one(
2386 "nsts",
2387 {"_id": nsir_admin["nst-id"]},
2388 {"_admin.usageState": "NOT_IN_USE"},
2389 )
tiernob4844ab2019-05-23 08:42:12 +00002390
tierno65ca36d2019-02-12 19:27:52 +01002391 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002392 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002393 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002394 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002395 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002396 :param indata: params to be used for the nsir
2397 :param kwargs: used to override the indata descriptor
2398 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002399 :return: the _id of nsi descriptor created at database
2400 """
2401
2402 try:
delacruzramo32bab472019-09-13 12:24:22 +02002403 step = "checking quotas"
2404 self.check_quota(session)
2405
tierno99d4b172019-07-02 09:28:40 +00002406 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002407 slice_request = self._remove_envelop(indata)
2408 # Override descriptor with query string kwargs
2409 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002410 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002411
Felipe Vicensb57758d2018-10-16 16:00:20 +02002412 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002413 step = "getting nstd id='{}' from database".format(
2414 slice_request.get("nstId")
2415 )
tiernob4844ab2019-05-23 08:42:12 +00002416 _filter = self._get_project_filter(session)
2417 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002418 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002419 # check NST is not disabled
2420 step = "checking NST operationalState"
2421 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002422 raise EngineException(
2423 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2424 "instance".format(slice_request["nstId"]),
2425 http_code=HTTPStatus.CONFLICT,
2426 )
tiernob4844ab2019-05-23 08:42:12 +00002427 del _filter["_id"]
2428
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002429 # check NSD is not disabled
2430 step = "checking operationalState"
2431 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002432 raise EngineException(
2433 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2434 "a network slice".format(slice_request["nstId"]),
2435 http_code=HTTPStatus.CONFLICT,
2436 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002437
Felipe Vicens07f31722018-10-29 15:16:44 +01002438 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002439 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002440 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002441 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002442
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002443 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002444 nsi_descriptor = {
2445 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002446 "name": slice_request["nsiName"],
2447 "description": slice_request.get("nsiDescription", ""),
2448 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002449 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002450 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002451 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002452 "nsr-ref-list": [],
2453 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002454 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002455 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002456 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002457
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002458 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002459 self.format_on_new(
2460 nsi_descriptor, session["project_id"], make_public=session["public"]
2461 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002462 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2463 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002464 nsi_descriptor["_admin"]["deployed"] = {}
2465 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2466 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2467
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002468 # Creating netslice-vld for the RO.
2469 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002470
2471 # Building the vlds list to be deployed
2472 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002473 nsi_vlds = []
2474
2475 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2476 # Getting template Instantiation parameters from NST
2477 nsi_vld = deepcopy(netslice_vlds)
2478 nsi_vld["shared-nsrs-list"] = []
2479 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2480 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002481
2482 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002483 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002484 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002485 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002486
Felipe Vicens09e65422019-01-22 15:06:46 +01002487 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002488 for member_ns in nstd["netslice-subnet"]:
2489 nsd_id = member_ns["nsd-ref"]
2490 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002491 member_ns["nsd-ref"], member_ns["id"]
2492 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002493 if nsd_id not in needed_nsds:
2494 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002495 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002496 nsd = self.db.get_one(
2497 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2498 )
tiernob4844ab2019-05-23 08:42:12 +00002499 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002500 nsd.pop("_admin")
2501 needed_nsds[nsd_id] = nsd
2502 else:
2503 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002504 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2505 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002506
Felipe Vicensb57758d2018-10-16 16:00:20 +02002507 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002508 member_ns["nsd-ref"], member_ns["id"]
2509 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002510
Felipe Vicens07f31722018-10-29 15:16:44 +01002511 # creates Network Services records (NSRs)
2512 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002513 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002514 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002515 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002516 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002517 # Check if the netslice-subnet is shared and if it is share if the nss exists
2518 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002519 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002520 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002521 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002522 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2523 "nsd-ref"
2524 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002525 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002526 nsi = self.db.get_one(
2527 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2528 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002529 if nsi and service.get("is-shared-nss"):
2530 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2531 for nsrs_detailed_item in nsrs_detailed_list:
2532 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002533 if nsrs_detailed_item["nss-id"] == service["id"]:
2534 _id_nsr = nsrs_detailed_item["nsrId"]
2535 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002536 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2537 if netslice_subnet["nss-id"] == service["id"]:
2538 indata_ns = netslice_subnet
2539 break
2540 else:
2541 indata_ns = {}
2542 if service.get("instantiation-parameters"):
2543 indata_ns = deepcopy(service["instantiation-parameters"])
2544 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002545
Felipe Vicens09e65422019-01-22 15:06:46 +01002546 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002547 indata_ns["nsName"] = (
2548 slice_request.get("nsiName") + "." + service["id"]
2549 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002550 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2551 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002552 if slice_request.get("ssh_keys"):
2553 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002554
Felipe Vicens09e65422019-01-22 15:06:46 +01002555 if ns_params:
2556 for ns_param in ns_params:
2557 if ns_param.get("id") == service["id"]:
2558 copy_ns_param = deepcopy(ns_param)
2559 del copy_ns_param["id"]
2560 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002561 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002562
2563 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002564 _id_nsr, _ = self.nsrTopic.new(
2565 rollback, session, indata_ns, kwargs, headers
2566 )
2567 nsrs_item = {
2568 "nsrId": _id_nsr,
2569 "shared": service.get("is-shared-nss"),
2570 "nsd-id": service["nsd-ref"],
2571 "nss-id": service["id"],
2572 "nslcmop_instantiate": None,
2573 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002574 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002575 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002576 nsi_netslice_subnet.append(indata_ns)
2577 nsr_ref = {"nsr-ref": _id_nsr}
2578 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002579
2580 # Adding the nsrs list to the nsi
2581 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002582 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002583 self.db.set_one(
2584 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2585 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002586
Felipe Vicens07f31722018-10-29 15:16:44 +01002587 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002588 self.db.create("nsis", nsi_descriptor)
2589 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002590 return nsi_id, None
garciadeblas4568a372021-03-24 09:19:48 +01002591 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2592 self.logger.exception(
2593 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2594 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002595 raise EngineException("Error {}: {}".format(step, e))
2596 except ValidationError as e:
2597 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2598
tierno65ca36d2019-02-12 19:27:52 +01002599 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002600 raise EngineException(
2601 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2602 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002603
2604
2605class NsiLcmOpTopic(BaseTopic):
2606 topic = "nsilcmops"
2607 topic_msg = "nsi"
2608 operation_schema = { # mapping between operation and jsonschema to validate
2609 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002610 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002611 }
garciadeblas4568a372021-03-24 09:19:48 +01002612
delacruzramo32bab472019-09-13 12:24:22 +02002613 def __init__(self, db, fs, msg, auth):
2614 BaseTopic.__init__(self, db, fs, msg, auth)
2615 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002616
2617 def _check_nsi_operation(self, session, nsir, operation, indata):
2618 """
2619 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002620 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002621 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2622 :param indata: descriptor with the parameters of the operation
2623 :return: None
2624 """
2625 nsds = {}
2626 nstd = nsir["network-slice-template"]
2627
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002628 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002629 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002630 for netslice_subnet in nstd["netslice-subnet"]:
2631 if nstId == netslice_subnet["id"]:
2632 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002633 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002634 _filter = self._get_project_filter(session)
2635 _filter["id"] = nsd_id
2636 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002637 return nsds[nsd_id]
2638 else:
garciadeblas4568a372021-03-24 09:19:48 +01002639 raise EngineException(
2640 "Invalid parameter nstId='{}' is not one of the "
2641 "nst:netslice-subnet".format(nstId)
2642 )
2643
Felipe Vicens07f31722018-10-29 15:16:44 +01002644 if operation == "instantiate":
2645 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002646 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002647 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002648
2649 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2650 now = time()
2651 _id = str(uuid4())
2652 nsilcmop = {
2653 "id": _id,
2654 "_id": _id,
2655 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2656 "statusEnteredTime": now,
2657 "netsliceInstanceId": netsliceInstanceId,
2658 "lcmOperationType": operation,
2659 "startTime": now,
2660 "isAutomaticInvocation": False,
2661 "operationParams": params,
2662 "isCancelPending": False,
2663 "links": {
2664 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002665 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2666 + netsliceInstanceId,
2667 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002668 }
2669 return nsilcmop
2670
Felipe Vicens09e65422019-01-22 15:06:46 +01002671 def add_shared_nsr_2vld(self, nsir, nsr_item):
2672 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2673 if nst_sb_item.get("is-shared-nss"):
2674 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2675 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2676 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002677 for admin_vld_nss_cp_ref_item in admin_vld_item[
2678 "nss-connection-point-ref"
2679 ]:
2680 if (
2681 admin_subnet_item["nss-id"]
2682 == admin_vld_nss_cp_ref_item["nss-ref"]
2683 ):
2684 if (
2685 not nsr_item["nsrId"]
2686 in admin_vld_item["shared-nsrs-list"]
2687 ):
2688 admin_vld_item["shared-nsrs-list"].append(
2689 nsr_item["nsrId"]
2690 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002691 break
2692 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002693 self.db.set_one(
2694 "nsis",
2695 {"_id": nsir["_id"]},
2696 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2697 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002698
tierno65ca36d2019-02-12 19:27:52 +01002699 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002700 """
2701 Performs a new operation over a ns
2702 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002703 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002704 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002705 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002706 operation: it can be: instantiate, terminate, action, TODO: update, heal
2707 :param kwargs: used to override the indata descriptor
2708 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002709 :return: id of the nslcmops
2710 """
2711 try:
2712 # Override descriptor with query string kwargs
2713 self._update_input_with_kwargs(indata, kwargs)
2714 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002715 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002716 validate_input(indata, self.operation_schema[operation])
2717
Felipe Vicens126af572019-06-05 19:13:04 +02002718 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002719 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002720 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002721 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002722 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002723 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002724
2725 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002726 if (
2727 not nsir["_admin"].get("nsiState")
2728 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2729 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002730 if operation == "terminate" and indata.get("autoremove"):
2731 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002732 return (
2733 None,
2734 None,
2735 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002736 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002737 raise EngineException(
2738 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2739 netsliceInstanceId, operation
2740 ),
2741 HTTPStatus.CONFLICT,
2742 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002743 else:
tierno65ca36d2019-02-12 19:27:52 +01002744 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002745 raise EngineException(
2746 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2747 netsliceInstanceId, operation
2748 ),
2749 HTTPStatus.CONFLICT,
2750 )
2751
Felipe Vicens07f31722018-10-29 15:16:44 +01002752 # Creating all the NS_operation (nslcmop)
2753 # Get service list from db
2754 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2755 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002756 # nslcmops_item = None
2757 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002758 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002759 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002760 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002761 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002762 _filter[
2763 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2764 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002765 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002766 nsi = self.db.get_one(
2767 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2768 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002769 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002770 _update = {
2771 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2772 index
2773 ): None
2774 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002775 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002776 if (
2777 nsi
2778 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002779 continue # do not create nsilcmop
2780 else: # instantiate
2781 # looks the first nsi fulfilling the conditions but not being the current NSIR
2782 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002783 nsi_nsr_item = next(
2784 n
2785 for n in nsi["_admin"]["nsrs-detailed-list"]
2786 if n["nsrId"] == nsr_id
2787 and n["shared"]
2788 and n["nslcmop_instantiate"]
2789 )
tierno40f742b2020-06-23 15:25:26 +00002790 self.add_shared_nsr_2vld(nsir, nsr_item)
2791 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002792 _update = {
2793 "_admin.nsrs-detailed-list.{}".format(
2794 index
2795 ): nsi_nsr_item
2796 }
tierno40f742b2020-06-23 15:25:26 +00002797 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2798 # continue to not create nslcmop since nsrs is shared and nsrs was created
2799 continue
2800 else:
2801 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002802
tierno40f742b2020-06-23 15:25:26 +00002803 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002804 try:
tierno0b8752f2020-05-12 09:42:02 +00002805 indata_ns = {
2806 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002807 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002808 # Including netslice_id in the ns instantiate Operation
2809 "netsliceInstanceId": netsliceInstanceId,
2810 }
2811 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002812 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002813 indata_ns.update(service["instantiate_params"])
2814
tierno99d4b172019-07-02 09:28:40 +00002815 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002816 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002817 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2818 rollback, session, indata_ns, None, headers, slice_object=True
2819 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002820 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002821 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002822 _update = {
2823 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2824 index
2825 ): nslcmop
2826 }
tierno40f742b2020-06-23 15:25:26 +00002827 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002828 except (DbException, EngineException) as e:
2829 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002830 self.logger.info(
2831 logging_prefix
2832 + "skipping NS={} because not found".format(nsr_id)
2833 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002834 pass
2835 else:
2836 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002837
2838 # Creates nsilcmop
2839 indata["nslcmops_ids"] = nslcmops
2840 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002841
garciadeblas4568a372021-03-24 09:19:48 +01002842 nsilcmop_desc = self._create_nsilcmop(
2843 session, netsliceInstanceId, operation, indata
2844 )
2845 self.format_on_new(
2846 nsilcmop_desc, session["project_id"], make_public=session["public"]
2847 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002848 _id = self.db.create("nsilcmops", nsilcmop_desc)
2849 rollback.append({"topic": "nsilcmops", "_id": _id})
2850 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002851 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002852 except ValidationError as e:
2853 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002854
tiernobee3bad2019-12-05 12:26:01 +00002855 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002856 raise EngineException(
2857 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2858 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002859
tierno65ca36d2019-02-12 19:27:52 +01002860 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002861 raise EngineException(
2862 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2863 )