blob: 39d98342cb2bcef6de376271a4aeab289bd89587 [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)
tiernob24258a2018-10-04 18:39:49 +0200351 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000352 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200353 else:
354 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100355
garciadeblas4568a372021-03-24 09:19:48 +0100356 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
357 vnfd_id, vnf_index
358 )
359 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
360 nsd,
361 vnfd,
362 vnfd_id,
363 vnf_index,
364 nsr_descriptor,
365 ns_request,
366 ns_k8s_namespace,
367 )
tierno36ec8602018-11-02 17:27:11 +0100368
garciadeblas4568a372021-03-24 09:19:48 +0100369 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
370 vnfd_id, vnf_index
371 )
garciaale7cbd03c2020-11-27 10:38:35 -0300372 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
373 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
tiernob24258a2018-10-04 18:39:49 +0200374
375 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300376 self._add_nsr_to_db(nsr_descriptor, rollback, session)
tiernobee085c2018-12-12 17:03:04 +0000377
378 step = "creating nsr temporal folder"
379 self.fs.mkdir(nsr_id)
380
tiernobdebce92019-07-01 15:36:49 +0000381 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100382 except (
383 ValidationError,
384 EngineException,
385 DbException,
386 MsgException,
387 FsException,
388 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000389 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200390
garciaale7cbd03c2020-11-27 10:38:35 -0300391 def _get_nsd_from_db(self, nsd_id, session):
392 _filter = self._get_project_filter(session)
393 _filter["_id"] = nsd_id
394 return self.db.get_one("nsds", _filter)
395
396 def _get_vnfd_from_db(self, vnfd_id, session):
397 _filter = self._get_project_filter(session)
398 _filter["id"] = vnfd_id
399 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
400 vnfd.pop("_admin")
401 return vnfd
402
403 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100404 self.format_on_new(
405 nsr_descriptor, session["project_id"], make_public=session["public"]
406 )
garciaale7cbd03c2020-11-27 10:38:35 -0300407 self.db.create("nsrs", nsr_descriptor)
408 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
409
410 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100411 self.format_on_new(
412 vnfr_descriptor, session["project_id"], make_public=session["public"]
413 )
garciaale7cbd03c2020-11-27 10:38:35 -0300414 self.db.create("vnfrs", vnfr_descriptor)
415 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
416
417 def _check_nsd_operational_state(self, nsd, ns_request):
418 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100419 raise EngineException(
420 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
421 "a network service".format(ns_request["nsdId"]),
422 http_code=HTTPStatus.CONFLICT,
423 )
garciaale7cbd03c2020-11-27 10:38:35 -0300424
425 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100426 additional_params, _ = self._format_additional_params(
427 ns_request, descriptor=nsd
428 )
garciaale7cbd03c2020-11-27 10:38:35 -0300429 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
430 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
431 if ns_request and ns_request.get("k8s-namespace"):
432 ns_k8s_namespace = ns_request["k8s-namespace"]
433 if additional_params and additional_params.get("k8s-namespace"):
434 ns_k8s_namespace = additional_params["k8s-namespace"]
435
436 return ns_k8s_namespace
437
bravofe76b8822021-02-26 16:57:52 -0300438 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300439 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100440 additional_params, _ = self._format_additional_params(
441 ns_request, descriptor=nsd
442 )
garciaale7cbd03c2020-11-27 10:38:35 -0300443
444 nsr_descriptor = {
445 "name": ns_request["nsName"],
446 "name-ref": ns_request["nsName"],
447 "short-name": ns_request["nsName"],
448 "admin-status": "ENABLED",
449 "nsState": "NOT_INSTANTIATED",
450 "currentOperation": "IDLE",
451 "currentOperationID": None,
452 "errorDescription": None,
453 "errorDetail": None,
454 "deploymentStatus": None,
455 "configurationStatus": None,
456 "vcaStatus": None,
457 "nsd": {k: v for k, v in nsd.items()},
458 "datacenter": ns_request["vimAccountId"],
459 "resource-orchestrator": "osmopenmano",
460 "description": ns_request.get("nsDescription", ""),
461 "constituent-vnfr-ref": [],
462 "operational-status": "init", # typedef ns-operational-
463 "config-status": "init", # typedef config-states
464 "detailed-status": "scheduled",
465 "orchestration-progress": {},
466 "create-time": now,
467 "nsd-name-ref": nsd["name"],
468 "operational-events": [], # "id", "timestamp", "description", "event",
469 "nsd-ref": nsd["id"],
470 "nsd-id": nsd["_id"],
471 "vnfd-id": [],
472 "instantiate_params": self._format_ns_request(ns_request),
473 "additionalParamsForNs": additional_params,
474 "ns-instance-config-ref": nsr_id,
475 "id": nsr_id,
476 "_id": nsr_id,
477 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
478 "flavor": [],
479 "image": [],
Alexis Romero03fb5842022-03-11 15:53:40 +0100480 "affinity-or-anti-affinity-group": [],
garciaale7cbd03c2020-11-27 10:38:35 -0300481 }
482 ns_request["nsr_id"] = nsr_id
483 if ns_request and ns_request.get("config-units"):
484 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300485 # Create vld
486 if nsd.get("virtual-link-desc"):
487 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
488 # Fill each vld with vnfd-connection-point-ref data
489 # TODO: Change for multiple df support
490 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
491 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
492 for vnf_profile in vnf_profiles:
493 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
494 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100495 all_vld_connection_point_data[
496 vlc.get("virtual-link-profile-id")
497 ].append(
498 {
499 "member-vnf-index-ref": cpd.get(
500 "constituent-base-element-id"
501 ),
502 "vnfd-connection-point-ref": cpd.get(
503 "constituent-cpd-id"
504 ),
505 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
506 }
507 )
garciaale7cbd03c2020-11-27 10:38:35 -0300508
bravofe76b8822021-02-26 16:57:52 -0300509 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
garciaale7cbd03c2020-11-27 10:38:35 -0300510
511 for vdu in vnfd.get("vdu", ()):
512 flavor_data = {}
513 guest_epa = {}
514 # Find this vdu compute and storage descriptors
515 vdu_virtual_compute = {}
516 vdu_virtual_storage = {}
517 for vcd in vnfd.get("virtual-compute-desc", ()):
518 if vcd.get("id") == vdu.get("virtual-compute-desc"):
519 vdu_virtual_compute = vcd
520 for vsd in vnfd.get("virtual-storage-desc", ()):
521 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
522 vdu_virtual_storage = vsd
523 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblas4568a372021-03-24 09:19:48 +0100524 if vdu_virtual_compute.get("virtual-cpu", {}).get(
525 "num-virtual-cpu"
526 ):
527 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
528 "num-virtual-cpu"
529 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300530 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
garciadeblas4568a372021-03-24 09:19:48 +0100531 flavor_data["memory-mb"] = (
532 float(vdu_virtual_compute["virtual-memory"]["size"])
533 * 1024.0
534 )
garciaale7cbd03c2020-11-27 10:38:35 -0300535 if vdu_virtual_storage.get("size-of-storage"):
garciadeblas4568a372021-03-24 09:19:48 +0100536 flavor_data["storage-gb"] = vdu_virtual_storage[
537 "size-of-storage"
538 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300539 # Get this vdu EPA info for guest_epa
540 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100541 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
542 "cpu-quota"
543 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300544 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
545 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
546 if vcpu_pinning.get("thread-policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100547 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
548 "thread-policy"
549 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300550 if vcpu_pinning.get("policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100551 cpu_policy = (
552 "SHARED"
553 if vcpu_pinning["policy"] == "dynamic"
554 else "DEDICATED"
555 )
garciaale7cbd03c2020-11-27 10:38:35 -0300556 guest_epa["cpu-pinning-policy"] = cpu_policy
557 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100558 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
559 "mem-quota"
560 ]
561 if vdu_virtual_compute.get("virtual-memory", {}).get(
562 "mempage-size"
563 ):
564 guest_epa["mempage-size"] = vdu_virtual_compute[
565 "virtual-memory"
566 ]["mempage-size"]
567 if vdu_virtual_compute.get("virtual-memory", {}).get(
568 "numa-node-policy"
569 ):
570 guest_epa["numa-node-policy"] = vdu_virtual_compute[
571 "virtual-memory"
572 ]["numa-node-policy"]
garciaale7cbd03c2020-11-27 10:38:35 -0300573 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100574 guest_epa["disk-io-quota"] = vdu_virtual_storage[
575 "disk-io-quota"
576 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300577
578 if guest_epa:
579 flavor_data["guest-epa"] = guest_epa
580
581 flavor_data["name"] = vdu["id"][:56] + "-flv"
582 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
583 nsr_descriptor["flavor"].append(flavor_data)
584
585 sw_image_id = vdu.get("sw-image-desc")
586 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000587 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
588 self._add_image_to_nsr(nsr_descriptor, image_data)
589
590 # also add alternative images to the list of images
591 for alt_image in vdu.get("alternative-sw-image-desc", ()):
592 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
593 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300594
Alexis Romero03fb5842022-03-11 15:53:40 +0100595 # Add Affinity or Anti-affinity group information to NSR
596 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
597 ag_prefix_name = "{}-{}".format(nsr_descriptor["name"][:16], vnf_profile.get("id")[:16])
598
599 for vdu_profile in vdu_profiles:
600 ag_data = {}
601 for ag in vdu_profile.get("affinity-or-anti-affinity-group", ()):
602 ag_data = self._get_affinity_or_anti_affinity_group_data_from_vnfd(vnfd, ag["id"])
603 self._add_affinity_or_anti_affinity_group_to_nsr(nsr_descriptor, ag_data, ag_prefix_name)
604
garciaale7cbd03c2020-11-27 10:38:35 -0300605 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100606 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
607 vld.get("id"), []
608 )
garciaale7cbd03c2020-11-27 10:38:35 -0300609 vld["name"] = vld["id"]
610 nsr_descriptor["vld"] = nsr_vld
611
612 return nsr_descriptor
613
Alexis Romero03fb5842022-03-11 15:53:40 +0100614 def _get_affinity_or_anti_affinity_group_data_from_vnfd(self, vnfd, ag_id):
615 """
616 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
617 """
618 affinity_or_anti_affinity_group = utils.find_in_list(
619 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()), lambda ag: ag["id"] == ag_id
620 )
621 ag_data = {}
622 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("id"):
623 ag_data["ag-id"] = affinity_or_anti_affinity_group["id"]
624 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("type"):
625 ag_data["type"] = affinity_or_anti_affinity_group["type"]
626 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("scope"):
627 ag_data["scope"] = affinity_or_anti_affinity_group["scope"]
628 return ag_data
629
630 def _add_affinity_or_anti_affinity_group_to_nsr(self, nsr_descriptor, ag_data, ag_prefix_name):
631 """
632 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
633 """
634 ag = next(
635 (
636 f
637 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
638 if all(f.get(k) == ag_data[k] for k in ag_data)
639 ),
640 None,
641 )
642 if not ag:
643 ag_data["id"] = str(len(nsr_descriptor["affinity-or-anti-affinity-group"]))
644 ag_data["name"] = "{}-{}-{}".format(ag_prefix_name, ag_data["ag-id"][:32], ag_data.get("id") or 0)
645 nsr_descriptor["affinity-or-anti-affinity-group"].append(ag_data)
646
lloretgalleg28c13b62021-02-08 11:48:48 +0000647 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100648 sw_image_desc = utils.find_in_list(
649 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
650 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000651 image_data = {}
652 if sw_image_desc.get("image"):
653 image_data["image"] = sw_image_desc["image"]
654 if sw_image_desc.get("checksum"):
655 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
656 if sw_image_desc.get("vim-type"):
657 image_data["vim-type"] = sw_image_desc["vim-type"]
658 return image_data
659
660 def _add_image_to_nsr(self, nsr_descriptor, image_data):
661 """
662 Adds image to nsr checking first it is not already added
663 """
garciadeblas4568a372021-03-24 09:19:48 +0100664 img = next(
665 (
666 f
667 for f in nsr_descriptor["image"]
668 if all(f.get(k) == image_data[k] for k in image_data)
669 ),
670 None,
671 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000672 if not img:
673 image_data["id"] = str(len(nsr_descriptor["image"]))
674 nsr_descriptor["image"].append(image_data)
675
garciadeblas4568a372021-03-24 09:19:48 +0100676 def _create_vnfr_descriptor_from_vnfd(
677 self,
678 nsd,
679 vnfd,
680 vnfd_id,
681 vnf_index,
682 nsr_descriptor,
683 ns_request,
684 ns_k8s_namespace,
685 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300686 vnfr_id = str(uuid4())
687 nsr_id = nsr_descriptor["id"]
688 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100689 additional_params, vnf_params = self._format_additional_params(
690 ns_request, vnf_index, descriptor=vnfd
691 )
garciaale7cbd03c2020-11-27 10:38:35 -0300692
693 vnfr_descriptor = {
694 "id": vnfr_id,
695 "_id": vnfr_id,
696 "nsr-id-ref": nsr_id,
697 "member-vnf-index-ref": vnf_index,
698 "additionalParamsForVnf": additional_params,
699 "created-time": now,
700 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
701 "vnfd-ref": vnfd_id,
702 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
703 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200704 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300705 "vdur": [],
706 "connection-point": [],
707 "ip-address": None, # mgmt-interface filled by LCM
708 }
709 vnf_k8s_namespace = ns_k8s_namespace
710 if vnf_params:
711 if vnf_params.get("k8s-namespace"):
712 vnf_k8s_namespace = vnf_params["k8s-namespace"]
713 if vnf_params.get("config-units"):
714 vnfr_descriptor["config-units"] = vnf_params["config-units"]
715
716 # Create vld
717 if vnfd.get("int-virtual-link-desc"):
718 vnfr_descriptor["vld"] = []
719 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
720 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
721
722 for cp in vnfd.get("ext-cpd", ()):
723 vnf_cp = {
724 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100725 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
726 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300727 "id": cp.get("id"),
728 # "ip-address", "mac-address" # filled by LCM
729 # vim-id # TODO it would be nice having a vim port id
730 }
731 vnfr_descriptor["connection-point"].append(vnf_cp)
732
733 # Create k8s-cluster information
734 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
735 if vnfd.get("k8s-cluster"):
736 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
737 all_k8s_cluster_nets_cpds = {}
738 for cpd in get_iterable(vnfd.get("ext-cpd")):
739 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100740 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
741 "id"
742 )
garciaale7cbd03c2020-11-27 10:38:35 -0300743 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
744 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100745 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
746 net.get("id")
747 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300748
749 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300750 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100751 additional_params, kdu_params = self._format_additional_params(
752 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
753 )
garciaale7cbd03c2020-11-27 10:38:35 -0300754 kdu_k8s_namespace = vnf_k8s_namespace
755 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
756 if kdu_params and kdu_params.get("k8s-namespace"):
757 kdu_k8s_namespace = kdu_params["k8s-namespace"]
758
romeromonserbfebfc02021-05-28 10:51:35 +0200759 kdu_deployment_name = ""
760 if kdu_params and kdu_params.get("kdu-deployment-name"):
761 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
762
garciaale7cbd03c2020-11-27 10:38:35 -0300763 kdur = {
764 "additionalParams": additional_params,
765 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200766 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000767 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300768 # TODO "name": "" Name of the VDU in the VIM
769 "ip-address": None, # mgmt-interface filled by LCM
770 "k8s-cluster": {},
771 }
772 if kdu_params and kdu_params.get("config-units"):
773 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000774 if kdu.get("helm-version"):
775 kdur["helm-version"] = kdu["helm-version"]
776 for k8s_type in ("helm-chart", "juju-bundle"):
777 if kdu.get(k8s_type):
778 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300779 if not vnfr_descriptor.get("kdur"):
780 vnfr_descriptor["kdur"] = []
781 vnfr_descriptor["kdur"].append(kdur)
782
783 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300784
garciaale7cbd03c2020-11-27 10:38:35 -0300785 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300786 vdu_mgmt_cp = []
787 try:
garciadeblas4568a372021-03-24 09:19:48 +0100788 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
789 "operate-vnf-op-config"
790 ]["day1-2"]
791 vdu_config = utils.find_in_list(
792 configs, lambda config: config["id"] == vdu["id"]
793 )
bravoff3c39552021-02-24 17:22:24 -0300794 except Exception:
795 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400796
797 try:
798 vdu_instantiation_level = utils.find_in_list(
799 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100800 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400801 )
802 except Exception:
803 vdu_instantiation_level = None
804
bravoff3c39552021-02-24 17:22:24 -0300805 if vdu_config:
806 external_connection_ee = utils.filter_in_list(
807 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100808 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300809 )
810 for ee in external_connection_ee:
811 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
812
garciaale7cbd03c2020-11-27 10:38:35 -0300813 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100814 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
815 )
bravof65e22e52021-11-10 17:58:58 -0300816
817 try:
818 vdu_virtual_storage_descriptors = utils.filter_in_list(
819 vnfd.get("virtual-storage-desc", []),
820 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
821 )
822 except Exception:
823 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300824 vdur = {
825 "vdu-id-ref": vdu["id"],
826 # TODO "name": "" Name of the VDU in the VIM
827 "ip-address": None, # mgmt-interface filled by LCM
828 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
829 "internal-connection-point": [],
830 "interfaces": [],
831 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100832 "vdu-name": vdu["name"],
bravof65e22e52021-11-10 17:58:58 -0300833 "virtual-storages": vdu_virtual_storage_descriptors
garciaale7cbd03c2020-11-27 10:38:35 -0300834 }
835 if vdu_params and vdu_params.get("config-units"):
836 vdur["config-units"] = vdu_params["config-units"]
837 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100838 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
839 "boot-data-drive"
840 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300841 if vdu.get("pdu-type"):
842 vdur["pdu-type"] = vdu["pdu-type"]
843 vdur["name"] = vdu["pdu-type"]
844 # TODO volumes: name, volume-id
845 for icp in vdu.get("int-cpd", ()):
846 vdu_icp = {
847 "id": icp["id"],
848 "connection-point-id": icp["id"],
849 "name": icp.get("id"),
850 }
bravof35766442021-02-04 14:58:04 -0300851
garciaale7cbd03c2020-11-27 10:38:35 -0300852 vdur["internal-connection-point"].append(vdu_icp)
853
854 for iface in icp.get("virtual-network-interface-requirement", ()):
855 iface_fields = ("name", "mac-address")
garciadeblas4568a372021-03-24 09:19:48 +0100856 vdu_iface = {
857 x: iface[x] for x in iface_fields if iface.get(x) is not None
858 }
garciaale7cbd03c2020-11-27 10:38:35 -0300859
860 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100861 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100862 vdu_iface["port-security-enabled"] = icp[
863 "port-security-enabled"
864 ]
sousaedu003844e2021-03-02 00:19:15 +0100865
866 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100867 vdu_iface["port-security-disable-strategy"] = icp[
868 "port-security-disable-strategy"
869 ]
sousaedu003844e2021-03-02 00:19:15 +0100870
garciaale7cbd03c2020-11-27 10:38:35 -0300871 for ext_cp in vnfd.get("ext-cpd", ()):
872 if not ext_cp.get("int-cpd"):
873 continue
874 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
875 continue
876 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100877 vdu_iface["external-connection-point-ref"] = ext_cp.get(
878 "id"
879 )
sousaedu003844e2021-03-02 00:19:15 +0100880
881 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100882 vdu_iface["port-security-enabled"] = ext_cp[
883 "port-security-enabled"
884 ]
sousaedu003844e2021-03-02 00:19:15 +0100885
886 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100887 vdu_iface["port-security-disable-strategy"] = ext_cp[
888 "port-security-disable-strategy"
889 ]
sousaedu003844e2021-03-02 00:19:15 +0100890
garciaale7cbd03c2020-11-27 10:38:35 -0300891 break
892
garciadeblas4568a372021-03-24 09:19:48 +0100893 if (
894 vnfd_mgmt_cp
895 and vdu_iface.get("external-connection-point-ref")
896 == vnfd_mgmt_cp
897 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300898 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300899 vdu_iface["mgmt-interface"] = True
900
901 for ecp in vdu_mgmt_cp:
902 if vdu_iface.get("external-connection-point-ref") == ecp:
903 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300904
905 if iface.get("virtual-interface"):
906 vdu_iface.update(deepcopy(iface["virtual-interface"]))
907
908 # look for network where this interface is connected
909 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
910 if iface_ext_cp:
911 # TODO: Change for multiple df support
912 for df in get_iterable(nsd.get("df")):
913 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100914 for vlc_index, vlc in enumerate(
915 get_iterable(
916 vnf_profile.get("virtual-link-connectivity")
917 )
918 ):
919 for cpd in get_iterable(
920 vlc.get("constituent-cpd-id")
921 ):
922 if (
923 cpd.get("constituent-cpd-id")
924 == iface_ext_cp
925 ):
926 vdu_iface["ns-vld-id"] = vlc.get(
927 "virtual-link-profile-id"
928 )
garciadeblas61c95912021-02-12 11:23:50 +0000929 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100930 if vdu_iface.get("type") in (
931 "SR-IOV",
932 "PCI-PASSTHROUGH",
933 ):
934 nsr_descriptor["vld"][vlc_index][
935 "pci-interfaces"
936 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300937 break
938 elif vdu_iface.get("internal-connection-point-ref"):
939 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000940 # TODO: store fixed IP address in the record (if it exists in the ICP)
941 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
942 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100943 ivld_index = utils.find_index_in_list(
944 vnfd.get("int-virtual-link-desc", ()),
945 lambda ivld: ivld["id"]
946 == icp.get("int-virtual-link-desc"),
947 )
garciadeblas61c95912021-02-12 11:23:50 +0000948 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300949
950 vdur["interfaces"].append(vdu_iface)
951
952 if vdu.get("sw-image-desc"):
953 sw_image = utils.find_in_list(
954 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100955 lambda image: image["id"] == vdu.get("sw-image-desc"),
956 )
garciaale7cbd03c2020-11-27 10:38:35 -0300957 nsr_sw_image_data = utils.find_in_list(
958 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100959 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300960 )
961 vdur["ns-image-id"] = nsr_sw_image_data["id"]
962
lloretgalleg28c13b62021-02-08 11:48:48 +0000963 if vdu.get("alternative-sw-image-desc"):
964 alt_image_ids = []
965 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
966 sw_image = utils.find_in_list(
967 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100968 lambda image: image["id"] == alt_image_id,
969 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000970 nsr_sw_image_data = utils.find_in_list(
971 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100972 lambda nsr_image: (
973 nsr_image.get("image") == sw_image.get("image")
974 ),
lloretgalleg28c13b62021-02-08 11:48:48 +0000975 )
976 alt_image_ids.append(nsr_sw_image_data["id"])
977 vdur["alt-image-ids"] = alt_image_ids
978
garciaale7cbd03c2020-11-27 10:38:35 -0300979 flavor_data_name = vdu["id"][:56] + "-flv"
980 nsr_flavor_desc = utils.find_in_list(
981 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +0100982 lambda flavor: flavor["name"] == flavor_data_name,
983 )
garciaale7cbd03c2020-11-27 10:38:35 -0300984
985 if nsr_flavor_desc:
986 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
987
Alexis Romero03fb5842022-03-11 15:53:40 +0100988 # Adding Affinity groups information to vdur
989 try:
990 ags_vdu_profile = utils.find_in_list(
991 vnfd.get("df")[0]["vdu-profile"],
992 lambda a_vdu: a_vdu["id"] == vdu["id"],
993 )
994 except Exception:
995 ags_vdu_profile = None
996
997 if ags_vdu_profile:
998 ags_ids = []
999 for ag in ags_vdu_profile.get("affinity-or-anti-affinity-group", ()):
1000 vdu_ag = utils.find_in_list(
1001 ags_vdu_profile.get("affinity-or-anti-affinity-group", ()),
1002 lambda ag_fp: ag_fp["id"] == ag["id"],
1003 )
1004 nsr_ags_data = utils.find_in_list(
1005 nsr_descriptor["affinity-or-anti-affinity-group"],
1006 lambda nsr_ag: (
1007 nsr_ag.get("ag-id") == vdu_ag.get("id")
1008 ),
1009 )
1010 ags_ids.append(nsr_ags_data["id"])
1011 vdur["affinity-or-anti-affinity-group-id"] = ags_ids
1012
bravof4ca51522021-04-22 10:03:02 -04001013 if vdu_instantiation_level:
1014 count = vdu_instantiation_level.get("number-of-instances")
1015 else:
1016 count = 1
1017
garciaale7cbd03c2020-11-27 10:38:35 -03001018 for index in range(0, count):
1019 vdur = deepcopy(vdur)
1020 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -04001021 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001022 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -04001023 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -03001024 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1025
1026 vdur["_id"] = str(uuid4())
1027 vdur["id"] = vdur["_id"]
1028 vdur["count-index"] = index
1029 vnfr_descriptor["vdur"].append(vdur)
1030
1031 return vnfr_descriptor
1032
K Sai Kiran57589552021-01-27 21:38:34 +05301033 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1034 """
1035 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1036 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1037 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1038 :param ns_instance_content: ns instance content
1039 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1040 :return: None
1041 """
1042 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
1043 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
1044 threshold_reached = time_delta > 120
1045 if force_refresh or threshold_reached:
1046 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1047 ns_instance_content["_admin"]["modified"] = time_now
1048 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1049 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
1050 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1051 nslcmop_desc["_admin"].pop("nsState")
1052 self.msg.write("ns", operation, nslcmop_desc)
1053 return
1054
1055 def show(self, session, _id, filter_q=None, api_req=False):
1056 """
1057 Get complete information on an ns instance.
1058 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1059 :param _id: string, ns instance id
1060 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1061 :param api_req: True if this call is serving an external API request. False if serving internal request.
1062 :return: dictionary, raise exception if not found.
1063 """
1064 ns_instance_content = super().show(session, _id, api_req)
1065 self.vca_status_refresh(session, ns_instance_content, filter_q)
1066 return ns_instance_content
1067
tierno65ca36d2019-02-12 19:27:52 +01001068 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001069 raise EngineException(
1070 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1071 )
tiernob24258a2018-10-04 18:39:49 +02001072
1073
1074class VnfrTopic(BaseTopic):
1075 topic = "vnfrs"
1076 topic_msg = None
1077
delacruzramo32bab472019-09-13 12:24:22 +02001078 def __init__(self, db, fs, msg, auth):
1079 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001080
tiernobee3bad2019-12-05 12:26:01 +00001081 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001082 raise EngineException(
1083 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1084 )
tiernob24258a2018-10-04 18:39:49 +02001085
tierno65ca36d2019-02-12 19:27:52 +01001086 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001087 raise EngineException(
1088 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1089 )
tiernob24258a2018-10-04 18:39:49 +02001090
tierno65ca36d2019-02-12 19:27:52 +01001091 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001092 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001093 raise EngineException(
1094 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1095 )
tiernob24258a2018-10-04 18:39:49 +02001096
1097
1098class NsLcmOpTopic(BaseTopic):
1099 topic = "nslcmops"
1100 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001101 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001102 "instantiate": ns_instantiate,
1103 "action": ns_action,
1104 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +00001105 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +02001106 }
1107
delacruzramo32bab472019-09-13 12:24:22 +02001108 def __init__(self, db, fs, msg, auth):
1109 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001110
tiernob24258a2018-10-04 18:39:49 +02001111 def _check_ns_operation(self, session, nsr, operation, indata):
1112 """
1113 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001114 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001115 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1116 :param indata: descriptor with the parameters of the operation
1117 :return: None
1118 """
garciaale7cbd03c2020-11-27 10:38:35 -03001119 if operation == "action":
1120 self._check_action_ns_operation(indata, nsr)
1121 elif operation == "scale":
1122 self._check_scale_ns_operation(indata, nsr)
1123 elif operation == "instantiate":
1124 self._check_instantiate_ns_operation(indata, nsr, session)
1125
1126 def _check_action_ns_operation(self, indata, nsr):
1127 nsd = nsr["nsd"]
1128 # check vnf_member_index
1129 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001130 indata["member_vnf_index"] = indata.pop(
1131 "vnf_member_index"
1132 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001133 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001134 vnfd = self._get_vnfd_from_vnf_member_index(
1135 indata["member_vnf_index"], nsr["_id"]
1136 )
bravof41a52052021-02-17 18:08:01 -03001137 try:
garciadeblas4568a372021-03-24 09:19:48 +01001138 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1139 "operate-vnf-op-config"
1140 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001141 except Exception:
1142 configs = []
1143
garciaale7cbd03c2020-11-27 10:38:35 -03001144 if indata.get("vdu_id"):
1145 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001146 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001147 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001148 )
garciaale7cbd03c2020-11-27 10:38:35 -03001149 elif indata.get("kdu_name"):
1150 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001151 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001152 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001153 )
garciaale7cbd03c2020-11-27 10:38:35 -03001154 else:
bravof41a52052021-02-17 18:08:01 -03001155 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001156 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001157 )
1158 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001159 descriptor_configuration = descriptor_configuration.get(
1160 "config-primitive"
1161 )
garciaale7cbd03c2020-11-27 10:38:35 -03001162 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001163 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1164 "config-primitive"
1165 )
garciaale7cbd03c2020-11-27 10:38:35 -03001166
1167 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001168 if indata.get("kdu_name") and indata["primitive"] in (
1169 "upgrade",
1170 "rollback",
1171 "status",
1172 "inspect",
1173 "readme",
1174 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001175 # TODO should be checked that rollback only can contains revsision_numbe????
1176 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001177 raise EngineException(
1178 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1179 indata["primitive"]
1180 )
1181 )
garciaale7cbd03c2020-11-27 10:38:35 -03001182 return
1183 # if not, check primitive
1184 for config_primitive in get_iterable(descriptor_configuration):
1185 if indata["primitive"] == config_primitive["name"]:
1186 # check needed primitive_params are provided
1187 if indata.get("primitive_params"):
1188 in_primitive_params_copy = copy(indata["primitive_params"])
1189 else:
1190 in_primitive_params_copy = {}
1191 for paramd in get_iterable(config_primitive.get("parameter")):
1192 if paramd["name"] in in_primitive_params_copy:
1193 del in_primitive_params_copy[paramd["name"]]
1194 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001195 raise EngineException(
1196 "Needed parameter {} not provided for primitive '{}'".format(
1197 paramd["name"], indata["primitive"]
1198 )
1199 )
garciaale7cbd03c2020-11-27 10:38:35 -03001200 # check no extra primitive params are provided
1201 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001202 raise EngineException(
1203 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1204 list(in_primitive_params_copy.keys()), indata["primitive"]
1205 )
1206 )
garciaale7cbd03c2020-11-27 10:38:35 -03001207 break
1208 else:
garciadeblas4568a372021-03-24 09:19:48 +01001209 raise EngineException(
1210 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1211 indata["primitive"]
1212 )
1213 )
garciaale7cbd03c2020-11-27 10:38:35 -03001214
1215 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001216 vnfd = self._get_vnfd_from_vnf_member_index(
1217 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1218 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001219 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001220 if (
1221 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1222 == scaling_aspect["id"]
1223 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001224 break
1225 else:
garciadeblas4568a372021-03-24 09:19:48 +01001226 raise EngineException(
1227 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1228 "present at vnfd:scaling-aspect".format(
1229 indata["scaleVnfData"]["scaleByStepData"][
1230 "scaling-group-descriptor"
1231 ]
1232 )
1233 )
garciaale7cbd03c2020-11-27 10:38:35 -03001234
1235 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001236 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001237 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001238 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001239 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001240 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1241 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1242 for in_vnf in get_iterable(indata.get("vnf")):
1243 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001244 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001245 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001246 else:
garciadeblas4568a372021-03-24 09:19:48 +01001247 vnfd = self._get_vnfd_from_vnf_member_index(
1248 member_vnf_index, nsr["_id"]
1249 )
1250 vnf_member_index_to_vnfd[
1251 member_vnf_index
1252 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001253 self._check_vnf_instantiation_params(in_vnf, vnfd)
1254 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001255 self._check_valid_vim_account(
1256 in_vnf["vimAccountId"], vim_accounts, session
1257 )
tierno260dd6f2019-09-02 10:48:56 +00001258
garciaale7cbd03c2020-11-27 10:38:35 -03001259 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001260 self._check_valid_wim_account(
1261 in_vld.get("wimAccountId"), wim_accounts, session
1262 )
garciaale7cbd03c2020-11-27 10:38:35 -03001263 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1264 if in_vld["name"] == vldd["id"]:
1265 break
tierno9cb7d672019-10-30 12:13:48 +00001266 else:
garciadeblas4568a372021-03-24 09:19:48 +01001267 raise EngineException(
1268 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1269 in_vld["name"]
1270 )
1271 )
tierno9cb7d672019-10-30 12:13:48 +00001272
garciaale7cbd03c2020-11-27 10:38:35 -03001273 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1274 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001275 vnfr = self.db.get_one(
1276 "vnfrs",
1277 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1278 fail_on_empty=False,
1279 )
garciaale7cbd03c2020-11-27 10:38:35 -03001280 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001281 raise EngineException(
1282 "Invalid parameter member_vnf_index='{}' is not one of the "
1283 "nsd:constituent-vnfd".format(member_vnf_index)
1284 )
garciaale7cbd03c2020-11-27 10:38:35 -03001285 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1286 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001287 raise EngineException(
1288 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1289 vnfr["vnfd-id"]
1290 )
1291 )
garciaale7cbd03c2020-11-27 10:38:35 -03001292 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001293
garciaale7cbd03c2020-11-27 10:38:35 -03001294 def _check_valid_vdu(self, vnfd, vdu_id):
1295 for vdud in get_iterable(vnfd.get("vdu")):
1296 if vdud["id"] == vdu_id:
1297 return vdud
1298 else:
garciadeblas4568a372021-03-24 09:19:48 +01001299 raise EngineException(
1300 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1301 vdu_id
1302 )
1303 )
garciaale7cbd03c2020-11-27 10:38:35 -03001304
1305 def _check_valid_kdu(self, vnfd, kdu_name):
1306 for kdud in get_iterable(vnfd.get("kdu")):
1307 if kdud["name"] == kdu_name:
1308 return kdud
1309 else:
garciadeblas4568a372021-03-24 09:19:48 +01001310 raise EngineException(
1311 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1312 kdu_name
1313 )
1314 )
garciaale7cbd03c2020-11-27 10:38:35 -03001315
1316 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1317 for in_vdu in get_iterable(in_vnf.get("vdu")):
1318 for vdu in get_iterable(vnfd.get("vdu")):
1319 if in_vdu["id"] == vdu["id"]:
1320 for volume in get_iterable(in_vdu.get("volume")):
1321 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1322 if volumed["id"] == volume["name"]:
1323 break
1324 else:
garciadeblas4568a372021-03-24 09:19:48 +01001325 raise EngineException(
1326 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1327 "volume:name='{}' is not present at "
1328 "vnfd:vdu:virtual-storage-desc list".format(
1329 in_vnf["member-vnf-index"],
1330 in_vdu["id"],
1331 volume["id"],
1332 )
1333 )
garciaale7cbd03c2020-11-27 10:38:35 -03001334
1335 vdu_if_names = set()
1336 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001337 for iface in get_iterable(
1338 cpd.get("virtual-network-interface-requirement")
1339 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001340 vdu_if_names.add(iface.get("name"))
1341
1342 for in_iface in get_iterable(in_vdu["interface"]):
1343 if in_iface["name"] in vdu_if_names:
1344 break
1345 else:
garciadeblas4568a372021-03-24 09:19:48 +01001346 raise EngineException(
1347 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1348 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1349 in_vnf["member-vnf-index"],
1350 in_vdu["id"],
1351 in_iface["name"],
1352 )
1353 )
garciaale7cbd03c2020-11-27 10:38:35 -03001354 break
1355
1356 else:
garciadeblas4568a372021-03-24 09:19:48 +01001357 raise EngineException(
1358 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1359 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1360 )
garciaale7cbd03c2020-11-27 10:38:35 -03001361
garciadeblas4568a372021-03-24 09:19:48 +01001362 vnfd_ivlds_cpds = {
1363 ivld.get("id"): set()
1364 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1365 }
garciaale7cbd03c2020-11-27 10:38:35 -03001366 for vdu in get_iterable(vnfd.get("vdu")):
1367 for cpd in get_iterable(vnfd.get("int-cpd")):
1368 if cpd.get("int-virtual-link-desc"):
1369 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1370
1371 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1372 if in_ivld.get("name") in vnfd_ivlds_cpds:
1373 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1374 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001375 break
tiernob24258a2018-10-04 18:39:49 +02001376 else:
garciadeblas4568a372021-03-24 09:19:48 +01001377 raise EngineException(
1378 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1379 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1380 "vnfd:internal-vld:name/id:internal-connection-point".format(
1381 in_vnf["member-vnf-index"],
1382 in_ivld["name"],
1383 in_icp["id-ref"],
1384 )
1385 )
tiernob24258a2018-10-04 18:39:49 +02001386 else:
garciadeblas4568a372021-03-24 09:19:48 +01001387 raise EngineException(
1388 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1389 " is not present at vnfd '{}'".format(
1390 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1391 )
1392 )
tiernob24258a2018-10-04 18:39:49 +02001393
garciaale7cbd03c2020-11-27 10:38:35 -03001394 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1395 if vim_account in vim_accounts:
1396 return
1397 try:
1398 db_filter = self._get_project_filter(session)
1399 db_filter["_id"] = vim_account
1400 self.db.get_one("vim_accounts", db_filter)
1401 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001402 raise EngineException(
1403 "Invalid vimAccountId='{}' not present for the project".format(
1404 vim_account
1405 )
1406 )
garciaale7cbd03c2020-11-27 10:38:35 -03001407 vim_accounts.append(vim_account)
1408
David Garcia98de2982021-10-13 17:14:01 +02001409 def _get_vim_account(self, vim_id: str, session):
1410 try:
1411 db_filter = self._get_project_filter(session)
1412 db_filter["_id"] = vim_id
1413 return self.db.get_one("vim_accounts", db_filter)
1414 except Exception:
1415 raise EngineException(
1416 "Invalid vimAccountId='{}' not present for the project".format(
1417 vim_id
1418 )
1419 )
1420
garciaale7cbd03c2020-11-27 10:38:35 -03001421 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1422 if not isinstance(wim_account, str):
1423 return
1424 if wim_account in wim_accounts:
1425 return
1426 try:
1427 db_filter = self._get_project_filter(session, write=False, show_all=True)
1428 db_filter["_id"] = wim_account
1429 self.db.get_one("wim_accounts", db_filter)
1430 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001431 raise EngineException(
1432 "Invalid wimAccountId='{}' not present for the project".format(
1433 wim_account
1434 )
1435 )
garciaale7cbd03c2020-11-27 10:38:35 -03001436 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001437
garciadeblas4568a372021-03-24 09:19:48 +01001438 def _look_for_pdu(
1439 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1440 ):
tiernocc103432018-10-19 14:10:35 +02001441 """
tierno36ec8602018-11-02 17:27:11 +01001442 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1443 (ip_address, ...) information.
1444 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001445 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001446 :param rollback: list with the database modifications to rollback if needed
1447 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1448 :param vim_account: vim_account where this vnfr should be deployed
1449 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1450 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1451 of the changed vnfr is needed
1452
1453 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1454 "vim-network-name": used at VIM
1455 "name": interface name
1456 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1457 "ns-vld-id": NSD vld where this interface is connected.
1458 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 +02001459 """
tierno36ec8602018-11-02 17:27:11 +01001460
1461 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001462 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1463 if not vdur.get("pdu-type"):
1464 continue
1465 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001466 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001467 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001468 pdu_filter["type"] = pdu_type
1469 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001470 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001471 # TODO feature 1417: "shared": True,
1472
1473 available_pdus = self.db.get_list("pdus", pdu_filter)
1474 for pdu in available_pdus:
1475 # step 1 check if this pdu contains needed interfaces:
1476 match_interfaces = True
1477 for vdur_interface in vdur["interfaces"]:
1478 for pdu_interface in pdu["interfaces"]:
1479 if pdu_interface["name"] == vdur_interface["name"]:
1480 # TODO feature 1417: match per mgmt type
1481 break
1482 else: # no interface found for name
1483 match_interfaces = False
1484 break
1485 if match_interfaces:
1486 break
1487 else:
1488 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001489 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001490 "names".format(
1491 pdu_type,
1492 vim_account,
1493 vnfr["member-vnf-index-ref"],
1494 vdur["vdu-id-ref"],
1495 )
1496 )
tiernocc103432018-10-19 14:10:35 +02001497
1498 # step 2. Update pdu
1499 rollback_pdu = {
1500 "_admin.usageState": pdu["_admin"]["usageState"],
1501 "_admin.usage.vnfr_id": None,
1502 "_admin.usage.nsr_id": None,
1503 "_admin.usage.vdur": None,
1504 }
garciadeblas4568a372021-03-24 09:19:48 +01001505 self.db.set_one(
1506 "pdus",
1507 {"_id": pdu["_id"]},
1508 {
1509 "_admin.usageState": "IN_USE",
1510 "_admin.usage": {
1511 "vnfr_id": vnfr["_id"],
1512 "nsr_id": vnfr["nsr-id-ref"],
1513 "vdur": vdur["vdu-id-ref"],
1514 },
1515 },
1516 )
1517 rollback.append(
1518 {
1519 "topic": "pdus",
1520 "_id": pdu["_id"],
1521 "operation": "set",
1522 "content": rollback_pdu,
1523 }
1524 )
tiernocc103432018-10-19 14:10:35 +02001525
1526 # step 3. Fill vnfr info by filling vdur
1527 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001528 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001529 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1530 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1531 for pdu_interface in pdu["interfaces"]:
1532 if pdu_interface["name"] == vdur_interface["name"]:
1533 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1534 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001535 if k in (
1536 "ip-address",
1537 "mac-address",
1538 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001539 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001540 vnfr_update_rollback[
1541 iface_text + ".{}".format(k)
1542 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001543 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001544 if vdur_interface.get(
1545 "mgmt-interface"
1546 ) or vdur_interface.get("mgmt-vnf"):
1547 vnfr_update_rollback[
1548 vdu_text + ".ip-address"
1549 ] = vdur.get("ip-address")
1550 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1551 "ip-address"
1552 ]
tierno36ec8602018-11-02 17:27:11 +01001553 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001554 vnfr_update_rollback["ip-address"] = vnfr.get(
1555 "ip-address"
1556 )
tierno36ec8602018-11-02 17:27:11 +01001557 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001558 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1559 "ip-address"
1560 ]
1561 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1562 "vim-network-id"
1563 ):
1564 ifaces_forcing_vim_network.append(
1565 {
1566 "name": vdur_interface.get("vnf-vld-id")
1567 or vdur_interface.get("ns-vld-id"),
1568 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1569 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1570 }
1571 )
gcalvino17d5b732018-12-17 16:26:21 +01001572 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001573 ifaces_forcing_vim_network[-1][
1574 "vim-network-id"
1575 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001576 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001577 ifaces_forcing_vim_network[-1][
1578 "vim-network-name"
1579 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001580 break
1581
tierno36ec8602018-11-02 17:27:11 +01001582 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001583
garciadeblas4568a372021-03-24 09:19:48 +01001584 def _look_for_k8scluster(
1585 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1586 ):
tierno9cb7d672019-10-30 12:13:48 +00001587 """
1588 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1589 Fills vnfr.kdur with the selected k8scluster
1590
1591 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1592 :param rollback: list with the database modifications to rollback if needed
1593 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1594 :param vim_account: vim_account where this vnfr should be deployed
1595 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1596 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1597 of the changed vnfr is needed
1598
1599 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1600 "vim-network-name": used at VIM
1601 "name": interface name
1602 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1603 "ns-vld-id": NSD vld where this interface is connected.
1604 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1605 """
1606
1607 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001608 if not vnfr.get("kdur"):
1609 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001610
tiernoc67b0e92019-11-05 12:45:29 +00001611 kdu_filter = self._get_project_filter(session)
1612 kdu_filter["vim_account"] = vim_account
1613 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1614 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1615
1616 k8s_requirements = {} # just for logging
1617 for k8scluster in available_k8sclusters:
1618 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001619 break
tiernoc67b0e92019-11-05 12:45:29 +00001620 # restrict by cni
1621 if vnfr["k8s-cluster"].get("cni"):
1622 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001623 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1624 k8scluster.get("cni", ())
1625 ):
tiernoc67b0e92019-11-05 12:45:29 +00001626 continue
1627 # restrict by version
1628 if vnfr["k8s-cluster"].get("version"):
1629 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1630 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1631 continue
1632 # restrict by number of networks
1633 if vnfr["k8s-cluster"].get("nets"):
1634 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001635 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1636 vnfr["k8s-cluster"]["nets"]
1637 ):
tiernoc67b0e92019-11-05 12:45:29 +00001638 continue
1639 break
1640 else:
garciadeblas4568a372021-03-24 09:19:48 +01001641 raise EngineException(
1642 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1643 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1644 )
1645 )
tierno9cb7d672019-10-30 12:13:48 +00001646
tiernoc67b0e92019-11-05 12:45:29 +00001647 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001648 # step 3. Fill vnfr info by filling kdur
1649 kdu_text = "kdur.{}.".format(kdur_index)
1650 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1651 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1652
tiernoc67b0e92019-11-05 12:45:29 +00001653 # step 4. Check VIM networks that forces the selected k8s_cluster
1654 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1655 k8scluster_net_list = list(k8scluster.get("nets").keys())
1656 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1657 # get a network from k8s_cluster nets. If name matches use this, if not use other
1658 if kdur_net["id"] in k8scluster_net_list: # name matches
1659 vim_net = k8scluster["nets"][kdur_net["id"]]
1660 k8scluster_net_list.remove(kdur_net["id"])
1661 else:
1662 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1663 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001664 vnfr_update_rollback[
1665 "k8s-cluster.nets.{}.vim_net".format(net_index)
1666 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001667 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001668 if vim_net and (
1669 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1670 ):
1671 ifaces_forcing_vim_network.append(
1672 {
1673 "name": kdur_net.get("vnf-vld-id")
1674 or kdur_net.get("ns-vld-id"),
1675 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1676 "ns-vld-id": kdur_net.get("ns-vld-id"),
1677 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1678 }
1679 )
tiernoc67b0e92019-11-05 12:45:29 +00001680 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001681 return ifaces_forcing_vim_network
1682
Gulsum Aticie395aa42021-11-10 20:59:06 +03001683 def _update_vnfrs_from_nsd(self, nsr):
1684 try:
1685 nsr_id = nsr["_id"]
1686 nsd = nsr["nsd"]
1687
1688 step = "Getting vnf_profiles from nsd"
1689 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1690 vld_fixed_ip_connection_point_data = {}
1691
1692 step = "Getting ip-address info from vnf_profile if it exists"
1693 for vnfp in vnf_profiles:
1694 # Checking ip-address info from nsd.vnf_profile and storing
1695 for vlc in vnfp.get("virtual-link-connectivity", ()):
1696 for cpd in vlc.get("constituent-cpd-id", ()):
1697 if cpd.get("ip-address"):
1698 step = "Storing ip-address info"
1699 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1700 "vnfd-connection-point-ref": cpd.get(
1701 "constituent-cpd-id"),
1702 "ip-address": cpd.get(
1703 "ip-address")}})
1704
1705 # Inserting ip address to vnfr
1706 if len(vld_fixed_ip_connection_point_data) > 0:
1707 step = "Getting vnfrs"
1708 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1709 for item in vld_fixed_ip_connection_point_data.keys():
1710 step = "Filtering vnfrs"
1711 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1712 if vnfr:
1713 vnfr_update = {}
1714 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1715 for iface_index, iface in enumerate(vdur["interfaces"]):
1716 step = "Looking for matched interface"
1717 if (
1718 iface.get("external-connection-point-ref")
1719 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1720 iface.get("ns-vld-id") == item.split('.')[0]
1721
1722 ):
1723 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1724 vdur_index, iface_index
1725 )
1726 step = "Storing info in order to update vnfr"
1727 vnfr_update[
1728 vnfr_update_text + ".ip-address"
1729 ] = increment_ip_mac(
1730 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1731 vdur.get("count-index", 0), )
1732 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1733
1734 step = "updating vnfr at database"
1735 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1736 except (
1737 ValidationError,
1738 EngineException,
1739 DbException,
1740 MsgException,
1741 FsException,
1742 ) as e:
1743 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1744
tiernocc103432018-10-19 14:10:35 +02001745 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001746 # get vnfr
1747 nsr_id = nsr["_id"]
1748 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1749
1750 for vnfr in vnfrs:
1751 vnfr_update = {}
1752 vnfr_update_rollback = {}
1753 member_vnf_index = vnfr["member-vnf-index-ref"]
1754 # update vim-account-id
1755
1756 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02001757 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001758 # check instantiate parameters
1759 for vnf_inst_params in get_iterable(indata.get("vnf")):
1760 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1761 continue
1762 if vnf_inst_params.get("vimAccountId"):
1763 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02001764 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001765
tiernocddb07d2020-10-06 08:28:00 +00001766 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1767 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1768 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1769 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1770 continue
garciadeblas4568a372021-03-24 09:19:48 +01001771 for iface_inst_param in get_iterable(
1772 vdu_inst_param.get("interface")
1773 ):
1774 iface_index, _ = next(
1775 i
1776 for i in enumerate(vdur["interfaces"])
1777 if i[1]["name"] == iface_inst_param["name"]
1778 )
1779 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1780 vdur_index, iface_index
1781 )
tiernocddb07d2020-10-06 08:28:00 +00001782 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001783 vnfr_update[
1784 vnfr_update_text + ".ip-address"
1785 ] = increment_ip_mac(
1786 iface_inst_param.get("ip-address"),
1787 vdur.get("count-index", 0),
1788 )
tierno1bd9d952020-11-13 15:56:51 +00001789 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001790 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001791 vnfr_update[
1792 vnfr_update_text + ".mac-address"
1793 ] = increment_ip_mac(
1794 iface_inst_param.get("mac-address"),
1795 vdur.get("count-index", 0),
1796 )
tierno1bd9d952020-11-13 15:56:51 +00001797 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001798 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001799 vnfr_update[
1800 vnfr_update_text + ".floating-ip-required"
1801 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001802 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1803 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001804 for ivld_inst_param in get_iterable(
1805 vnf_inst_params.get("internal-vld")
1806 ):
1807 for icp_inst_param in get_iterable(
1808 ivld_inst_param.get("internal-connection-point")
1809 ):
tiernocddb07d2020-10-06 08:28:00 +00001810 # look for iface
1811 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1812 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001813 if (
1814 iface.get("internal-connection-point-ref")
1815 == icp_inst_param["id-ref"]
1816 ):
1817 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1818 vdur_index, iface_index
1819 )
tiernocddb07d2020-10-06 08:28:00 +00001820 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001821 vnfr_update[
1822 vnfr_update_text + ".ip-address"
1823 ] = increment_ip_mac(
1824 icp_inst_param.get("ip-address"),
1825 vdur.get("count-index", 0),
1826 )
1827 vnfr_update[
1828 vnfr_update_text + ".fixed-ip"
1829 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001830 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001831 vnfr_update[
1832 vnfr_update_text + ".mac-address"
1833 ] = increment_ip_mac(
1834 icp_inst_param.get("mac-address"),
1835 vdur.get("count-index", 0),
1836 )
1837 vnfr_update[
1838 vnfr_update_text + ".fixed-mac"
1839 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001840 break
1841 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1842 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001843 for vnfcp_inst_param in get_iterable(
1844 vld_inst_param.get("vnfd-connection-point-ref")
1845 ):
tiernocddb07d2020-10-06 08:28:00 +00001846 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1847 continue
1848 # look for iface
1849 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1850 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001851 if (
1852 iface.get("external-connection-point-ref")
1853 == vnfcp_inst_param["vnfd-connection-point-ref"]
1854 ):
1855 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1856 vdur_index, iface_index
1857 )
tiernocddb07d2020-10-06 08:28:00 +00001858 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001859 vnfr_update[
1860 vnfr_update_text + ".ip-address"
1861 ] = increment_ip_mac(
1862 vnfcp_inst_param.get("ip-address"),
1863 vdur.get("count-index", 0),
1864 )
tierno1bd9d952020-11-13 15:56:51 +00001865 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001866 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001867 vnfr_update[
1868 vnfr_update_text + ".mac-address"
1869 ] = increment_ip_mac(
1870 vnfcp_inst_param.get("mac-address"),
1871 vdur.get("count-index", 0),
1872 )
tierno1bd9d952020-11-13 15:56:51 +00001873 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001874 break
1875
tiernocc103432018-10-19 14:10:35 +02001876 vnfr_update["vim-account-id"] = vim_account
1877 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1878
David Garciaecb41322021-03-31 19:10:46 +02001879 if vca_id:
1880 vnfr_update["vca-id"] = vca_id
1881 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1882
tiernocc103432018-10-19 14:10:35 +02001883 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01001884 ifaces_forcing_vim_network = self._look_for_pdu(
1885 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1886 )
tiernocc103432018-10-19 14:10:35 +02001887
tierno9cb7d672019-10-30 12:13:48 +00001888 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01001889 ifaces_forcing_vim_network += self._look_for_k8scluster(
1890 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1891 )
tierno9cb7d672019-10-30 12:13:48 +00001892 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001893 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01001894 rollback.append(
1895 {
1896 "topic": "vnfrs",
1897 "_id": vnfr["_id"],
1898 "operation": "set",
1899 "content": vnfr_update_rollback,
1900 }
1901 )
tierno36ec8602018-11-02 17:27:11 +01001902
1903 # Update indada in case pdu forces to use a concrete vim-network-name
1904 # TODO check if user has already insert a vim-network-name and raises an error
1905 if not ifaces_forcing_vim_network:
1906 continue
1907 for iface_info in ifaces_forcing_vim_network:
1908 if iface_info.get("ns-vld-id"):
1909 if "vld" not in indata:
1910 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001911 indata["vld"].append(
1912 {
1913 key: iface_info[key]
1914 for key in ("name", "vim-network-name", "vim-network-id")
1915 if iface_info.get(key)
1916 }
1917 )
tierno36ec8602018-11-02 17:27:11 +01001918
1919 elif iface_info.get("vnf-vld-id"):
1920 if "vnf" not in indata:
1921 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001922 indata["vnf"].append(
1923 {
1924 "member-vnf-index": member_vnf_index,
1925 "internal-vld": [
1926 {
1927 key: iface_info[key]
1928 for key in (
1929 "name",
1930 "vim-network-name",
1931 "vim-network-id",
1932 )
1933 if iface_info.get(key)
1934 }
1935 ],
1936 }
1937 )
tierno36ec8602018-11-02 17:27:11 +01001938
1939 @staticmethod
1940 def _create_nslcmop(nsr_id, operation, params):
1941 """
1942 Creates a ns-lcm-opp content to be stored at database.
1943 :param nsr_id: internal id of the instance
1944 :param operation: instantiate, terminate, scale, action, ...
1945 :param params: user parameters for the operation
1946 :return: dictionary following SOL005 format
1947 """
tiernob24258a2018-10-04 18:39:49 +02001948 now = time()
1949 _id = str(uuid4())
1950 nslcmop = {
1951 "id": _id,
1952 "_id": _id,
1953 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001954 "queuePosition": None,
1955 "stage": None,
1956 "errorMessage": None,
1957 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001958 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001959 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001960 "lcmOperationType": operation,
1961 "startTime": now,
1962 "isAutomaticInvocation": False,
1963 "operationParams": params,
1964 "isCancelPending": False,
1965 "links": {
1966 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001967 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01001968 },
tiernob24258a2018-10-04 18:39:49 +02001969 }
1970 return nslcmop
1971
magnussonlf318b302020-01-20 18:38:18 +01001972 def _get_enabled_vims(self, session):
1973 """
1974 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1975 :param session: current session with user information
1976 """
1977 db_filter = self._get_project_filter(session)
1978 db_filter["_admin.operationalState"] = "ENABLED"
1979 vims = self.db.get_list("vim_accounts", db_filter)
1980 vimAccounts = []
1981 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01001982 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01001983 return vimAccounts
1984
garciadeblas4568a372021-03-24 09:19:48 +01001985 def new(
1986 self,
1987 rollback,
1988 session,
1989 indata=None,
1990 kwargs=None,
1991 headers=None,
1992 slice_object=False,
1993 ):
tiernob24258a2018-10-04 18:39:49 +02001994 """
1995 Performs a new operation over a ns
1996 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001997 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001998 :param indata: descriptor with the parameters of the operation. It must contains among others
1999 nsInstanceId: _id of the nsr to perform the operation
2000 operation: it can be: instantiate, terminate, action, TODO: update, heal
2001 :param kwargs: used to override the indata descriptor
2002 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02002003 :return: id of the nslcmops
2004 """
garciadeblas4568a372021-03-24 09:19:48 +01002005
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002006 def check_if_nsr_is_not_slice_member(session, nsr_id):
2007 nsis = None
2008 db_filter = self._get_project_filter(session)
2009 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002010 nsis = self.db.get_one(
2011 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2012 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002013 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01002014 raise EngineException(
2015 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2016 nsr_id, nsis["_id"]
2017 ),
2018 http_code=HTTPStatus.CONFLICT,
2019 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002020
tiernob24258a2018-10-04 18:39:49 +02002021 try:
2022 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00002023 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02002024 operation = indata["lcmOperationType"]
2025 nsInstanceId = indata["nsInstanceId"]
2026
2027 validate_input(indata, self.operation_schema[operation])
2028 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01002029 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02002030 _filter["_id"] = nsInstanceId
2031 nsr = self.db.get_one("nsrs", _filter)
2032
2033 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02002034 if operation == "terminate" and slice_object is False:
2035 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01002036 if (
2037 not nsr["_admin"].get("nsState")
2038 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2039 ):
tiernob24258a2018-10-04 18:39:49 +02002040 if operation == "terminate" and indata.get("autoremove"):
2041 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002042 return (
2043 None,
2044 None,
2045 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02002046 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002047 raise EngineException(
2048 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2049 nsInstanceId, operation
2050 ),
2051 HTTPStatus.CONFLICT,
2052 )
tiernob24258a2018-10-04 18:39:49 +02002053 else:
tierno65ca36d2019-02-12 19:27:52 +01002054 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002055 raise EngineException(
2056 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2057 nsInstanceId, operation
2058 ),
2059 HTTPStatus.CONFLICT,
2060 )
tiernob24258a2018-10-04 18:39:49 +02002061 self._check_ns_operation(session, nsr, operation, indata)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01002062 if (indata.get("primitive_params")):
2063 indata["primitive_params"] = json.dumps(indata["primitive_params"])
2064 elif (indata.get("additionalParamsForVnf")):
2065 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
tierno36ec8602018-11-02 17:27:11 +01002066
tiernocc103432018-10-19 14:10:35 +02002067 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03002068 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002069 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01002070
2071 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002072 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002073 self.format_on_new(
2074 nslcmop_desc, session["project_id"], make_public=session["public"]
2075 )
magnussonlf318b302020-01-20 18:38:18 +01002076 if indata.get("placement-engine"):
2077 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002078 nslcmop_desc["operationParams"][
2079 "validVimAccounts"
2080 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002081 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002082 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002083 if not slice_object:
2084 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002085 return _id, None
2086 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002087 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2088 # except DbException as e:
2089 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2090
tiernobee3bad2019-12-05 12:26:01 +00002091 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002092 raise EngineException(
2093 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2094 )
tiernob24258a2018-10-04 18:39:49 +02002095
tierno65ca36d2019-02-12 19:27:52 +01002096 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002097 raise EngineException(
2098 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2099 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002100
2101
2102class NsiTopic(BaseTopic):
2103 topic = "nsis"
2104 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002105 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002106
delacruzramo32bab472019-09-13 12:24:22 +02002107 def __init__(self, db, fs, msg, auth):
2108 BaseTopic.__init__(self, db, fs, msg, auth)
2109 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002110
Felipe Vicensc37b3842019-01-12 12:24:42 +01002111 @staticmethod
2112 def _format_ns_request(ns_request):
2113 formated_request = copy(ns_request)
2114 # TODO: Add request params
2115 return formated_request
2116
2117 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002118 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002119 """
2120 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002121 :param slice_request: User instantiation additional parameters
2122 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002123 """
tiernofd160572019-01-21 10:41:37 +00002124 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2125 if additional_params:
2126 for k, v in additional_params.items():
2127 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002128 raise EngineException(
2129 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2130 k
2131 )
2132 )
tiernofd160572019-01-21 10:41:37 +00002133 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002134 raise EngineException(
2135 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2136 k
2137 )
2138 )
tiernofd160572019-01-21 10:41:37 +00002139 if isinstance(v, (dict, tuple, list)):
2140 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002141 return additional_params
2142
Felipe Vicensb57758d2018-10-16 16:00:20 +02002143 def _check_descriptor_dependencies(self, session, descriptor):
2144 """
2145 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01002146 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002147 :param descriptor: descriptor to be inserted or edit
2148 :return: None or raises exception
2149 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002150 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002151 return
Felipe Vicens07f31722018-10-29 15:16:44 +01002152 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002153 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
garciadeblas4568a372021-03-24 09:19:48 +01002154 raise EngineException(
2155 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2156 nstd_id
2157 ),
2158 http_code=HTTPStatus.CONFLICT,
2159 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002160
tiernob4844ab2019-05-23 08:42:12 +00002161 def check_conflict_on_del(self, session, _id, db_content):
2162 """
2163 Check that NSI is not instantiated
2164 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2165 :param _id: nsi internal id
2166 :param db_content: The database content of the _id
2167 :return: None or raises EngineException with the conflict
2168 """
tierno65ca36d2019-02-12 19:27:52 +01002169 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002170 return
tiernob4844ab2019-05-23 08:42:12 +00002171 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002172 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002173 raise EngineException(
2174 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2175 "Launch 'terminate' operation first; or force deletion".format(_id),
2176 http_code=HTTPStatus.CONFLICT,
2177 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002178
tiernobee3bad2019-12-05 12:26:01 +00002179 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002180 """
tiernob4844ab2019-05-23 08:42:12 +00002181 Deletes associated nsilcmops from database. Deletes associated filesystem.
2182 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002183 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002184 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002185 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002186 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002187 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002188 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002189
Felipe Vicens09e65422019-01-22 15:06:46 +01002190 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002191 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002192 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2193 nsr_id = nsrs_detailed_item["nsrId"]
2194 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002195 _filter = {
2196 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2197 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2198 "_id.ne": nsir["_id"],
2199 }
2200 nsi = self.db.get_one(
2201 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2202 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002203 if nsi: # last one using nsr
2204 continue
2205 try:
garciadeblas4568a372021-03-24 09:19:48 +01002206 self.nsrTopic.delete(
2207 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2208 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002209 except (DbException, EngineException) as e:
2210 if e.http_code == HTTPStatus.NOT_FOUND:
2211 pass
2212 else:
2213 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002214
tiernob4844ab2019-05-23 08:42:12 +00002215 # delete related nsilcmops database entries
2216 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002217
tiernob4844ab2019-05-23 08:42:12 +00002218 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002219 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002220 if nsir_admin and nsir_admin.get("nst-id"):
2221 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002222 nsis_list = self.db.get_one(
2223 "nsis",
2224 {"nst-id": nsir_admin["nst-id"]},
2225 fail_on_empty=False,
2226 fail_on_more=False,
2227 )
tiernob4844ab2019-05-23 08:42:12 +00002228 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002229 self.db.set_one(
2230 "nsts",
2231 {"_id": nsir_admin["nst-id"]},
2232 {"_admin.usageState": "NOT_IN_USE"},
2233 )
tiernob4844ab2019-05-23 08:42:12 +00002234
tierno65ca36d2019-02-12 19:27:52 +01002235 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002236 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002237 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002238 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002239 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002240 :param indata: params to be used for the nsir
2241 :param kwargs: used to override the indata descriptor
2242 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002243 :return: the _id of nsi descriptor created at database
2244 """
2245
2246 try:
delacruzramo32bab472019-09-13 12:24:22 +02002247 step = "checking quotas"
2248 self.check_quota(session)
2249
tierno99d4b172019-07-02 09:28:40 +00002250 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002251 slice_request = self._remove_envelop(indata)
2252 # Override descriptor with query string kwargs
2253 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002254 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002255
Felipe Vicensb57758d2018-10-16 16:00:20 +02002256 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002257 step = "getting nstd id='{}' from database".format(
2258 slice_request.get("nstId")
2259 )
tiernob4844ab2019-05-23 08:42:12 +00002260 _filter = self._get_project_filter(session)
2261 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002262 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002263 # check NST is not disabled
2264 step = "checking NST operationalState"
2265 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002266 raise EngineException(
2267 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2268 "instance".format(slice_request["nstId"]),
2269 http_code=HTTPStatus.CONFLICT,
2270 )
tiernob4844ab2019-05-23 08:42:12 +00002271 del _filter["_id"]
2272
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002273 # check NSD is not disabled
2274 step = "checking operationalState"
2275 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002276 raise EngineException(
2277 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2278 "a network slice".format(slice_request["nstId"]),
2279 http_code=HTTPStatus.CONFLICT,
2280 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002281
Felipe Vicens07f31722018-10-29 15:16:44 +01002282 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002283 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002284 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002285 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002286
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002287 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002288 nsi_descriptor = {
2289 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002290 "name": slice_request["nsiName"],
2291 "description": slice_request.get("nsiDescription", ""),
2292 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002293 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002294 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002295 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002296 "nsr-ref-list": [],
2297 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002298 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002299 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002300 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002301
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002302 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002303 self.format_on_new(
2304 nsi_descriptor, session["project_id"], make_public=session["public"]
2305 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002306 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2307 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002308 nsi_descriptor["_admin"]["deployed"] = {}
2309 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2310 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2311
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002312 # Creating netslice-vld for the RO.
2313 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002314
2315 # Building the vlds list to be deployed
2316 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002317 nsi_vlds = []
2318
2319 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2320 # Getting template Instantiation parameters from NST
2321 nsi_vld = deepcopy(netslice_vlds)
2322 nsi_vld["shared-nsrs-list"] = []
2323 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2324 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002325
2326 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002327 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002328 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002329 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002330
Felipe Vicens09e65422019-01-22 15:06:46 +01002331 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002332 for member_ns in nstd["netslice-subnet"]:
2333 nsd_id = member_ns["nsd-ref"]
2334 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002335 member_ns["nsd-ref"], member_ns["id"]
2336 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002337 if nsd_id not in needed_nsds:
2338 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002339 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002340 nsd = self.db.get_one(
2341 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2342 )
tiernob4844ab2019-05-23 08:42:12 +00002343 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002344 nsd.pop("_admin")
2345 needed_nsds[nsd_id] = nsd
2346 else:
2347 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002348 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2349 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002350
Felipe Vicensb57758d2018-10-16 16:00:20 +02002351 step = "filling nsir nsd-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
Felipe Vicens07f31722018-10-29 15:16:44 +01002355 # creates Network Services records (NSRs)
2356 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002357 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002358 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002359 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002360 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002361 # Check if the netslice-subnet is shared and if it is share if the nss exists
2362 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002363 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002364 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002365 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002366 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2367 "nsd-ref"
2368 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002369 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002370 nsi = self.db.get_one(
2371 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2372 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002373 if nsi and service.get("is-shared-nss"):
2374 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2375 for nsrs_detailed_item in nsrs_detailed_list:
2376 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002377 if nsrs_detailed_item["nss-id"] == service["id"]:
2378 _id_nsr = nsrs_detailed_item["nsrId"]
2379 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002380 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2381 if netslice_subnet["nss-id"] == service["id"]:
2382 indata_ns = netslice_subnet
2383 break
2384 else:
2385 indata_ns = {}
2386 if service.get("instantiation-parameters"):
2387 indata_ns = deepcopy(service["instantiation-parameters"])
2388 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002389
Felipe Vicens09e65422019-01-22 15:06:46 +01002390 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002391 indata_ns["nsName"] = (
2392 slice_request.get("nsiName") + "." + service["id"]
2393 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002394 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2395 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002396 if slice_request.get("ssh_keys"):
2397 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002398
Felipe Vicens09e65422019-01-22 15:06:46 +01002399 if ns_params:
2400 for ns_param in ns_params:
2401 if ns_param.get("id") == service["id"]:
2402 copy_ns_param = deepcopy(ns_param)
2403 del copy_ns_param["id"]
2404 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002405 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002406
2407 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002408 _id_nsr, _ = self.nsrTopic.new(
2409 rollback, session, indata_ns, kwargs, headers
2410 )
2411 nsrs_item = {
2412 "nsrId": _id_nsr,
2413 "shared": service.get("is-shared-nss"),
2414 "nsd-id": service["nsd-ref"],
2415 "nss-id": service["id"],
2416 "nslcmop_instantiate": None,
2417 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002418 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002419 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002420 nsi_netslice_subnet.append(indata_ns)
2421 nsr_ref = {"nsr-ref": _id_nsr}
2422 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002423
2424 # Adding the nsrs list to the nsi
2425 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002426 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002427 self.db.set_one(
2428 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2429 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002430
Felipe Vicens07f31722018-10-29 15:16:44 +01002431 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002432 self.db.create("nsis", nsi_descriptor)
2433 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002434 return nsi_id, None
garciadeblas4568a372021-03-24 09:19:48 +01002435 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2436 self.logger.exception(
2437 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2438 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002439 raise EngineException("Error {}: {}".format(step, e))
2440 except ValidationError as e:
2441 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2442
tierno65ca36d2019-02-12 19:27:52 +01002443 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002444 raise EngineException(
2445 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2446 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002447
2448
2449class NsiLcmOpTopic(BaseTopic):
2450 topic = "nsilcmops"
2451 topic_msg = "nsi"
2452 operation_schema = { # mapping between operation and jsonschema to validate
2453 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002454 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002455 }
garciadeblas4568a372021-03-24 09:19:48 +01002456
delacruzramo32bab472019-09-13 12:24:22 +02002457 def __init__(self, db, fs, msg, auth):
2458 BaseTopic.__init__(self, db, fs, msg, auth)
2459 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002460
2461 def _check_nsi_operation(self, session, nsir, operation, indata):
2462 """
2463 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002464 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002465 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2466 :param indata: descriptor with the parameters of the operation
2467 :return: None
2468 """
2469 nsds = {}
2470 nstd = nsir["network-slice-template"]
2471
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002472 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002473 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002474 for netslice_subnet in nstd["netslice-subnet"]:
2475 if nstId == netslice_subnet["id"]:
2476 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002477 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002478 _filter = self._get_project_filter(session)
2479 _filter["id"] = nsd_id
2480 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002481 return nsds[nsd_id]
2482 else:
garciadeblas4568a372021-03-24 09:19:48 +01002483 raise EngineException(
2484 "Invalid parameter nstId='{}' is not one of the "
2485 "nst:netslice-subnet".format(nstId)
2486 )
2487
Felipe Vicens07f31722018-10-29 15:16:44 +01002488 if operation == "instantiate":
2489 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002490 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002491 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002492
2493 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2494 now = time()
2495 _id = str(uuid4())
2496 nsilcmop = {
2497 "id": _id,
2498 "_id": _id,
2499 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2500 "statusEnteredTime": now,
2501 "netsliceInstanceId": netsliceInstanceId,
2502 "lcmOperationType": operation,
2503 "startTime": now,
2504 "isAutomaticInvocation": False,
2505 "operationParams": params,
2506 "isCancelPending": False,
2507 "links": {
2508 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002509 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2510 + netsliceInstanceId,
2511 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002512 }
2513 return nsilcmop
2514
Felipe Vicens09e65422019-01-22 15:06:46 +01002515 def add_shared_nsr_2vld(self, nsir, nsr_item):
2516 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2517 if nst_sb_item.get("is-shared-nss"):
2518 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2519 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2520 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002521 for admin_vld_nss_cp_ref_item in admin_vld_item[
2522 "nss-connection-point-ref"
2523 ]:
2524 if (
2525 admin_subnet_item["nss-id"]
2526 == admin_vld_nss_cp_ref_item["nss-ref"]
2527 ):
2528 if (
2529 not nsr_item["nsrId"]
2530 in admin_vld_item["shared-nsrs-list"]
2531 ):
2532 admin_vld_item["shared-nsrs-list"].append(
2533 nsr_item["nsrId"]
2534 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002535 break
2536 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002537 self.db.set_one(
2538 "nsis",
2539 {"_id": nsir["_id"]},
2540 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2541 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002542
tierno65ca36d2019-02-12 19:27:52 +01002543 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002544 """
2545 Performs a new operation over a ns
2546 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002547 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002548 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002549 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002550 operation: it can be: instantiate, terminate, action, TODO: update, heal
2551 :param kwargs: used to override the indata descriptor
2552 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002553 :return: id of the nslcmops
2554 """
2555 try:
2556 # Override descriptor with query string kwargs
2557 self._update_input_with_kwargs(indata, kwargs)
2558 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002559 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002560 validate_input(indata, self.operation_schema[operation])
2561
Felipe Vicens126af572019-06-05 19:13:04 +02002562 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002563 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002564 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002565 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002566 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002567 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002568
2569 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002570 if (
2571 not nsir["_admin"].get("nsiState")
2572 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2573 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002574 if operation == "terminate" and indata.get("autoremove"):
2575 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002576 return (
2577 None,
2578 None,
2579 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002580 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002581 raise EngineException(
2582 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2583 netsliceInstanceId, operation
2584 ),
2585 HTTPStatus.CONFLICT,
2586 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002587 else:
tierno65ca36d2019-02-12 19:27:52 +01002588 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002589 raise EngineException(
2590 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2591 netsliceInstanceId, operation
2592 ),
2593 HTTPStatus.CONFLICT,
2594 )
2595
Felipe Vicens07f31722018-10-29 15:16:44 +01002596 # Creating all the NS_operation (nslcmop)
2597 # Get service list from db
2598 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2599 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002600 # nslcmops_item = None
2601 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002602 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002603 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002604 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002605 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002606 _filter[
2607 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2608 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002609 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002610 nsi = self.db.get_one(
2611 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2612 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002613 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002614 _update = {
2615 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2616 index
2617 ): None
2618 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002619 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002620 if (
2621 nsi
2622 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002623 continue # do not create nsilcmop
2624 else: # instantiate
2625 # looks the first nsi fulfilling the conditions but not being the current NSIR
2626 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002627 nsi_nsr_item = next(
2628 n
2629 for n in nsi["_admin"]["nsrs-detailed-list"]
2630 if n["nsrId"] == nsr_id
2631 and n["shared"]
2632 and n["nslcmop_instantiate"]
2633 )
tierno40f742b2020-06-23 15:25:26 +00002634 self.add_shared_nsr_2vld(nsir, nsr_item)
2635 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002636 _update = {
2637 "_admin.nsrs-detailed-list.{}".format(
2638 index
2639 ): nsi_nsr_item
2640 }
tierno40f742b2020-06-23 15:25:26 +00002641 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2642 # continue to not create nslcmop since nsrs is shared and nsrs was created
2643 continue
2644 else:
2645 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002646
tierno40f742b2020-06-23 15:25:26 +00002647 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002648 try:
tierno0b8752f2020-05-12 09:42:02 +00002649 indata_ns = {
2650 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002651 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002652 # Including netslice_id in the ns instantiate Operation
2653 "netsliceInstanceId": netsliceInstanceId,
2654 }
2655 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002656 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002657 indata_ns.update(service["instantiate_params"])
2658
tierno99d4b172019-07-02 09:28:40 +00002659 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002660 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002661 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2662 rollback, session, indata_ns, None, headers, slice_object=True
2663 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002664 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002665 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002666 _update = {
2667 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2668 index
2669 ): nslcmop
2670 }
tierno40f742b2020-06-23 15:25:26 +00002671 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002672 except (DbException, EngineException) as e:
2673 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002674 self.logger.info(
2675 logging_prefix
2676 + "skipping NS={} because not found".format(nsr_id)
2677 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002678 pass
2679 else:
2680 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002681
2682 # Creates nsilcmop
2683 indata["nslcmops_ids"] = nslcmops
2684 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002685
garciadeblas4568a372021-03-24 09:19:48 +01002686 nsilcmop_desc = self._create_nsilcmop(
2687 session, netsliceInstanceId, operation, indata
2688 )
2689 self.format_on_new(
2690 nsilcmop_desc, session["project_id"], make_public=session["public"]
2691 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002692 _id = self.db.create("nsilcmops", nsilcmop_desc)
2693 rollback.append({"topic": "nsilcmops", "_id": _id})
2694 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002695 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002696 except ValidationError as e:
2697 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002698
tiernobee3bad2019-12-05 12:26:01 +00002699 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002700 raise EngineException(
2701 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2702 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002703
tierno65ca36d2019-02-12 19:27:52 +01002704 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002705 raise EngineException(
2706 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2707 )