blob: b4ce2706a6abbc81e00fad9fc9997c73fdc0d14f [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", ())
600 ag_prefix_name = "{}-{}".format(nsr_descriptor["name"][:16], vnf_profile.get("id")[:16])
601
602 for vdu_profile in vdu_profiles:
603 ag_data = {}
604 for ag in vdu_profile.get("affinity-or-anti-affinity-group", ()):
605 ag_data = self._get_affinity_or_anti_affinity_group_data_from_vnfd(vnfd, ag["id"])
606 self._add_affinity_or_anti_affinity_group_to_nsr(nsr_descriptor, ag_data, ag_prefix_name)
607
garciaale7cbd03c2020-11-27 10:38:35 -0300608 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100609 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
610 vld.get("id"), []
611 )
garciaale7cbd03c2020-11-27 10:38:35 -0300612 vld["name"] = vld["id"]
613 nsr_descriptor["vld"] = nsr_vld
614
615 return nsr_descriptor
616
Alexis Romero03fb5842022-03-11 15:53:40 +0100617 def _get_affinity_or_anti_affinity_group_data_from_vnfd(self, vnfd, ag_id):
618 """
619 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
620 """
621 affinity_or_anti_affinity_group = utils.find_in_list(
622 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()), lambda ag: ag["id"] == ag_id
623 )
624 ag_data = {}
625 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("id"):
626 ag_data["ag-id"] = affinity_or_anti_affinity_group["id"]
627 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("type"):
628 ag_data["type"] = affinity_or_anti_affinity_group["type"]
629 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("scope"):
630 ag_data["scope"] = affinity_or_anti_affinity_group["scope"]
631 return ag_data
632
633 def _add_affinity_or_anti_affinity_group_to_nsr(self, nsr_descriptor, ag_data, ag_prefix_name):
634 """
635 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
636 """
637 ag = next(
638 (
639 f
640 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
641 if all(f.get(k) == ag_data[k] for k in ag_data)
642 ),
643 None,
644 )
645 if not ag:
646 ag_data["id"] = str(len(nsr_descriptor["affinity-or-anti-affinity-group"]))
647 ag_data["name"] = "{}-{}-{}".format(ag_prefix_name, ag_data["ag-id"][:32], ag_data.get("id") or 0)
648 nsr_descriptor["affinity-or-anti-affinity-group"].append(ag_data)
649
lloretgalleg28c13b62021-02-08 11:48:48 +0000650 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100651 sw_image_desc = utils.find_in_list(
652 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
653 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000654 image_data = {}
655 if sw_image_desc.get("image"):
656 image_data["image"] = sw_image_desc["image"]
657 if sw_image_desc.get("checksum"):
658 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
659 if sw_image_desc.get("vim-type"):
660 image_data["vim-type"] = sw_image_desc["vim-type"]
661 return image_data
662
663 def _add_image_to_nsr(self, nsr_descriptor, image_data):
664 """
665 Adds image to nsr checking first it is not already added
666 """
garciadeblas4568a372021-03-24 09:19:48 +0100667 img = next(
668 (
669 f
670 for f in nsr_descriptor["image"]
671 if all(f.get(k) == image_data[k] for k in image_data)
672 ),
673 None,
674 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000675 if not img:
676 image_data["id"] = str(len(nsr_descriptor["image"]))
677 nsr_descriptor["image"].append(image_data)
678
garciadeblas4568a372021-03-24 09:19:48 +0100679 def _create_vnfr_descriptor_from_vnfd(
680 self,
681 nsd,
682 vnfd,
683 vnfd_id,
684 vnf_index,
685 nsr_descriptor,
686 ns_request,
687 ns_k8s_namespace,
688 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300689 vnfr_id = str(uuid4())
690 nsr_id = nsr_descriptor["id"]
691 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100692 additional_params, vnf_params = self._format_additional_params(
693 ns_request, vnf_index, descriptor=vnfd
694 )
garciaale7cbd03c2020-11-27 10:38:35 -0300695
696 vnfr_descriptor = {
697 "id": vnfr_id,
698 "_id": vnfr_id,
699 "nsr-id-ref": nsr_id,
700 "member-vnf-index-ref": vnf_index,
701 "additionalParamsForVnf": additional_params,
702 "created-time": now,
703 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
704 "vnfd-ref": vnfd_id,
705 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
706 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200707 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300708 "vdur": [],
709 "connection-point": [],
710 "ip-address": None, # mgmt-interface filled by LCM
711 }
beierlmcee2ebf2022-03-29 17:42:48 -0400712
713 # Revision backwards compatility. Only specify the revision in the record if
714 # the original VNFD has a revision.
715 if "revision" in vnfd:
716 vnfr_descriptor["revision"] = vnfd["revision"]
717
718
garciaale7cbd03c2020-11-27 10:38:35 -0300719 vnf_k8s_namespace = ns_k8s_namespace
720 if vnf_params:
721 if vnf_params.get("k8s-namespace"):
722 vnf_k8s_namespace = vnf_params["k8s-namespace"]
723 if vnf_params.get("config-units"):
724 vnfr_descriptor["config-units"] = vnf_params["config-units"]
725
726 # Create vld
727 if vnfd.get("int-virtual-link-desc"):
728 vnfr_descriptor["vld"] = []
729 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
730 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
731
732 for cp in vnfd.get("ext-cpd", ()):
733 vnf_cp = {
734 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100735 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
736 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300737 "id": cp.get("id"),
738 # "ip-address", "mac-address" # filled by LCM
739 # vim-id # TODO it would be nice having a vim port id
740 }
741 vnfr_descriptor["connection-point"].append(vnf_cp)
742
743 # Create k8s-cluster information
744 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
745 if vnfd.get("k8s-cluster"):
746 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
747 all_k8s_cluster_nets_cpds = {}
748 for cpd in get_iterable(vnfd.get("ext-cpd")):
749 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100750 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
751 "id"
752 )
garciaale7cbd03c2020-11-27 10:38:35 -0300753 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
754 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100755 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
756 net.get("id")
757 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300758
759 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300760 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100761 additional_params, kdu_params = self._format_additional_params(
762 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
763 )
garciaale7cbd03c2020-11-27 10:38:35 -0300764 kdu_k8s_namespace = vnf_k8s_namespace
765 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
766 if kdu_params and kdu_params.get("k8s-namespace"):
767 kdu_k8s_namespace = kdu_params["k8s-namespace"]
768
romeromonserbfebfc02021-05-28 10:51:35 +0200769 kdu_deployment_name = ""
770 if kdu_params and kdu_params.get("kdu-deployment-name"):
771 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
772
garciaale7cbd03c2020-11-27 10:38:35 -0300773 kdur = {
774 "additionalParams": additional_params,
775 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200776 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000777 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300778 # TODO "name": "" Name of the VDU in the VIM
779 "ip-address": None, # mgmt-interface filled by LCM
780 "k8s-cluster": {},
781 }
782 if kdu_params and kdu_params.get("config-units"):
783 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000784 if kdu.get("helm-version"):
785 kdur["helm-version"] = kdu["helm-version"]
786 for k8s_type in ("helm-chart", "juju-bundle"):
787 if kdu.get(k8s_type):
788 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300789 if not vnfr_descriptor.get("kdur"):
790 vnfr_descriptor["kdur"] = []
791 vnfr_descriptor["kdur"].append(kdur)
792
793 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300794
garciaale7cbd03c2020-11-27 10:38:35 -0300795 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300796 vdu_mgmt_cp = []
797 try:
garciadeblas4568a372021-03-24 09:19:48 +0100798 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
799 "operate-vnf-op-config"
800 ]["day1-2"]
801 vdu_config = utils.find_in_list(
802 configs, lambda config: config["id"] == vdu["id"]
803 )
bravoff3c39552021-02-24 17:22:24 -0300804 except Exception:
805 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400806
807 try:
808 vdu_instantiation_level = utils.find_in_list(
809 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100810 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400811 )
812 except Exception:
813 vdu_instantiation_level = None
814
bravoff3c39552021-02-24 17:22:24 -0300815 if vdu_config:
816 external_connection_ee = utils.filter_in_list(
817 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100818 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300819 )
820 for ee in external_connection_ee:
821 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
822
garciaale7cbd03c2020-11-27 10:38:35 -0300823 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100824 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
825 )
bravof65e22e52021-11-10 17:58:58 -0300826
827 try:
828 vdu_virtual_storage_descriptors = utils.filter_in_list(
829 vnfd.get("virtual-storage-desc", []),
830 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
831 )
832 except Exception:
833 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300834 vdur = {
835 "vdu-id-ref": vdu["id"],
836 # TODO "name": "" Name of the VDU in the VIM
837 "ip-address": None, # mgmt-interface filled by LCM
838 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
839 "internal-connection-point": [],
840 "interfaces": [],
841 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100842 "vdu-name": vdu["name"],
bravof65e22e52021-11-10 17:58:58 -0300843 "virtual-storages": vdu_virtual_storage_descriptors
garciaale7cbd03c2020-11-27 10:38:35 -0300844 }
845 if vdu_params and vdu_params.get("config-units"):
846 vdur["config-units"] = vdu_params["config-units"]
847 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100848 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
849 "boot-data-drive"
850 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300851 if vdu.get("pdu-type"):
852 vdur["pdu-type"] = vdu["pdu-type"]
853 vdur["name"] = vdu["pdu-type"]
854 # TODO volumes: name, volume-id
855 for icp in vdu.get("int-cpd", ()):
856 vdu_icp = {
857 "id": icp["id"],
858 "connection-point-id": icp["id"],
859 "name": icp.get("id"),
860 }
bravof35766442021-02-04 14:58:04 -0300861
garciaale7cbd03c2020-11-27 10:38:35 -0300862 vdur["internal-connection-point"].append(vdu_icp)
863
864 for iface in icp.get("virtual-network-interface-requirement", ()):
865 iface_fields = ("name", "mac-address")
garciadeblas4568a372021-03-24 09:19:48 +0100866 vdu_iface = {
867 x: iface[x] for x in iface_fields if iface.get(x) is not None
868 }
garciaale7cbd03c2020-11-27 10:38:35 -0300869
870 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100871 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100872 vdu_iface["port-security-enabled"] = icp[
873 "port-security-enabled"
874 ]
sousaedu003844e2021-03-02 00:19:15 +0100875
876 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100877 vdu_iface["port-security-disable-strategy"] = icp[
878 "port-security-disable-strategy"
879 ]
sousaedu003844e2021-03-02 00:19:15 +0100880
garciaale7cbd03c2020-11-27 10:38:35 -0300881 for ext_cp in vnfd.get("ext-cpd", ()):
882 if not ext_cp.get("int-cpd"):
883 continue
884 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
885 continue
886 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100887 vdu_iface["external-connection-point-ref"] = ext_cp.get(
888 "id"
889 )
sousaedu003844e2021-03-02 00:19:15 +0100890
891 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100892 vdu_iface["port-security-enabled"] = ext_cp[
893 "port-security-enabled"
894 ]
sousaedu003844e2021-03-02 00:19:15 +0100895
896 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100897 vdu_iface["port-security-disable-strategy"] = ext_cp[
898 "port-security-disable-strategy"
899 ]
sousaedu003844e2021-03-02 00:19:15 +0100900
garciaale7cbd03c2020-11-27 10:38:35 -0300901 break
902
garciadeblas4568a372021-03-24 09:19:48 +0100903 if (
904 vnfd_mgmt_cp
905 and vdu_iface.get("external-connection-point-ref")
906 == vnfd_mgmt_cp
907 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300908 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300909 vdu_iface["mgmt-interface"] = True
910
911 for ecp in vdu_mgmt_cp:
912 if vdu_iface.get("external-connection-point-ref") == ecp:
913 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300914
915 if iface.get("virtual-interface"):
916 vdu_iface.update(deepcopy(iface["virtual-interface"]))
917
918 # look for network where this interface is connected
919 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
920 if iface_ext_cp:
921 # TODO: Change for multiple df support
922 for df in get_iterable(nsd.get("df")):
923 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100924 for vlc_index, vlc in enumerate(
925 get_iterable(
926 vnf_profile.get("virtual-link-connectivity")
927 )
928 ):
929 for cpd in get_iterable(
930 vlc.get("constituent-cpd-id")
931 ):
932 if (
933 cpd.get("constituent-cpd-id")
934 == iface_ext_cp
935 ):
936 vdu_iface["ns-vld-id"] = vlc.get(
937 "virtual-link-profile-id"
938 )
garciadeblas61c95912021-02-12 11:23:50 +0000939 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100940 if vdu_iface.get("type") in (
941 "SR-IOV",
942 "PCI-PASSTHROUGH",
943 ):
944 nsr_descriptor["vld"][vlc_index][
945 "pci-interfaces"
946 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300947 break
948 elif vdu_iface.get("internal-connection-point-ref"):
949 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000950 # TODO: store fixed IP address in the record (if it exists in the ICP)
951 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
952 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100953 ivld_index = utils.find_index_in_list(
954 vnfd.get("int-virtual-link-desc", ()),
955 lambda ivld: ivld["id"]
956 == icp.get("int-virtual-link-desc"),
957 )
garciadeblas61c95912021-02-12 11:23:50 +0000958 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300959
960 vdur["interfaces"].append(vdu_iface)
961
962 if vdu.get("sw-image-desc"):
963 sw_image = utils.find_in_list(
964 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100965 lambda image: image["id"] == vdu.get("sw-image-desc"),
966 )
garciaale7cbd03c2020-11-27 10:38:35 -0300967 nsr_sw_image_data = utils.find_in_list(
968 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100969 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300970 )
971 vdur["ns-image-id"] = nsr_sw_image_data["id"]
972
lloretgalleg28c13b62021-02-08 11:48:48 +0000973 if vdu.get("alternative-sw-image-desc"):
974 alt_image_ids = []
975 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
976 sw_image = utils.find_in_list(
977 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100978 lambda image: image["id"] == alt_image_id,
979 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000980 nsr_sw_image_data = utils.find_in_list(
981 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100982 lambda nsr_image: (
983 nsr_image.get("image") == sw_image.get("image")
984 ),
lloretgalleg28c13b62021-02-08 11:48:48 +0000985 )
986 alt_image_ids.append(nsr_sw_image_data["id"])
987 vdur["alt-image-ids"] = alt_image_ids
988
garciaale7cbd03c2020-11-27 10:38:35 -0300989 flavor_data_name = vdu["id"][:56] + "-flv"
990 nsr_flavor_desc = utils.find_in_list(
991 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +0100992 lambda flavor: flavor["name"] == flavor_data_name,
993 )
garciaale7cbd03c2020-11-27 10:38:35 -0300994
995 if nsr_flavor_desc:
996 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
997
Alexis Romero03fb5842022-03-11 15:53:40 +0100998 # Adding Affinity groups information to vdur
999 try:
1000 ags_vdu_profile = utils.find_in_list(
1001 vnfd.get("df")[0]["vdu-profile"],
1002 lambda a_vdu: a_vdu["id"] == vdu["id"],
1003 )
1004 except Exception:
1005 ags_vdu_profile = None
1006
1007 if ags_vdu_profile:
1008 ags_ids = []
1009 for ag in ags_vdu_profile.get("affinity-or-anti-affinity-group", ()):
1010 vdu_ag = utils.find_in_list(
1011 ags_vdu_profile.get("affinity-or-anti-affinity-group", ()),
1012 lambda ag_fp: ag_fp["id"] == ag["id"],
1013 )
1014 nsr_ags_data = utils.find_in_list(
1015 nsr_descriptor["affinity-or-anti-affinity-group"],
1016 lambda nsr_ag: (
1017 nsr_ag.get("ag-id") == vdu_ag.get("id")
1018 ),
1019 )
1020 ags_ids.append(nsr_ags_data["id"])
1021 vdur["affinity-or-anti-affinity-group-id"] = ags_ids
1022
bravof4ca51522021-04-22 10:03:02 -04001023 if vdu_instantiation_level:
1024 count = vdu_instantiation_level.get("number-of-instances")
1025 else:
1026 count = 1
1027
garciaale7cbd03c2020-11-27 10:38:35 -03001028 for index in range(0, count):
1029 vdur = deepcopy(vdur)
1030 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001031 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001032 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001033 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001034 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1035
1036 vdur["_id"] = str(uuid4())
1037 vdur["id"] = vdur["_id"]
1038 vdur["count-index"] = index
1039 vnfr_descriptor["vdur"].append(vdur)
1040
1041 return vnfr_descriptor
1042
K Sai Kiran57589552021-01-27 21:38:34 +05301043 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1044 """
1045 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1046 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1047 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1048 :param ns_instance_content: ns instance content
1049 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1050 :return: None
1051 """
1052 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
1053 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
1054 threshold_reached = time_delta > 120
1055 if force_refresh or threshold_reached:
1056 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1057 ns_instance_content["_admin"]["modified"] = time_now
1058 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1059 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
1060 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1061 nslcmop_desc["_admin"].pop("nsState")
1062 self.msg.write("ns", operation, nslcmop_desc)
1063 return
1064
1065 def show(self, session, _id, filter_q=None, api_req=False):
1066 """
1067 Get complete information on an ns instance.
1068 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1069 :param _id: string, ns instance id
1070 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1071 :param api_req: True if this call is serving an external API request. False if serving internal request.
1072 :return: dictionary, raise exception if not found.
1073 """
1074 ns_instance_content = super().show(session, _id, api_req)
1075 self.vca_status_refresh(session, ns_instance_content, filter_q)
1076 return ns_instance_content
1077
tierno65ca36d2019-02-12 19:27:52 +01001078 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001079 raise EngineException(
1080 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1081 )
tiernob24258a2018-10-04 18:39:49 +02001082
1083
1084class VnfrTopic(BaseTopic):
1085 topic = "vnfrs"
1086 topic_msg = None
1087
delacruzramo32bab472019-09-13 12:24:22 +02001088 def __init__(self, db, fs, msg, auth):
1089 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001090
tiernobee3bad2019-12-05 12:26:01 +00001091 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001092 raise EngineException(
1093 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1094 )
tiernob24258a2018-10-04 18:39:49 +02001095
tierno65ca36d2019-02-12 19:27:52 +01001096 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001097 raise EngineException(
1098 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1099 )
tiernob24258a2018-10-04 18:39:49 +02001100
tierno65ca36d2019-02-12 19:27:52 +01001101 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001102 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001103 raise EngineException(
1104 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1105 )
tiernob24258a2018-10-04 18:39:49 +02001106
1107
1108class NsLcmOpTopic(BaseTopic):
1109 topic = "nslcmops"
1110 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001111 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001112 "instantiate": ns_instantiate,
1113 "action": ns_action,
1114 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +00001115 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +02001116 }
1117
delacruzramo32bab472019-09-13 12:24:22 +02001118 def __init__(self, db, fs, msg, auth):
1119 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001120
tiernob24258a2018-10-04 18:39:49 +02001121 def _check_ns_operation(self, session, nsr, operation, indata):
1122 """
1123 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001124 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001125 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1126 :param indata: descriptor with the parameters of the operation
1127 :return: None
1128 """
garciaale7cbd03c2020-11-27 10:38:35 -03001129 if operation == "action":
1130 self._check_action_ns_operation(indata, nsr)
1131 elif operation == "scale":
1132 self._check_scale_ns_operation(indata, nsr)
1133 elif operation == "instantiate":
1134 self._check_instantiate_ns_operation(indata, nsr, session)
1135
1136 def _check_action_ns_operation(self, indata, nsr):
1137 nsd = nsr["nsd"]
1138 # check vnf_member_index
1139 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001140 indata["member_vnf_index"] = indata.pop(
1141 "vnf_member_index"
1142 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001143 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001144 vnfd = self._get_vnfd_from_vnf_member_index(
1145 indata["member_vnf_index"], nsr["_id"]
1146 )
bravof41a52052021-02-17 18:08:01 -03001147 try:
garciadeblas4568a372021-03-24 09:19:48 +01001148 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1149 "operate-vnf-op-config"
1150 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001151 except Exception:
1152 configs = []
1153
garciaale7cbd03c2020-11-27 10:38:35 -03001154 if indata.get("vdu_id"):
1155 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001156 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001157 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001158 )
garciaale7cbd03c2020-11-27 10:38:35 -03001159 elif indata.get("kdu_name"):
1160 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001161 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001162 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001163 )
garciaale7cbd03c2020-11-27 10:38:35 -03001164 else:
bravof41a52052021-02-17 18:08:01 -03001165 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001166 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001167 )
1168 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001169 descriptor_configuration = descriptor_configuration.get(
1170 "config-primitive"
1171 )
garciaale7cbd03c2020-11-27 10:38:35 -03001172 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001173 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1174 "config-primitive"
1175 )
garciaale7cbd03c2020-11-27 10:38:35 -03001176
1177 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001178 if indata.get("kdu_name") and indata["primitive"] in (
1179 "upgrade",
1180 "rollback",
1181 "status",
1182 "inspect",
1183 "readme",
1184 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001185 # TODO should be checked that rollback only can contains revsision_numbe????
1186 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001187 raise EngineException(
1188 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1189 indata["primitive"]
1190 )
1191 )
garciaale7cbd03c2020-11-27 10:38:35 -03001192 return
1193 # if not, check primitive
1194 for config_primitive in get_iterable(descriptor_configuration):
1195 if indata["primitive"] == config_primitive["name"]:
1196 # check needed primitive_params are provided
1197 if indata.get("primitive_params"):
1198 in_primitive_params_copy = copy(indata["primitive_params"])
1199 else:
1200 in_primitive_params_copy = {}
1201 for paramd in get_iterable(config_primitive.get("parameter")):
1202 if paramd["name"] in in_primitive_params_copy:
1203 del in_primitive_params_copy[paramd["name"]]
1204 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001205 raise EngineException(
1206 "Needed parameter {} not provided for primitive '{}'".format(
1207 paramd["name"], indata["primitive"]
1208 )
1209 )
garciaale7cbd03c2020-11-27 10:38:35 -03001210 # check no extra primitive params are provided
1211 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001212 raise EngineException(
1213 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1214 list(in_primitive_params_copy.keys()), indata["primitive"]
1215 )
1216 )
garciaale7cbd03c2020-11-27 10:38:35 -03001217 break
1218 else:
garciadeblas4568a372021-03-24 09:19:48 +01001219 raise EngineException(
1220 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1221 indata["primitive"]
1222 )
1223 )
garciaale7cbd03c2020-11-27 10:38:35 -03001224
1225 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001226 vnfd = self._get_vnfd_from_vnf_member_index(
1227 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1228 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001229 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001230 if (
1231 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1232 == scaling_aspect["id"]
1233 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001234 break
1235 else:
garciadeblas4568a372021-03-24 09:19:48 +01001236 raise EngineException(
1237 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1238 "present at vnfd:scaling-aspect".format(
1239 indata["scaleVnfData"]["scaleByStepData"][
1240 "scaling-group-descriptor"
1241 ]
1242 )
1243 )
garciaale7cbd03c2020-11-27 10:38:35 -03001244
1245 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001246 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001247 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001248 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001249 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001250 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1251 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1252 for in_vnf in get_iterable(indata.get("vnf")):
1253 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001254 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001255 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001256 else:
garciadeblas4568a372021-03-24 09:19:48 +01001257 vnfd = self._get_vnfd_from_vnf_member_index(
1258 member_vnf_index, nsr["_id"]
1259 )
1260 vnf_member_index_to_vnfd[
1261 member_vnf_index
1262 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001263 self._check_vnf_instantiation_params(in_vnf, vnfd)
1264 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001265 self._check_valid_vim_account(
1266 in_vnf["vimAccountId"], vim_accounts, session
1267 )
tierno260dd6f2019-09-02 10:48:56 +00001268
garciaale7cbd03c2020-11-27 10:38:35 -03001269 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001270 self._check_valid_wim_account(
1271 in_vld.get("wimAccountId"), wim_accounts, session
1272 )
garciaale7cbd03c2020-11-27 10:38:35 -03001273 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1274 if in_vld["name"] == vldd["id"]:
1275 break
tierno9cb7d672019-10-30 12:13:48 +00001276 else:
garciadeblas4568a372021-03-24 09:19:48 +01001277 raise EngineException(
1278 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1279 in_vld["name"]
1280 )
1281 )
tierno9cb7d672019-10-30 12:13:48 +00001282
garciaale7cbd03c2020-11-27 10:38:35 -03001283 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1284 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001285 vnfr = self.db.get_one(
1286 "vnfrs",
1287 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1288 fail_on_empty=False,
1289 )
garciaale7cbd03c2020-11-27 10:38:35 -03001290 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001291 raise EngineException(
1292 "Invalid parameter member_vnf_index='{}' is not one of the "
1293 "nsd:constituent-vnfd".format(member_vnf_index)
1294 )
beierlmcee2ebf2022-03-29 17:42:48 -04001295
1296 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1297 if "revision" in vnfr:
1298 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
1299 vnfd = self.db.get_one("vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False)
1300 else:
1301 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1302
garciaale7cbd03c2020-11-27 10:38:35 -03001303 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001304 raise EngineException(
1305 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1306 vnfr["vnfd-id"]
1307 )
1308 )
garciaale7cbd03c2020-11-27 10:38:35 -03001309 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001310
garciaale7cbd03c2020-11-27 10:38:35 -03001311 def _check_valid_vdu(self, vnfd, vdu_id):
1312 for vdud in get_iterable(vnfd.get("vdu")):
1313 if vdud["id"] == vdu_id:
1314 return vdud
1315 else:
garciadeblas4568a372021-03-24 09:19:48 +01001316 raise EngineException(
1317 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1318 vdu_id
1319 )
1320 )
garciaale7cbd03c2020-11-27 10:38:35 -03001321
1322 def _check_valid_kdu(self, vnfd, kdu_name):
1323 for kdud in get_iterable(vnfd.get("kdu")):
1324 if kdud["name"] == kdu_name:
1325 return kdud
1326 else:
garciadeblas4568a372021-03-24 09:19:48 +01001327 raise EngineException(
1328 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1329 kdu_name
1330 )
1331 )
garciaale7cbd03c2020-11-27 10:38:35 -03001332
1333 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1334 for in_vdu in get_iterable(in_vnf.get("vdu")):
1335 for vdu in get_iterable(vnfd.get("vdu")):
1336 if in_vdu["id"] == vdu["id"]:
1337 for volume in get_iterable(in_vdu.get("volume")):
1338 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1339 if volumed["id"] == volume["name"]:
1340 break
1341 else:
garciadeblas4568a372021-03-24 09:19:48 +01001342 raise EngineException(
1343 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1344 "volume:name='{}' is not present at "
1345 "vnfd:vdu:virtual-storage-desc list".format(
1346 in_vnf["member-vnf-index"],
1347 in_vdu["id"],
1348 volume["id"],
1349 )
1350 )
garciaale7cbd03c2020-11-27 10:38:35 -03001351
1352 vdu_if_names = set()
1353 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001354 for iface in get_iterable(
1355 cpd.get("virtual-network-interface-requirement")
1356 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001357 vdu_if_names.add(iface.get("name"))
1358
1359 for in_iface in get_iterable(in_vdu["interface"]):
1360 if in_iface["name"] in vdu_if_names:
1361 break
1362 else:
garciadeblas4568a372021-03-24 09:19:48 +01001363 raise EngineException(
1364 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1365 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1366 in_vnf["member-vnf-index"],
1367 in_vdu["id"],
1368 in_iface["name"],
1369 )
1370 )
garciaale7cbd03c2020-11-27 10:38:35 -03001371 break
1372
1373 else:
garciadeblas4568a372021-03-24 09:19:48 +01001374 raise EngineException(
1375 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1376 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1377 )
garciaale7cbd03c2020-11-27 10:38:35 -03001378
garciadeblas4568a372021-03-24 09:19:48 +01001379 vnfd_ivlds_cpds = {
1380 ivld.get("id"): set()
1381 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1382 }
garciaale7cbd03c2020-11-27 10:38:35 -03001383 for vdu in get_iterable(vnfd.get("vdu")):
1384 for cpd in get_iterable(vnfd.get("int-cpd")):
1385 if cpd.get("int-virtual-link-desc"):
1386 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1387
1388 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1389 if in_ivld.get("name") in vnfd_ivlds_cpds:
1390 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1391 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001392 break
tiernob24258a2018-10-04 18:39:49 +02001393 else:
garciadeblas4568a372021-03-24 09:19:48 +01001394 raise EngineException(
1395 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1396 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1397 "vnfd:internal-vld:name/id:internal-connection-point".format(
1398 in_vnf["member-vnf-index"],
1399 in_ivld["name"],
1400 in_icp["id-ref"],
1401 )
1402 )
tiernob24258a2018-10-04 18:39:49 +02001403 else:
garciadeblas4568a372021-03-24 09:19:48 +01001404 raise EngineException(
1405 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1406 " is not present at vnfd '{}'".format(
1407 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1408 )
1409 )
tiernob24258a2018-10-04 18:39:49 +02001410
garciaale7cbd03c2020-11-27 10:38:35 -03001411 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1412 if vim_account in vim_accounts:
1413 return
1414 try:
1415 db_filter = self._get_project_filter(session)
1416 db_filter["_id"] = vim_account
1417 self.db.get_one("vim_accounts", db_filter)
1418 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001419 raise EngineException(
1420 "Invalid vimAccountId='{}' not present for the project".format(
1421 vim_account
1422 )
1423 )
garciaale7cbd03c2020-11-27 10:38:35 -03001424 vim_accounts.append(vim_account)
1425
David Garcia98de2982021-10-13 17:14:01 +02001426 def _get_vim_account(self, vim_id: str, session):
1427 try:
1428 db_filter = self._get_project_filter(session)
1429 db_filter["_id"] = vim_id
1430 return self.db.get_one("vim_accounts", db_filter)
1431 except Exception:
1432 raise EngineException(
1433 "Invalid vimAccountId='{}' not present for the project".format(
1434 vim_id
1435 )
1436 )
1437
garciaale7cbd03c2020-11-27 10:38:35 -03001438 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1439 if not isinstance(wim_account, str):
1440 return
1441 if wim_account in wim_accounts:
1442 return
1443 try:
1444 db_filter = self._get_project_filter(session, write=False, show_all=True)
1445 db_filter["_id"] = wim_account
1446 self.db.get_one("wim_accounts", db_filter)
1447 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001448 raise EngineException(
1449 "Invalid wimAccountId='{}' not present for the project".format(
1450 wim_account
1451 )
1452 )
garciaale7cbd03c2020-11-27 10:38:35 -03001453 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001454
garciadeblas4568a372021-03-24 09:19:48 +01001455 def _look_for_pdu(
1456 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1457 ):
tiernocc103432018-10-19 14:10:35 +02001458 """
tierno36ec8602018-11-02 17:27:11 +01001459 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1460 (ip_address, ...) information.
1461 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001462 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001463 :param rollback: list with the database modifications to rollback if needed
1464 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1465 :param vim_account: vim_account where this vnfr should be deployed
1466 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1467 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1468 of the changed vnfr is needed
1469
1470 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1471 "vim-network-name": used at VIM
1472 "name": interface name
1473 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1474 "ns-vld-id": NSD vld where this interface is connected.
1475 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 +02001476 """
tierno36ec8602018-11-02 17:27:11 +01001477
1478 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001479 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1480 if not vdur.get("pdu-type"):
1481 continue
1482 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001483 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001484 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001485 pdu_filter["type"] = pdu_type
1486 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001487 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001488 # TODO feature 1417: "shared": True,
1489
1490 available_pdus = self.db.get_list("pdus", pdu_filter)
1491 for pdu in available_pdus:
1492 # step 1 check if this pdu contains needed interfaces:
1493 match_interfaces = True
1494 for vdur_interface in vdur["interfaces"]:
1495 for pdu_interface in pdu["interfaces"]:
1496 if pdu_interface["name"] == vdur_interface["name"]:
1497 # TODO feature 1417: match per mgmt type
1498 break
1499 else: # no interface found for name
1500 match_interfaces = False
1501 break
1502 if match_interfaces:
1503 break
1504 else:
1505 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001506 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001507 "names".format(
1508 pdu_type,
1509 vim_account,
1510 vnfr["member-vnf-index-ref"],
1511 vdur["vdu-id-ref"],
1512 )
1513 )
tiernocc103432018-10-19 14:10:35 +02001514
1515 # step 2. Update pdu
1516 rollback_pdu = {
1517 "_admin.usageState": pdu["_admin"]["usageState"],
1518 "_admin.usage.vnfr_id": None,
1519 "_admin.usage.nsr_id": None,
1520 "_admin.usage.vdur": None,
1521 }
garciadeblas4568a372021-03-24 09:19:48 +01001522 self.db.set_one(
1523 "pdus",
1524 {"_id": pdu["_id"]},
1525 {
1526 "_admin.usageState": "IN_USE",
1527 "_admin.usage": {
1528 "vnfr_id": vnfr["_id"],
1529 "nsr_id": vnfr["nsr-id-ref"],
1530 "vdur": vdur["vdu-id-ref"],
1531 },
1532 },
1533 )
1534 rollback.append(
1535 {
1536 "topic": "pdus",
1537 "_id": pdu["_id"],
1538 "operation": "set",
1539 "content": rollback_pdu,
1540 }
1541 )
tiernocc103432018-10-19 14:10:35 +02001542
1543 # step 3. Fill vnfr info by filling vdur
1544 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001545 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001546 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1547 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1548 for pdu_interface in pdu["interfaces"]:
1549 if pdu_interface["name"] == vdur_interface["name"]:
1550 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1551 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001552 if k in (
1553 "ip-address",
1554 "mac-address",
1555 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001556 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001557 vnfr_update_rollback[
1558 iface_text + ".{}".format(k)
1559 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001560 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001561 if vdur_interface.get(
1562 "mgmt-interface"
1563 ) or vdur_interface.get("mgmt-vnf"):
1564 vnfr_update_rollback[
1565 vdu_text + ".ip-address"
1566 ] = vdur.get("ip-address")
1567 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1568 "ip-address"
1569 ]
tierno36ec8602018-11-02 17:27:11 +01001570 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001571 vnfr_update_rollback["ip-address"] = vnfr.get(
1572 "ip-address"
1573 )
tierno36ec8602018-11-02 17:27:11 +01001574 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001575 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1576 "ip-address"
1577 ]
1578 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1579 "vim-network-id"
1580 ):
1581 ifaces_forcing_vim_network.append(
1582 {
1583 "name": vdur_interface.get("vnf-vld-id")
1584 or vdur_interface.get("ns-vld-id"),
1585 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1586 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1587 }
1588 )
gcalvino17d5b732018-12-17 16:26:21 +01001589 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001590 ifaces_forcing_vim_network[-1][
1591 "vim-network-id"
1592 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001593 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001594 ifaces_forcing_vim_network[-1][
1595 "vim-network-name"
1596 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001597 break
1598
tierno36ec8602018-11-02 17:27:11 +01001599 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001600
garciadeblas4568a372021-03-24 09:19:48 +01001601 def _look_for_k8scluster(
1602 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1603 ):
tierno9cb7d672019-10-30 12:13:48 +00001604 """
1605 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1606 Fills vnfr.kdur with the selected k8scluster
1607
1608 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1609 :param rollback: list with the database modifications to rollback if needed
1610 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1611 :param vim_account: vim_account where this vnfr should be deployed
1612 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1613 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1614 of the changed vnfr is needed
1615
1616 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1617 "vim-network-name": used at VIM
1618 "name": interface name
1619 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1620 "ns-vld-id": NSD vld where this interface is connected.
1621 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1622 """
1623
1624 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001625 if not vnfr.get("kdur"):
1626 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001627
tiernoc67b0e92019-11-05 12:45:29 +00001628 kdu_filter = self._get_project_filter(session)
1629 kdu_filter["vim_account"] = vim_account
1630 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1631 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1632
1633 k8s_requirements = {} # just for logging
1634 for k8scluster in available_k8sclusters:
1635 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001636 break
tiernoc67b0e92019-11-05 12:45:29 +00001637 # restrict by cni
1638 if vnfr["k8s-cluster"].get("cni"):
1639 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001640 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1641 k8scluster.get("cni", ())
1642 ):
tiernoc67b0e92019-11-05 12:45:29 +00001643 continue
1644 # restrict by version
1645 if vnfr["k8s-cluster"].get("version"):
1646 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1647 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1648 continue
1649 # restrict by number of networks
1650 if vnfr["k8s-cluster"].get("nets"):
1651 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001652 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1653 vnfr["k8s-cluster"]["nets"]
1654 ):
tiernoc67b0e92019-11-05 12:45:29 +00001655 continue
1656 break
1657 else:
garciadeblas4568a372021-03-24 09:19:48 +01001658 raise EngineException(
1659 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1660 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1661 )
1662 )
tierno9cb7d672019-10-30 12:13:48 +00001663
tiernoc67b0e92019-11-05 12:45:29 +00001664 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001665 # step 3. Fill vnfr info by filling kdur
1666 kdu_text = "kdur.{}.".format(kdur_index)
1667 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1668 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1669
tiernoc67b0e92019-11-05 12:45:29 +00001670 # step 4. Check VIM networks that forces the selected k8s_cluster
1671 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1672 k8scluster_net_list = list(k8scluster.get("nets").keys())
1673 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1674 # get a network from k8s_cluster nets. If name matches use this, if not use other
1675 if kdur_net["id"] in k8scluster_net_list: # name matches
1676 vim_net = k8scluster["nets"][kdur_net["id"]]
1677 k8scluster_net_list.remove(kdur_net["id"])
1678 else:
1679 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1680 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001681 vnfr_update_rollback[
1682 "k8s-cluster.nets.{}.vim_net".format(net_index)
1683 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001684 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001685 if vim_net and (
1686 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1687 ):
1688 ifaces_forcing_vim_network.append(
1689 {
1690 "name": kdur_net.get("vnf-vld-id")
1691 or kdur_net.get("ns-vld-id"),
1692 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1693 "ns-vld-id": kdur_net.get("ns-vld-id"),
1694 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1695 }
1696 )
tiernoc67b0e92019-11-05 12:45:29 +00001697 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001698 return ifaces_forcing_vim_network
1699
Gulsum Aticie395aa42021-11-10 20:59:06 +03001700 def _update_vnfrs_from_nsd(self, nsr):
1701 try:
1702 nsr_id = nsr["_id"]
1703 nsd = nsr["nsd"]
1704
1705 step = "Getting vnf_profiles from nsd"
1706 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1707 vld_fixed_ip_connection_point_data = {}
1708
1709 step = "Getting ip-address info from vnf_profile if it exists"
1710 for vnfp in vnf_profiles:
1711 # Checking ip-address info from nsd.vnf_profile and storing
1712 for vlc in vnfp.get("virtual-link-connectivity", ()):
1713 for cpd in vlc.get("constituent-cpd-id", ()):
1714 if cpd.get("ip-address"):
1715 step = "Storing ip-address info"
1716 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1717 "vnfd-connection-point-ref": cpd.get(
1718 "constituent-cpd-id"),
1719 "ip-address": cpd.get(
1720 "ip-address")}})
1721
1722 # Inserting ip address to vnfr
1723 if len(vld_fixed_ip_connection_point_data) > 0:
1724 step = "Getting vnfrs"
1725 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1726 for item in vld_fixed_ip_connection_point_data.keys():
1727 step = "Filtering vnfrs"
1728 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1729 if vnfr:
1730 vnfr_update = {}
1731 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1732 for iface_index, iface in enumerate(vdur["interfaces"]):
1733 step = "Looking for matched interface"
1734 if (
1735 iface.get("external-connection-point-ref")
1736 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1737 iface.get("ns-vld-id") == item.split('.')[0]
1738
1739 ):
1740 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1741 vdur_index, iface_index
1742 )
1743 step = "Storing info in order to update vnfr"
1744 vnfr_update[
1745 vnfr_update_text + ".ip-address"
1746 ] = increment_ip_mac(
1747 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1748 vdur.get("count-index", 0), )
1749 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1750
1751 step = "updating vnfr at database"
1752 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1753 except (
1754 ValidationError,
1755 EngineException,
1756 DbException,
1757 MsgException,
1758 FsException,
1759 ) as e:
1760 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1761
tiernocc103432018-10-19 14:10:35 +02001762 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001763 # get vnfr
1764 nsr_id = nsr["_id"]
1765 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1766
1767 for vnfr in vnfrs:
1768 vnfr_update = {}
1769 vnfr_update_rollback = {}
1770 member_vnf_index = vnfr["member-vnf-index-ref"]
1771 # update vim-account-id
1772
1773 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02001774 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001775 # check instantiate parameters
1776 for vnf_inst_params in get_iterable(indata.get("vnf")):
1777 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1778 continue
1779 if vnf_inst_params.get("vimAccountId"):
1780 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02001781 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001782
tiernocddb07d2020-10-06 08:28:00 +00001783 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1784 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1785 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1786 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1787 continue
garciadeblas4568a372021-03-24 09:19:48 +01001788 for iface_inst_param in get_iterable(
1789 vdu_inst_param.get("interface")
1790 ):
1791 iface_index, _ = next(
1792 i
1793 for i in enumerate(vdur["interfaces"])
1794 if i[1]["name"] == iface_inst_param["name"]
1795 )
1796 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1797 vdur_index, iface_index
1798 )
tiernocddb07d2020-10-06 08:28:00 +00001799 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001800 vnfr_update[
1801 vnfr_update_text + ".ip-address"
1802 ] = increment_ip_mac(
1803 iface_inst_param.get("ip-address"),
1804 vdur.get("count-index", 0),
1805 )
tierno1bd9d952020-11-13 15:56:51 +00001806 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001807 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001808 vnfr_update[
1809 vnfr_update_text + ".mac-address"
1810 ] = increment_ip_mac(
1811 iface_inst_param.get("mac-address"),
1812 vdur.get("count-index", 0),
1813 )
tierno1bd9d952020-11-13 15:56:51 +00001814 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001815 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001816 vnfr_update[
1817 vnfr_update_text + ".floating-ip-required"
1818 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001819 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1820 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001821 for ivld_inst_param in get_iterable(
1822 vnf_inst_params.get("internal-vld")
1823 ):
1824 for icp_inst_param in get_iterable(
1825 ivld_inst_param.get("internal-connection-point")
1826 ):
tiernocddb07d2020-10-06 08:28:00 +00001827 # look for iface
1828 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1829 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001830 if (
1831 iface.get("internal-connection-point-ref")
1832 == icp_inst_param["id-ref"]
1833 ):
1834 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1835 vdur_index, iface_index
1836 )
tiernocddb07d2020-10-06 08:28:00 +00001837 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001838 vnfr_update[
1839 vnfr_update_text + ".ip-address"
1840 ] = increment_ip_mac(
1841 icp_inst_param.get("ip-address"),
1842 vdur.get("count-index", 0),
1843 )
1844 vnfr_update[
1845 vnfr_update_text + ".fixed-ip"
1846 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001847 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001848 vnfr_update[
1849 vnfr_update_text + ".mac-address"
1850 ] = increment_ip_mac(
1851 icp_inst_param.get("mac-address"),
1852 vdur.get("count-index", 0),
1853 )
1854 vnfr_update[
1855 vnfr_update_text + ".fixed-mac"
1856 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001857 break
1858 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1859 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001860 for vnfcp_inst_param in get_iterable(
1861 vld_inst_param.get("vnfd-connection-point-ref")
1862 ):
tiernocddb07d2020-10-06 08:28:00 +00001863 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1864 continue
1865 # look for iface
1866 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1867 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001868 if (
1869 iface.get("external-connection-point-ref")
1870 == vnfcp_inst_param["vnfd-connection-point-ref"]
1871 ):
1872 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1873 vdur_index, iface_index
1874 )
tiernocddb07d2020-10-06 08:28:00 +00001875 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001876 vnfr_update[
1877 vnfr_update_text + ".ip-address"
1878 ] = increment_ip_mac(
1879 vnfcp_inst_param.get("ip-address"),
1880 vdur.get("count-index", 0),
1881 )
tierno1bd9d952020-11-13 15:56:51 +00001882 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001883 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001884 vnfr_update[
1885 vnfr_update_text + ".mac-address"
1886 ] = increment_ip_mac(
1887 vnfcp_inst_param.get("mac-address"),
1888 vdur.get("count-index", 0),
1889 )
tierno1bd9d952020-11-13 15:56:51 +00001890 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001891 break
1892
tiernocc103432018-10-19 14:10:35 +02001893 vnfr_update["vim-account-id"] = vim_account
1894 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1895
David Garciaecb41322021-03-31 19:10:46 +02001896 if vca_id:
1897 vnfr_update["vca-id"] = vca_id
1898 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1899
tiernocc103432018-10-19 14:10:35 +02001900 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01001901 ifaces_forcing_vim_network = self._look_for_pdu(
1902 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1903 )
tiernocc103432018-10-19 14:10:35 +02001904
tierno9cb7d672019-10-30 12:13:48 +00001905 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01001906 ifaces_forcing_vim_network += self._look_for_k8scluster(
1907 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1908 )
tierno9cb7d672019-10-30 12:13:48 +00001909 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001910 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01001911 rollback.append(
1912 {
1913 "topic": "vnfrs",
1914 "_id": vnfr["_id"],
1915 "operation": "set",
1916 "content": vnfr_update_rollback,
1917 }
1918 )
tierno36ec8602018-11-02 17:27:11 +01001919
1920 # Update indada in case pdu forces to use a concrete vim-network-name
1921 # TODO check if user has already insert a vim-network-name and raises an error
1922 if not ifaces_forcing_vim_network:
1923 continue
1924 for iface_info in ifaces_forcing_vim_network:
1925 if iface_info.get("ns-vld-id"):
1926 if "vld" not in indata:
1927 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001928 indata["vld"].append(
1929 {
1930 key: iface_info[key]
1931 for key in ("name", "vim-network-name", "vim-network-id")
1932 if iface_info.get(key)
1933 }
1934 )
tierno36ec8602018-11-02 17:27:11 +01001935
1936 elif iface_info.get("vnf-vld-id"):
1937 if "vnf" not in indata:
1938 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001939 indata["vnf"].append(
1940 {
1941 "member-vnf-index": member_vnf_index,
1942 "internal-vld": [
1943 {
1944 key: iface_info[key]
1945 for key in (
1946 "name",
1947 "vim-network-name",
1948 "vim-network-id",
1949 )
1950 if iface_info.get(key)
1951 }
1952 ],
1953 }
1954 )
tierno36ec8602018-11-02 17:27:11 +01001955
1956 @staticmethod
1957 def _create_nslcmop(nsr_id, operation, params):
1958 """
1959 Creates a ns-lcm-opp content to be stored at database.
1960 :param nsr_id: internal id of the instance
1961 :param operation: instantiate, terminate, scale, action, ...
1962 :param params: user parameters for the operation
1963 :return: dictionary following SOL005 format
1964 """
tiernob24258a2018-10-04 18:39:49 +02001965 now = time()
1966 _id = str(uuid4())
1967 nslcmop = {
1968 "id": _id,
1969 "_id": _id,
1970 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001971 "queuePosition": None,
1972 "stage": None,
1973 "errorMessage": None,
1974 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001975 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001976 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001977 "lcmOperationType": operation,
1978 "startTime": now,
1979 "isAutomaticInvocation": False,
1980 "operationParams": params,
1981 "isCancelPending": False,
1982 "links": {
1983 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001984 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01001985 },
tiernob24258a2018-10-04 18:39:49 +02001986 }
1987 return nslcmop
1988
magnussonlf318b302020-01-20 18:38:18 +01001989 def _get_enabled_vims(self, session):
1990 """
1991 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1992 :param session: current session with user information
1993 """
1994 db_filter = self._get_project_filter(session)
1995 db_filter["_admin.operationalState"] = "ENABLED"
1996 vims = self.db.get_list("vim_accounts", db_filter)
1997 vimAccounts = []
1998 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01001999 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01002000 return vimAccounts
2001
garciadeblas4568a372021-03-24 09:19:48 +01002002 def new(
2003 self,
2004 rollback,
2005 session,
2006 indata=None,
2007 kwargs=None,
2008 headers=None,
2009 slice_object=False,
2010 ):
tiernob24258a2018-10-04 18:39:49 +02002011 """
2012 Performs a new operation over a ns
2013 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002014 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02002015 :param indata: descriptor with the parameters of the operation. It must contains among others
2016 nsInstanceId: _id of the nsr to perform the operation
2017 operation: it can be: instantiate, terminate, action, TODO: update, heal
2018 :param kwargs: used to override the indata descriptor
2019 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002020 :return: id of the nslcmops
2021 """
garciadeblas4568a372021-03-24 09:19:48 +01002022
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002023 def check_if_nsr_is_not_slice_member(session, nsr_id):
2024 nsis = None
2025 db_filter = self._get_project_filter(session)
2026 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002027 nsis = self.db.get_one(
2028 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2029 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002030 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002031 raise EngineException(
2032 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2033 nsr_id, nsis["_id"]
2034 ),
2035 http_code=HTTPStatus.CONFLICT,
2036 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002037
tiernob24258a2018-10-04 18:39:49 +02002038 try:
2039 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002040 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002041 operation = indata["lcmOperationType"]
2042 nsInstanceId = indata["nsInstanceId"]
2043
2044 validate_input(indata, self.operation_schema[operation])
2045 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002046 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002047 _filter["_id"] = nsInstanceId
2048 nsr = self.db.get_one("nsrs", _filter)
2049
2050 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002051 if operation == "terminate" and slice_object is False:
2052 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002053 if (
2054 not nsr["_admin"].get("nsState")
2055 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2056 ):
tiernob24258a2018-10-04 18:39:49 +02002057 if operation == "terminate" and indata.get("autoremove"):
2058 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002059 return (
2060 None,
2061 None,
2062 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002063 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002064 raise EngineException(
2065 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2066 nsInstanceId, operation
2067 ),
2068 HTTPStatus.CONFLICT,
2069 )
tiernob24258a2018-10-04 18:39:49 +02002070 else:
tierno65ca36d2019-02-12 19:27:52 +01002071 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002072 raise EngineException(
2073 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2074 nsInstanceId, operation
2075 ),
2076 HTTPStatus.CONFLICT,
2077 )
tiernob24258a2018-10-04 18:39:49 +02002078 self._check_ns_operation(session, nsr, operation, indata)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002079 if (indata.get("primitive_params")):
2080 indata["primitive_params"] = json.dumps(indata["primitive_params"])
2081 elif (indata.get("additionalParamsForVnf")):
2082 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
tierno36ec8602018-11-02 17:27:11 +01002083
tiernocc103432018-10-19 14:10:35 +02002084 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002085 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002086 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01002087
2088 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002089 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002090 self.format_on_new(
2091 nslcmop_desc, session["project_id"], make_public=session["public"]
2092 )
magnussonlf318b302020-01-20 18:38:18 +01002093 if indata.get("placement-engine"):
2094 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002095 nslcmop_desc["operationParams"][
2096 "validVimAccounts"
2097 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002098 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002099 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002100 if not slice_object:
2101 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002102 return _id, None
2103 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002104 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2105 # except DbException as e:
2106 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2107
tiernobee3bad2019-12-05 12:26:01 +00002108 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002109 raise EngineException(
2110 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2111 )
tiernob24258a2018-10-04 18:39:49 +02002112
tierno65ca36d2019-02-12 19:27:52 +01002113 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002114 raise EngineException(
2115 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2116 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002117
2118
2119class NsiTopic(BaseTopic):
2120 topic = "nsis"
2121 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002122 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002123
delacruzramo32bab472019-09-13 12:24:22 +02002124 def __init__(self, db, fs, msg, auth):
2125 BaseTopic.__init__(self, db, fs, msg, auth)
2126 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002127
Felipe Vicensc37b3842019-01-12 12:24:42 +01002128 @staticmethod
2129 def _format_ns_request(ns_request):
2130 formated_request = copy(ns_request)
2131 # TODO: Add request params
2132 return formated_request
2133
2134 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002135 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002136 """
2137 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002138 :param slice_request: User instantiation additional parameters
2139 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002140 """
tiernofd160572019-01-21 10:41:37 +00002141 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2142 if additional_params:
2143 for k, v in additional_params.items():
2144 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002145 raise EngineException(
2146 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2147 k
2148 )
2149 )
tiernofd160572019-01-21 10:41:37 +00002150 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002151 raise EngineException(
2152 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2153 k
2154 )
2155 )
tiernofd160572019-01-21 10:41:37 +00002156 if isinstance(v, (dict, tuple, list)):
2157 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002158 return additional_params
2159
Felipe Vicensb57758d2018-10-16 16:00:20 +02002160 def _check_descriptor_dependencies(self, session, descriptor):
2161 """
2162 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01002163 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002164 :param descriptor: descriptor to be inserted or edit
2165 :return: None or raises exception
2166 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002167 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002168 return
Felipe Vicens07f31722018-10-29 15:16:44 +01002169 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002170 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
garciadeblas4568a372021-03-24 09:19:48 +01002171 raise EngineException(
2172 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2173 nstd_id
2174 ),
2175 http_code=HTTPStatus.CONFLICT,
2176 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002177
tiernob4844ab2019-05-23 08:42:12 +00002178 def check_conflict_on_del(self, session, _id, db_content):
2179 """
2180 Check that NSI is not instantiated
2181 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2182 :param _id: nsi internal id
2183 :param db_content: The database content of the _id
2184 :return: None or raises EngineException with the conflict
2185 """
tierno65ca36d2019-02-12 19:27:52 +01002186 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002187 return
tiernob4844ab2019-05-23 08:42:12 +00002188 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002189 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002190 raise EngineException(
2191 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2192 "Launch 'terminate' operation first; or force deletion".format(_id),
2193 http_code=HTTPStatus.CONFLICT,
2194 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002195
tiernobee3bad2019-12-05 12:26:01 +00002196 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002197 """
tiernob4844ab2019-05-23 08:42:12 +00002198 Deletes associated nsilcmops from database. Deletes associated filesystem.
2199 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002200 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002201 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002202 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002203 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002204 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002205 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002206
Felipe Vicens09e65422019-01-22 15:06:46 +01002207 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002208 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002209 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2210 nsr_id = nsrs_detailed_item["nsrId"]
2211 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002212 _filter = {
2213 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2214 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2215 "_id.ne": nsir["_id"],
2216 }
2217 nsi = self.db.get_one(
2218 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2219 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002220 if nsi: # last one using nsr
2221 continue
2222 try:
garciadeblas4568a372021-03-24 09:19:48 +01002223 self.nsrTopic.delete(
2224 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2225 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002226 except (DbException, EngineException) as e:
2227 if e.http_code == HTTPStatus.NOT_FOUND:
2228 pass
2229 else:
2230 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002231
tiernob4844ab2019-05-23 08:42:12 +00002232 # delete related nsilcmops database entries
2233 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002234
tiernob4844ab2019-05-23 08:42:12 +00002235 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002236 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002237 if nsir_admin and nsir_admin.get("nst-id"):
2238 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002239 nsis_list = self.db.get_one(
2240 "nsis",
2241 {"nst-id": nsir_admin["nst-id"]},
2242 fail_on_empty=False,
2243 fail_on_more=False,
2244 )
tiernob4844ab2019-05-23 08:42:12 +00002245 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002246 self.db.set_one(
2247 "nsts",
2248 {"_id": nsir_admin["nst-id"]},
2249 {"_admin.usageState": "NOT_IN_USE"},
2250 )
tiernob4844ab2019-05-23 08:42:12 +00002251
tierno65ca36d2019-02-12 19:27:52 +01002252 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002253 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002254 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002255 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002256 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002257 :param indata: params to be used for the nsir
2258 :param kwargs: used to override the indata descriptor
2259 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002260 :return: the _id of nsi descriptor created at database
2261 """
2262
2263 try:
delacruzramo32bab472019-09-13 12:24:22 +02002264 step = "checking quotas"
2265 self.check_quota(session)
2266
tierno99d4b172019-07-02 09:28:40 +00002267 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002268 slice_request = self._remove_envelop(indata)
2269 # Override descriptor with query string kwargs
2270 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002271 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002272
Felipe Vicensb57758d2018-10-16 16:00:20 +02002273 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002274 step = "getting nstd id='{}' from database".format(
2275 slice_request.get("nstId")
2276 )
tiernob4844ab2019-05-23 08:42:12 +00002277 _filter = self._get_project_filter(session)
2278 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002279 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002280 # check NST is not disabled
2281 step = "checking NST operationalState"
2282 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002283 raise EngineException(
2284 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2285 "instance".format(slice_request["nstId"]),
2286 http_code=HTTPStatus.CONFLICT,
2287 )
tiernob4844ab2019-05-23 08:42:12 +00002288 del _filter["_id"]
2289
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002290 # check NSD is not disabled
2291 step = "checking operationalState"
2292 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002293 raise EngineException(
2294 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2295 "a network slice".format(slice_request["nstId"]),
2296 http_code=HTTPStatus.CONFLICT,
2297 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002298
Felipe Vicens07f31722018-10-29 15:16:44 +01002299 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002300 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002301 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002302 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002303
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002304 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002305 nsi_descriptor = {
2306 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002307 "name": slice_request["nsiName"],
2308 "description": slice_request.get("nsiDescription", ""),
2309 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002310 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002311 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002312 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002313 "nsr-ref-list": [],
2314 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002315 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002316 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002317 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002318
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002319 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002320 self.format_on_new(
2321 nsi_descriptor, session["project_id"], make_public=session["public"]
2322 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002323 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2324 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002325 nsi_descriptor["_admin"]["deployed"] = {}
2326 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2327 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2328
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002329 # Creating netslice-vld for the RO.
2330 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002331
2332 # Building the vlds list to be deployed
2333 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002334 nsi_vlds = []
2335
2336 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2337 # Getting template Instantiation parameters from NST
2338 nsi_vld = deepcopy(netslice_vlds)
2339 nsi_vld["shared-nsrs-list"] = []
2340 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2341 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002342
2343 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002344 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002345 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002346 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002347
Felipe Vicens09e65422019-01-22 15:06:46 +01002348 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002349 for member_ns in nstd["netslice-subnet"]:
2350 nsd_id = member_ns["nsd-ref"]
2351 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002352 member_ns["nsd-ref"], member_ns["id"]
2353 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002354 if nsd_id not in needed_nsds:
2355 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002356 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002357 nsd = self.db.get_one(
2358 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2359 )
tiernob4844ab2019-05-23 08:42:12 +00002360 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002361 nsd.pop("_admin")
2362 needed_nsds[nsd_id] = nsd
2363 else:
2364 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002365 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2366 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002367
Felipe Vicensb57758d2018-10-16 16:00:20 +02002368 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002369 member_ns["nsd-ref"], member_ns["id"]
2370 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002371
Felipe Vicens07f31722018-10-29 15:16:44 +01002372 # creates Network Services records (NSRs)
2373 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002374 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002375 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002376 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002377 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002378 # Check if the netslice-subnet is shared and if it is share if the nss exists
2379 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002380 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002381 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002382 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002383 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2384 "nsd-ref"
2385 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002386 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002387 nsi = self.db.get_one(
2388 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2389 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002390 if nsi and service.get("is-shared-nss"):
2391 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2392 for nsrs_detailed_item in nsrs_detailed_list:
2393 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002394 if nsrs_detailed_item["nss-id"] == service["id"]:
2395 _id_nsr = nsrs_detailed_item["nsrId"]
2396 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002397 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2398 if netslice_subnet["nss-id"] == service["id"]:
2399 indata_ns = netslice_subnet
2400 break
2401 else:
2402 indata_ns = {}
2403 if service.get("instantiation-parameters"):
2404 indata_ns = deepcopy(service["instantiation-parameters"])
2405 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002406
Felipe Vicens09e65422019-01-22 15:06:46 +01002407 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002408 indata_ns["nsName"] = (
2409 slice_request.get("nsiName") + "." + service["id"]
2410 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002411 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2412 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002413 if slice_request.get("ssh_keys"):
2414 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002415
Felipe Vicens09e65422019-01-22 15:06:46 +01002416 if ns_params:
2417 for ns_param in ns_params:
2418 if ns_param.get("id") == service["id"]:
2419 copy_ns_param = deepcopy(ns_param)
2420 del copy_ns_param["id"]
2421 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002422 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002423
2424 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002425 _id_nsr, _ = self.nsrTopic.new(
2426 rollback, session, indata_ns, kwargs, headers
2427 )
2428 nsrs_item = {
2429 "nsrId": _id_nsr,
2430 "shared": service.get("is-shared-nss"),
2431 "nsd-id": service["nsd-ref"],
2432 "nss-id": service["id"],
2433 "nslcmop_instantiate": None,
2434 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002435 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002436 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002437 nsi_netslice_subnet.append(indata_ns)
2438 nsr_ref = {"nsr-ref": _id_nsr}
2439 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002440
2441 # Adding the nsrs list to the nsi
2442 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002443 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002444 self.db.set_one(
2445 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2446 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002447
Felipe Vicens07f31722018-10-29 15:16:44 +01002448 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002449 self.db.create("nsis", nsi_descriptor)
2450 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002451 return nsi_id, None
garciadeblas4568a372021-03-24 09:19:48 +01002452 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2453 self.logger.exception(
2454 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2455 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002456 raise EngineException("Error {}: {}".format(step, e))
2457 except ValidationError as e:
2458 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2459
tierno65ca36d2019-02-12 19:27:52 +01002460 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002461 raise EngineException(
2462 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2463 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002464
2465
2466class NsiLcmOpTopic(BaseTopic):
2467 topic = "nsilcmops"
2468 topic_msg = "nsi"
2469 operation_schema = { # mapping between operation and jsonschema to validate
2470 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002471 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002472 }
garciadeblas4568a372021-03-24 09:19:48 +01002473
delacruzramo32bab472019-09-13 12:24:22 +02002474 def __init__(self, db, fs, msg, auth):
2475 BaseTopic.__init__(self, db, fs, msg, auth)
2476 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002477
2478 def _check_nsi_operation(self, session, nsir, operation, indata):
2479 """
2480 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002481 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002482 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2483 :param indata: descriptor with the parameters of the operation
2484 :return: None
2485 """
2486 nsds = {}
2487 nstd = nsir["network-slice-template"]
2488
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002489 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002490 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002491 for netslice_subnet in nstd["netslice-subnet"]:
2492 if nstId == netslice_subnet["id"]:
2493 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002494 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002495 _filter = self._get_project_filter(session)
2496 _filter["id"] = nsd_id
2497 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002498 return nsds[nsd_id]
2499 else:
garciadeblas4568a372021-03-24 09:19:48 +01002500 raise EngineException(
2501 "Invalid parameter nstId='{}' is not one of the "
2502 "nst:netslice-subnet".format(nstId)
2503 )
2504
Felipe Vicens07f31722018-10-29 15:16:44 +01002505 if operation == "instantiate":
2506 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002507 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002508 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002509
2510 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2511 now = time()
2512 _id = str(uuid4())
2513 nsilcmop = {
2514 "id": _id,
2515 "_id": _id,
2516 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2517 "statusEnteredTime": now,
2518 "netsliceInstanceId": netsliceInstanceId,
2519 "lcmOperationType": operation,
2520 "startTime": now,
2521 "isAutomaticInvocation": False,
2522 "operationParams": params,
2523 "isCancelPending": False,
2524 "links": {
2525 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002526 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2527 + netsliceInstanceId,
2528 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002529 }
2530 return nsilcmop
2531
Felipe Vicens09e65422019-01-22 15:06:46 +01002532 def add_shared_nsr_2vld(self, nsir, nsr_item):
2533 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2534 if nst_sb_item.get("is-shared-nss"):
2535 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2536 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2537 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002538 for admin_vld_nss_cp_ref_item in admin_vld_item[
2539 "nss-connection-point-ref"
2540 ]:
2541 if (
2542 admin_subnet_item["nss-id"]
2543 == admin_vld_nss_cp_ref_item["nss-ref"]
2544 ):
2545 if (
2546 not nsr_item["nsrId"]
2547 in admin_vld_item["shared-nsrs-list"]
2548 ):
2549 admin_vld_item["shared-nsrs-list"].append(
2550 nsr_item["nsrId"]
2551 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002552 break
2553 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002554 self.db.set_one(
2555 "nsis",
2556 {"_id": nsir["_id"]},
2557 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2558 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002559
tierno65ca36d2019-02-12 19:27:52 +01002560 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002561 """
2562 Performs a new operation over a ns
2563 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002564 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002565 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002566 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002567 operation: it can be: instantiate, terminate, action, TODO: update, heal
2568 :param kwargs: used to override the indata descriptor
2569 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002570 :return: id of the nslcmops
2571 """
2572 try:
2573 # Override descriptor with query string kwargs
2574 self._update_input_with_kwargs(indata, kwargs)
2575 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002576 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002577 validate_input(indata, self.operation_schema[operation])
2578
Felipe Vicens126af572019-06-05 19:13:04 +02002579 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002580 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002581 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002582 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002583 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002584 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002585
2586 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002587 if (
2588 not nsir["_admin"].get("nsiState")
2589 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2590 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002591 if operation == "terminate" and indata.get("autoremove"):
2592 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002593 return (
2594 None,
2595 None,
2596 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002597 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002598 raise EngineException(
2599 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2600 netsliceInstanceId, operation
2601 ),
2602 HTTPStatus.CONFLICT,
2603 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002604 else:
tierno65ca36d2019-02-12 19:27:52 +01002605 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002606 raise EngineException(
2607 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2608 netsliceInstanceId, operation
2609 ),
2610 HTTPStatus.CONFLICT,
2611 )
2612
Felipe Vicens07f31722018-10-29 15:16:44 +01002613 # Creating all the NS_operation (nslcmop)
2614 # Get service list from db
2615 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2616 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002617 # nslcmops_item = None
2618 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002619 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002620 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002621 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002622 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002623 _filter[
2624 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2625 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002626 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002627 nsi = self.db.get_one(
2628 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2629 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002630 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002631 _update = {
2632 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2633 index
2634 ): None
2635 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002636 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002637 if (
2638 nsi
2639 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002640 continue # do not create nsilcmop
2641 else: # instantiate
2642 # looks the first nsi fulfilling the conditions but not being the current NSIR
2643 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002644 nsi_nsr_item = next(
2645 n
2646 for n in nsi["_admin"]["nsrs-detailed-list"]
2647 if n["nsrId"] == nsr_id
2648 and n["shared"]
2649 and n["nslcmop_instantiate"]
2650 )
tierno40f742b2020-06-23 15:25:26 +00002651 self.add_shared_nsr_2vld(nsir, nsr_item)
2652 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002653 _update = {
2654 "_admin.nsrs-detailed-list.{}".format(
2655 index
2656 ): nsi_nsr_item
2657 }
tierno40f742b2020-06-23 15:25:26 +00002658 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2659 # continue to not create nslcmop since nsrs is shared and nsrs was created
2660 continue
2661 else:
2662 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002663
tierno40f742b2020-06-23 15:25:26 +00002664 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002665 try:
tierno0b8752f2020-05-12 09:42:02 +00002666 indata_ns = {
2667 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002668 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002669 # Including netslice_id in the ns instantiate Operation
2670 "netsliceInstanceId": netsliceInstanceId,
2671 }
2672 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002673 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002674 indata_ns.update(service["instantiate_params"])
2675
tierno99d4b172019-07-02 09:28:40 +00002676 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002677 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002678 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2679 rollback, session, indata_ns, None, headers, slice_object=True
2680 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002681 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002682 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002683 _update = {
2684 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2685 index
2686 ): nslcmop
2687 }
tierno40f742b2020-06-23 15:25:26 +00002688 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002689 except (DbException, EngineException) as e:
2690 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002691 self.logger.info(
2692 logging_prefix
2693 + "skipping NS={} because not found".format(nsr_id)
2694 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002695 pass
2696 else:
2697 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002698
2699 # Creates nsilcmop
2700 indata["nslcmops_ids"] = nslcmops
2701 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002702
garciadeblas4568a372021-03-24 09:19:48 +01002703 nsilcmop_desc = self._create_nsilcmop(
2704 session, netsliceInstanceId, operation, indata
2705 )
2706 self.format_on_new(
2707 nsilcmop_desc, session["project_id"], make_public=session["public"]
2708 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002709 _id = self.db.create("nsilcmops", nsilcmop_desc)
2710 rollback.append({"topic": "nsilcmops", "_id": _id})
2711 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002712 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002713 except ValidationError as e:
2714 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002715
tiernobee3bad2019-12-05 12:26:01 +00002716 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002717 raise EngineException(
2718 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2719 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002720
tierno65ca36d2019-02-12 19:27:52 +01002721 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002722 raise EngineException(
2723 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2724 )