blob: 8632e9465b4296375b5afd07b3fe5b8a3d68587c [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,
29 nsi_instantiate,
30)
31from osm_nbi.base_topic import (
32 BaseTopic,
33 EngineException,
34 get_iterable,
35 deep_get,
36 increment_ip_mac,
37)
tiernobee085c2018-12-12 17:03:04 +000038from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010039from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000040from osm_common.msgbase import MsgException
41from osm_common.fsbase import FsException
garciaale7cbd03c2020-11-27 10:38:35 -030042from osm_nbi import utils
garciadeblas4568a372021-03-24 09:19:48 +010043from re import (
44 match,
45) # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020046
47__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
48
49
50class NsrTopic(BaseTopic):
51 topic = "nsrs"
52 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000053 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000054 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020055
delacruzramo32bab472019-09-13 12:24:22 +020056 def __init__(self, db, fs, msg, auth):
57 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020058
59 def _check_descriptor_dependencies(self, session, descriptor):
60 """
61 Check that the dependent descriptors exist on a new descriptor or edition
62 :param session: client session information
63 :param descriptor: descriptor to be inserted or edit
64 :return: None or raises exception
65 """
66 if not descriptor.get("nsdId"):
67 return
68 nsd_id = descriptor["nsdId"]
69 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
garciadeblas4568a372021-03-24 09:19:48 +010070 raise EngineException(
71 "Descriptor error at nsdId='{}' references a non exist nsd".format(
72 nsd_id
73 ),
74 http_code=HTTPStatus.CONFLICT,
75 )
tiernob24258a2018-10-04 18:39:49 +020076
77 @staticmethod
78 def format_on_new(content, project_id=None, make_public=False):
79 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
80 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000081 return None
tiernob24258a2018-10-04 18:39:49 +020082
tiernob4844ab2019-05-23 08:42:12 +000083 def check_conflict_on_del(self, session, _id, db_content):
84 """
85 Check that NSR is not instantiated
86 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
87 :param _id: nsr internal id
88 :param db_content: The database content of the nsr
89 :return: None or raises EngineException with the conflict
90 """
tierno65ca36d2019-02-12 19:27:52 +010091 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020092 return
tiernob4844ab2019-05-23 08:42:12 +000093 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020094 if nsr["_admin"].get("nsState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +010095 raise EngineException(
96 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
97 "Launch 'terminate' operation first; or force deletion".format(_id),
98 http_code=HTTPStatus.CONFLICT,
99 )
tiernob24258a2018-10-04 18:39:49 +0200100
tiernobee3bad2019-12-05 12:26:01 +0000101 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +0000102 """
103 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
104 Set usageState of pdu, vnfd, nsd
105 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
106 :param _id: server internal id
107 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +0000108 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +0000109 :return: None if ok or raises EngineException with the problem
110 """
tiernobee085c2018-12-12 17:03:04 +0000111 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +0200112 self.db.del_list("nslcmops", {"nsInstanceId": _id})
113 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +0000114
tiernob24258a2018-10-04 18:39:49 +0200115 # set all used pdus as free
garciadeblas4568a372021-03-24 09:19:48 +0100116 self.db.set_list(
117 "pdus",
118 {"_admin.usage.nsr_id": _id},
119 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
120 )
tiernob24258a2018-10-04 18:39:49 +0200121
tiernob4844ab2019-05-23 08:42:12 +0000122 # Set NSD usageState
123 nsr = db_content
124 used_nsd_id = nsr.get("nsd-id")
125 if used_nsd_id:
126 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100127 nsrs_list = self.db.get_one(
128 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
129 )
tiernob4844ab2019-05-23 08:42:12 +0000130 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100131 self.db.set_one(
132 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
133 )
tiernob4844ab2019-05-23 08:42:12 +0000134
135 # Set VNFD usageState
136 used_vnfd_id_list = nsr.get("vnfd-id")
137 if used_vnfd_id_list:
138 for used_vnfd_id in used_vnfd_id_list:
139 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100140 nsrs_list = self.db.get_one(
141 "nsrs",
142 {"vnfd-id": used_vnfd_id},
143 fail_on_empty=False,
144 fail_on_more=False,
145 )
tiernob4844ab2019-05-23 08:42:12 +0000146 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100147 self.db.set_one(
148 "vnfds",
149 {"_id": used_vnfd_id},
150 {"_admin.usageState": "NOT_IN_USE"},
151 )
tiernob4844ab2019-05-23 08:42:12 +0000152
tiernof0441ea2020-05-26 15:39:18 +0000153 # delete extra ro_nsrs used for internal RO module
154 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
155
tiernobee085c2018-12-12 17:03:04 +0000156 @staticmethod
157 def _format_ns_request(ns_request):
158 formated_request = copy(ns_request)
159 formated_request.pop("additionalParamsForNs", None)
160 formated_request.pop("additionalParamsForVnf", None)
161 return formated_request
162
163 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +0100164 def _format_additional_params(
165 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
166 ):
tiernobee085c2018-12-12 17:03:04 +0000167 """
168 Get and format user additional params for NS or VNF
169 :param ns_request: User instantiation additional parameters
170 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
171 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000172 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000173 """
174 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000175 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000176 if not member_vnf_index:
177 additional_params = copy(ns_request.get("additionalParamsForNs"))
178 where_ = "additionalParamsForNs"
179 elif ns_request.get("additionalParamsForVnf"):
garciadeblas4568a372021-03-24 09:19:48 +0100180 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
181 member_vnf_index
182 )
183 item = next(
184 (
185 x
186 for x in ns_request["additionalParamsForVnf"]
187 if x["member-vnf-index"] == member_vnf_index
188 ),
189 None,
190 )
tierno714954e2019-11-29 13:43:26 +0000191 if item:
tierno54db2e42020-04-06 15:29:42 +0000192 if not vdu_id and not kdu_name:
193 other_params = item
tierno714954e2019-11-29 13:43:26 +0000194 additional_params = copy(item.get("additionalParams")) or {}
195 if vdu_id and item.get("additionalParamsForVdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100196 item_vdu = next(
197 (
198 x
199 for x in item["additionalParamsForVdu"]
200 if x["vdu_id"] == vdu_id
201 ),
202 None,
203 )
tiernobce98f02020-04-17 11:27:47 +0000204 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000205 if item_vdu and item_vdu.get("additionalParams"):
206 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000207 additional_params = item_vdu["additionalParams"]
208 if kdu_name:
209 additional_params = {}
210 if item.get("additionalParamsForKdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100211 item_kdu = next(
212 (
213 x
214 for x in item["additionalParamsForKdu"]
215 if x["kdu_name"] == kdu_name
216 ),
217 None,
218 )
tiernobce98f02020-04-17 11:27:47 +0000219 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000220 if item_kdu and item_kdu.get("additionalParams"):
garciadeblas4568a372021-03-24 09:19:48 +0100221 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
222 kdu_name
223 )
tiernob091dc12019-12-02 15:53:25 +0000224 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000225
tiernobee085c2018-12-12 17:03:04 +0000226 if additional_params:
227 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000228 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
garciadeblas4568a372021-03-24 09:19:48 +0100229 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
230 raise EngineException(
231 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
232 "and underscores, and cannot start with a digit".format(
233 where_, k
234 )
235 )
delacruzramo36ffe552019-05-03 14:52:37 +0200236 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000237 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +0100238 raise EngineException(
239 "Invalid param at {}:{}. Only string keys are allowed".format(
240 where_, k
241 )
242 )
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100243 if "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +0100244 raise EngineException(
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100245 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
garciadeblas4568a372021-03-24 09:19:48 +0100246 where_, k
247 )
248 )
tiernobee085c2018-12-12 17:03:04 +0000249 if isinstance(v, (dict, tuple, list)):
250 additional_params[k] = "!!yaml " + safe_dump(v)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +0100251 if kdu_name:
252 additional_params = json.dumps(additional_params)
tiernobee085c2018-12-12 17:03:04 +0000253
254 if descriptor:
bravof41a52052021-02-17 18:08:01 -0300255 for df in descriptor.get("df", []):
256 # check that enough parameters are supplied for the initial-config-primitive
257 # TODO: check for cloud-init
258 if member_vnf_index:
garciaale7cbd03c2020-11-27 10:38:35 -0300259 initial_primitives = []
garciadeblas4568a372021-03-24 09:19:48 +0100260 if (
261 "lcm-operations-configuration" in df
262 and "operate-vnf-op-config"
263 in df["lcm-operations-configuration"]
264 ):
265 for config in df["lcm-operations-configuration"][
266 "operate-vnf-op-config"
267 ].get("day1-2", []):
268 for primitive in get_iterable(
269 config.get("initial-config-primitive")
270 ):
bravof41a52052021-02-17 18:08:01 -0300271 initial_primitives.append(primitive)
272 else:
garciadeblas4568a372021-03-24 09:19:48 +0100273 initial_primitives = deep_get(
274 descriptor, ("ns-configuration", "initial-config-primitive")
275 )
tiernobee085c2018-12-12 17:03:04 +0000276
bravof41a52052021-02-17 18:08:01 -0300277 for initial_primitive in get_iterable(initial_primitives):
278 for param in get_iterable(initial_primitive.get("parameter")):
garciadeblas4568a372021-03-24 09:19:48 +0100279 if param["value"].startswith("<") and param["value"].endswith(
280 ">"
281 ):
282 if param["value"] in (
283 "<rw_mgmt_ip>",
284 "<VDU_SCALE_INFO>",
285 "<ns_config_info>",
286 ):
bravof41a52052021-02-17 18:08:01 -0300287 continue
garciadeblas4568a372021-03-24 09:19:48 +0100288 if (
289 not additional_params
290 or param["value"][1:-1] not in additional_params
291 ):
292 raise EngineException(
293 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
294 "initial-config-primitive[name={}] not supplied".format(
295 param["value"],
296 descriptor["id"],
297 initial_primitive["name"],
298 )
299 )
tierno714954e2019-11-29 13:43:26 +0000300
tierno54db2e42020-04-06 15:29:42 +0000301 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000302
tierno65ca36d2019-02-12 19:27:52 +0100303 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200304 """
305 Creates a new nsr into database. It also creates needed vnfrs
306 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200308 :param indata: params to be used for the nsr
309 :param kwargs: used to override the indata descriptor
310 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000311 :return: the _id of nsr descriptor created at database. Or an exception of type
312 EngineException, ValidationError, DbException, FsException, MsgException.
313 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200314 """
tiernob24258a2018-10-04 18:39:49 +0200315 try:
delacruzramo32bab472019-09-13 12:24:22 +0200316 step = "checking quotas"
317 self.check_quota(session)
318
tierno99d4b172019-07-02 09:28:40 +0000319 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200320 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200321 self._update_input_with_kwargs(ns_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -0300322 ns_request = self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200323
tiernob24258a2018-10-04 18:39:49 +0200324 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale7cbd03c2020-11-27 10:38:35 -0300325 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
326 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200327
Frank Bryden3c64ab62020-07-21 14:25:32 +0000328 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300329 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000330
tiernob24258a2018-10-04 18:39:49 +0200331 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300332 nsr_id = str(uuid4())
garciadeblas4568a372021-03-24 09:19:48 +0100333 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
334 nsd, ns_request, nsr_id, session
335 )
tierno54db2e42020-04-06 15:29:42 +0000336
garciaale7cbd03c2020-11-27 10:38:35 -0300337 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200338 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300339 # TODO: Change for multiple df support
K Sai Kiranbb006022021-05-20 11:09:49 +0530340 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
garciaale7cbd03c2020-11-27 10:38:35 -0300341 for vnfp in vnf_profiles:
342 vnfd_id = vnfp.get("vnfd-id")
343 vnf_index = vnfp.get("id")
garciadeblas4568a372021-03-24 09:19:48 +0100344 step = (
345 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
346 vnfd_id, vnf_index
347 )
348 )
tiernob24258a2018-10-04 18:39:49 +0200349 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300350 vnfd = self._get_vnfd_from_db(vnfd_id, session)
beierlmcee2ebf2022-03-29 17:42:48 -0400351 if "revision" in vnfd["_admin"]:
352 vnfd["revision"] = vnfd["_admin"]["revision"]
353 vnfd.pop("_admin")
tiernob24258a2018-10-04 18:39:49 +0200354 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000355 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200356 else:
357 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100358
garciadeblas4568a372021-03-24 09:19:48 +0100359 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
360 vnfd_id, vnf_index
361 )
362 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
363 nsd,
364 vnfd,
365 vnfd_id,
366 vnf_index,
367 nsr_descriptor,
368 ns_request,
369 ns_k8s_namespace,
370 )
tierno36ec8602018-11-02 17:27:11 +0100371
garciadeblas4568a372021-03-24 09:19:48 +0100372 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
373 vnfd_id, vnf_index
374 )
garciaale7cbd03c2020-11-27 10:38:35 -0300375 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
376 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
tiernob24258a2018-10-04 18:39:49 +0200377
378 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300379 self._add_nsr_to_db(nsr_descriptor, rollback, session)
tiernobee085c2018-12-12 17:03:04 +0000380
381 step = "creating nsr temporal folder"
382 self.fs.mkdir(nsr_id)
383
tiernobdebce92019-07-01 15:36:49 +0000384 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100385 except (
386 ValidationError,
387 EngineException,
388 DbException,
389 MsgException,
390 FsException,
391 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000392 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200393
garciaale7cbd03c2020-11-27 10:38:35 -0300394 def _get_nsd_from_db(self, nsd_id, session):
395 _filter = self._get_project_filter(session)
396 _filter["_id"] = nsd_id
397 return self.db.get_one("nsds", _filter)
398
399 def _get_vnfd_from_db(self, vnfd_id, session):
400 _filter = self._get_project_filter(session)
401 _filter["id"] = vnfd_id
402 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
garciaale7cbd03c2020-11-27 10:38:35 -0300403 return vnfd
404
405 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100406 self.format_on_new(
407 nsr_descriptor, session["project_id"], make_public=session["public"]
408 )
garciaale7cbd03c2020-11-27 10:38:35 -0300409 self.db.create("nsrs", nsr_descriptor)
410 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
411
412 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100413 self.format_on_new(
414 vnfr_descriptor, session["project_id"], make_public=session["public"]
415 )
garciaale7cbd03c2020-11-27 10:38:35 -0300416 self.db.create("vnfrs", vnfr_descriptor)
417 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
418
419 def _check_nsd_operational_state(self, nsd, ns_request):
420 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100421 raise EngineException(
422 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
423 "a network service".format(ns_request["nsdId"]),
424 http_code=HTTPStatus.CONFLICT,
425 )
garciaale7cbd03c2020-11-27 10:38:35 -0300426
427 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100428 additional_params, _ = self._format_additional_params(
429 ns_request, descriptor=nsd
430 )
garciaale7cbd03c2020-11-27 10:38:35 -0300431 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
432 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
433 if ns_request and ns_request.get("k8s-namespace"):
434 ns_k8s_namespace = ns_request["k8s-namespace"]
435 if additional_params and additional_params.get("k8s-namespace"):
436 ns_k8s_namespace = additional_params["k8s-namespace"]
437
438 return ns_k8s_namespace
439
bravofe76b8822021-02-26 16:57:52 -0300440 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300441 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100442 additional_params, _ = self._format_additional_params(
443 ns_request, descriptor=nsd
444 )
garciaale7cbd03c2020-11-27 10:38:35 -0300445
446 nsr_descriptor = {
447 "name": ns_request["nsName"],
448 "name-ref": ns_request["nsName"],
449 "short-name": ns_request["nsName"],
450 "admin-status": "ENABLED",
451 "nsState": "NOT_INSTANTIATED",
452 "currentOperation": "IDLE",
453 "currentOperationID": None,
454 "errorDescription": None,
455 "errorDetail": None,
456 "deploymentStatus": None,
457 "configurationStatus": None,
458 "vcaStatus": None,
459 "nsd": {k: v for k, v in nsd.items()},
460 "datacenter": ns_request["vimAccountId"],
461 "resource-orchestrator": "osmopenmano",
462 "description": ns_request.get("nsDescription", ""),
463 "constituent-vnfr-ref": [],
464 "operational-status": "init", # typedef ns-operational-
465 "config-status": "init", # typedef config-states
466 "detailed-status": "scheduled",
467 "orchestration-progress": {},
468 "create-time": now,
469 "nsd-name-ref": nsd["name"],
470 "operational-events": [], # "id", "timestamp", "description", "event",
471 "nsd-ref": nsd["id"],
472 "nsd-id": nsd["_id"],
473 "vnfd-id": [],
474 "instantiate_params": self._format_ns_request(ns_request),
475 "additionalParamsForNs": additional_params,
476 "ns-instance-config-ref": nsr_id,
477 "id": nsr_id,
478 "_id": nsr_id,
479 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
480 "flavor": [],
481 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100482 "affinity-or-anti-affinity-group": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300483 }
484 ns_request["nsr_id"] = nsr_id
485 if ns_request and ns_request.get("config-units"):
486 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300487 # Create vld
488 if nsd.get("virtual-link-desc"):
489 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
490 # Fill each vld with vnfd-connection-point-ref data
491 # TODO: Change for multiple df support
492 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
493 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
494 for vnf_profile in vnf_profiles:
495 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
496 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100497 all_vld_connection_point_data[
498 vlc.get("virtual-link-profile-id")
499 ].append(
500 {
501 "member-vnf-index-ref": cpd.get(
502 "constituent-base-element-id"
503 ),
504 "vnfd-connection-point-ref": cpd.get(
505 "constituent-cpd-id"
506 ),
507 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
508 }
509 )
garciaale7cbd03c2020-11-27 10:38:35 -0300510
bravofe76b8822021-02-26 16:57:52 -0300511 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
beierlmcee2ebf2022-03-29 17:42:48 -0400512 vnfd.pop("_admin")
garciaale7cbd03c2020-11-27 10:38:35 -0300513
514 for vdu in vnfd.get("vdu", ()):
515 flavor_data = {}
516 guest_epa = {}
517 # Find this vdu compute and storage descriptors
518 vdu_virtual_compute = {}
519 vdu_virtual_storage = {}
520 for vcd in vnfd.get("virtual-compute-desc", ()):
521 if vcd.get("id") == vdu.get("virtual-compute-desc"):
522 vdu_virtual_compute = vcd
523 for vsd in vnfd.get("virtual-storage-desc", ()):
524 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
525 vdu_virtual_storage = vsd
526 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblas4568a372021-03-24 09:19:48 +0100527 if vdu_virtual_compute.get("virtual-cpu", {}).get(
528 "num-virtual-cpu"
529 ):
530 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
531 "num-virtual-cpu"
532 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300533 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
garciadeblas4568a372021-03-24 09:19:48 +0100534 flavor_data["memory-mb"] = (
535 float(vdu_virtual_compute["virtual-memory"]["size"])
536 * 1024.0
537 )
garciaale7cbd03c2020-11-27 10:38:35 -0300538 if vdu_virtual_storage.get("size-of-storage"):
garciadeblas4568a372021-03-24 09:19:48 +0100539 flavor_data["storage-gb"] = vdu_virtual_storage[
540 "size-of-storage"
541 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300542 # Get this vdu EPA info for guest_epa
543 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100544 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
545 "cpu-quota"
546 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300547 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
548 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
549 if vcpu_pinning.get("thread-policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100550 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
551 "thread-policy"
552 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300553 if vcpu_pinning.get("policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100554 cpu_policy = (
555 "SHARED"
556 if vcpu_pinning["policy"] == "dynamic"
557 else "DEDICATED"
558 )
garciaale7cbd03c2020-11-27 10:38:35 -0300559 guest_epa["cpu-pinning-policy"] = cpu_policy
560 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100561 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
562 "mem-quota"
563 ]
564 if vdu_virtual_compute.get("virtual-memory", {}).get(
565 "mempage-size"
566 ):
567 guest_epa["mempage-size"] = vdu_virtual_compute[
568 "virtual-memory"
569 ]["mempage-size"]
570 if vdu_virtual_compute.get("virtual-memory", {}).get(
571 "numa-node-policy"
572 ):
573 guest_epa["numa-node-policy"] = vdu_virtual_compute[
574 "virtual-memory"
575 ]["numa-node-policy"]
garciaale7cbd03c2020-11-27 10:38:35 -0300576 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100577 guest_epa["disk-io-quota"] = vdu_virtual_storage[
578 "disk-io-quota"
579 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300580
581 if guest_epa:
582 flavor_data["guest-epa"] = guest_epa
583
584 flavor_data["name"] = vdu["id"][:56] + "-flv"
585 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
586 nsr_descriptor["flavor"].append(flavor_data)
587
588 sw_image_id = vdu.get("sw-image-desc")
589 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000590 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
591 self._add_image_to_nsr(nsr_descriptor, image_data)
592
593 # also add alternative images to the list of images
594 for alt_image in vdu.get("alternative-sw-image-desc", ()):
595 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
596 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300597
Alexis Romero03fb5842022-03-11 15:53:40 +0100598 # Add Affinity or Anti-affinity group information to NSR
599 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
Alexis Romeroee31f532022-04-26 19:10:21 +0200600 affinity_group_prefix_name = "{}-{}".format(
601 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
602 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100603
604 for vdu_profile in vdu_profiles:
Alexis Romeroee31f532022-04-26 19:10:21 +0200605 affinity_group_data = {}
606 for affinity_group in vdu_profile.get(
607 "affinity-or-anti-affinity-group", ()
608 ):
609 affinity_group_data = (
610 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
611 vnfd, affinity_group["id"]
612 )
613 )
614 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
615 self._add_affinity_or_anti_affinity_group_to_nsr(
616 nsr_descriptor,
617 affinity_group_data,
618 affinity_group_prefix_name,
619 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100620
garciaale7cbd03c2020-11-27 10:38:35 -0300621 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100622 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
623 vld.get("id"), []
624 )
garciaale7cbd03c2020-11-27 10:38:35 -0300625 vld["name"] = vld["id"]
626 nsr_descriptor["vld"] = nsr_vld
627
628 return nsr_descriptor
629
Alexis Romeroee31f532022-04-26 19:10:21 +0200630 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
631 self, vnfd, affinity_group_id
632 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100633 """
634 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
635 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200636 affinity_group = utils.find_in_list(
637 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
638 lambda ag: ag["id"] == affinity_group_id,
Alexis Romero03fb5842022-03-11 15:53:40 +0100639 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200640 affinity_group_data = {}
641 if affinity_group:
642 if affinity_group.get("id"):
643 affinity_group_data["ag-id"] = affinity_group["id"]
644 if affinity_group.get("type"):
645 affinity_group_data["type"] = affinity_group["type"]
646 if affinity_group.get("scope"):
647 affinity_group_data["scope"] = affinity_group["scope"]
648 return affinity_group_data
Alexis Romero03fb5842022-03-11 15:53:40 +0100649
Alexis Romeroee31f532022-04-26 19:10:21 +0200650 def _add_affinity_or_anti_affinity_group_to_nsr(
651 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
652 ):
Alexis Romero03fb5842022-03-11 15:53:40 +0100653 """
654 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
655 """
Alexis Romeroee31f532022-04-26 19:10:21 +0200656 affinity_group = next(
Alexis Romero03fb5842022-03-11 15:53:40 +0100657 (
658 f
659 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
Alexis Romeroee31f532022-04-26 19:10:21 +0200660 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
Alexis Romero03fb5842022-03-11 15:53:40 +0100661 ),
662 None,
663 )
Alexis Romeroee31f532022-04-26 19:10:21 +0200664 if not affinity_group:
665 affinity_group_data["id"] = str(
666 len(nsr_descriptor["affinity-or-anti-affinity-group"])
667 )
668 affinity_group_data["name"] = "{}-{}".format(
669 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
670 )
671 nsr_descriptor["affinity-or-anti-affinity-group"].append(
672 affinity_group_data
673 )
Alexis Romero03fb5842022-03-11 15:53:40 +0100674
lloretgalleg28c13b62021-02-08 11:48:48 +0000675 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100676 sw_image_desc = utils.find_in_list(
677 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
678 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000679 image_data = {}
680 if sw_image_desc.get("image"):
681 image_data["image"] = sw_image_desc["image"]
682 if sw_image_desc.get("checksum"):
683 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
684 if sw_image_desc.get("vim-type"):
685 image_data["vim-type"] = sw_image_desc["vim-type"]
686 return image_data
687
688 def _add_image_to_nsr(self, nsr_descriptor, image_data):
689 """
690 Adds image to nsr checking first it is not already added
691 """
garciadeblas4568a372021-03-24 09:19:48 +0100692 img = next(
693 (
694 f
695 for f in nsr_descriptor["image"]
696 if all(f.get(k) == image_data[k] for k in image_data)
697 ),
698 None,
699 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000700 if not img:
701 image_data["id"] = str(len(nsr_descriptor["image"]))
702 nsr_descriptor["image"].append(image_data)
703
garciadeblas4568a372021-03-24 09:19:48 +0100704 def _create_vnfr_descriptor_from_vnfd(
705 self,
706 nsd,
707 vnfd,
708 vnfd_id,
709 vnf_index,
710 nsr_descriptor,
711 ns_request,
712 ns_k8s_namespace,
713 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300714 vnfr_id = str(uuid4())
715 nsr_id = nsr_descriptor["id"]
716 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100717 additional_params, vnf_params = self._format_additional_params(
718 ns_request, vnf_index, descriptor=vnfd
719 )
garciaale7cbd03c2020-11-27 10:38:35 -0300720
721 vnfr_descriptor = {
722 "id": vnfr_id,
723 "_id": vnfr_id,
724 "nsr-id-ref": nsr_id,
725 "member-vnf-index-ref": vnf_index,
726 "additionalParamsForVnf": additional_params,
727 "created-time": now,
728 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
729 "vnfd-ref": vnfd_id,
730 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
731 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200732 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300733 "vdur": [],
734 "connection-point": [],
735 "ip-address": None, # mgmt-interface filled by LCM
736 }
beierlmcee2ebf2022-03-29 17:42:48 -0400737
738 # Revision backwards compatility. Only specify the revision in the record if
739 # the original VNFD has a revision.
740 if "revision" in vnfd:
741 vnfr_descriptor["revision"] = vnfd["revision"]
742
743
garciaale7cbd03c2020-11-27 10:38:35 -0300744 vnf_k8s_namespace = ns_k8s_namespace
745 if vnf_params:
746 if vnf_params.get("k8s-namespace"):
747 vnf_k8s_namespace = vnf_params["k8s-namespace"]
748 if vnf_params.get("config-units"):
749 vnfr_descriptor["config-units"] = vnf_params["config-units"]
750
751 # Create vld
752 if vnfd.get("int-virtual-link-desc"):
753 vnfr_descriptor["vld"] = []
754 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
755 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
756
757 for cp in vnfd.get("ext-cpd", ()):
758 vnf_cp = {
759 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100760 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
761 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300762 "id": cp.get("id"),
763 # "ip-address", "mac-address" # filled by LCM
764 # vim-id # TODO it would be nice having a vim port id
765 }
766 vnfr_descriptor["connection-point"].append(vnf_cp)
767
768 # Create k8s-cluster information
769 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
770 if vnfd.get("k8s-cluster"):
771 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
772 all_k8s_cluster_nets_cpds = {}
773 for cpd in get_iterable(vnfd.get("ext-cpd")):
774 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100775 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
776 "id"
777 )
garciaale7cbd03c2020-11-27 10:38:35 -0300778 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
779 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100780 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
781 net.get("id")
782 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300783
784 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300785 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100786 additional_params, kdu_params = self._format_additional_params(
787 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
788 )
garciaale7cbd03c2020-11-27 10:38:35 -0300789 kdu_k8s_namespace = vnf_k8s_namespace
790 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
791 if kdu_params and kdu_params.get("k8s-namespace"):
792 kdu_k8s_namespace = kdu_params["k8s-namespace"]
793
romeromonserbfebfc02021-05-28 10:51:35 +0200794 kdu_deployment_name = ""
795 if kdu_params and kdu_params.get("kdu-deployment-name"):
796 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
797
garciaale7cbd03c2020-11-27 10:38:35 -0300798 kdur = {
799 "additionalParams": additional_params,
800 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200801 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000802 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300803 # TODO "name": "" Name of the VDU in the VIM
804 "ip-address": None, # mgmt-interface filled by LCM
805 "k8s-cluster": {},
806 }
807 if kdu_params and kdu_params.get("config-units"):
808 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000809 if kdu.get("helm-version"):
810 kdur["helm-version"] = kdu["helm-version"]
811 for k8s_type in ("helm-chart", "juju-bundle"):
812 if kdu.get(k8s_type):
813 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300814 if not vnfr_descriptor.get("kdur"):
815 vnfr_descriptor["kdur"] = []
816 vnfr_descriptor["kdur"].append(kdur)
817
818 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300819
garciaale7cbd03c2020-11-27 10:38:35 -0300820 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300821 vdu_mgmt_cp = []
822 try:
garciadeblas4568a372021-03-24 09:19:48 +0100823 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
824 "operate-vnf-op-config"
825 ]["day1-2"]
826 vdu_config = utils.find_in_list(
827 configs, lambda config: config["id"] == vdu["id"]
828 )
bravoff3c39552021-02-24 17:22:24 -0300829 except Exception:
830 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400831
832 try:
833 vdu_instantiation_level = utils.find_in_list(
834 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100835 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400836 )
837 except Exception:
838 vdu_instantiation_level = None
839
bravoff3c39552021-02-24 17:22:24 -0300840 if vdu_config:
841 external_connection_ee = utils.filter_in_list(
842 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100843 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300844 )
845 for ee in external_connection_ee:
846 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
847
garciaale7cbd03c2020-11-27 10:38:35 -0300848 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100849 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
850 )
bravof65e22e52021-11-10 17:58:58 -0300851
852 try:
853 vdu_virtual_storage_descriptors = utils.filter_in_list(
854 vnfd.get("virtual-storage-desc", []),
855 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
856 )
857 except Exception:
858 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300859 vdur = {
860 "vdu-id-ref": vdu["id"],
861 # TODO "name": "" Name of the VDU in the VIM
862 "ip-address": None, # mgmt-interface filled by LCM
863 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
864 "internal-connection-point": [],
865 "interfaces": [],
866 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100867 "vdu-name": vdu["name"],
bravof65e22e52021-11-10 17:58:58 -0300868 "virtual-storages": vdu_virtual_storage_descriptors
garciaale7cbd03c2020-11-27 10:38:35 -0300869 }
870 if vdu_params and vdu_params.get("config-units"):
871 vdur["config-units"] = vdu_params["config-units"]
872 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100873 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
874 "boot-data-drive"
875 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300876 if vdu.get("pdu-type"):
877 vdur["pdu-type"] = vdu["pdu-type"]
878 vdur["name"] = vdu["pdu-type"]
879 # TODO volumes: name, volume-id
880 for icp in vdu.get("int-cpd", ()):
881 vdu_icp = {
882 "id": icp["id"],
883 "connection-point-id": icp["id"],
884 "name": icp.get("id"),
885 }
bravof35766442021-02-04 14:58:04 -0300886
garciaale7cbd03c2020-11-27 10:38:35 -0300887 vdur["internal-connection-point"].append(vdu_icp)
888
889 for iface in icp.get("virtual-network-interface-requirement", ()):
890 iface_fields = ("name", "mac-address")
garciadeblas4568a372021-03-24 09:19:48 +0100891 vdu_iface = {
892 x: iface[x] for x in iface_fields if iface.get(x) is not None
893 }
garciaale7cbd03c2020-11-27 10:38:35 -0300894
895 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100896 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100897 vdu_iface["port-security-enabled"] = icp[
898 "port-security-enabled"
899 ]
sousaedu003844e2021-03-02 00:19:15 +0100900
901 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100902 vdu_iface["port-security-disable-strategy"] = icp[
903 "port-security-disable-strategy"
904 ]
sousaedu003844e2021-03-02 00:19:15 +0100905
garciaale7cbd03c2020-11-27 10:38:35 -0300906 for ext_cp in vnfd.get("ext-cpd", ()):
907 if not ext_cp.get("int-cpd"):
908 continue
909 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
910 continue
911 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100912 vdu_iface["external-connection-point-ref"] = ext_cp.get(
913 "id"
914 )
sousaedu003844e2021-03-02 00:19:15 +0100915
916 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100917 vdu_iface["port-security-enabled"] = ext_cp[
918 "port-security-enabled"
919 ]
sousaedu003844e2021-03-02 00:19:15 +0100920
921 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100922 vdu_iface["port-security-disable-strategy"] = ext_cp[
923 "port-security-disable-strategy"
924 ]
sousaedu003844e2021-03-02 00:19:15 +0100925
garciaale7cbd03c2020-11-27 10:38:35 -0300926 break
927
garciadeblas4568a372021-03-24 09:19:48 +0100928 if (
929 vnfd_mgmt_cp
930 and vdu_iface.get("external-connection-point-ref")
931 == vnfd_mgmt_cp
932 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300933 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300934 vdu_iface["mgmt-interface"] = True
935
936 for ecp in vdu_mgmt_cp:
937 if vdu_iface.get("external-connection-point-ref") == ecp:
938 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300939
940 if iface.get("virtual-interface"):
941 vdu_iface.update(deepcopy(iface["virtual-interface"]))
942
943 # look for network where this interface is connected
944 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
945 if iface_ext_cp:
946 # TODO: Change for multiple df support
947 for df in get_iterable(nsd.get("df")):
948 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100949 for vlc_index, vlc in enumerate(
950 get_iterable(
951 vnf_profile.get("virtual-link-connectivity")
952 )
953 ):
954 for cpd in get_iterable(
955 vlc.get("constituent-cpd-id")
956 ):
957 if (
958 cpd.get("constituent-cpd-id")
959 == iface_ext_cp
960 ):
961 vdu_iface["ns-vld-id"] = vlc.get(
962 "virtual-link-profile-id"
963 )
garciadeblas61c95912021-02-12 11:23:50 +0000964 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100965 if vdu_iface.get("type") in (
966 "SR-IOV",
967 "PCI-PASSTHROUGH",
968 ):
969 nsr_descriptor["vld"][vlc_index][
970 "pci-interfaces"
971 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300972 break
973 elif vdu_iface.get("internal-connection-point-ref"):
974 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000975 # TODO: store fixed IP address in the record (if it exists in the ICP)
976 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
977 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100978 ivld_index = utils.find_index_in_list(
979 vnfd.get("int-virtual-link-desc", ()),
980 lambda ivld: ivld["id"]
981 == icp.get("int-virtual-link-desc"),
982 )
garciadeblas61c95912021-02-12 11:23:50 +0000983 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300984
985 vdur["interfaces"].append(vdu_iface)
986
987 if vdu.get("sw-image-desc"):
988 sw_image = utils.find_in_list(
989 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100990 lambda image: image["id"] == vdu.get("sw-image-desc"),
991 )
garciaale7cbd03c2020-11-27 10:38:35 -0300992 nsr_sw_image_data = utils.find_in_list(
993 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100994 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300995 )
996 vdur["ns-image-id"] = nsr_sw_image_data["id"]
997
lloretgalleg28c13b62021-02-08 11:48:48 +0000998 if vdu.get("alternative-sw-image-desc"):
999 alt_image_ids = []
1000 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1001 sw_image = utils.find_in_list(
1002 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +01001003 lambda image: image["id"] == alt_image_id,
1004 )
lloretgalleg28c13b62021-02-08 11:48:48 +00001005 nsr_sw_image_data = utils.find_in_list(
1006 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +01001007 lambda nsr_image: (
1008 nsr_image.get("image") == sw_image.get("image")
1009 ),
lloretgalleg28c13b62021-02-08 11:48:48 +00001010 )
1011 alt_image_ids.append(nsr_sw_image_data["id"])
1012 vdur["alt-image-ids"] = alt_image_ids
1013
garciaale7cbd03c2020-11-27 10:38:35 -03001014 flavor_data_name = vdu["id"][:56] + "-flv"
1015 nsr_flavor_desc = utils.find_in_list(
1016 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +01001017 lambda flavor: flavor["name"] == flavor_data_name,
1018 )
garciaale7cbd03c2020-11-27 10:38:35 -03001019
1020 if nsr_flavor_desc:
1021 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1022
Alexis Romero03fb5842022-03-11 15:53:40 +01001023 # Adding Affinity groups information to vdur
1024 try:
Alexis Romeroee31f532022-04-26 19:10:21 +02001025 vdu_profile_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001026 vnfd.get("df")[0]["vdu-profile"],
1027 lambda a_vdu: a_vdu["id"] == vdu["id"],
1028 )
1029 except Exception:
Alexis Romeroee31f532022-04-26 19:10:21 +02001030 vdu_profile_affinity_group = None
Alexis Romero03fb5842022-03-11 15:53:40 +01001031
Alexis Romeroee31f532022-04-26 19:10:21 +02001032 if vdu_profile_affinity_group:
1033 affinity_group_ids = []
1034 for affinity_group in vdu_profile_affinity_group.get(
1035 "affinity-or-anti-affinity-group", ()
1036 ):
1037 vdu_affinity_group = utils.find_in_list(
1038 vdu_profile_affinity_group.get(
1039 "affinity-or-anti-affinity-group", ()
1040 ),
1041 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
Alexis Romero03fb5842022-03-11 15:53:40 +01001042 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001043 nsr_affinity_group = utils.find_in_list(
Alexis Romero03fb5842022-03-11 15:53:40 +01001044 nsr_descriptor["affinity-or-anti-affinity-group"],
1045 lambda nsr_ag: (
Alexis Romeroee31f532022-04-26 19:10:21 +02001046 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1047 and nsr_ag.get("member-vnf-index")
1048 == vnfr_descriptor.get("member-vnf-index-ref")
Alexis Romero03fb5842022-03-11 15:53:40 +01001049 ),
1050 )
Alexis Romeroee31f532022-04-26 19:10:21 +02001051 # Update Affinity Group VIM name if VDU instantiation parameter is present
1052 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1053 vnf_params_affinity_group = utils.find_in_list(
1054 vnf_params["affinity-or-anti-affinity-group"],
1055 lambda vnfp_ag: (
1056 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1057 ),
1058 )
1059 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1060 nsr_affinity_group[
1061 "vim-affinity-group-id"
1062 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1063 affinity_group_ids.append(nsr_affinity_group["id"])
1064 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
Alexis Romero03fb5842022-03-11 15:53:40 +01001065
bravof4ca51522021-04-22 10:03:02 -04001066 if vdu_instantiation_level:
1067 count = vdu_instantiation_level.get("number-of-instances")
1068 else:
1069 count = 1
1070
garciaale7cbd03c2020-11-27 10:38:35 -03001071 for index in range(0, count):
1072 vdur = deepcopy(vdur)
1073 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001074 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001075 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001076 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001077 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1078
1079 vdur["_id"] = str(uuid4())
1080 vdur["id"] = vdur["_id"]
1081 vdur["count-index"] = index
1082 vnfr_descriptor["vdur"].append(vdur)
1083
1084 return vnfr_descriptor
1085
K Sai Kiran57589552021-01-27 21:38:34 +05301086 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1087 """
1088 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1089 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1090 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1091 :param ns_instance_content: ns instance content
1092 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1093 :return: None
1094 """
1095 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
1096 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
1097 threshold_reached = time_delta > 120
1098 if force_refresh or threshold_reached:
1099 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1100 ns_instance_content["_admin"]["modified"] = time_now
1101 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1102 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
1103 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1104 nslcmop_desc["_admin"].pop("nsState")
1105 self.msg.write("ns", operation, nslcmop_desc)
1106 return
1107
1108 def show(self, session, _id, filter_q=None, api_req=False):
1109 """
1110 Get complete information on an ns instance.
1111 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1112 :param _id: string, ns instance id
1113 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1114 :param api_req: True if this call is serving an external API request. False if serving internal request.
1115 :return: dictionary, raise exception if not found.
1116 """
1117 ns_instance_content = super().show(session, _id, api_req)
1118 self.vca_status_refresh(session, ns_instance_content, filter_q)
1119 return ns_instance_content
1120
tierno65ca36d2019-02-12 19:27:52 +01001121 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001122 raise EngineException(
1123 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1124 )
tiernob24258a2018-10-04 18:39:49 +02001125
1126
1127class VnfrTopic(BaseTopic):
1128 topic = "vnfrs"
1129 topic_msg = None
1130
delacruzramo32bab472019-09-13 12:24:22 +02001131 def __init__(self, db, fs, msg, auth):
1132 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001133
tiernobee3bad2019-12-05 12:26:01 +00001134 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001135 raise EngineException(
1136 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1137 )
tiernob24258a2018-10-04 18:39:49 +02001138
tierno65ca36d2019-02-12 19:27:52 +01001139 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001140 raise EngineException(
1141 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1142 )
tiernob24258a2018-10-04 18:39:49 +02001143
tierno65ca36d2019-02-12 19:27:52 +01001144 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001145 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001146 raise EngineException(
1147 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1148 )
tiernob24258a2018-10-04 18:39:49 +02001149
1150
1151class NsLcmOpTopic(BaseTopic):
1152 topic = "nslcmops"
1153 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001154 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001155 "instantiate": ns_instantiate,
1156 "action": ns_action,
1157 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +00001158 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +02001159 }
1160
delacruzramo32bab472019-09-13 12:24:22 +02001161 def __init__(self, db, fs, msg, auth):
1162 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001163
tiernob24258a2018-10-04 18:39:49 +02001164 def _check_ns_operation(self, session, nsr, operation, indata):
1165 """
1166 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001167 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001168 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1169 :param indata: descriptor with the parameters of the operation
1170 :return: None
1171 """
garciaale7cbd03c2020-11-27 10:38:35 -03001172 if operation == "action":
1173 self._check_action_ns_operation(indata, nsr)
1174 elif operation == "scale":
1175 self._check_scale_ns_operation(indata, nsr)
1176 elif operation == "instantiate":
1177 self._check_instantiate_ns_operation(indata, nsr, session)
1178
1179 def _check_action_ns_operation(self, indata, nsr):
1180 nsd = nsr["nsd"]
1181 # check vnf_member_index
1182 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001183 indata["member_vnf_index"] = indata.pop(
1184 "vnf_member_index"
1185 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001186 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001187 vnfd = self._get_vnfd_from_vnf_member_index(
1188 indata["member_vnf_index"], nsr["_id"]
1189 )
bravof41a52052021-02-17 18:08:01 -03001190 try:
garciadeblas4568a372021-03-24 09:19:48 +01001191 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1192 "operate-vnf-op-config"
1193 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001194 except Exception:
1195 configs = []
1196
garciaale7cbd03c2020-11-27 10:38:35 -03001197 if indata.get("vdu_id"):
1198 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001199 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001200 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001201 )
garciaale7cbd03c2020-11-27 10:38:35 -03001202 elif indata.get("kdu_name"):
1203 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001204 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001205 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001206 )
garciaale7cbd03c2020-11-27 10:38:35 -03001207 else:
bravof41a52052021-02-17 18:08:01 -03001208 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001209 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001210 )
1211 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001212 descriptor_configuration = descriptor_configuration.get(
1213 "config-primitive"
1214 )
garciaale7cbd03c2020-11-27 10:38:35 -03001215 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001216 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1217 "config-primitive"
1218 )
garciaale7cbd03c2020-11-27 10:38:35 -03001219
1220 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001221 if indata.get("kdu_name") and indata["primitive"] in (
1222 "upgrade",
1223 "rollback",
1224 "status",
1225 "inspect",
1226 "readme",
1227 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001228 # TODO should be checked that rollback only can contains revsision_numbe????
1229 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001230 raise EngineException(
1231 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1232 indata["primitive"]
1233 )
1234 )
garciaale7cbd03c2020-11-27 10:38:35 -03001235 return
1236 # if not, check primitive
1237 for config_primitive in get_iterable(descriptor_configuration):
1238 if indata["primitive"] == config_primitive["name"]:
1239 # check needed primitive_params are provided
1240 if indata.get("primitive_params"):
1241 in_primitive_params_copy = copy(indata["primitive_params"])
1242 else:
1243 in_primitive_params_copy = {}
1244 for paramd in get_iterable(config_primitive.get("parameter")):
1245 if paramd["name"] in in_primitive_params_copy:
1246 del in_primitive_params_copy[paramd["name"]]
1247 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001248 raise EngineException(
1249 "Needed parameter {} not provided for primitive '{}'".format(
1250 paramd["name"], indata["primitive"]
1251 )
1252 )
garciaale7cbd03c2020-11-27 10:38:35 -03001253 # check no extra primitive params are provided
1254 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001255 raise EngineException(
1256 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1257 list(in_primitive_params_copy.keys()), indata["primitive"]
1258 )
1259 )
garciaale7cbd03c2020-11-27 10:38:35 -03001260 break
1261 else:
garciadeblas4568a372021-03-24 09:19:48 +01001262 raise EngineException(
1263 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1264 indata["primitive"]
1265 )
1266 )
garciaale7cbd03c2020-11-27 10:38:35 -03001267
1268 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001269 vnfd = self._get_vnfd_from_vnf_member_index(
1270 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1271 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001272 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001273 if (
1274 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1275 == scaling_aspect["id"]
1276 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001277 break
1278 else:
garciadeblas4568a372021-03-24 09:19:48 +01001279 raise EngineException(
1280 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1281 "present at vnfd:scaling-aspect".format(
1282 indata["scaleVnfData"]["scaleByStepData"][
1283 "scaling-group-descriptor"
1284 ]
1285 )
1286 )
garciaale7cbd03c2020-11-27 10:38:35 -03001287
1288 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001289 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001290 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001291 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001292 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001293 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1294 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1295 for in_vnf in get_iterable(indata.get("vnf")):
1296 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001297 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001298 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001299 else:
garciadeblas4568a372021-03-24 09:19:48 +01001300 vnfd = self._get_vnfd_from_vnf_member_index(
1301 member_vnf_index, nsr["_id"]
1302 )
1303 vnf_member_index_to_vnfd[
1304 member_vnf_index
1305 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001306 self._check_vnf_instantiation_params(in_vnf, vnfd)
1307 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001308 self._check_valid_vim_account(
1309 in_vnf["vimAccountId"], vim_accounts, session
1310 )
tierno260dd6f2019-09-02 10:48:56 +00001311
garciaale7cbd03c2020-11-27 10:38:35 -03001312 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001313 self._check_valid_wim_account(
1314 in_vld.get("wimAccountId"), wim_accounts, session
1315 )
garciaale7cbd03c2020-11-27 10:38:35 -03001316 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1317 if in_vld["name"] == vldd["id"]:
1318 break
tierno9cb7d672019-10-30 12:13:48 +00001319 else:
garciadeblas4568a372021-03-24 09:19:48 +01001320 raise EngineException(
1321 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1322 in_vld["name"]
1323 )
1324 )
tierno9cb7d672019-10-30 12:13:48 +00001325
garciaale7cbd03c2020-11-27 10:38:35 -03001326 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1327 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001328 vnfr = self.db.get_one(
1329 "vnfrs",
1330 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1331 fail_on_empty=False,
1332 )
garciaale7cbd03c2020-11-27 10:38:35 -03001333 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001334 raise EngineException(
1335 "Invalid parameter member_vnf_index='{}' is not one of the "
1336 "nsd:constituent-vnfd".format(member_vnf_index)
1337 )
beierlmcee2ebf2022-03-29 17:42:48 -04001338
1339 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1340 if "revision" in vnfr:
1341 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
1342 vnfd = self.db.get_one("vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False)
1343 else:
1344 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1345
garciaale7cbd03c2020-11-27 10:38:35 -03001346 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001347 raise EngineException(
1348 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1349 vnfr["vnfd-id"]
1350 )
1351 )
garciaale7cbd03c2020-11-27 10:38:35 -03001352 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001353
garciaale7cbd03c2020-11-27 10:38:35 -03001354 def _check_valid_vdu(self, vnfd, vdu_id):
1355 for vdud in get_iterable(vnfd.get("vdu")):
1356 if vdud["id"] == vdu_id:
1357 return vdud
1358 else:
garciadeblas4568a372021-03-24 09:19:48 +01001359 raise EngineException(
1360 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1361 vdu_id
1362 )
1363 )
garciaale7cbd03c2020-11-27 10:38:35 -03001364
1365 def _check_valid_kdu(self, vnfd, kdu_name):
1366 for kdud in get_iterable(vnfd.get("kdu")):
1367 if kdud["name"] == kdu_name:
1368 return kdud
1369 else:
garciadeblas4568a372021-03-24 09:19:48 +01001370 raise EngineException(
1371 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1372 kdu_name
1373 )
1374 )
garciaale7cbd03c2020-11-27 10:38:35 -03001375
1376 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1377 for in_vdu in get_iterable(in_vnf.get("vdu")):
1378 for vdu in get_iterable(vnfd.get("vdu")):
1379 if in_vdu["id"] == vdu["id"]:
1380 for volume in get_iterable(in_vdu.get("volume")):
1381 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1382 if volumed["id"] == volume["name"]:
1383 break
1384 else:
garciadeblas4568a372021-03-24 09:19:48 +01001385 raise EngineException(
1386 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1387 "volume:name='{}' is not present at "
1388 "vnfd:vdu:virtual-storage-desc list".format(
1389 in_vnf["member-vnf-index"],
1390 in_vdu["id"],
1391 volume["id"],
1392 )
1393 )
garciaale7cbd03c2020-11-27 10:38:35 -03001394
1395 vdu_if_names = set()
1396 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001397 for iface in get_iterable(
1398 cpd.get("virtual-network-interface-requirement")
1399 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001400 vdu_if_names.add(iface.get("name"))
1401
1402 for in_iface in get_iterable(in_vdu["interface"]):
1403 if in_iface["name"] in vdu_if_names:
1404 break
1405 else:
garciadeblas4568a372021-03-24 09:19:48 +01001406 raise EngineException(
1407 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1408 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1409 in_vnf["member-vnf-index"],
1410 in_vdu["id"],
1411 in_iface["name"],
1412 )
1413 )
garciaale7cbd03c2020-11-27 10:38:35 -03001414 break
1415
1416 else:
garciadeblas4568a372021-03-24 09:19:48 +01001417 raise EngineException(
1418 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1419 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1420 )
garciaale7cbd03c2020-11-27 10:38:35 -03001421
garciadeblas4568a372021-03-24 09:19:48 +01001422 vnfd_ivlds_cpds = {
1423 ivld.get("id"): set()
1424 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1425 }
garciaale7cbd03c2020-11-27 10:38:35 -03001426 for vdu in get_iterable(vnfd.get("vdu")):
1427 for cpd in get_iterable(vnfd.get("int-cpd")):
1428 if cpd.get("int-virtual-link-desc"):
1429 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1430
1431 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1432 if in_ivld.get("name") in vnfd_ivlds_cpds:
1433 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1434 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001435 break
tiernob24258a2018-10-04 18:39:49 +02001436 else:
garciadeblas4568a372021-03-24 09:19:48 +01001437 raise EngineException(
1438 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1439 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1440 "vnfd:internal-vld:name/id:internal-connection-point".format(
1441 in_vnf["member-vnf-index"],
1442 in_ivld["name"],
1443 in_icp["id-ref"],
1444 )
1445 )
tiernob24258a2018-10-04 18:39:49 +02001446 else:
garciadeblas4568a372021-03-24 09:19:48 +01001447 raise EngineException(
1448 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1449 " is not present at vnfd '{}'".format(
1450 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1451 )
1452 )
tiernob24258a2018-10-04 18:39:49 +02001453
garciaale7cbd03c2020-11-27 10:38:35 -03001454 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1455 if vim_account in vim_accounts:
1456 return
1457 try:
1458 db_filter = self._get_project_filter(session)
1459 db_filter["_id"] = vim_account
1460 self.db.get_one("vim_accounts", db_filter)
1461 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001462 raise EngineException(
1463 "Invalid vimAccountId='{}' not present for the project".format(
1464 vim_account
1465 )
1466 )
garciaale7cbd03c2020-11-27 10:38:35 -03001467 vim_accounts.append(vim_account)
1468
David Garcia98de2982021-10-13 17:14:01 +02001469 def _get_vim_account(self, vim_id: str, session):
1470 try:
1471 db_filter = self._get_project_filter(session)
1472 db_filter["_id"] = vim_id
1473 return self.db.get_one("vim_accounts", db_filter)
1474 except Exception:
1475 raise EngineException(
1476 "Invalid vimAccountId='{}' not present for the project".format(
1477 vim_id
1478 )
1479 )
1480
garciaale7cbd03c2020-11-27 10:38:35 -03001481 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1482 if not isinstance(wim_account, str):
1483 return
1484 if wim_account in wim_accounts:
1485 return
1486 try:
1487 db_filter = self._get_project_filter(session, write=False, show_all=True)
1488 db_filter["_id"] = wim_account
1489 self.db.get_one("wim_accounts", db_filter)
1490 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001491 raise EngineException(
1492 "Invalid wimAccountId='{}' not present for the project".format(
1493 wim_account
1494 )
1495 )
garciaale7cbd03c2020-11-27 10:38:35 -03001496 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001497
garciadeblas4568a372021-03-24 09:19:48 +01001498 def _look_for_pdu(
1499 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1500 ):
tiernocc103432018-10-19 14:10:35 +02001501 """
tierno36ec8602018-11-02 17:27:11 +01001502 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1503 (ip_address, ...) information.
1504 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001505 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001506 :param rollback: list with the database modifications to rollback if needed
1507 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1508 :param vim_account: vim_account where this vnfr should be deployed
1509 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1510 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1511 of the changed vnfr is needed
1512
1513 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1514 "vim-network-name": used at VIM
1515 "name": interface name
1516 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1517 "ns-vld-id": NSD vld where this interface is connected.
1518 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 +02001519 """
tierno36ec8602018-11-02 17:27:11 +01001520
1521 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001522 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1523 if not vdur.get("pdu-type"):
1524 continue
1525 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001526 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001527 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001528 pdu_filter["type"] = pdu_type
1529 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001530 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001531 # TODO feature 1417: "shared": True,
1532
1533 available_pdus = self.db.get_list("pdus", pdu_filter)
1534 for pdu in available_pdus:
1535 # step 1 check if this pdu contains needed interfaces:
1536 match_interfaces = True
1537 for vdur_interface in vdur["interfaces"]:
1538 for pdu_interface in pdu["interfaces"]:
1539 if pdu_interface["name"] == vdur_interface["name"]:
1540 # TODO feature 1417: match per mgmt type
1541 break
1542 else: # no interface found for name
1543 match_interfaces = False
1544 break
1545 if match_interfaces:
1546 break
1547 else:
1548 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001549 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001550 "names".format(
1551 pdu_type,
1552 vim_account,
1553 vnfr["member-vnf-index-ref"],
1554 vdur["vdu-id-ref"],
1555 )
1556 )
tiernocc103432018-10-19 14:10:35 +02001557
1558 # step 2. Update pdu
1559 rollback_pdu = {
1560 "_admin.usageState": pdu["_admin"]["usageState"],
1561 "_admin.usage.vnfr_id": None,
1562 "_admin.usage.nsr_id": None,
1563 "_admin.usage.vdur": None,
1564 }
garciadeblas4568a372021-03-24 09:19:48 +01001565 self.db.set_one(
1566 "pdus",
1567 {"_id": pdu["_id"]},
1568 {
1569 "_admin.usageState": "IN_USE",
1570 "_admin.usage": {
1571 "vnfr_id": vnfr["_id"],
1572 "nsr_id": vnfr["nsr-id-ref"],
1573 "vdur": vdur["vdu-id-ref"],
1574 },
1575 },
1576 )
1577 rollback.append(
1578 {
1579 "topic": "pdus",
1580 "_id": pdu["_id"],
1581 "operation": "set",
1582 "content": rollback_pdu,
1583 }
1584 )
tiernocc103432018-10-19 14:10:35 +02001585
1586 # step 3. Fill vnfr info by filling vdur
1587 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001588 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001589 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1590 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1591 for pdu_interface in pdu["interfaces"]:
1592 if pdu_interface["name"] == vdur_interface["name"]:
1593 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1594 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001595 if k in (
1596 "ip-address",
1597 "mac-address",
1598 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001599 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001600 vnfr_update_rollback[
1601 iface_text + ".{}".format(k)
1602 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001603 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001604 if vdur_interface.get(
1605 "mgmt-interface"
1606 ) or vdur_interface.get("mgmt-vnf"):
1607 vnfr_update_rollback[
1608 vdu_text + ".ip-address"
1609 ] = vdur.get("ip-address")
1610 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1611 "ip-address"
1612 ]
tierno36ec8602018-11-02 17:27:11 +01001613 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001614 vnfr_update_rollback["ip-address"] = vnfr.get(
1615 "ip-address"
1616 )
tierno36ec8602018-11-02 17:27:11 +01001617 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001618 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1619 "ip-address"
1620 ]
1621 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1622 "vim-network-id"
1623 ):
1624 ifaces_forcing_vim_network.append(
1625 {
1626 "name": vdur_interface.get("vnf-vld-id")
1627 or vdur_interface.get("ns-vld-id"),
1628 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1629 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1630 }
1631 )
gcalvino17d5b732018-12-17 16:26:21 +01001632 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001633 ifaces_forcing_vim_network[-1][
1634 "vim-network-id"
1635 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001636 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001637 ifaces_forcing_vim_network[-1][
1638 "vim-network-name"
1639 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001640 break
1641
tierno36ec8602018-11-02 17:27:11 +01001642 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001643
garciadeblas4568a372021-03-24 09:19:48 +01001644 def _look_for_k8scluster(
1645 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1646 ):
tierno9cb7d672019-10-30 12:13:48 +00001647 """
1648 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1649 Fills vnfr.kdur with the selected k8scluster
1650
1651 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1652 :param rollback: list with the database modifications to rollback if needed
1653 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1654 :param vim_account: vim_account where this vnfr should be deployed
1655 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1656 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1657 of the changed vnfr is needed
1658
1659 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1660 "vim-network-name": used at VIM
1661 "name": interface name
1662 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1663 "ns-vld-id": NSD vld where this interface is connected.
1664 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1665 """
1666
1667 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001668 if not vnfr.get("kdur"):
1669 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001670
tiernoc67b0e92019-11-05 12:45:29 +00001671 kdu_filter = self._get_project_filter(session)
1672 kdu_filter["vim_account"] = vim_account
1673 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1674 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1675
1676 k8s_requirements = {} # just for logging
1677 for k8scluster in available_k8sclusters:
1678 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001679 break
tiernoc67b0e92019-11-05 12:45:29 +00001680 # restrict by cni
1681 if vnfr["k8s-cluster"].get("cni"):
1682 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001683 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1684 k8scluster.get("cni", ())
1685 ):
tiernoc67b0e92019-11-05 12:45:29 +00001686 continue
1687 # restrict by version
1688 if vnfr["k8s-cluster"].get("version"):
1689 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1690 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1691 continue
1692 # restrict by number of networks
1693 if vnfr["k8s-cluster"].get("nets"):
1694 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001695 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1696 vnfr["k8s-cluster"]["nets"]
1697 ):
tiernoc67b0e92019-11-05 12:45:29 +00001698 continue
1699 break
1700 else:
garciadeblas4568a372021-03-24 09:19:48 +01001701 raise EngineException(
1702 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1703 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1704 )
1705 )
tierno9cb7d672019-10-30 12:13:48 +00001706
tiernoc67b0e92019-11-05 12:45:29 +00001707 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001708 # step 3. Fill vnfr info by filling kdur
1709 kdu_text = "kdur.{}.".format(kdur_index)
1710 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1711 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1712
tiernoc67b0e92019-11-05 12:45:29 +00001713 # step 4. Check VIM networks that forces the selected k8s_cluster
1714 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1715 k8scluster_net_list = list(k8scluster.get("nets").keys())
1716 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1717 # get a network from k8s_cluster nets. If name matches use this, if not use other
1718 if kdur_net["id"] in k8scluster_net_list: # name matches
1719 vim_net = k8scluster["nets"][kdur_net["id"]]
1720 k8scluster_net_list.remove(kdur_net["id"])
1721 else:
1722 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1723 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001724 vnfr_update_rollback[
1725 "k8s-cluster.nets.{}.vim_net".format(net_index)
1726 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001727 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001728 if vim_net and (
1729 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1730 ):
1731 ifaces_forcing_vim_network.append(
1732 {
1733 "name": kdur_net.get("vnf-vld-id")
1734 or kdur_net.get("ns-vld-id"),
1735 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1736 "ns-vld-id": kdur_net.get("ns-vld-id"),
1737 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1738 }
1739 )
tiernoc67b0e92019-11-05 12:45:29 +00001740 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001741 return ifaces_forcing_vim_network
1742
Gulsum Aticie395aa42021-11-10 20:59:06 +03001743 def _update_vnfrs_from_nsd(self, nsr):
1744 try:
1745 nsr_id = nsr["_id"]
1746 nsd = nsr["nsd"]
1747
1748 step = "Getting vnf_profiles from nsd"
1749 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1750 vld_fixed_ip_connection_point_data = {}
1751
1752 step = "Getting ip-address info from vnf_profile if it exists"
1753 for vnfp in vnf_profiles:
1754 # Checking ip-address info from nsd.vnf_profile and storing
1755 for vlc in vnfp.get("virtual-link-connectivity", ()):
1756 for cpd in vlc.get("constituent-cpd-id", ()):
1757 if cpd.get("ip-address"):
1758 step = "Storing ip-address info"
1759 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1760 "vnfd-connection-point-ref": cpd.get(
1761 "constituent-cpd-id"),
1762 "ip-address": cpd.get(
1763 "ip-address")}})
1764
1765 # Inserting ip address to vnfr
1766 if len(vld_fixed_ip_connection_point_data) > 0:
1767 step = "Getting vnfrs"
1768 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1769 for item in vld_fixed_ip_connection_point_data.keys():
1770 step = "Filtering vnfrs"
1771 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1772 if vnfr:
1773 vnfr_update = {}
1774 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1775 for iface_index, iface in enumerate(vdur["interfaces"]):
1776 step = "Looking for matched interface"
1777 if (
1778 iface.get("external-connection-point-ref")
1779 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1780 iface.get("ns-vld-id") == item.split('.')[0]
1781
1782 ):
1783 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1784 vdur_index, iface_index
1785 )
1786 step = "Storing info in order to update vnfr"
1787 vnfr_update[
1788 vnfr_update_text + ".ip-address"
1789 ] = increment_ip_mac(
1790 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1791 vdur.get("count-index", 0), )
1792 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1793
1794 step = "updating vnfr at database"
1795 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1796 except (
1797 ValidationError,
1798 EngineException,
1799 DbException,
1800 MsgException,
1801 FsException,
1802 ) as e:
1803 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1804
tiernocc103432018-10-19 14:10:35 +02001805 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001806 # get vnfr
1807 nsr_id = nsr["_id"]
1808 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1809
1810 for vnfr in vnfrs:
1811 vnfr_update = {}
1812 vnfr_update_rollback = {}
1813 member_vnf_index = vnfr["member-vnf-index-ref"]
1814 # update vim-account-id
1815
1816 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02001817 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001818 # check instantiate parameters
1819 for vnf_inst_params in get_iterable(indata.get("vnf")):
1820 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1821 continue
1822 if vnf_inst_params.get("vimAccountId"):
1823 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02001824 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001825
tiernocddb07d2020-10-06 08:28:00 +00001826 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1827 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1828 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1829 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1830 continue
garciadeblas4568a372021-03-24 09:19:48 +01001831 for iface_inst_param in get_iterable(
1832 vdu_inst_param.get("interface")
1833 ):
1834 iface_index, _ = next(
1835 i
1836 for i in enumerate(vdur["interfaces"])
1837 if i[1]["name"] == iface_inst_param["name"]
1838 )
1839 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1840 vdur_index, iface_index
1841 )
tiernocddb07d2020-10-06 08:28:00 +00001842 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001843 vnfr_update[
1844 vnfr_update_text + ".ip-address"
1845 ] = increment_ip_mac(
1846 iface_inst_param.get("ip-address"),
1847 vdur.get("count-index", 0),
1848 )
tierno1bd9d952020-11-13 15:56:51 +00001849 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001850 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001851 vnfr_update[
1852 vnfr_update_text + ".mac-address"
1853 ] = increment_ip_mac(
1854 iface_inst_param.get("mac-address"),
1855 vdur.get("count-index", 0),
1856 )
tierno1bd9d952020-11-13 15:56:51 +00001857 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001858 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001859 vnfr_update[
1860 vnfr_update_text + ".floating-ip-required"
1861 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001862 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1863 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001864 for ivld_inst_param in get_iterable(
1865 vnf_inst_params.get("internal-vld")
1866 ):
1867 for icp_inst_param in get_iterable(
1868 ivld_inst_param.get("internal-connection-point")
1869 ):
tiernocddb07d2020-10-06 08:28:00 +00001870 # look for iface
1871 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1872 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001873 if (
1874 iface.get("internal-connection-point-ref")
1875 == icp_inst_param["id-ref"]
1876 ):
1877 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1878 vdur_index, iface_index
1879 )
tiernocddb07d2020-10-06 08:28:00 +00001880 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001881 vnfr_update[
1882 vnfr_update_text + ".ip-address"
1883 ] = increment_ip_mac(
1884 icp_inst_param.get("ip-address"),
1885 vdur.get("count-index", 0),
1886 )
1887 vnfr_update[
1888 vnfr_update_text + ".fixed-ip"
1889 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001890 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001891 vnfr_update[
1892 vnfr_update_text + ".mac-address"
1893 ] = increment_ip_mac(
1894 icp_inst_param.get("mac-address"),
1895 vdur.get("count-index", 0),
1896 )
1897 vnfr_update[
1898 vnfr_update_text + ".fixed-mac"
1899 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001900 break
1901 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1902 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001903 for vnfcp_inst_param in get_iterable(
1904 vld_inst_param.get("vnfd-connection-point-ref")
1905 ):
tiernocddb07d2020-10-06 08:28:00 +00001906 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1907 continue
1908 # look for iface
1909 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1910 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001911 if (
1912 iface.get("external-connection-point-ref")
1913 == vnfcp_inst_param["vnfd-connection-point-ref"]
1914 ):
1915 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1916 vdur_index, iface_index
1917 )
tiernocddb07d2020-10-06 08:28:00 +00001918 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001919 vnfr_update[
1920 vnfr_update_text + ".ip-address"
1921 ] = increment_ip_mac(
1922 vnfcp_inst_param.get("ip-address"),
1923 vdur.get("count-index", 0),
1924 )
tierno1bd9d952020-11-13 15:56:51 +00001925 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001926 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001927 vnfr_update[
1928 vnfr_update_text + ".mac-address"
1929 ] = increment_ip_mac(
1930 vnfcp_inst_param.get("mac-address"),
1931 vdur.get("count-index", 0),
1932 )
tierno1bd9d952020-11-13 15:56:51 +00001933 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001934 break
1935
tiernocc103432018-10-19 14:10:35 +02001936 vnfr_update["vim-account-id"] = vim_account
1937 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1938
David Garciaecb41322021-03-31 19:10:46 +02001939 if vca_id:
1940 vnfr_update["vca-id"] = vca_id
1941 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1942
tiernocc103432018-10-19 14:10:35 +02001943 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01001944 ifaces_forcing_vim_network = self._look_for_pdu(
1945 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1946 )
tiernocc103432018-10-19 14:10:35 +02001947
tierno9cb7d672019-10-30 12:13:48 +00001948 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01001949 ifaces_forcing_vim_network += self._look_for_k8scluster(
1950 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1951 )
tierno9cb7d672019-10-30 12:13:48 +00001952 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001953 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01001954 rollback.append(
1955 {
1956 "topic": "vnfrs",
1957 "_id": vnfr["_id"],
1958 "operation": "set",
1959 "content": vnfr_update_rollback,
1960 }
1961 )
tierno36ec8602018-11-02 17:27:11 +01001962
1963 # Update indada in case pdu forces to use a concrete vim-network-name
1964 # TODO check if user has already insert a vim-network-name and raises an error
1965 if not ifaces_forcing_vim_network:
1966 continue
1967 for iface_info in ifaces_forcing_vim_network:
1968 if iface_info.get("ns-vld-id"):
1969 if "vld" not in indata:
1970 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001971 indata["vld"].append(
1972 {
1973 key: iface_info[key]
1974 for key in ("name", "vim-network-name", "vim-network-id")
1975 if iface_info.get(key)
1976 }
1977 )
tierno36ec8602018-11-02 17:27:11 +01001978
1979 elif iface_info.get("vnf-vld-id"):
1980 if "vnf" not in indata:
1981 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001982 indata["vnf"].append(
1983 {
1984 "member-vnf-index": member_vnf_index,
1985 "internal-vld": [
1986 {
1987 key: iface_info[key]
1988 for key in (
1989 "name",
1990 "vim-network-name",
1991 "vim-network-id",
1992 )
1993 if iface_info.get(key)
1994 }
1995 ],
1996 }
1997 )
tierno36ec8602018-11-02 17:27:11 +01001998
1999 @staticmethod
2000 def _create_nslcmop(nsr_id, operation, params):
2001 """
2002 Creates a ns-lcm-opp content to be stored at database.
2003 :param nsr_id: internal id of the instance
2004 :param operation: instantiate, terminate, scale, action, ...
2005 :param params: user parameters for the operation
2006 :return: dictionary following SOL005 format
2007 """
tiernob24258a2018-10-04 18:39:49 +02002008 now = time()
2009 _id = str(uuid4())
2010 nslcmop = {
2011 "id": _id,
2012 "_id": _id,
2013 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00002014 "queuePosition": None,
2015 "stage": None,
2016 "errorMessage": None,
2017 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02002018 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01002019 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02002020 "lcmOperationType": operation,
2021 "startTime": now,
2022 "isAutomaticInvocation": False,
2023 "operationParams": params,
2024 "isCancelPending": False,
2025 "links": {
2026 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01002027 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01002028 },
tiernob24258a2018-10-04 18:39:49 +02002029 }
2030 return nslcmop
2031
magnussonlf318b302020-01-20 18:38:18 +01002032 def _get_enabled_vims(self, session):
2033 """
2034 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2035 :param session: current session with user information
2036 """
2037 db_filter = self._get_project_filter(session)
2038 db_filter["_admin.operationalState"] = "ENABLED"
2039 vims = self.db.get_list("vim_accounts", db_filter)
2040 vimAccounts = []
2041 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01002042 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002043 return vimAccounts
2044
garciadeblas4568a372021-03-24 09:19:48 +01002045 def new(
2046 self,
2047 rollback,
2048 session,
2049 indata=None,
2050 kwargs=None,
2051 headers=None,
2052 slice_object=False,
2053 ):
tiernob24258a2018-10-04 18:39:49 +02002054 """
2055 Performs a new operation over a ns
2056 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002057 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002058 :param indata: descriptor with the parameters of the operation. It must contains among others
2059 nsInstanceId: _id of the nsr to perform the operation
2060 operation: it can be: instantiate, terminate, action, TODO: update, heal
2061 :param kwargs: used to override the indata descriptor
2062 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002063 :return: id of the nslcmops
2064 """
garciadeblas4568a372021-03-24 09:19:48 +01002065
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002066 def check_if_nsr_is_not_slice_member(session, nsr_id):
2067 nsis = None
2068 db_filter = self._get_project_filter(session)
2069 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002070 nsis = self.db.get_one(
2071 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2072 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002073 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002074 raise EngineException(
2075 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2076 nsr_id, nsis["_id"]
2077 ),
2078 http_code=HTTPStatus.CONFLICT,
2079 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002080
tiernob24258a2018-10-04 18:39:49 +02002081 try:
2082 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002083 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002084 operation = indata["lcmOperationType"]
2085 nsInstanceId = indata["nsInstanceId"]
2086
2087 validate_input(indata, self.operation_schema[operation])
2088 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002089 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002090 _filter["_id"] = nsInstanceId
2091 nsr = self.db.get_one("nsrs", _filter)
2092
2093 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002094 if operation == "terminate" and slice_object is False:
2095 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002096 if (
2097 not nsr["_admin"].get("nsState")
2098 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2099 ):
tiernob24258a2018-10-04 18:39:49 +02002100 if operation == "terminate" and indata.get("autoremove"):
2101 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002102 return (
2103 None,
2104 None,
2105 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002106 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002107 raise EngineException(
2108 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2109 nsInstanceId, operation
2110 ),
2111 HTTPStatus.CONFLICT,
2112 )
tiernob24258a2018-10-04 18:39:49 +02002113 else:
tierno65ca36d2019-02-12 19:27:52 +01002114 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002115 raise EngineException(
2116 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2117 nsInstanceId, operation
2118 ),
2119 HTTPStatus.CONFLICT,
2120 )
tiernob24258a2018-10-04 18:39:49 +02002121 self._check_ns_operation(session, nsr, operation, indata)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002122 if (indata.get("primitive_params")):
2123 indata["primitive_params"] = json.dumps(indata["primitive_params"])
2124 elif (indata.get("additionalParamsForVnf")):
2125 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
tierno36ec8602018-11-02 17:27:11 +01002126
tiernocc103432018-10-19 14:10:35 +02002127 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002128 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002129 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01002130
2131 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002132 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002133 self.format_on_new(
2134 nslcmop_desc, session["project_id"], make_public=session["public"]
2135 )
magnussonlf318b302020-01-20 18:38:18 +01002136 if indata.get("placement-engine"):
2137 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002138 nslcmop_desc["operationParams"][
2139 "validVimAccounts"
2140 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002141 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002142 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002143 if not slice_object:
2144 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002145 return _id, None
2146 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002147 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2148 # except DbException as e:
2149 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2150
tiernobee3bad2019-12-05 12:26:01 +00002151 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002152 raise EngineException(
2153 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2154 )
tiernob24258a2018-10-04 18:39:49 +02002155
tierno65ca36d2019-02-12 19:27:52 +01002156 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002157 raise EngineException(
2158 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2159 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002160
2161
2162class NsiTopic(BaseTopic):
2163 topic = "nsis"
2164 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002165 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002166
delacruzramo32bab472019-09-13 12:24:22 +02002167 def __init__(self, db, fs, msg, auth):
2168 BaseTopic.__init__(self, db, fs, msg, auth)
2169 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002170
Felipe Vicensc37b3842019-01-12 12:24:42 +01002171 @staticmethod
2172 def _format_ns_request(ns_request):
2173 formated_request = copy(ns_request)
2174 # TODO: Add request params
2175 return formated_request
2176
2177 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002178 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002179 """
2180 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002181 :param slice_request: User instantiation additional parameters
2182 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002183 """
tiernofd160572019-01-21 10:41:37 +00002184 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2185 if additional_params:
2186 for k, v in additional_params.items():
2187 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002188 raise EngineException(
2189 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2190 k
2191 )
2192 )
tiernofd160572019-01-21 10:41:37 +00002193 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002194 raise EngineException(
2195 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2196 k
2197 )
2198 )
tiernofd160572019-01-21 10:41:37 +00002199 if isinstance(v, (dict, tuple, list)):
2200 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002201 return additional_params
2202
Felipe Vicensb57758d2018-10-16 16:00:20 +02002203 def _check_descriptor_dependencies(self, session, descriptor):
2204 """
2205 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01002206 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002207 :param descriptor: descriptor to be inserted or edit
2208 :return: None or raises exception
2209 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002210 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002211 return
Felipe Vicens07f31722018-10-29 15:16:44 +01002212 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002213 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
garciadeblas4568a372021-03-24 09:19:48 +01002214 raise EngineException(
2215 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2216 nstd_id
2217 ),
2218 http_code=HTTPStatus.CONFLICT,
2219 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002220
tiernob4844ab2019-05-23 08:42:12 +00002221 def check_conflict_on_del(self, session, _id, db_content):
2222 """
2223 Check that NSI is not instantiated
2224 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2225 :param _id: nsi internal id
2226 :param db_content: The database content of the _id
2227 :return: None or raises EngineException with the conflict
2228 """
tierno65ca36d2019-02-12 19:27:52 +01002229 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002230 return
tiernob4844ab2019-05-23 08:42:12 +00002231 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002232 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002233 raise EngineException(
2234 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2235 "Launch 'terminate' operation first; or force deletion".format(_id),
2236 http_code=HTTPStatus.CONFLICT,
2237 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002238
tiernobee3bad2019-12-05 12:26:01 +00002239 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002240 """
tiernob4844ab2019-05-23 08:42:12 +00002241 Deletes associated nsilcmops from database. Deletes associated filesystem.
2242 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002243 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002244 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002245 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002246 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002247 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002248 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002249
Felipe Vicens09e65422019-01-22 15:06:46 +01002250 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002251 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002252 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2253 nsr_id = nsrs_detailed_item["nsrId"]
2254 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002255 _filter = {
2256 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2257 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2258 "_id.ne": nsir["_id"],
2259 }
2260 nsi = self.db.get_one(
2261 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2262 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002263 if nsi: # last one using nsr
2264 continue
2265 try:
garciadeblas4568a372021-03-24 09:19:48 +01002266 self.nsrTopic.delete(
2267 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2268 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002269 except (DbException, EngineException) as e:
2270 if e.http_code == HTTPStatus.NOT_FOUND:
2271 pass
2272 else:
2273 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002274
tiernob4844ab2019-05-23 08:42:12 +00002275 # delete related nsilcmops database entries
2276 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002277
tiernob4844ab2019-05-23 08:42:12 +00002278 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002279 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002280 if nsir_admin and nsir_admin.get("nst-id"):
2281 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002282 nsis_list = self.db.get_one(
2283 "nsis",
2284 {"nst-id": nsir_admin["nst-id"]},
2285 fail_on_empty=False,
2286 fail_on_more=False,
2287 )
tiernob4844ab2019-05-23 08:42:12 +00002288 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002289 self.db.set_one(
2290 "nsts",
2291 {"_id": nsir_admin["nst-id"]},
2292 {"_admin.usageState": "NOT_IN_USE"},
2293 )
tiernob4844ab2019-05-23 08:42:12 +00002294
tierno65ca36d2019-02-12 19:27:52 +01002295 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002296 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002297 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002298 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002299 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002300 :param indata: params to be used for the nsir
2301 :param kwargs: used to override the indata descriptor
2302 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002303 :return: the _id of nsi descriptor created at database
2304 """
2305
2306 try:
delacruzramo32bab472019-09-13 12:24:22 +02002307 step = "checking quotas"
2308 self.check_quota(session)
2309
tierno99d4b172019-07-02 09:28:40 +00002310 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002311 slice_request = self._remove_envelop(indata)
2312 # Override descriptor with query string kwargs
2313 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002314 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002315
Felipe Vicensb57758d2018-10-16 16:00:20 +02002316 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002317 step = "getting nstd id='{}' from database".format(
2318 slice_request.get("nstId")
2319 )
tiernob4844ab2019-05-23 08:42:12 +00002320 _filter = self._get_project_filter(session)
2321 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002322 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002323 # check NST is not disabled
2324 step = "checking NST operationalState"
2325 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002326 raise EngineException(
2327 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2328 "instance".format(slice_request["nstId"]),
2329 http_code=HTTPStatus.CONFLICT,
2330 )
tiernob4844ab2019-05-23 08:42:12 +00002331 del _filter["_id"]
2332
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002333 # check NSD is not disabled
2334 step = "checking operationalState"
2335 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002336 raise EngineException(
2337 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2338 "a network slice".format(slice_request["nstId"]),
2339 http_code=HTTPStatus.CONFLICT,
2340 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002341
Felipe Vicens07f31722018-10-29 15:16:44 +01002342 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002343 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002344 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002345 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002346
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002347 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002348 nsi_descriptor = {
2349 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002350 "name": slice_request["nsiName"],
2351 "description": slice_request.get("nsiDescription", ""),
2352 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002353 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002354 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002355 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002356 "nsr-ref-list": [],
2357 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002358 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002359 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002360 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002361
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002362 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002363 self.format_on_new(
2364 nsi_descriptor, session["project_id"], make_public=session["public"]
2365 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002366 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2367 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002368 nsi_descriptor["_admin"]["deployed"] = {}
2369 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2370 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2371
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002372 # Creating netslice-vld for the RO.
2373 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002374
2375 # Building the vlds list to be deployed
2376 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002377 nsi_vlds = []
2378
2379 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2380 # Getting template Instantiation parameters from NST
2381 nsi_vld = deepcopy(netslice_vlds)
2382 nsi_vld["shared-nsrs-list"] = []
2383 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2384 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002385
2386 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002387 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002388 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002389 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002390
Felipe Vicens09e65422019-01-22 15:06:46 +01002391 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002392 for member_ns in nstd["netslice-subnet"]:
2393 nsd_id = member_ns["nsd-ref"]
2394 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002395 member_ns["nsd-ref"], member_ns["id"]
2396 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002397 if nsd_id not in needed_nsds:
2398 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002399 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002400 nsd = self.db.get_one(
2401 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2402 )
tiernob4844ab2019-05-23 08:42:12 +00002403 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002404 nsd.pop("_admin")
2405 needed_nsds[nsd_id] = nsd
2406 else:
2407 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002408 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2409 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002410
Felipe Vicensb57758d2018-10-16 16:00:20 +02002411 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002412 member_ns["nsd-ref"], member_ns["id"]
2413 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002414
Felipe Vicens07f31722018-10-29 15:16:44 +01002415 # creates Network Services records (NSRs)
2416 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002417 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002418 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002419 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002420 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002421 # Check if the netslice-subnet is shared and if it is share if the nss exists
2422 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002423 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002424 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002425 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002426 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2427 "nsd-ref"
2428 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002429 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002430 nsi = self.db.get_one(
2431 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2432 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002433 if nsi and service.get("is-shared-nss"):
2434 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2435 for nsrs_detailed_item in nsrs_detailed_list:
2436 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002437 if nsrs_detailed_item["nss-id"] == service["id"]:
2438 _id_nsr = nsrs_detailed_item["nsrId"]
2439 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002440 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2441 if netslice_subnet["nss-id"] == service["id"]:
2442 indata_ns = netslice_subnet
2443 break
2444 else:
2445 indata_ns = {}
2446 if service.get("instantiation-parameters"):
2447 indata_ns = deepcopy(service["instantiation-parameters"])
2448 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002449
Felipe Vicens09e65422019-01-22 15:06:46 +01002450 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002451 indata_ns["nsName"] = (
2452 slice_request.get("nsiName") + "." + service["id"]
2453 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002454 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2455 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002456 if slice_request.get("ssh_keys"):
2457 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002458
Felipe Vicens09e65422019-01-22 15:06:46 +01002459 if ns_params:
2460 for ns_param in ns_params:
2461 if ns_param.get("id") == service["id"]:
2462 copy_ns_param = deepcopy(ns_param)
2463 del copy_ns_param["id"]
2464 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002465 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002466
2467 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002468 _id_nsr, _ = self.nsrTopic.new(
2469 rollback, session, indata_ns, kwargs, headers
2470 )
2471 nsrs_item = {
2472 "nsrId": _id_nsr,
2473 "shared": service.get("is-shared-nss"),
2474 "nsd-id": service["nsd-ref"],
2475 "nss-id": service["id"],
2476 "nslcmop_instantiate": None,
2477 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002478 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002479 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002480 nsi_netslice_subnet.append(indata_ns)
2481 nsr_ref = {"nsr-ref": _id_nsr}
2482 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002483
2484 # Adding the nsrs list to the nsi
2485 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002486 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002487 self.db.set_one(
2488 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2489 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002490
Felipe Vicens07f31722018-10-29 15:16:44 +01002491 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002492 self.db.create("nsis", nsi_descriptor)
2493 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002494 return nsi_id, None
garciadeblas4568a372021-03-24 09:19:48 +01002495 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2496 self.logger.exception(
2497 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2498 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002499 raise EngineException("Error {}: {}".format(step, e))
2500 except ValidationError as e:
2501 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2502
tierno65ca36d2019-02-12 19:27:52 +01002503 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002504 raise EngineException(
2505 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2506 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002507
2508
2509class NsiLcmOpTopic(BaseTopic):
2510 topic = "nsilcmops"
2511 topic_msg = "nsi"
2512 operation_schema = { # mapping between operation and jsonschema to validate
2513 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002514 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002515 }
garciadeblas4568a372021-03-24 09:19:48 +01002516
delacruzramo32bab472019-09-13 12:24:22 +02002517 def __init__(self, db, fs, msg, auth):
2518 BaseTopic.__init__(self, db, fs, msg, auth)
2519 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002520
2521 def _check_nsi_operation(self, session, nsir, operation, indata):
2522 """
2523 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002524 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002525 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2526 :param indata: descriptor with the parameters of the operation
2527 :return: None
2528 """
2529 nsds = {}
2530 nstd = nsir["network-slice-template"]
2531
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002532 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002533 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002534 for netslice_subnet in nstd["netslice-subnet"]:
2535 if nstId == netslice_subnet["id"]:
2536 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002537 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002538 _filter = self._get_project_filter(session)
2539 _filter["id"] = nsd_id
2540 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002541 return nsds[nsd_id]
2542 else:
garciadeblas4568a372021-03-24 09:19:48 +01002543 raise EngineException(
2544 "Invalid parameter nstId='{}' is not one of the "
2545 "nst:netslice-subnet".format(nstId)
2546 )
2547
Felipe Vicens07f31722018-10-29 15:16:44 +01002548 if operation == "instantiate":
2549 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002550 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002551 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002552
2553 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2554 now = time()
2555 _id = str(uuid4())
2556 nsilcmop = {
2557 "id": _id,
2558 "_id": _id,
2559 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2560 "statusEnteredTime": now,
2561 "netsliceInstanceId": netsliceInstanceId,
2562 "lcmOperationType": operation,
2563 "startTime": now,
2564 "isAutomaticInvocation": False,
2565 "operationParams": params,
2566 "isCancelPending": False,
2567 "links": {
2568 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002569 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2570 + netsliceInstanceId,
2571 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002572 }
2573 return nsilcmop
2574
Felipe Vicens09e65422019-01-22 15:06:46 +01002575 def add_shared_nsr_2vld(self, nsir, nsr_item):
2576 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2577 if nst_sb_item.get("is-shared-nss"):
2578 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2579 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2580 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002581 for admin_vld_nss_cp_ref_item in admin_vld_item[
2582 "nss-connection-point-ref"
2583 ]:
2584 if (
2585 admin_subnet_item["nss-id"]
2586 == admin_vld_nss_cp_ref_item["nss-ref"]
2587 ):
2588 if (
2589 not nsr_item["nsrId"]
2590 in admin_vld_item["shared-nsrs-list"]
2591 ):
2592 admin_vld_item["shared-nsrs-list"].append(
2593 nsr_item["nsrId"]
2594 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002595 break
2596 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002597 self.db.set_one(
2598 "nsis",
2599 {"_id": nsir["_id"]},
2600 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2601 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002602
tierno65ca36d2019-02-12 19:27:52 +01002603 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002604 """
2605 Performs a new operation over a ns
2606 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002607 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002608 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002609 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002610 operation: it can be: instantiate, terminate, action, TODO: update, heal
2611 :param kwargs: used to override the indata descriptor
2612 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002613 :return: id of the nslcmops
2614 """
2615 try:
2616 # Override descriptor with query string kwargs
2617 self._update_input_with_kwargs(indata, kwargs)
2618 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002619 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002620 validate_input(indata, self.operation_schema[operation])
2621
Felipe Vicens126af572019-06-05 19:13:04 +02002622 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002623 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002624 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002625 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002626 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002627 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002628
2629 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002630 if (
2631 not nsir["_admin"].get("nsiState")
2632 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2633 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002634 if operation == "terminate" and indata.get("autoremove"):
2635 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002636 return (
2637 None,
2638 None,
2639 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002640 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002641 raise EngineException(
2642 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2643 netsliceInstanceId, operation
2644 ),
2645 HTTPStatus.CONFLICT,
2646 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002647 else:
tierno65ca36d2019-02-12 19:27:52 +01002648 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002649 raise EngineException(
2650 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2651 netsliceInstanceId, operation
2652 ),
2653 HTTPStatus.CONFLICT,
2654 )
2655
Felipe Vicens07f31722018-10-29 15:16:44 +01002656 # Creating all the NS_operation (nslcmop)
2657 # Get service list from db
2658 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2659 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002660 # nslcmops_item = None
2661 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002662 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002663 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002664 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002665 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002666 _filter[
2667 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2668 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002669 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002670 nsi = self.db.get_one(
2671 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2672 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002673 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002674 _update = {
2675 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2676 index
2677 ): None
2678 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002679 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002680 if (
2681 nsi
2682 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002683 continue # do not create nsilcmop
2684 else: # instantiate
2685 # looks the first nsi fulfilling the conditions but not being the current NSIR
2686 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002687 nsi_nsr_item = next(
2688 n
2689 for n in nsi["_admin"]["nsrs-detailed-list"]
2690 if n["nsrId"] == nsr_id
2691 and n["shared"]
2692 and n["nslcmop_instantiate"]
2693 )
tierno40f742b2020-06-23 15:25:26 +00002694 self.add_shared_nsr_2vld(nsir, nsr_item)
2695 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002696 _update = {
2697 "_admin.nsrs-detailed-list.{}".format(
2698 index
2699 ): nsi_nsr_item
2700 }
tierno40f742b2020-06-23 15:25:26 +00002701 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2702 # continue to not create nslcmop since nsrs is shared and nsrs was created
2703 continue
2704 else:
2705 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002706
tierno40f742b2020-06-23 15:25:26 +00002707 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002708 try:
tierno0b8752f2020-05-12 09:42:02 +00002709 indata_ns = {
2710 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002711 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002712 # Including netslice_id in the ns instantiate Operation
2713 "netsliceInstanceId": netsliceInstanceId,
2714 }
2715 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002716 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002717 indata_ns.update(service["instantiate_params"])
2718
tierno99d4b172019-07-02 09:28:40 +00002719 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002720 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002721 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2722 rollback, session, indata_ns, None, headers, slice_object=True
2723 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002724 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002725 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002726 _update = {
2727 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2728 index
2729 ): nslcmop
2730 }
tierno40f742b2020-06-23 15:25:26 +00002731 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002732 except (DbException, EngineException) as e:
2733 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002734 self.logger.info(
2735 logging_prefix
2736 + "skipping NS={} because not found".format(nsr_id)
2737 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002738 pass
2739 else:
2740 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002741
2742 # Creates nsilcmop
2743 indata["nslcmops_ids"] = nslcmops
2744 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002745
garciadeblas4568a372021-03-24 09:19:48 +01002746 nsilcmop_desc = self._create_nsilcmop(
2747 session, netsliceInstanceId, operation, indata
2748 )
2749 self.format_on_new(
2750 nsilcmop_desc, session["project_id"], make_public=session["public"]
2751 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002752 _id = self.db.create("nsilcmops", nsilcmop_desc)
2753 rollback.append({"topic": "nsilcmops", "_id": _id})
2754 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002755 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002756 except ValidationError as e:
2757 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002758
tiernobee3bad2019-12-05 12:26:01 +00002759 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002760 raise EngineException(
2761 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2762 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002763
tierno65ca36d2019-02-12 19:27:52 +01002764 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002765 raise EngineException(
2766 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2767 )