blob: 22580d152adf6b9528aca0713070197a85005161 [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": [],
480 }
481 ns_request["nsr_id"] = nsr_id
482 if ns_request and ns_request.get("config-units"):
483 nsr_descriptor["config-units"] = ns_request["config-units"]
garciaale7cbd03c2020-11-27 10:38:35 -0300484 # Create vld
485 if nsd.get("virtual-link-desc"):
486 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
487 # Fill each vld with vnfd-connection-point-ref data
488 # TODO: Change for multiple df support
489 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
490 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
491 for vnf_profile in vnf_profiles:
492 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
493 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100494 all_vld_connection_point_data[
495 vlc.get("virtual-link-profile-id")
496 ].append(
497 {
498 "member-vnf-index-ref": cpd.get(
499 "constituent-base-element-id"
500 ),
501 "vnfd-connection-point-ref": cpd.get(
502 "constituent-cpd-id"
503 ),
504 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
505 }
506 )
garciaale7cbd03c2020-11-27 10:38:35 -0300507
bravofe76b8822021-02-26 16:57:52 -0300508 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
garciaale7cbd03c2020-11-27 10:38:35 -0300509
510 for vdu in vnfd.get("vdu", ()):
511 flavor_data = {}
512 guest_epa = {}
513 # Find this vdu compute and storage descriptors
514 vdu_virtual_compute = {}
515 vdu_virtual_storage = {}
516 for vcd in vnfd.get("virtual-compute-desc", ()):
517 if vcd.get("id") == vdu.get("virtual-compute-desc"):
518 vdu_virtual_compute = vcd
519 for vsd in vnfd.get("virtual-storage-desc", ()):
520 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
521 vdu_virtual_storage = vsd
522 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblas4568a372021-03-24 09:19:48 +0100523 if vdu_virtual_compute.get("virtual-cpu", {}).get(
524 "num-virtual-cpu"
525 ):
526 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
527 "num-virtual-cpu"
528 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300529 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
garciadeblas4568a372021-03-24 09:19:48 +0100530 flavor_data["memory-mb"] = (
531 float(vdu_virtual_compute["virtual-memory"]["size"])
532 * 1024.0
533 )
garciaale7cbd03c2020-11-27 10:38:35 -0300534 if vdu_virtual_storage.get("size-of-storage"):
garciadeblas4568a372021-03-24 09:19:48 +0100535 flavor_data["storage-gb"] = vdu_virtual_storage[
536 "size-of-storage"
537 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300538 # Get this vdu EPA info for guest_epa
539 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100540 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
541 "cpu-quota"
542 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300543 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
544 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
545 if vcpu_pinning.get("thread-policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100546 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
547 "thread-policy"
548 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300549 if vcpu_pinning.get("policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100550 cpu_policy = (
551 "SHARED"
552 if vcpu_pinning["policy"] == "dynamic"
553 else "DEDICATED"
554 )
garciaale7cbd03c2020-11-27 10:38:35 -0300555 guest_epa["cpu-pinning-policy"] = cpu_policy
556 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100557 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
558 "mem-quota"
559 ]
560 if vdu_virtual_compute.get("virtual-memory", {}).get(
561 "mempage-size"
562 ):
563 guest_epa["mempage-size"] = vdu_virtual_compute[
564 "virtual-memory"
565 ]["mempage-size"]
566 if vdu_virtual_compute.get("virtual-memory", {}).get(
567 "numa-node-policy"
568 ):
569 guest_epa["numa-node-policy"] = vdu_virtual_compute[
570 "virtual-memory"
571 ]["numa-node-policy"]
garciaale7cbd03c2020-11-27 10:38:35 -0300572 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100573 guest_epa["disk-io-quota"] = vdu_virtual_storage[
574 "disk-io-quota"
575 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300576
577 if guest_epa:
578 flavor_data["guest-epa"] = guest_epa
579
580 flavor_data["name"] = vdu["id"][:56] + "-flv"
581 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
582 nsr_descriptor["flavor"].append(flavor_data)
583
584 sw_image_id = vdu.get("sw-image-desc")
585 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000586 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
587 self._add_image_to_nsr(nsr_descriptor, image_data)
588
589 # also add alternative images to the list of images
590 for alt_image in vdu.get("alternative-sw-image-desc", ()):
591 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
592 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300593
594 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100595 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
596 vld.get("id"), []
597 )
garciaale7cbd03c2020-11-27 10:38:35 -0300598 vld["name"] = vld["id"]
599 nsr_descriptor["vld"] = nsr_vld
600
601 return nsr_descriptor
602
lloretgalleg28c13b62021-02-08 11:48:48 +0000603 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100604 sw_image_desc = utils.find_in_list(
605 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
606 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000607 image_data = {}
608 if sw_image_desc.get("image"):
609 image_data["image"] = sw_image_desc["image"]
610 if sw_image_desc.get("checksum"):
611 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
612 if sw_image_desc.get("vim-type"):
613 image_data["vim-type"] = sw_image_desc["vim-type"]
614 return image_data
615
616 def _add_image_to_nsr(self, nsr_descriptor, image_data):
617 """
618 Adds image to nsr checking first it is not already added
619 """
garciadeblas4568a372021-03-24 09:19:48 +0100620 img = next(
621 (
622 f
623 for f in nsr_descriptor["image"]
624 if all(f.get(k) == image_data[k] for k in image_data)
625 ),
626 None,
627 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000628 if not img:
629 image_data["id"] = str(len(nsr_descriptor["image"]))
630 nsr_descriptor["image"].append(image_data)
631
garciadeblas4568a372021-03-24 09:19:48 +0100632 def _create_vnfr_descriptor_from_vnfd(
633 self,
634 nsd,
635 vnfd,
636 vnfd_id,
637 vnf_index,
638 nsr_descriptor,
639 ns_request,
640 ns_k8s_namespace,
641 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300642 vnfr_id = str(uuid4())
643 nsr_id = nsr_descriptor["id"]
644 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100645 additional_params, vnf_params = self._format_additional_params(
646 ns_request, vnf_index, descriptor=vnfd
647 )
garciaale7cbd03c2020-11-27 10:38:35 -0300648
649 vnfr_descriptor = {
650 "id": vnfr_id,
651 "_id": vnfr_id,
652 "nsr-id-ref": nsr_id,
653 "member-vnf-index-ref": vnf_index,
654 "additionalParamsForVnf": additional_params,
655 "created-time": now,
656 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
657 "vnfd-ref": vnfd_id,
658 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
659 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200660 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300661 "vdur": [],
662 "connection-point": [],
663 "ip-address": None, # mgmt-interface filled by LCM
664 }
665 vnf_k8s_namespace = ns_k8s_namespace
666 if vnf_params:
667 if vnf_params.get("k8s-namespace"):
668 vnf_k8s_namespace = vnf_params["k8s-namespace"]
669 if vnf_params.get("config-units"):
670 vnfr_descriptor["config-units"] = vnf_params["config-units"]
671
672 # Create vld
673 if vnfd.get("int-virtual-link-desc"):
674 vnfr_descriptor["vld"] = []
675 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
676 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
677
678 for cp in vnfd.get("ext-cpd", ()):
679 vnf_cp = {
680 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100681 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
682 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300683 "id": cp.get("id"),
684 # "ip-address", "mac-address" # filled by LCM
685 # vim-id # TODO it would be nice having a vim port id
686 }
687 vnfr_descriptor["connection-point"].append(vnf_cp)
688
689 # Create k8s-cluster information
690 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
691 if vnfd.get("k8s-cluster"):
692 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
693 all_k8s_cluster_nets_cpds = {}
694 for cpd in get_iterable(vnfd.get("ext-cpd")):
695 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100696 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
697 "id"
698 )
garciaale7cbd03c2020-11-27 10:38:35 -0300699 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
700 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100701 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
702 net.get("id")
703 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300704
705 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300706 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100707 additional_params, kdu_params = self._format_additional_params(
708 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
709 )
garciaale7cbd03c2020-11-27 10:38:35 -0300710 kdu_k8s_namespace = vnf_k8s_namespace
711 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
712 if kdu_params and kdu_params.get("k8s-namespace"):
713 kdu_k8s_namespace = kdu_params["k8s-namespace"]
714
romeromonserbfebfc02021-05-28 10:51:35 +0200715 kdu_deployment_name = ""
716 if kdu_params and kdu_params.get("kdu-deployment-name"):
717 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
718
garciaale7cbd03c2020-11-27 10:38:35 -0300719 kdur = {
720 "additionalParams": additional_params,
721 "k8s-namespace": kdu_k8s_namespace,
romeromonserbfebfc02021-05-28 10:51:35 +0200722 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000723 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300724 # TODO "name": "" Name of the VDU in the VIM
725 "ip-address": None, # mgmt-interface filled by LCM
726 "k8s-cluster": {},
727 }
728 if kdu_params and kdu_params.get("config-units"):
729 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000730 if kdu.get("helm-version"):
731 kdur["helm-version"] = kdu["helm-version"]
732 for k8s_type in ("helm-chart", "juju-bundle"):
733 if kdu.get(k8s_type):
734 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300735 if not vnfr_descriptor.get("kdur"):
736 vnfr_descriptor["kdur"] = []
737 vnfr_descriptor["kdur"].append(kdur)
738
739 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300740
garciaale7cbd03c2020-11-27 10:38:35 -0300741 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300742 vdu_mgmt_cp = []
743 try:
garciadeblas4568a372021-03-24 09:19:48 +0100744 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
745 "operate-vnf-op-config"
746 ]["day1-2"]
747 vdu_config = utils.find_in_list(
748 configs, lambda config: config["id"] == vdu["id"]
749 )
bravoff3c39552021-02-24 17:22:24 -0300750 except Exception:
751 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400752
753 try:
754 vdu_instantiation_level = utils.find_in_list(
755 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100756 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400757 )
758 except Exception:
759 vdu_instantiation_level = None
760
bravoff3c39552021-02-24 17:22:24 -0300761 if vdu_config:
762 external_connection_ee = utils.filter_in_list(
763 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100764 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300765 )
766 for ee in external_connection_ee:
767 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
768
garciaale7cbd03c2020-11-27 10:38:35 -0300769 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100770 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
771 )
bravof65e22e52021-11-10 17:58:58 -0300772
773 try:
774 vdu_virtual_storage_descriptors = utils.filter_in_list(
775 vnfd.get("virtual-storage-desc", []),
776 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
777 )
778 except Exception:
779 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300780 vdur = {
781 "vdu-id-ref": vdu["id"],
782 # TODO "name": "" Name of the VDU in the VIM
783 "ip-address": None, # mgmt-interface filled by LCM
784 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
785 "internal-connection-point": [],
786 "interfaces": [],
787 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100788 "vdu-name": vdu["name"],
bravof65e22e52021-11-10 17:58:58 -0300789 "virtual-storages": vdu_virtual_storage_descriptors
garciaale7cbd03c2020-11-27 10:38:35 -0300790 }
791 if vdu_params and vdu_params.get("config-units"):
792 vdur["config-units"] = vdu_params["config-units"]
793 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100794 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
795 "boot-data-drive"
796 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300797 if vdu.get("pdu-type"):
798 vdur["pdu-type"] = vdu["pdu-type"]
799 vdur["name"] = vdu["pdu-type"]
800 # TODO volumes: name, volume-id
801 for icp in vdu.get("int-cpd", ()):
802 vdu_icp = {
803 "id": icp["id"],
804 "connection-point-id": icp["id"],
805 "name": icp.get("id"),
806 }
bravof35766442021-02-04 14:58:04 -0300807
garciaale7cbd03c2020-11-27 10:38:35 -0300808 vdur["internal-connection-point"].append(vdu_icp)
809
810 for iface in icp.get("virtual-network-interface-requirement", ()):
811 iface_fields = ("name", "mac-address")
garciadeblas4568a372021-03-24 09:19:48 +0100812 vdu_iface = {
813 x: iface[x] for x in iface_fields if iface.get(x) is not None
814 }
garciaale7cbd03c2020-11-27 10:38:35 -0300815
816 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100817 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100818 vdu_iface["port-security-enabled"] = icp[
819 "port-security-enabled"
820 ]
sousaedu003844e2021-03-02 00:19:15 +0100821
822 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100823 vdu_iface["port-security-disable-strategy"] = icp[
824 "port-security-disable-strategy"
825 ]
sousaedu003844e2021-03-02 00:19:15 +0100826
garciaale7cbd03c2020-11-27 10:38:35 -0300827 for ext_cp in vnfd.get("ext-cpd", ()):
828 if not ext_cp.get("int-cpd"):
829 continue
830 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
831 continue
832 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100833 vdu_iface["external-connection-point-ref"] = ext_cp.get(
834 "id"
835 )
sousaedu003844e2021-03-02 00:19:15 +0100836
837 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100838 vdu_iface["port-security-enabled"] = ext_cp[
839 "port-security-enabled"
840 ]
sousaedu003844e2021-03-02 00:19:15 +0100841
842 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100843 vdu_iface["port-security-disable-strategy"] = ext_cp[
844 "port-security-disable-strategy"
845 ]
sousaedu003844e2021-03-02 00:19:15 +0100846
garciaale7cbd03c2020-11-27 10:38:35 -0300847 break
848
garciadeblas4568a372021-03-24 09:19:48 +0100849 if (
850 vnfd_mgmt_cp
851 and vdu_iface.get("external-connection-point-ref")
852 == vnfd_mgmt_cp
853 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300854 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300855 vdu_iface["mgmt-interface"] = True
856
857 for ecp in vdu_mgmt_cp:
858 if vdu_iface.get("external-connection-point-ref") == ecp:
859 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300860
861 if iface.get("virtual-interface"):
862 vdu_iface.update(deepcopy(iface["virtual-interface"]))
863
864 # look for network where this interface is connected
865 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
866 if iface_ext_cp:
867 # TODO: Change for multiple df support
868 for df in get_iterable(nsd.get("df")):
869 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100870 for vlc_index, vlc in enumerate(
871 get_iterable(
872 vnf_profile.get("virtual-link-connectivity")
873 )
874 ):
875 for cpd in get_iterable(
876 vlc.get("constituent-cpd-id")
877 ):
878 if (
879 cpd.get("constituent-cpd-id")
880 == iface_ext_cp
881 ):
882 vdu_iface["ns-vld-id"] = vlc.get(
883 "virtual-link-profile-id"
884 )
garciadeblas61c95912021-02-12 11:23:50 +0000885 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100886 if vdu_iface.get("type") in (
887 "SR-IOV",
888 "PCI-PASSTHROUGH",
889 ):
890 nsr_descriptor["vld"][vlc_index][
891 "pci-interfaces"
892 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300893 break
894 elif vdu_iface.get("internal-connection-point-ref"):
895 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000896 # TODO: store fixed IP address in the record (if it exists in the ICP)
897 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
898 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100899 ivld_index = utils.find_index_in_list(
900 vnfd.get("int-virtual-link-desc", ()),
901 lambda ivld: ivld["id"]
902 == icp.get("int-virtual-link-desc"),
903 )
garciadeblas61c95912021-02-12 11:23:50 +0000904 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300905
906 vdur["interfaces"].append(vdu_iface)
907
908 if vdu.get("sw-image-desc"):
909 sw_image = utils.find_in_list(
910 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100911 lambda image: image["id"] == vdu.get("sw-image-desc"),
912 )
garciaale7cbd03c2020-11-27 10:38:35 -0300913 nsr_sw_image_data = utils.find_in_list(
914 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100915 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300916 )
917 vdur["ns-image-id"] = nsr_sw_image_data["id"]
918
lloretgalleg28c13b62021-02-08 11:48:48 +0000919 if vdu.get("alternative-sw-image-desc"):
920 alt_image_ids = []
921 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
922 sw_image = utils.find_in_list(
923 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100924 lambda image: image["id"] == alt_image_id,
925 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000926 nsr_sw_image_data = utils.find_in_list(
927 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100928 lambda nsr_image: (
929 nsr_image.get("image") == sw_image.get("image")
930 ),
lloretgalleg28c13b62021-02-08 11:48:48 +0000931 )
932 alt_image_ids.append(nsr_sw_image_data["id"])
933 vdur["alt-image-ids"] = alt_image_ids
934
garciaale7cbd03c2020-11-27 10:38:35 -0300935 flavor_data_name = vdu["id"][:56] + "-flv"
936 nsr_flavor_desc = utils.find_in_list(
937 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +0100938 lambda flavor: flavor["name"] == flavor_data_name,
939 )
garciaale7cbd03c2020-11-27 10:38:35 -0300940
941 if nsr_flavor_desc:
942 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
943
bravof4ca51522021-04-22 10:03:02 -0400944 if vdu_instantiation_level:
945 count = vdu_instantiation_level.get("number-of-instances")
946 else:
947 count = 1
948
garciaale7cbd03c2020-11-27 10:38:35 -0300949 for index in range(0, count):
950 vdur = deepcopy(vdur)
951 for iface in vdur["interfaces"]:
bravofb7cdee12021-07-01 09:32:30 -0400952 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -0300953 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofb7cdee12021-07-01 09:32:30 -0400954 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -0300955 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
956
957 vdur["_id"] = str(uuid4())
958 vdur["id"] = vdur["_id"]
959 vdur["count-index"] = index
960 vnfr_descriptor["vdur"].append(vdur)
961
962 return vnfr_descriptor
963
K Sai Kiran57589552021-01-27 21:38:34 +0530964 def vca_status_refresh(self, session, ns_instance_content, filter_q):
965 """
966 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
967 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
968 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
969 :param ns_instance_content: ns instance content
970 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
971 :return: None
972 """
973 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
974 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
975 threshold_reached = time_delta > 120
976 if force_refresh or threshold_reached:
977 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
978 ns_instance_content["_admin"]["modified"] = time_now
979 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
980 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
981 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
982 nslcmop_desc["_admin"].pop("nsState")
983 self.msg.write("ns", operation, nslcmop_desc)
984 return
985
986 def show(self, session, _id, filter_q=None, api_req=False):
987 """
988 Get complete information on an ns instance.
989 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
990 :param _id: string, ns instance id
991 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
992 :param api_req: True if this call is serving an external API request. False if serving internal request.
993 :return: dictionary, raise exception if not found.
994 """
995 ns_instance_content = super().show(session, _id, api_req)
996 self.vca_status_refresh(session, ns_instance_content, filter_q)
997 return ns_instance_content
998
tierno65ca36d2019-02-12 19:27:52 +0100999 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001000 raise EngineException(
1001 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1002 )
tiernob24258a2018-10-04 18:39:49 +02001003
1004
1005class VnfrTopic(BaseTopic):
1006 topic = "vnfrs"
1007 topic_msg = None
1008
delacruzramo32bab472019-09-13 12:24:22 +02001009 def __init__(self, db, fs, msg, auth):
1010 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001011
tiernobee3bad2019-12-05 12:26:01 +00001012 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001013 raise EngineException(
1014 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1015 )
tiernob24258a2018-10-04 18:39:49 +02001016
tierno65ca36d2019-02-12 19:27:52 +01001017 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001018 raise EngineException(
1019 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1020 )
tiernob24258a2018-10-04 18:39:49 +02001021
tierno65ca36d2019-02-12 19:27:52 +01001022 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001023 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001024 raise EngineException(
1025 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1026 )
tiernob24258a2018-10-04 18:39:49 +02001027
1028
1029class NsLcmOpTopic(BaseTopic):
1030 topic = "nslcmops"
1031 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001032 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001033 "instantiate": ns_instantiate,
1034 "action": ns_action,
1035 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +00001036 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +02001037 }
1038
delacruzramo32bab472019-09-13 12:24:22 +02001039 def __init__(self, db, fs, msg, auth):
1040 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001041
tiernob24258a2018-10-04 18:39:49 +02001042 def _check_ns_operation(self, session, nsr, operation, indata):
1043 """
1044 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001045 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001046 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1047 :param indata: descriptor with the parameters of the operation
1048 :return: None
1049 """
garciaale7cbd03c2020-11-27 10:38:35 -03001050 if operation == "action":
1051 self._check_action_ns_operation(indata, nsr)
1052 elif operation == "scale":
1053 self._check_scale_ns_operation(indata, nsr)
1054 elif operation == "instantiate":
1055 self._check_instantiate_ns_operation(indata, nsr, session)
1056
1057 def _check_action_ns_operation(self, indata, nsr):
1058 nsd = nsr["nsd"]
1059 # check vnf_member_index
1060 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001061 indata["member_vnf_index"] = indata.pop(
1062 "vnf_member_index"
1063 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001064 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001065 vnfd = self._get_vnfd_from_vnf_member_index(
1066 indata["member_vnf_index"], nsr["_id"]
1067 )
bravof41a52052021-02-17 18:08:01 -03001068 try:
garciadeblas4568a372021-03-24 09:19:48 +01001069 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1070 "operate-vnf-op-config"
1071 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001072 except Exception:
1073 configs = []
1074
garciaale7cbd03c2020-11-27 10:38:35 -03001075 if indata.get("vdu_id"):
1076 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001077 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001078 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001079 )
garciaale7cbd03c2020-11-27 10:38:35 -03001080 elif indata.get("kdu_name"):
1081 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001082 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001083 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001084 )
garciaale7cbd03c2020-11-27 10:38:35 -03001085 else:
bravof41a52052021-02-17 18:08:01 -03001086 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001087 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001088 )
1089 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001090 descriptor_configuration = descriptor_configuration.get(
1091 "config-primitive"
1092 )
garciaale7cbd03c2020-11-27 10:38:35 -03001093 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001094 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1095 "config-primitive"
1096 )
garciaale7cbd03c2020-11-27 10:38:35 -03001097
1098 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001099 if indata.get("kdu_name") and indata["primitive"] in (
1100 "upgrade",
1101 "rollback",
1102 "status",
1103 "inspect",
1104 "readme",
1105 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001106 # TODO should be checked that rollback only can contains revsision_numbe????
1107 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001108 raise EngineException(
1109 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1110 indata["primitive"]
1111 )
1112 )
garciaale7cbd03c2020-11-27 10:38:35 -03001113 return
1114 # if not, check primitive
1115 for config_primitive in get_iterable(descriptor_configuration):
1116 if indata["primitive"] == config_primitive["name"]:
1117 # check needed primitive_params are provided
1118 if indata.get("primitive_params"):
1119 in_primitive_params_copy = copy(indata["primitive_params"])
1120 else:
1121 in_primitive_params_copy = {}
1122 for paramd in get_iterable(config_primitive.get("parameter")):
1123 if paramd["name"] in in_primitive_params_copy:
1124 del in_primitive_params_copy[paramd["name"]]
1125 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001126 raise EngineException(
1127 "Needed parameter {} not provided for primitive '{}'".format(
1128 paramd["name"], indata["primitive"]
1129 )
1130 )
garciaale7cbd03c2020-11-27 10:38:35 -03001131 # check no extra primitive params are provided
1132 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001133 raise EngineException(
1134 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1135 list(in_primitive_params_copy.keys()), indata["primitive"]
1136 )
1137 )
garciaale7cbd03c2020-11-27 10:38:35 -03001138 break
1139 else:
garciadeblas4568a372021-03-24 09:19:48 +01001140 raise EngineException(
1141 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1142 indata["primitive"]
1143 )
1144 )
garciaale7cbd03c2020-11-27 10:38:35 -03001145
1146 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001147 vnfd = self._get_vnfd_from_vnf_member_index(
1148 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1149 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001150 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001151 if (
1152 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1153 == scaling_aspect["id"]
1154 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001155 break
1156 else:
garciadeblas4568a372021-03-24 09:19:48 +01001157 raise EngineException(
1158 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1159 "present at vnfd:scaling-aspect".format(
1160 indata["scaleVnfData"]["scaleByStepData"][
1161 "scaling-group-descriptor"
1162 ]
1163 )
1164 )
garciaale7cbd03c2020-11-27 10:38:35 -03001165
1166 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001167 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001168 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001169 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001170 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001171 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1172 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1173 for in_vnf in get_iterable(indata.get("vnf")):
1174 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001175 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001176 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001177 else:
garciadeblas4568a372021-03-24 09:19:48 +01001178 vnfd = self._get_vnfd_from_vnf_member_index(
1179 member_vnf_index, nsr["_id"]
1180 )
1181 vnf_member_index_to_vnfd[
1182 member_vnf_index
1183 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001184 self._check_vnf_instantiation_params(in_vnf, vnfd)
1185 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001186 self._check_valid_vim_account(
1187 in_vnf["vimAccountId"], vim_accounts, session
1188 )
tierno260dd6f2019-09-02 10:48:56 +00001189
garciaale7cbd03c2020-11-27 10:38:35 -03001190 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001191 self._check_valid_wim_account(
1192 in_vld.get("wimAccountId"), wim_accounts, session
1193 )
garciaale7cbd03c2020-11-27 10:38:35 -03001194 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1195 if in_vld["name"] == vldd["id"]:
1196 break
tierno9cb7d672019-10-30 12:13:48 +00001197 else:
garciadeblas4568a372021-03-24 09:19:48 +01001198 raise EngineException(
1199 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1200 in_vld["name"]
1201 )
1202 )
tierno9cb7d672019-10-30 12:13:48 +00001203
garciaale7cbd03c2020-11-27 10:38:35 -03001204 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1205 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001206 vnfr = self.db.get_one(
1207 "vnfrs",
1208 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1209 fail_on_empty=False,
1210 )
garciaale7cbd03c2020-11-27 10:38:35 -03001211 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001212 raise EngineException(
1213 "Invalid parameter member_vnf_index='{}' is not one of the "
1214 "nsd:constituent-vnfd".format(member_vnf_index)
1215 )
garciaale7cbd03c2020-11-27 10:38:35 -03001216 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1217 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001218 raise EngineException(
1219 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1220 vnfr["vnfd-id"]
1221 )
1222 )
garciaale7cbd03c2020-11-27 10:38:35 -03001223 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001224
garciaale7cbd03c2020-11-27 10:38:35 -03001225 def _check_valid_vdu(self, vnfd, vdu_id):
1226 for vdud in get_iterable(vnfd.get("vdu")):
1227 if vdud["id"] == vdu_id:
1228 return vdud
1229 else:
garciadeblas4568a372021-03-24 09:19:48 +01001230 raise EngineException(
1231 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1232 vdu_id
1233 )
1234 )
garciaale7cbd03c2020-11-27 10:38:35 -03001235
1236 def _check_valid_kdu(self, vnfd, kdu_name):
1237 for kdud in get_iterable(vnfd.get("kdu")):
1238 if kdud["name"] == kdu_name:
1239 return kdud
1240 else:
garciadeblas4568a372021-03-24 09:19:48 +01001241 raise EngineException(
1242 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1243 kdu_name
1244 )
1245 )
garciaale7cbd03c2020-11-27 10:38:35 -03001246
1247 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1248 for in_vdu in get_iterable(in_vnf.get("vdu")):
1249 for vdu in get_iterable(vnfd.get("vdu")):
1250 if in_vdu["id"] == vdu["id"]:
1251 for volume in get_iterable(in_vdu.get("volume")):
1252 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1253 if volumed["id"] == volume["name"]:
1254 break
1255 else:
garciadeblas4568a372021-03-24 09:19:48 +01001256 raise EngineException(
1257 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1258 "volume:name='{}' is not present at "
1259 "vnfd:vdu:virtual-storage-desc list".format(
1260 in_vnf["member-vnf-index"],
1261 in_vdu["id"],
1262 volume["id"],
1263 )
1264 )
garciaale7cbd03c2020-11-27 10:38:35 -03001265
1266 vdu_if_names = set()
1267 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001268 for iface in get_iterable(
1269 cpd.get("virtual-network-interface-requirement")
1270 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001271 vdu_if_names.add(iface.get("name"))
1272
1273 for in_iface in get_iterable(in_vdu["interface"]):
1274 if in_iface["name"] in vdu_if_names:
1275 break
1276 else:
garciadeblas4568a372021-03-24 09:19:48 +01001277 raise EngineException(
1278 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1279 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1280 in_vnf["member-vnf-index"],
1281 in_vdu["id"],
1282 in_iface["name"],
1283 )
1284 )
garciaale7cbd03c2020-11-27 10:38:35 -03001285 break
1286
1287 else:
garciadeblas4568a372021-03-24 09:19:48 +01001288 raise EngineException(
1289 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1290 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1291 )
garciaale7cbd03c2020-11-27 10:38:35 -03001292
garciadeblas4568a372021-03-24 09:19:48 +01001293 vnfd_ivlds_cpds = {
1294 ivld.get("id"): set()
1295 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1296 }
garciaale7cbd03c2020-11-27 10:38:35 -03001297 for vdu in get_iterable(vnfd.get("vdu")):
1298 for cpd in get_iterable(vnfd.get("int-cpd")):
1299 if cpd.get("int-virtual-link-desc"):
1300 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1301
1302 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1303 if in_ivld.get("name") in vnfd_ivlds_cpds:
1304 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1305 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001306 break
tiernob24258a2018-10-04 18:39:49 +02001307 else:
garciadeblas4568a372021-03-24 09:19:48 +01001308 raise EngineException(
1309 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1310 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1311 "vnfd:internal-vld:name/id:internal-connection-point".format(
1312 in_vnf["member-vnf-index"],
1313 in_ivld["name"],
1314 in_icp["id-ref"],
1315 )
1316 )
tiernob24258a2018-10-04 18:39:49 +02001317 else:
garciadeblas4568a372021-03-24 09:19:48 +01001318 raise EngineException(
1319 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1320 " is not present at vnfd '{}'".format(
1321 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1322 )
1323 )
tiernob24258a2018-10-04 18:39:49 +02001324
garciaale7cbd03c2020-11-27 10:38:35 -03001325 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1326 if vim_account in vim_accounts:
1327 return
1328 try:
1329 db_filter = self._get_project_filter(session)
1330 db_filter["_id"] = vim_account
1331 self.db.get_one("vim_accounts", db_filter)
1332 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001333 raise EngineException(
1334 "Invalid vimAccountId='{}' not present for the project".format(
1335 vim_account
1336 )
1337 )
garciaale7cbd03c2020-11-27 10:38:35 -03001338 vim_accounts.append(vim_account)
1339
David Garcia98de2982021-10-13 17:14:01 +02001340 def _get_vim_account(self, vim_id: str, session):
1341 try:
1342 db_filter = self._get_project_filter(session)
1343 db_filter["_id"] = vim_id
1344 return self.db.get_one("vim_accounts", db_filter)
1345 except Exception:
1346 raise EngineException(
1347 "Invalid vimAccountId='{}' not present for the project".format(
1348 vim_id
1349 )
1350 )
1351
garciaale7cbd03c2020-11-27 10:38:35 -03001352 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1353 if not isinstance(wim_account, str):
1354 return
1355 if wim_account in wim_accounts:
1356 return
1357 try:
1358 db_filter = self._get_project_filter(session, write=False, show_all=True)
1359 db_filter["_id"] = wim_account
1360 self.db.get_one("wim_accounts", db_filter)
1361 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001362 raise EngineException(
1363 "Invalid wimAccountId='{}' not present for the project".format(
1364 wim_account
1365 )
1366 )
garciaale7cbd03c2020-11-27 10:38:35 -03001367 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001368
garciadeblas4568a372021-03-24 09:19:48 +01001369 def _look_for_pdu(
1370 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1371 ):
tiernocc103432018-10-19 14:10:35 +02001372 """
tierno36ec8602018-11-02 17:27:11 +01001373 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1374 (ip_address, ...) information.
1375 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001376 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001377 :param rollback: list with the database modifications to rollback if needed
1378 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1379 :param vim_account: vim_account where this vnfr should be deployed
1380 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1381 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1382 of the changed vnfr is needed
1383
1384 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1385 "vim-network-name": used at VIM
1386 "name": interface name
1387 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1388 "ns-vld-id": NSD vld where this interface is connected.
1389 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 +02001390 """
tierno36ec8602018-11-02 17:27:11 +01001391
1392 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001393 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1394 if not vdur.get("pdu-type"):
1395 continue
1396 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001397 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001398 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001399 pdu_filter["type"] = pdu_type
1400 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001401 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001402 # TODO feature 1417: "shared": True,
1403
1404 available_pdus = self.db.get_list("pdus", pdu_filter)
1405 for pdu in available_pdus:
1406 # step 1 check if this pdu contains needed interfaces:
1407 match_interfaces = True
1408 for vdur_interface in vdur["interfaces"]:
1409 for pdu_interface in pdu["interfaces"]:
1410 if pdu_interface["name"] == vdur_interface["name"]:
1411 # TODO feature 1417: match per mgmt type
1412 break
1413 else: # no interface found for name
1414 match_interfaces = False
1415 break
1416 if match_interfaces:
1417 break
1418 else:
1419 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001420 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001421 "names".format(
1422 pdu_type,
1423 vim_account,
1424 vnfr["member-vnf-index-ref"],
1425 vdur["vdu-id-ref"],
1426 )
1427 )
tiernocc103432018-10-19 14:10:35 +02001428
1429 # step 2. Update pdu
1430 rollback_pdu = {
1431 "_admin.usageState": pdu["_admin"]["usageState"],
1432 "_admin.usage.vnfr_id": None,
1433 "_admin.usage.nsr_id": None,
1434 "_admin.usage.vdur": None,
1435 }
garciadeblas4568a372021-03-24 09:19:48 +01001436 self.db.set_one(
1437 "pdus",
1438 {"_id": pdu["_id"]},
1439 {
1440 "_admin.usageState": "IN_USE",
1441 "_admin.usage": {
1442 "vnfr_id": vnfr["_id"],
1443 "nsr_id": vnfr["nsr-id-ref"],
1444 "vdur": vdur["vdu-id-ref"],
1445 },
1446 },
1447 )
1448 rollback.append(
1449 {
1450 "topic": "pdus",
1451 "_id": pdu["_id"],
1452 "operation": "set",
1453 "content": rollback_pdu,
1454 }
1455 )
tiernocc103432018-10-19 14:10:35 +02001456
1457 # step 3. Fill vnfr info by filling vdur
1458 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001459 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001460 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1461 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1462 for pdu_interface in pdu["interfaces"]:
1463 if pdu_interface["name"] == vdur_interface["name"]:
1464 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1465 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001466 if k in (
1467 "ip-address",
1468 "mac-address",
1469 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001470 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001471 vnfr_update_rollback[
1472 iface_text + ".{}".format(k)
1473 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001474 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001475 if vdur_interface.get(
1476 "mgmt-interface"
1477 ) or vdur_interface.get("mgmt-vnf"):
1478 vnfr_update_rollback[
1479 vdu_text + ".ip-address"
1480 ] = vdur.get("ip-address")
1481 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1482 "ip-address"
1483 ]
tierno36ec8602018-11-02 17:27:11 +01001484 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001485 vnfr_update_rollback["ip-address"] = vnfr.get(
1486 "ip-address"
1487 )
tierno36ec8602018-11-02 17:27:11 +01001488 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001489 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1490 "ip-address"
1491 ]
1492 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1493 "vim-network-id"
1494 ):
1495 ifaces_forcing_vim_network.append(
1496 {
1497 "name": vdur_interface.get("vnf-vld-id")
1498 or vdur_interface.get("ns-vld-id"),
1499 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1500 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1501 }
1502 )
gcalvino17d5b732018-12-17 16:26:21 +01001503 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001504 ifaces_forcing_vim_network[-1][
1505 "vim-network-id"
1506 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001507 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001508 ifaces_forcing_vim_network[-1][
1509 "vim-network-name"
1510 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001511 break
1512
tierno36ec8602018-11-02 17:27:11 +01001513 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001514
garciadeblas4568a372021-03-24 09:19:48 +01001515 def _look_for_k8scluster(
1516 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1517 ):
tierno9cb7d672019-10-30 12:13:48 +00001518 """
1519 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1520 Fills vnfr.kdur with the selected k8scluster
1521
1522 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1523 :param rollback: list with the database modifications to rollback if needed
1524 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1525 :param vim_account: vim_account where this vnfr should be deployed
1526 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1527 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1528 of the changed vnfr is needed
1529
1530 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1531 "vim-network-name": used at VIM
1532 "name": interface name
1533 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1534 "ns-vld-id": NSD vld where this interface is connected.
1535 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1536 """
1537
1538 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001539 if not vnfr.get("kdur"):
1540 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001541
tiernoc67b0e92019-11-05 12:45:29 +00001542 kdu_filter = self._get_project_filter(session)
1543 kdu_filter["vim_account"] = vim_account
1544 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1545 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1546
1547 k8s_requirements = {} # just for logging
1548 for k8scluster in available_k8sclusters:
1549 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001550 break
tiernoc67b0e92019-11-05 12:45:29 +00001551 # restrict by cni
1552 if vnfr["k8s-cluster"].get("cni"):
1553 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001554 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1555 k8scluster.get("cni", ())
1556 ):
tiernoc67b0e92019-11-05 12:45:29 +00001557 continue
1558 # restrict by version
1559 if vnfr["k8s-cluster"].get("version"):
1560 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1561 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1562 continue
1563 # restrict by number of networks
1564 if vnfr["k8s-cluster"].get("nets"):
1565 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001566 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1567 vnfr["k8s-cluster"]["nets"]
1568 ):
tiernoc67b0e92019-11-05 12:45:29 +00001569 continue
1570 break
1571 else:
garciadeblas4568a372021-03-24 09:19:48 +01001572 raise EngineException(
1573 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1574 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1575 )
1576 )
tierno9cb7d672019-10-30 12:13:48 +00001577
tiernoc67b0e92019-11-05 12:45:29 +00001578 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001579 # step 3. Fill vnfr info by filling kdur
1580 kdu_text = "kdur.{}.".format(kdur_index)
1581 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1582 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1583
tiernoc67b0e92019-11-05 12:45:29 +00001584 # step 4. Check VIM networks that forces the selected k8s_cluster
1585 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1586 k8scluster_net_list = list(k8scluster.get("nets").keys())
1587 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1588 # get a network from k8s_cluster nets. If name matches use this, if not use other
1589 if kdur_net["id"] in k8scluster_net_list: # name matches
1590 vim_net = k8scluster["nets"][kdur_net["id"]]
1591 k8scluster_net_list.remove(kdur_net["id"])
1592 else:
1593 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1594 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001595 vnfr_update_rollback[
1596 "k8s-cluster.nets.{}.vim_net".format(net_index)
1597 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001598 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001599 if vim_net and (
1600 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1601 ):
1602 ifaces_forcing_vim_network.append(
1603 {
1604 "name": kdur_net.get("vnf-vld-id")
1605 or kdur_net.get("ns-vld-id"),
1606 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1607 "ns-vld-id": kdur_net.get("ns-vld-id"),
1608 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1609 }
1610 )
tiernoc67b0e92019-11-05 12:45:29 +00001611 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001612 return ifaces_forcing_vim_network
1613
Gulsum Aticie395aa42021-11-10 20:59:06 +03001614 def _update_vnfrs_from_nsd(self, nsr):
1615 try:
1616 nsr_id = nsr["_id"]
1617 nsd = nsr["nsd"]
1618
1619 step = "Getting vnf_profiles from nsd"
1620 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1621 vld_fixed_ip_connection_point_data = {}
1622
1623 step = "Getting ip-address info from vnf_profile if it exists"
1624 for vnfp in vnf_profiles:
1625 # Checking ip-address info from nsd.vnf_profile and storing
1626 for vlc in vnfp.get("virtual-link-connectivity", ()):
1627 for cpd in vlc.get("constituent-cpd-id", ()):
1628 if cpd.get("ip-address"):
1629 step = "Storing ip-address info"
1630 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1631 "vnfd-connection-point-ref": cpd.get(
1632 "constituent-cpd-id"),
1633 "ip-address": cpd.get(
1634 "ip-address")}})
1635
1636 # Inserting ip address to vnfr
1637 if len(vld_fixed_ip_connection_point_data) > 0:
1638 step = "Getting vnfrs"
1639 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1640 for item in vld_fixed_ip_connection_point_data.keys():
1641 step = "Filtering vnfrs"
1642 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1643 if vnfr:
1644 vnfr_update = {}
1645 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1646 for iface_index, iface in enumerate(vdur["interfaces"]):
1647 step = "Looking for matched interface"
1648 if (
1649 iface.get("external-connection-point-ref")
1650 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1651 iface.get("ns-vld-id") == item.split('.')[0]
1652
1653 ):
1654 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1655 vdur_index, iface_index
1656 )
1657 step = "Storing info in order to update vnfr"
1658 vnfr_update[
1659 vnfr_update_text + ".ip-address"
1660 ] = increment_ip_mac(
1661 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1662 vdur.get("count-index", 0), )
1663 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1664
1665 step = "updating vnfr at database"
1666 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1667 except (
1668 ValidationError,
1669 EngineException,
1670 DbException,
1671 MsgException,
1672 FsException,
1673 ) as e:
1674 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1675
tiernocc103432018-10-19 14:10:35 +02001676 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001677 # get vnfr
1678 nsr_id = nsr["_id"]
1679 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1680
1681 for vnfr in vnfrs:
1682 vnfr_update = {}
1683 vnfr_update_rollback = {}
1684 member_vnf_index = vnfr["member-vnf-index-ref"]
1685 # update vim-account-id
1686
1687 vim_account = indata["vimAccountId"]
David Garcia98de2982021-10-13 17:14:01 +02001688 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001689 # check instantiate parameters
1690 for vnf_inst_params in get_iterable(indata.get("vnf")):
1691 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1692 continue
1693 if vnf_inst_params.get("vimAccountId"):
1694 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia98de2982021-10-13 17:14:01 +02001695 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001696
tiernocddb07d2020-10-06 08:28:00 +00001697 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1698 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1699 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1700 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1701 continue
garciadeblas4568a372021-03-24 09:19:48 +01001702 for iface_inst_param in get_iterable(
1703 vdu_inst_param.get("interface")
1704 ):
1705 iface_index, _ = next(
1706 i
1707 for i in enumerate(vdur["interfaces"])
1708 if i[1]["name"] == iface_inst_param["name"]
1709 )
1710 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1711 vdur_index, iface_index
1712 )
tiernocddb07d2020-10-06 08:28:00 +00001713 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001714 vnfr_update[
1715 vnfr_update_text + ".ip-address"
1716 ] = increment_ip_mac(
1717 iface_inst_param.get("ip-address"),
1718 vdur.get("count-index", 0),
1719 )
tierno1bd9d952020-11-13 15:56:51 +00001720 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001721 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001722 vnfr_update[
1723 vnfr_update_text + ".mac-address"
1724 ] = increment_ip_mac(
1725 iface_inst_param.get("mac-address"),
1726 vdur.get("count-index", 0),
1727 )
tierno1bd9d952020-11-13 15:56:51 +00001728 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001729 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001730 vnfr_update[
1731 vnfr_update_text + ".floating-ip-required"
1732 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001733 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1734 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001735 for ivld_inst_param in get_iterable(
1736 vnf_inst_params.get("internal-vld")
1737 ):
1738 for icp_inst_param in get_iterable(
1739 ivld_inst_param.get("internal-connection-point")
1740 ):
tiernocddb07d2020-10-06 08:28:00 +00001741 # look for iface
1742 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1743 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001744 if (
1745 iface.get("internal-connection-point-ref")
1746 == icp_inst_param["id-ref"]
1747 ):
1748 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1749 vdur_index, iface_index
1750 )
tiernocddb07d2020-10-06 08:28:00 +00001751 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001752 vnfr_update[
1753 vnfr_update_text + ".ip-address"
1754 ] = increment_ip_mac(
1755 icp_inst_param.get("ip-address"),
1756 vdur.get("count-index", 0),
1757 )
1758 vnfr_update[
1759 vnfr_update_text + ".fixed-ip"
1760 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001761 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001762 vnfr_update[
1763 vnfr_update_text + ".mac-address"
1764 ] = increment_ip_mac(
1765 icp_inst_param.get("mac-address"),
1766 vdur.get("count-index", 0),
1767 )
1768 vnfr_update[
1769 vnfr_update_text + ".fixed-mac"
1770 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001771 break
1772 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1773 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001774 for vnfcp_inst_param in get_iterable(
1775 vld_inst_param.get("vnfd-connection-point-ref")
1776 ):
tiernocddb07d2020-10-06 08:28:00 +00001777 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1778 continue
1779 # look for iface
1780 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1781 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001782 if (
1783 iface.get("external-connection-point-ref")
1784 == vnfcp_inst_param["vnfd-connection-point-ref"]
1785 ):
1786 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1787 vdur_index, iface_index
1788 )
tiernocddb07d2020-10-06 08:28:00 +00001789 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001790 vnfr_update[
1791 vnfr_update_text + ".ip-address"
1792 ] = increment_ip_mac(
1793 vnfcp_inst_param.get("ip-address"),
1794 vdur.get("count-index", 0),
1795 )
tierno1bd9d952020-11-13 15:56:51 +00001796 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001797 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001798 vnfr_update[
1799 vnfr_update_text + ".mac-address"
1800 ] = increment_ip_mac(
1801 vnfcp_inst_param.get("mac-address"),
1802 vdur.get("count-index", 0),
1803 )
tierno1bd9d952020-11-13 15:56:51 +00001804 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001805 break
1806
tiernocc103432018-10-19 14:10:35 +02001807 vnfr_update["vim-account-id"] = vim_account
1808 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1809
David Garciaecb41322021-03-31 19:10:46 +02001810 if vca_id:
1811 vnfr_update["vca-id"] = vca_id
1812 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1813
tiernocc103432018-10-19 14:10:35 +02001814 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01001815 ifaces_forcing_vim_network = self._look_for_pdu(
1816 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1817 )
tiernocc103432018-10-19 14:10:35 +02001818
tierno9cb7d672019-10-30 12:13:48 +00001819 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01001820 ifaces_forcing_vim_network += self._look_for_k8scluster(
1821 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1822 )
tierno9cb7d672019-10-30 12:13:48 +00001823 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001824 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01001825 rollback.append(
1826 {
1827 "topic": "vnfrs",
1828 "_id": vnfr["_id"],
1829 "operation": "set",
1830 "content": vnfr_update_rollback,
1831 }
1832 )
tierno36ec8602018-11-02 17:27:11 +01001833
1834 # Update indada in case pdu forces to use a concrete vim-network-name
1835 # TODO check if user has already insert a vim-network-name and raises an error
1836 if not ifaces_forcing_vim_network:
1837 continue
1838 for iface_info in ifaces_forcing_vim_network:
1839 if iface_info.get("ns-vld-id"):
1840 if "vld" not in indata:
1841 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001842 indata["vld"].append(
1843 {
1844 key: iface_info[key]
1845 for key in ("name", "vim-network-name", "vim-network-id")
1846 if iface_info.get(key)
1847 }
1848 )
tierno36ec8602018-11-02 17:27:11 +01001849
1850 elif iface_info.get("vnf-vld-id"):
1851 if "vnf" not in indata:
1852 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001853 indata["vnf"].append(
1854 {
1855 "member-vnf-index": member_vnf_index,
1856 "internal-vld": [
1857 {
1858 key: iface_info[key]
1859 for key in (
1860 "name",
1861 "vim-network-name",
1862 "vim-network-id",
1863 )
1864 if iface_info.get(key)
1865 }
1866 ],
1867 }
1868 )
tierno36ec8602018-11-02 17:27:11 +01001869
1870 @staticmethod
1871 def _create_nslcmop(nsr_id, operation, params):
1872 """
1873 Creates a ns-lcm-opp content to be stored at database.
1874 :param nsr_id: internal id of the instance
1875 :param operation: instantiate, terminate, scale, action, ...
1876 :param params: user parameters for the operation
1877 :return: dictionary following SOL005 format
1878 """
tiernob24258a2018-10-04 18:39:49 +02001879 now = time()
1880 _id = str(uuid4())
1881 nslcmop = {
1882 "id": _id,
1883 "_id": _id,
1884 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001885 "queuePosition": None,
1886 "stage": None,
1887 "errorMessage": None,
1888 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001889 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001890 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001891 "lcmOperationType": operation,
1892 "startTime": now,
1893 "isAutomaticInvocation": False,
1894 "operationParams": params,
1895 "isCancelPending": False,
1896 "links": {
1897 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001898 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01001899 },
tiernob24258a2018-10-04 18:39:49 +02001900 }
1901 return nslcmop
1902
magnussonlf318b302020-01-20 18:38:18 +01001903 def _get_enabled_vims(self, session):
1904 """
1905 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1906 :param session: current session with user information
1907 """
1908 db_filter = self._get_project_filter(session)
1909 db_filter["_admin.operationalState"] = "ENABLED"
1910 vims = self.db.get_list("vim_accounts", db_filter)
1911 vimAccounts = []
1912 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01001913 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01001914 return vimAccounts
1915
garciadeblas4568a372021-03-24 09:19:48 +01001916 def new(
1917 self,
1918 rollback,
1919 session,
1920 indata=None,
1921 kwargs=None,
1922 headers=None,
1923 slice_object=False,
1924 ):
tiernob24258a2018-10-04 18:39:49 +02001925 """
1926 Performs a new operation over a ns
1927 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001928 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001929 :param indata: descriptor with the parameters of the operation. It must contains among others
1930 nsInstanceId: _id of the nsr to perform the operation
1931 operation: it can be: instantiate, terminate, action, TODO: update, heal
1932 :param kwargs: used to override the indata descriptor
1933 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02001934 :return: id of the nslcmops
1935 """
garciadeblas4568a372021-03-24 09:19:48 +01001936
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001937 def check_if_nsr_is_not_slice_member(session, nsr_id):
1938 nsis = None
1939 db_filter = self._get_project_filter(session)
1940 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01001941 nsis = self.db.get_one(
1942 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
1943 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001944 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01001945 raise EngineException(
1946 "The NS instance {} cannot be terminated because is used by the slice {}".format(
1947 nsr_id, nsis["_id"]
1948 ),
1949 http_code=HTTPStatus.CONFLICT,
1950 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001951
tiernob24258a2018-10-04 18:39:49 +02001952 try:
1953 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00001954 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02001955 operation = indata["lcmOperationType"]
1956 nsInstanceId = indata["nsInstanceId"]
1957
1958 validate_input(indata, self.operation_schema[operation])
1959 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01001960 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02001961 _filter["_id"] = nsInstanceId
1962 nsr = self.db.get_one("nsrs", _filter)
1963
1964 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001965 if operation == "terminate" and slice_object is False:
1966 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01001967 if (
1968 not nsr["_admin"].get("nsState")
1969 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
1970 ):
tiernob24258a2018-10-04 18:39:49 +02001971 if operation == "terminate" and indata.get("autoremove"):
1972 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01001973 return (
1974 None,
1975 None,
1976 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02001977 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01001978 raise EngineException(
1979 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1980 nsInstanceId, operation
1981 ),
1982 HTTPStatus.CONFLICT,
1983 )
tiernob24258a2018-10-04 18:39:49 +02001984 else:
tierno65ca36d2019-02-12 19:27:52 +01001985 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01001986 raise EngineException(
1987 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1988 nsInstanceId, operation
1989 ),
1990 HTTPStatus.CONFLICT,
1991 )
tiernob24258a2018-10-04 18:39:49 +02001992 self._check_ns_operation(session, nsr, operation, indata)
Guillermo Calvino7fcbd4f2022-01-26 17:37:56 +01001993 if (indata.get("primitive_params")):
1994 indata["primitive_params"] = json.dumps(indata["primitive_params"])
1995 elif (indata.get("additionalParamsForVnf")):
1996 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
tierno36ec8602018-11-02 17:27:11 +01001997
tiernocc103432018-10-19 14:10:35 +02001998 if operation == "instantiate":
Gulsum Aticie395aa42021-11-10 20:59:06 +03001999 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02002000 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01002001
2002 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00002003 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002004 self.format_on_new(
2005 nslcmop_desc, session["project_id"], make_public=session["public"]
2006 )
magnussonlf318b302020-01-20 18:38:18 +01002007 if indata.get("placement-engine"):
2008 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002009 nslcmop_desc["operationParams"][
2010 "validVimAccounts"
2011 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002012 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002013 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002014 if not slice_object:
2015 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002016 return _id, None
2017 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002018 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2019 # except DbException as e:
2020 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2021
tiernobee3bad2019-12-05 12:26:01 +00002022 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002023 raise EngineException(
2024 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2025 )
tiernob24258a2018-10-04 18:39:49 +02002026
tierno65ca36d2019-02-12 19:27:52 +01002027 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002028 raise EngineException(
2029 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2030 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002031
2032
2033class NsiTopic(BaseTopic):
2034 topic = "nsis"
2035 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002036 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002037
delacruzramo32bab472019-09-13 12:24:22 +02002038 def __init__(self, db, fs, msg, auth):
2039 BaseTopic.__init__(self, db, fs, msg, auth)
2040 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002041
Felipe Vicensc37b3842019-01-12 12:24:42 +01002042 @staticmethod
2043 def _format_ns_request(ns_request):
2044 formated_request = copy(ns_request)
2045 # TODO: Add request params
2046 return formated_request
2047
2048 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002049 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002050 """
2051 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002052 :param slice_request: User instantiation additional parameters
2053 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002054 """
tiernofd160572019-01-21 10:41:37 +00002055 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2056 if additional_params:
2057 for k, v in additional_params.items():
2058 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002059 raise EngineException(
2060 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2061 k
2062 )
2063 )
tiernofd160572019-01-21 10:41:37 +00002064 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002065 raise EngineException(
2066 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2067 k
2068 )
2069 )
tiernofd160572019-01-21 10:41:37 +00002070 if isinstance(v, (dict, tuple, list)):
2071 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002072 return additional_params
2073
Felipe Vicensb57758d2018-10-16 16:00:20 +02002074 def _check_descriptor_dependencies(self, session, descriptor):
2075 """
2076 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01002077 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002078 :param descriptor: descriptor to be inserted or edit
2079 :return: None or raises exception
2080 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002081 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002082 return
Felipe Vicens07f31722018-10-29 15:16:44 +01002083 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002084 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
garciadeblas4568a372021-03-24 09:19:48 +01002085 raise EngineException(
2086 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2087 nstd_id
2088 ),
2089 http_code=HTTPStatus.CONFLICT,
2090 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002091
tiernob4844ab2019-05-23 08:42:12 +00002092 def check_conflict_on_del(self, session, _id, db_content):
2093 """
2094 Check that NSI is not instantiated
2095 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2096 :param _id: nsi internal id
2097 :param db_content: The database content of the _id
2098 :return: None or raises EngineException with the conflict
2099 """
tierno65ca36d2019-02-12 19:27:52 +01002100 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002101 return
tiernob4844ab2019-05-23 08:42:12 +00002102 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002103 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002104 raise EngineException(
2105 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2106 "Launch 'terminate' operation first; or force deletion".format(_id),
2107 http_code=HTTPStatus.CONFLICT,
2108 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002109
tiernobee3bad2019-12-05 12:26:01 +00002110 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002111 """
tiernob4844ab2019-05-23 08:42:12 +00002112 Deletes associated nsilcmops from database. Deletes associated filesystem.
2113 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002114 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002115 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002116 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002117 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002118 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002119 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002120
Felipe Vicens09e65422019-01-22 15:06:46 +01002121 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002122 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002123 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2124 nsr_id = nsrs_detailed_item["nsrId"]
2125 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002126 _filter = {
2127 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2128 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2129 "_id.ne": nsir["_id"],
2130 }
2131 nsi = self.db.get_one(
2132 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2133 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002134 if nsi: # last one using nsr
2135 continue
2136 try:
garciadeblas4568a372021-03-24 09:19:48 +01002137 self.nsrTopic.delete(
2138 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2139 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002140 except (DbException, EngineException) as e:
2141 if e.http_code == HTTPStatus.NOT_FOUND:
2142 pass
2143 else:
2144 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002145
tiernob4844ab2019-05-23 08:42:12 +00002146 # delete related nsilcmops database entries
2147 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002148
tiernob4844ab2019-05-23 08:42:12 +00002149 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002150 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002151 if nsir_admin and nsir_admin.get("nst-id"):
2152 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002153 nsis_list = self.db.get_one(
2154 "nsis",
2155 {"nst-id": nsir_admin["nst-id"]},
2156 fail_on_empty=False,
2157 fail_on_more=False,
2158 )
tiernob4844ab2019-05-23 08:42:12 +00002159 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002160 self.db.set_one(
2161 "nsts",
2162 {"_id": nsir_admin["nst-id"]},
2163 {"_admin.usageState": "NOT_IN_USE"},
2164 )
tiernob4844ab2019-05-23 08:42:12 +00002165
tierno65ca36d2019-02-12 19:27:52 +01002166 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002167 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002168 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002169 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002170 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002171 :param indata: params to be used for the nsir
2172 :param kwargs: used to override the indata descriptor
2173 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002174 :return: the _id of nsi descriptor created at database
2175 """
2176
2177 try:
delacruzramo32bab472019-09-13 12:24:22 +02002178 step = "checking quotas"
2179 self.check_quota(session)
2180
tierno99d4b172019-07-02 09:28:40 +00002181 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002182 slice_request = self._remove_envelop(indata)
2183 # Override descriptor with query string kwargs
2184 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002185 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002186
Felipe Vicensb57758d2018-10-16 16:00:20 +02002187 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002188 step = "getting nstd id='{}' from database".format(
2189 slice_request.get("nstId")
2190 )
tiernob4844ab2019-05-23 08:42:12 +00002191 _filter = self._get_project_filter(session)
2192 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002193 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002194 # check NST is not disabled
2195 step = "checking NST operationalState"
2196 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002197 raise EngineException(
2198 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2199 "instance".format(slice_request["nstId"]),
2200 http_code=HTTPStatus.CONFLICT,
2201 )
tiernob4844ab2019-05-23 08:42:12 +00002202 del _filter["_id"]
2203
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002204 # check NSD is not disabled
2205 step = "checking operationalState"
2206 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002207 raise EngineException(
2208 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2209 "a network slice".format(slice_request["nstId"]),
2210 http_code=HTTPStatus.CONFLICT,
2211 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002212
Felipe Vicens07f31722018-10-29 15:16:44 +01002213 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002214 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002215 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002216 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002217
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002218 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002219 nsi_descriptor = {
2220 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002221 "name": slice_request["nsiName"],
2222 "description": slice_request.get("nsiDescription", ""),
2223 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002224 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002225 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002226 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002227 "nsr-ref-list": [],
2228 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002229 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002230 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002231 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002232
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002233 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002234 self.format_on_new(
2235 nsi_descriptor, session["project_id"], make_public=session["public"]
2236 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002237 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2238 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002239 nsi_descriptor["_admin"]["deployed"] = {}
2240 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2241 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2242
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002243 # Creating netslice-vld for the RO.
2244 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002245
2246 # Building the vlds list to be deployed
2247 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002248 nsi_vlds = []
2249
2250 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2251 # Getting template Instantiation parameters from NST
2252 nsi_vld = deepcopy(netslice_vlds)
2253 nsi_vld["shared-nsrs-list"] = []
2254 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2255 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002256
2257 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002258 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002259 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002260 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002261
Felipe Vicens09e65422019-01-22 15:06:46 +01002262 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002263 for member_ns in nstd["netslice-subnet"]:
2264 nsd_id = member_ns["nsd-ref"]
2265 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002266 member_ns["nsd-ref"], member_ns["id"]
2267 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002268 if nsd_id not in needed_nsds:
2269 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002270 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002271 nsd = self.db.get_one(
2272 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2273 )
tiernob4844ab2019-05-23 08:42:12 +00002274 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002275 nsd.pop("_admin")
2276 needed_nsds[nsd_id] = nsd
2277 else:
2278 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002279 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2280 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002281
Felipe Vicensb57758d2018-10-16 16:00:20 +02002282 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002283 member_ns["nsd-ref"], member_ns["id"]
2284 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002285
Felipe Vicens07f31722018-10-29 15:16:44 +01002286 # creates Network Services records (NSRs)
2287 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002288 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002289 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002290 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002291 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002292 # Check if the netslice-subnet is shared and if it is share if the nss exists
2293 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002294 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002295 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002296 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002297 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2298 "nsd-ref"
2299 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002300 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002301 nsi = self.db.get_one(
2302 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2303 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002304 if nsi and service.get("is-shared-nss"):
2305 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2306 for nsrs_detailed_item in nsrs_detailed_list:
2307 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002308 if nsrs_detailed_item["nss-id"] == service["id"]:
2309 _id_nsr = nsrs_detailed_item["nsrId"]
2310 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002311 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2312 if netslice_subnet["nss-id"] == service["id"]:
2313 indata_ns = netslice_subnet
2314 break
2315 else:
2316 indata_ns = {}
2317 if service.get("instantiation-parameters"):
2318 indata_ns = deepcopy(service["instantiation-parameters"])
2319 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002320
Felipe Vicens09e65422019-01-22 15:06:46 +01002321 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002322 indata_ns["nsName"] = (
2323 slice_request.get("nsiName") + "." + service["id"]
2324 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002325 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2326 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002327 if slice_request.get("ssh_keys"):
2328 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002329
Felipe Vicens09e65422019-01-22 15:06:46 +01002330 if ns_params:
2331 for ns_param in ns_params:
2332 if ns_param.get("id") == service["id"]:
2333 copy_ns_param = deepcopy(ns_param)
2334 del copy_ns_param["id"]
2335 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002336 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002337
2338 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002339 _id_nsr, _ = self.nsrTopic.new(
2340 rollback, session, indata_ns, kwargs, headers
2341 )
2342 nsrs_item = {
2343 "nsrId": _id_nsr,
2344 "shared": service.get("is-shared-nss"),
2345 "nsd-id": service["nsd-ref"],
2346 "nss-id": service["id"],
2347 "nslcmop_instantiate": None,
2348 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002349 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002350 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002351 nsi_netslice_subnet.append(indata_ns)
2352 nsr_ref = {"nsr-ref": _id_nsr}
2353 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002354
2355 # Adding the nsrs list to the nsi
2356 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002357 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002358 self.db.set_one(
2359 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2360 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002361
Felipe Vicens07f31722018-10-29 15:16:44 +01002362 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002363 self.db.create("nsis", nsi_descriptor)
2364 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002365 return nsi_id, None
garciadeblas4568a372021-03-24 09:19:48 +01002366 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2367 self.logger.exception(
2368 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2369 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002370 raise EngineException("Error {}: {}".format(step, e))
2371 except ValidationError as e:
2372 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2373
tierno65ca36d2019-02-12 19:27:52 +01002374 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002375 raise EngineException(
2376 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2377 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002378
2379
2380class NsiLcmOpTopic(BaseTopic):
2381 topic = "nsilcmops"
2382 topic_msg = "nsi"
2383 operation_schema = { # mapping between operation and jsonschema to validate
2384 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002385 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002386 }
garciadeblas4568a372021-03-24 09:19:48 +01002387
delacruzramo32bab472019-09-13 12:24:22 +02002388 def __init__(self, db, fs, msg, auth):
2389 BaseTopic.__init__(self, db, fs, msg, auth)
2390 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002391
2392 def _check_nsi_operation(self, session, nsir, operation, indata):
2393 """
2394 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002395 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002396 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2397 :param indata: descriptor with the parameters of the operation
2398 :return: None
2399 """
2400 nsds = {}
2401 nstd = nsir["network-slice-template"]
2402
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002403 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002404 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002405 for netslice_subnet in nstd["netslice-subnet"]:
2406 if nstId == netslice_subnet["id"]:
2407 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002408 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002409 _filter = self._get_project_filter(session)
2410 _filter["id"] = nsd_id
2411 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002412 return nsds[nsd_id]
2413 else:
garciadeblas4568a372021-03-24 09:19:48 +01002414 raise EngineException(
2415 "Invalid parameter nstId='{}' is not one of the "
2416 "nst:netslice-subnet".format(nstId)
2417 )
2418
Felipe Vicens07f31722018-10-29 15:16:44 +01002419 if operation == "instantiate":
2420 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002421 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002422 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002423
2424 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2425 now = time()
2426 _id = str(uuid4())
2427 nsilcmop = {
2428 "id": _id,
2429 "_id": _id,
2430 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2431 "statusEnteredTime": now,
2432 "netsliceInstanceId": netsliceInstanceId,
2433 "lcmOperationType": operation,
2434 "startTime": now,
2435 "isAutomaticInvocation": False,
2436 "operationParams": params,
2437 "isCancelPending": False,
2438 "links": {
2439 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002440 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2441 + netsliceInstanceId,
2442 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002443 }
2444 return nsilcmop
2445
Felipe Vicens09e65422019-01-22 15:06:46 +01002446 def add_shared_nsr_2vld(self, nsir, nsr_item):
2447 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2448 if nst_sb_item.get("is-shared-nss"):
2449 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2450 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2451 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002452 for admin_vld_nss_cp_ref_item in admin_vld_item[
2453 "nss-connection-point-ref"
2454 ]:
2455 if (
2456 admin_subnet_item["nss-id"]
2457 == admin_vld_nss_cp_ref_item["nss-ref"]
2458 ):
2459 if (
2460 not nsr_item["nsrId"]
2461 in admin_vld_item["shared-nsrs-list"]
2462 ):
2463 admin_vld_item["shared-nsrs-list"].append(
2464 nsr_item["nsrId"]
2465 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002466 break
2467 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002468 self.db.set_one(
2469 "nsis",
2470 {"_id": nsir["_id"]},
2471 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2472 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002473
tierno65ca36d2019-02-12 19:27:52 +01002474 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002475 """
2476 Performs a new operation over a ns
2477 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002478 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002479 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002480 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002481 operation: it can be: instantiate, terminate, action, TODO: update, heal
2482 :param kwargs: used to override the indata descriptor
2483 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002484 :return: id of the nslcmops
2485 """
2486 try:
2487 # Override descriptor with query string kwargs
2488 self._update_input_with_kwargs(indata, kwargs)
2489 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002490 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002491 validate_input(indata, self.operation_schema[operation])
2492
Felipe Vicens126af572019-06-05 19:13:04 +02002493 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002494 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002495 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002496 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002497 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002498 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002499
2500 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002501 if (
2502 not nsir["_admin"].get("nsiState")
2503 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2504 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002505 if operation == "terminate" and indata.get("autoremove"):
2506 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002507 return (
2508 None,
2509 None,
2510 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002511 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002512 raise EngineException(
2513 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2514 netsliceInstanceId, operation
2515 ),
2516 HTTPStatus.CONFLICT,
2517 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002518 else:
tierno65ca36d2019-02-12 19:27:52 +01002519 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002520 raise EngineException(
2521 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2522 netsliceInstanceId, operation
2523 ),
2524 HTTPStatus.CONFLICT,
2525 )
2526
Felipe Vicens07f31722018-10-29 15:16:44 +01002527 # Creating all the NS_operation (nslcmop)
2528 # Get service list from db
2529 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2530 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002531 # nslcmops_item = None
2532 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002533 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002534 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002535 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002536 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002537 _filter[
2538 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2539 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002540 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002541 nsi = self.db.get_one(
2542 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2543 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002544 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002545 _update = {
2546 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2547 index
2548 ): None
2549 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002550 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002551 if (
2552 nsi
2553 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002554 continue # do not create nsilcmop
2555 else: # instantiate
2556 # looks the first nsi fulfilling the conditions but not being the current NSIR
2557 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002558 nsi_nsr_item = next(
2559 n
2560 for n in nsi["_admin"]["nsrs-detailed-list"]
2561 if n["nsrId"] == nsr_id
2562 and n["shared"]
2563 and n["nslcmop_instantiate"]
2564 )
tierno40f742b2020-06-23 15:25:26 +00002565 self.add_shared_nsr_2vld(nsir, nsr_item)
2566 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002567 _update = {
2568 "_admin.nsrs-detailed-list.{}".format(
2569 index
2570 ): nsi_nsr_item
2571 }
tierno40f742b2020-06-23 15:25:26 +00002572 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2573 # continue to not create nslcmop since nsrs is shared and nsrs was created
2574 continue
2575 else:
2576 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002577
tierno40f742b2020-06-23 15:25:26 +00002578 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002579 try:
tierno0b8752f2020-05-12 09:42:02 +00002580 indata_ns = {
2581 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002582 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002583 # Including netslice_id in the ns instantiate Operation
2584 "netsliceInstanceId": netsliceInstanceId,
2585 }
2586 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002587 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002588 indata_ns.update(service["instantiate_params"])
2589
tierno99d4b172019-07-02 09:28:40 +00002590 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002591 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002592 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2593 rollback, session, indata_ns, None, headers, slice_object=True
2594 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002595 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002596 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002597 _update = {
2598 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2599 index
2600 ): nslcmop
2601 }
tierno40f742b2020-06-23 15:25:26 +00002602 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002603 except (DbException, EngineException) as e:
2604 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002605 self.logger.info(
2606 logging_prefix
2607 + "skipping NS={} because not found".format(nsr_id)
2608 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002609 pass
2610 else:
2611 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002612
2613 # Creates nsilcmop
2614 indata["nslcmops_ids"] = nslcmops
2615 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002616
garciadeblas4568a372021-03-24 09:19:48 +01002617 nsilcmop_desc = self._create_nsilcmop(
2618 session, netsliceInstanceId, operation, indata
2619 )
2620 self.format_on_new(
2621 nsilcmop_desc, session["project_id"], make_public=session["public"]
2622 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002623 _id = self.db.create("nsilcmops", nsilcmop_desc)
2624 rollback.append({"topic": "nsilcmops", "_id": _id})
2625 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002626 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002627 except ValidationError as e:
2628 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002629
tiernobee3bad2019-12-05 12:26:01 +00002630 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002631 raise EngineException(
2632 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2633 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002634
tierno65ca36d2019-02-12 19:27:52 +01002635 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002636 raise EngineException(
2637 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2638 )