blob: 4e88de53a098affd208649d217b23eebc729da9d [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
17from uuid import uuid4
18from http import HTTPStatus
19from time import time
tiernocc103432018-10-19 14:10:35 +020020from copy import copy, deepcopy
garciadeblas4568a372021-03-24 09:19:48 +010021from osm_nbi.validation import (
22 validate_input,
23 ValidationError,
24 ns_instantiate,
25 ns_terminate,
26 ns_action,
27 ns_scale,
28 nsi_instantiate,
29)
30from osm_nbi.base_topic import (
31 BaseTopic,
32 EngineException,
33 get_iterable,
34 deep_get,
35 increment_ip_mac,
36)
tiernobee085c2018-12-12 17:03:04 +000037from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010038from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000039from osm_common.msgbase import MsgException
40from osm_common.fsbase import FsException
garciaale7cbd03c2020-11-27 10:38:35 -030041from osm_nbi import utils
garciadeblas4568a372021-03-24 09:19:48 +010042from re import (
43 match,
44) # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020045
46__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
47
48
49class NsrTopic(BaseTopic):
50 topic = "nsrs"
51 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000052 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000053 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020054
delacruzramo32bab472019-09-13 12:24:22 +020055 def __init__(self, db, fs, msg, auth):
56 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020057
58 def _check_descriptor_dependencies(self, session, descriptor):
59 """
60 Check that the dependent descriptors exist on a new descriptor or edition
61 :param session: client session information
62 :param descriptor: descriptor to be inserted or edit
63 :return: None or raises exception
64 """
65 if not descriptor.get("nsdId"):
66 return
67 nsd_id = descriptor["nsdId"]
68 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
garciadeblas4568a372021-03-24 09:19:48 +010069 raise EngineException(
70 "Descriptor error at nsdId='{}' references a non exist nsd".format(
71 nsd_id
72 ),
73 http_code=HTTPStatus.CONFLICT,
74 )
tiernob24258a2018-10-04 18:39:49 +020075
76 @staticmethod
77 def format_on_new(content, project_id=None, make_public=False):
78 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
79 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000080 return None
tiernob24258a2018-10-04 18:39:49 +020081
tiernob4844ab2019-05-23 08:42:12 +000082 def check_conflict_on_del(self, session, _id, db_content):
83 """
84 Check that NSR is not instantiated
85 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
86 :param _id: nsr internal id
87 :param db_content: The database content of the nsr
88 :return: None or raises EngineException with the conflict
89 """
tierno65ca36d2019-02-12 19:27:52 +010090 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020091 return
tiernob4844ab2019-05-23 08:42:12 +000092 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020093 if nsr["_admin"].get("nsState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +010094 raise EngineException(
95 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
96 "Launch 'terminate' operation first; or force deletion".format(_id),
97 http_code=HTTPStatus.CONFLICT,
98 )
tiernob24258a2018-10-04 18:39:49 +020099
tiernobee3bad2019-12-05 12:26:01 +0000100 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +0000101 """
102 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
103 Set usageState of pdu, vnfd, nsd
104 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
105 :param _id: server internal id
106 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +0000107 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +0000108 :return: None if ok or raises EngineException with the problem
109 """
tiernobee085c2018-12-12 17:03:04 +0000110 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +0200111 self.db.del_list("nslcmops", {"nsInstanceId": _id})
112 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +0000113
tiernob24258a2018-10-04 18:39:49 +0200114 # set all used pdus as free
garciadeblas4568a372021-03-24 09:19:48 +0100115 self.db.set_list(
116 "pdus",
117 {"_admin.usage.nsr_id": _id},
118 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
119 )
tiernob24258a2018-10-04 18:39:49 +0200120
tiernob4844ab2019-05-23 08:42:12 +0000121 # Set NSD usageState
122 nsr = db_content
123 used_nsd_id = nsr.get("nsd-id")
124 if used_nsd_id:
125 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100126 nsrs_list = self.db.get_one(
127 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
128 )
tiernob4844ab2019-05-23 08:42:12 +0000129 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100130 self.db.set_one(
131 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
132 )
tiernob4844ab2019-05-23 08:42:12 +0000133
134 # Set VNFD usageState
135 used_vnfd_id_list = nsr.get("vnfd-id")
136 if used_vnfd_id_list:
137 for used_vnfd_id in used_vnfd_id_list:
138 # check if used by another NSR
garciadeblas4568a372021-03-24 09:19:48 +0100139 nsrs_list = self.db.get_one(
140 "nsrs",
141 {"vnfd-id": used_vnfd_id},
142 fail_on_empty=False,
143 fail_on_more=False,
144 )
tiernob4844ab2019-05-23 08:42:12 +0000145 if not nsrs_list:
garciadeblas4568a372021-03-24 09:19:48 +0100146 self.db.set_one(
147 "vnfds",
148 {"_id": used_vnfd_id},
149 {"_admin.usageState": "NOT_IN_USE"},
150 )
tiernob4844ab2019-05-23 08:42:12 +0000151
tiernof0441ea2020-05-26 15:39:18 +0000152 # delete extra ro_nsrs used for internal RO module
153 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
154
tiernobee085c2018-12-12 17:03:04 +0000155 @staticmethod
156 def _format_ns_request(ns_request):
157 formated_request = copy(ns_request)
158 formated_request.pop("additionalParamsForNs", None)
159 formated_request.pop("additionalParamsForVnf", None)
160 return formated_request
161
162 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +0100163 def _format_additional_params(
164 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
165 ):
tiernobee085c2018-12-12 17:03:04 +0000166 """
167 Get and format user additional params for NS or VNF
168 :param ns_request: User instantiation additional parameters
169 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
170 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000171 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000172 """
173 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000174 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000175 if not member_vnf_index:
176 additional_params = copy(ns_request.get("additionalParamsForNs"))
177 where_ = "additionalParamsForNs"
178 elif ns_request.get("additionalParamsForVnf"):
garciadeblas4568a372021-03-24 09:19:48 +0100179 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
180 member_vnf_index
181 )
182 item = next(
183 (
184 x
185 for x in ns_request["additionalParamsForVnf"]
186 if x["member-vnf-index"] == member_vnf_index
187 ),
188 None,
189 )
tierno714954e2019-11-29 13:43:26 +0000190 if item:
tierno54db2e42020-04-06 15:29:42 +0000191 if not vdu_id and not kdu_name:
192 other_params = item
tierno714954e2019-11-29 13:43:26 +0000193 additional_params = copy(item.get("additionalParams")) or {}
194 if vdu_id and item.get("additionalParamsForVdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100195 item_vdu = next(
196 (
197 x
198 for x in item["additionalParamsForVdu"]
199 if x["vdu_id"] == vdu_id
200 ),
201 None,
202 )
tiernobce98f02020-04-17 11:27:47 +0000203 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000204 if item_vdu and item_vdu.get("additionalParams"):
205 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000206 additional_params = item_vdu["additionalParams"]
207 if kdu_name:
208 additional_params = {}
209 if item.get("additionalParamsForKdu"):
garciadeblas4568a372021-03-24 09:19:48 +0100210 item_kdu = next(
211 (
212 x
213 for x in item["additionalParamsForKdu"]
214 if x["kdu_name"] == kdu_name
215 ),
216 None,
217 )
tiernobce98f02020-04-17 11:27:47 +0000218 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000219 if item_kdu and item_kdu.get("additionalParams"):
garciadeblas4568a372021-03-24 09:19:48 +0100220 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
221 kdu_name
222 )
tiernob091dc12019-12-02 15:53:25 +0000223 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000224
tiernobee085c2018-12-12 17:03:04 +0000225 if additional_params:
226 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000227 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
garciadeblas4568a372021-03-24 09:19:48 +0100228 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
229 raise EngineException(
230 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
231 "and underscores, and cannot start with a digit".format(
232 where_, k
233 )
234 )
delacruzramo36ffe552019-05-03 14:52:37 +0200235 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000236 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +0100237 raise EngineException(
238 "Invalid param at {}:{}. Only string keys are allowed".format(
239 where_, k
240 )
241 )
tiernobee085c2018-12-12 17:03:04 +0000242 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +0100243 raise EngineException(
244 "Invalid param at {}:{}. Keys must not contain dots or $".format(
245 where_, k
246 )
247 )
tiernobee085c2018-12-12 17:03:04 +0000248 if isinstance(v, (dict, tuple, list)):
249 additional_params[k] = "!!yaml " + safe_dump(v)
250
251 if descriptor:
bravof41a52052021-02-17 18:08:01 -0300252 for df in descriptor.get("df", []):
253 # check that enough parameters are supplied for the initial-config-primitive
254 # TODO: check for cloud-init
255 if member_vnf_index:
garciaale7cbd03c2020-11-27 10:38:35 -0300256 initial_primitives = []
garciadeblas4568a372021-03-24 09:19:48 +0100257 if (
258 "lcm-operations-configuration" in df
259 and "operate-vnf-op-config"
260 in df["lcm-operations-configuration"]
261 ):
262 for config in df["lcm-operations-configuration"][
263 "operate-vnf-op-config"
264 ].get("day1-2", []):
265 for primitive in get_iterable(
266 config.get("initial-config-primitive")
267 ):
bravof41a52052021-02-17 18:08:01 -0300268 initial_primitives.append(primitive)
269 else:
garciadeblas4568a372021-03-24 09:19:48 +0100270 initial_primitives = deep_get(
271 descriptor, ("ns-configuration", "initial-config-primitive")
272 )
tiernobee085c2018-12-12 17:03:04 +0000273
bravof41a52052021-02-17 18:08:01 -0300274 for initial_primitive in get_iterable(initial_primitives):
275 for param in get_iterable(initial_primitive.get("parameter")):
garciadeblas4568a372021-03-24 09:19:48 +0100276 if param["value"].startswith("<") and param["value"].endswith(
277 ">"
278 ):
279 if param["value"] in (
280 "<rw_mgmt_ip>",
281 "<VDU_SCALE_INFO>",
282 "<ns_config_info>",
283 ):
bravof41a52052021-02-17 18:08:01 -0300284 continue
garciadeblas4568a372021-03-24 09:19:48 +0100285 if (
286 not additional_params
287 or param["value"][1:-1] not in additional_params
288 ):
289 raise EngineException(
290 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
291 "initial-config-primitive[name={}] not supplied".format(
292 param["value"],
293 descriptor["id"],
294 initial_primitive["name"],
295 )
296 )
tierno714954e2019-11-29 13:43:26 +0000297
tierno54db2e42020-04-06 15:29:42 +0000298 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000299
tierno65ca36d2019-02-12 19:27:52 +0100300 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200301 """
302 Creates a new nsr into database. It also creates needed vnfrs
303 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100304 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200305 :param indata: params to be used for the nsr
306 :param kwargs: used to override the indata descriptor
307 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000308 :return: the _id of nsr descriptor created at database. Or an exception of type
309 EngineException, ValidationError, DbException, FsException, MsgException.
310 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200311 """
tiernob24258a2018-10-04 18:39:49 +0200312 try:
delacruzramo32bab472019-09-13 12:24:22 +0200313 step = "checking quotas"
314 self.check_quota(session)
315
tierno99d4b172019-07-02 09:28:40 +0000316 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200317 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200318 self._update_input_with_kwargs(ns_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -0300319 ns_request = self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200320
tiernob24258a2018-10-04 18:39:49 +0200321 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale7cbd03c2020-11-27 10:38:35 -0300322 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
323 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200324
Frank Bryden3c64ab62020-07-21 14:25:32 +0000325 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300326 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000327
tiernob24258a2018-10-04 18:39:49 +0200328 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300329 nsr_id = str(uuid4())
garciadeblas4568a372021-03-24 09:19:48 +0100330 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
331 nsd, ns_request, nsr_id, session
332 )
tierno54db2e42020-04-06 15:29:42 +0000333
garciaale7cbd03c2020-11-27 10:38:35 -0300334 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200335 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300336 # TODO: Change for multiple df support
337 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
338 for vnfp in vnf_profiles:
339 vnfd_id = vnfp.get("vnfd-id")
340 vnf_index = vnfp.get("id")
garciadeblas4568a372021-03-24 09:19:48 +0100341 step = (
342 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
343 vnfd_id, vnf_index
344 )
345 )
tiernob24258a2018-10-04 18:39:49 +0200346 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300347 vnfd = self._get_vnfd_from_db(vnfd_id, session)
tiernob24258a2018-10-04 18:39:49 +0200348 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000349 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200350 else:
351 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100352
garciadeblas4568a372021-03-24 09:19:48 +0100353 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
354 vnfd_id, vnf_index
355 )
356 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
357 nsd,
358 vnfd,
359 vnfd_id,
360 vnf_index,
361 nsr_descriptor,
362 ns_request,
363 ns_k8s_namespace,
364 )
tierno36ec8602018-11-02 17:27:11 +0100365
garciadeblas4568a372021-03-24 09:19:48 +0100366 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
367 vnfd_id, vnf_index
368 )
garciaale7cbd03c2020-11-27 10:38:35 -0300369 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
370 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
tiernob24258a2018-10-04 18:39:49 +0200371
372 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300373 self._add_nsr_to_db(nsr_descriptor, rollback, session)
tiernobee085c2018-12-12 17:03:04 +0000374
375 step = "creating nsr temporal folder"
376 self.fs.mkdir(nsr_id)
377
tiernobdebce92019-07-01 15:36:49 +0000378 return nsr_id, None
garciadeblas4568a372021-03-24 09:19:48 +0100379 except (
380 ValidationError,
381 EngineException,
382 DbException,
383 MsgException,
384 FsException,
385 ) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000386 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200387
garciaale7cbd03c2020-11-27 10:38:35 -0300388 def _get_nsd_from_db(self, nsd_id, session):
389 _filter = self._get_project_filter(session)
390 _filter["_id"] = nsd_id
391 return self.db.get_one("nsds", _filter)
392
393 def _get_vnfd_from_db(self, vnfd_id, session):
394 _filter = self._get_project_filter(session)
395 _filter["id"] = vnfd_id
396 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
397 vnfd.pop("_admin")
398 return vnfd
399
400 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100401 self.format_on_new(
402 nsr_descriptor, session["project_id"], make_public=session["public"]
403 )
garciaale7cbd03c2020-11-27 10:38:35 -0300404 self.db.create("nsrs", nsr_descriptor)
405 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
406
407 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
garciadeblas4568a372021-03-24 09:19:48 +0100408 self.format_on_new(
409 vnfr_descriptor, session["project_id"], make_public=session["public"]
410 )
garciaale7cbd03c2020-11-27 10:38:35 -0300411 self.db.create("vnfrs", vnfr_descriptor)
412 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
413
414 def _check_nsd_operational_state(self, nsd, ns_request):
415 if nsd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +0100416 raise EngineException(
417 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
418 "a network service".format(ns_request["nsdId"]),
419 http_code=HTTPStatus.CONFLICT,
420 )
garciaale7cbd03c2020-11-27 10:38:35 -0300421
422 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
garciadeblas4568a372021-03-24 09:19:48 +0100423 additional_params, _ = self._format_additional_params(
424 ns_request, descriptor=nsd
425 )
garciaale7cbd03c2020-11-27 10:38:35 -0300426 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
427 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
428 if ns_request and ns_request.get("k8s-namespace"):
429 ns_k8s_namespace = ns_request["k8s-namespace"]
430 if additional_params and additional_params.get("k8s-namespace"):
431 ns_k8s_namespace = additional_params["k8s-namespace"]
432
433 return ns_k8s_namespace
434
bravofe76b8822021-02-26 16:57:52 -0300435 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300436 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100437 additional_params, _ = self._format_additional_params(
438 ns_request, descriptor=nsd
439 )
garciaale7cbd03c2020-11-27 10:38:35 -0300440
441 nsr_descriptor = {
442 "name": ns_request["nsName"],
443 "name-ref": ns_request["nsName"],
444 "short-name": ns_request["nsName"],
445 "admin-status": "ENABLED",
446 "nsState": "NOT_INSTANTIATED",
447 "currentOperation": "IDLE",
448 "currentOperationID": None,
449 "errorDescription": None,
450 "errorDetail": None,
451 "deploymentStatus": None,
452 "configurationStatus": None,
453 "vcaStatus": None,
454 "nsd": {k: v for k, v in nsd.items()},
455 "datacenter": ns_request["vimAccountId"],
456 "resource-orchestrator": "osmopenmano",
457 "description": ns_request.get("nsDescription", ""),
458 "constituent-vnfr-ref": [],
459 "operational-status": "init", # typedef ns-operational-
460 "config-status": "init", # typedef config-states
461 "detailed-status": "scheduled",
462 "orchestration-progress": {},
463 "create-time": now,
464 "nsd-name-ref": nsd["name"],
465 "operational-events": [], # "id", "timestamp", "description", "event",
466 "nsd-ref": nsd["id"],
467 "nsd-id": nsd["_id"],
468 "vnfd-id": [],
469 "instantiate_params": self._format_ns_request(ns_request),
470 "additionalParamsForNs": additional_params,
471 "ns-instance-config-ref": nsr_id,
472 "id": nsr_id,
473 "_id": nsr_id,
474 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
475 "flavor": [],
476 "image": [],
477 }
478 ns_request["nsr_id"] = nsr_id
479 if ns_request and ns_request.get("config-units"):
480 nsr_descriptor["config-units"] = ns_request["config-units"]
481
482 # Create vld
483 if nsd.get("virtual-link-desc"):
484 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
485 # Fill each vld with vnfd-connection-point-ref data
486 # TODO: Change for multiple df support
487 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
488 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
489 for vnf_profile in vnf_profiles:
490 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
491 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100492 all_vld_connection_point_data[
493 vlc.get("virtual-link-profile-id")
494 ].append(
495 {
496 "member-vnf-index-ref": cpd.get(
497 "constituent-base-element-id"
498 ),
499 "vnfd-connection-point-ref": cpd.get(
500 "constituent-cpd-id"
501 ),
502 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
503 }
504 )
garciaale7cbd03c2020-11-27 10:38:35 -0300505
bravofe76b8822021-02-26 16:57:52 -0300506 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
garciaale7cbd03c2020-11-27 10:38:35 -0300507
508 for vdu in vnfd.get("vdu", ()):
509 flavor_data = {}
510 guest_epa = {}
511 # Find this vdu compute and storage descriptors
512 vdu_virtual_compute = {}
513 vdu_virtual_storage = {}
514 for vcd in vnfd.get("virtual-compute-desc", ()):
515 if vcd.get("id") == vdu.get("virtual-compute-desc"):
516 vdu_virtual_compute = vcd
517 for vsd in vnfd.get("virtual-storage-desc", ()):
518 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
519 vdu_virtual_storage = vsd
520 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblas4568a372021-03-24 09:19:48 +0100521 if vdu_virtual_compute.get("virtual-cpu", {}).get(
522 "num-virtual-cpu"
523 ):
524 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
525 "num-virtual-cpu"
526 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300527 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
garciadeblas4568a372021-03-24 09:19:48 +0100528 flavor_data["memory-mb"] = (
529 float(vdu_virtual_compute["virtual-memory"]["size"])
530 * 1024.0
531 )
garciaale7cbd03c2020-11-27 10:38:35 -0300532 if vdu_virtual_storage.get("size-of-storage"):
garciadeblas4568a372021-03-24 09:19:48 +0100533 flavor_data["storage-gb"] = vdu_virtual_storage[
534 "size-of-storage"
535 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300536 # Get this vdu EPA info for guest_epa
537 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100538 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
539 "cpu-quota"
540 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300541 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
542 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
543 if vcpu_pinning.get("thread-policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100544 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
545 "thread-policy"
546 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300547 if vcpu_pinning.get("policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100548 cpu_policy = (
549 "SHARED"
550 if vcpu_pinning["policy"] == "dynamic"
551 else "DEDICATED"
552 )
garciaale7cbd03c2020-11-27 10:38:35 -0300553 guest_epa["cpu-pinning-policy"] = cpu_policy
554 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100555 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
556 "mem-quota"
557 ]
558 if vdu_virtual_compute.get("virtual-memory", {}).get(
559 "mempage-size"
560 ):
561 guest_epa["mempage-size"] = vdu_virtual_compute[
562 "virtual-memory"
563 ]["mempage-size"]
564 if vdu_virtual_compute.get("virtual-memory", {}).get(
565 "numa-node-policy"
566 ):
567 guest_epa["numa-node-policy"] = vdu_virtual_compute[
568 "virtual-memory"
569 ]["numa-node-policy"]
garciaale7cbd03c2020-11-27 10:38:35 -0300570 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100571 guest_epa["disk-io-quota"] = vdu_virtual_storage[
572 "disk-io-quota"
573 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300574
575 if guest_epa:
576 flavor_data["guest-epa"] = guest_epa
577
578 flavor_data["name"] = vdu["id"][:56] + "-flv"
579 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
580 nsr_descriptor["flavor"].append(flavor_data)
581
582 sw_image_id = vdu.get("sw-image-desc")
583 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000584 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
585 self._add_image_to_nsr(nsr_descriptor, image_data)
586
587 # also add alternative images to the list of images
588 for alt_image in vdu.get("alternative-sw-image-desc", ()):
589 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
590 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300591
592 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100593 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
594 vld.get("id"), []
595 )
garciaale7cbd03c2020-11-27 10:38:35 -0300596 vld["name"] = vld["id"]
597 nsr_descriptor["vld"] = nsr_vld
598
599 return nsr_descriptor
600
lloretgalleg28c13b62021-02-08 11:48:48 +0000601 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100602 sw_image_desc = utils.find_in_list(
603 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
604 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000605 image_data = {}
606 if sw_image_desc.get("image"):
607 image_data["image"] = sw_image_desc["image"]
608 if sw_image_desc.get("checksum"):
609 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
610 if sw_image_desc.get("vim-type"):
611 image_data["vim-type"] = sw_image_desc["vim-type"]
612 return image_data
613
614 def _add_image_to_nsr(self, nsr_descriptor, image_data):
615 """
616 Adds image to nsr checking first it is not already added
617 """
garciadeblas4568a372021-03-24 09:19:48 +0100618 img = next(
619 (
620 f
621 for f in nsr_descriptor["image"]
622 if all(f.get(k) == image_data[k] for k in image_data)
623 ),
624 None,
625 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000626 if not img:
627 image_data["id"] = str(len(nsr_descriptor["image"]))
628 nsr_descriptor["image"].append(image_data)
629
garciadeblas4568a372021-03-24 09:19:48 +0100630 def _create_vnfr_descriptor_from_vnfd(
631 self,
632 nsd,
633 vnfd,
634 vnfd_id,
635 vnf_index,
636 nsr_descriptor,
637 ns_request,
638 ns_k8s_namespace,
639 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300640 vnfr_id = str(uuid4())
641 nsr_id = nsr_descriptor["id"]
642 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100643 additional_params, vnf_params = self._format_additional_params(
644 ns_request, vnf_index, descriptor=vnfd
645 )
garciaale7cbd03c2020-11-27 10:38:35 -0300646
647 vnfr_descriptor = {
648 "id": vnfr_id,
649 "_id": vnfr_id,
650 "nsr-id-ref": nsr_id,
651 "member-vnf-index-ref": vnf_index,
652 "additionalParamsForVnf": additional_params,
653 "created-time": now,
654 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
655 "vnfd-ref": vnfd_id,
656 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
657 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200658 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300659 "vdur": [],
660 "connection-point": [],
661 "ip-address": None, # mgmt-interface filled by LCM
662 }
663 vnf_k8s_namespace = ns_k8s_namespace
664 if vnf_params:
665 if vnf_params.get("k8s-namespace"):
666 vnf_k8s_namespace = vnf_params["k8s-namespace"]
667 if vnf_params.get("config-units"):
668 vnfr_descriptor["config-units"] = vnf_params["config-units"]
669
670 # Create vld
671 if vnfd.get("int-virtual-link-desc"):
672 vnfr_descriptor["vld"] = []
673 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
674 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
675
676 for cp in vnfd.get("ext-cpd", ()):
677 vnf_cp = {
678 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100679 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
680 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300681 "id": cp.get("id"),
682 # "ip-address", "mac-address" # filled by LCM
683 # vim-id # TODO it would be nice having a vim port id
684 }
685 vnfr_descriptor["connection-point"].append(vnf_cp)
686
687 # Create k8s-cluster information
688 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
689 if vnfd.get("k8s-cluster"):
690 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
691 all_k8s_cluster_nets_cpds = {}
692 for cpd in get_iterable(vnfd.get("ext-cpd")):
693 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100694 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
695 "id"
696 )
garciaale7cbd03c2020-11-27 10:38:35 -0300697 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
698 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100699 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
700 net.get("id")
701 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300702
703 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300704 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100705 additional_params, kdu_params = self._format_additional_params(
706 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
707 )
garciaale7cbd03c2020-11-27 10:38:35 -0300708 kdu_k8s_namespace = vnf_k8s_namespace
709 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
710 if kdu_params and kdu_params.get("k8s-namespace"):
711 kdu_k8s_namespace = kdu_params["k8s-namespace"]
romeromonserc47d0452021-05-28 11:44:53 +0200712 kdu_deployment_name = ""
713 if kdu_params and kdu_params.get("kdu-deployment-name"):
714 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
garciaale7cbd03c2020-11-27 10:38:35 -0300715
716 kdur = {
717 "additionalParams": additional_params,
718 "k8s-namespace": kdu_k8s_namespace,
romeromonserc47d0452021-05-28 11:44:53 +0200719 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000720 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300721 # TODO "name": "" Name of the VDU in the VIM
722 "ip-address": None, # mgmt-interface filled by LCM
723 "k8s-cluster": {},
724 }
725 if kdu_params and kdu_params.get("config-units"):
726 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000727 if kdu.get("helm-version"):
728 kdur["helm-version"] = kdu["helm-version"]
729 for k8s_type in ("helm-chart", "juju-bundle"):
730 if kdu.get(k8s_type):
731 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300732 if not vnfr_descriptor.get("kdur"):
733 vnfr_descriptor["kdur"] = []
734 vnfr_descriptor["kdur"].append(kdur)
735
736 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300737
garciaale7cbd03c2020-11-27 10:38:35 -0300738 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300739 vdu_mgmt_cp = []
740 try:
garciadeblas4568a372021-03-24 09:19:48 +0100741 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
742 "operate-vnf-op-config"
743 ]["day1-2"]
744 vdu_config = utils.find_in_list(
745 configs, lambda config: config["id"] == vdu["id"]
746 )
bravoff3c39552021-02-24 17:22:24 -0300747 except Exception:
748 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400749
750 try:
751 vdu_instantiation_level = utils.find_in_list(
752 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100753 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400754 )
755 except Exception:
756 vdu_instantiation_level = None
757
bravoff3c39552021-02-24 17:22:24 -0300758 if vdu_config:
759 external_connection_ee = utils.filter_in_list(
760 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100761 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300762 )
763 for ee in external_connection_ee:
764 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
765
garciaale7cbd03c2020-11-27 10:38:35 -0300766 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100767 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
768 )
garciaale7cbd03c2020-11-27 10:38:35 -0300769 vdur = {
770 "vdu-id-ref": vdu["id"],
771 # TODO "name": "" Name of the VDU in the VIM
772 "ip-address": None, # mgmt-interface filled by LCM
773 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
774 "internal-connection-point": [],
775 "interfaces": [],
776 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100777 "vdu-name": vdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300778 }
779 if vdu_params and vdu_params.get("config-units"):
780 vdur["config-units"] = vdu_params["config-units"]
781 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100782 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
783 "boot-data-drive"
784 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300785 if vdu.get("pdu-type"):
786 vdur["pdu-type"] = vdu["pdu-type"]
787 vdur["name"] = vdu["pdu-type"]
788 # TODO volumes: name, volume-id
789 for icp in vdu.get("int-cpd", ()):
790 vdu_icp = {
791 "id": icp["id"],
792 "connection-point-id": icp["id"],
793 "name": icp.get("id"),
794 }
bravof35766442021-02-04 14:58:04 -0300795
garciaale7cbd03c2020-11-27 10:38:35 -0300796 vdur["internal-connection-point"].append(vdu_icp)
797
798 for iface in icp.get("virtual-network-interface-requirement", ()):
799 iface_fields = ("name", "mac-address")
garciadeblas4568a372021-03-24 09:19:48 +0100800 vdu_iface = {
801 x: iface[x] for x in iface_fields if iface.get(x) is not None
802 }
garciaale7cbd03c2020-11-27 10:38:35 -0300803
804 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100805 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100806 vdu_iface["port-security-enabled"] = icp[
807 "port-security-enabled"
808 ]
sousaedu003844e2021-03-02 00:19:15 +0100809
810 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100811 vdu_iface["port-security-disable-strategy"] = icp[
812 "port-security-disable-strategy"
813 ]
sousaedu003844e2021-03-02 00:19:15 +0100814
garciaale7cbd03c2020-11-27 10:38:35 -0300815 for ext_cp in vnfd.get("ext-cpd", ()):
816 if not ext_cp.get("int-cpd"):
817 continue
818 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
819 continue
820 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100821 vdu_iface["external-connection-point-ref"] = ext_cp.get(
822 "id"
823 )
sousaedu003844e2021-03-02 00:19:15 +0100824
825 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100826 vdu_iface["port-security-enabled"] = ext_cp[
827 "port-security-enabled"
828 ]
sousaedu003844e2021-03-02 00:19:15 +0100829
830 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100831 vdu_iface["port-security-disable-strategy"] = ext_cp[
832 "port-security-disable-strategy"
833 ]
sousaedu003844e2021-03-02 00:19:15 +0100834
garciaale7cbd03c2020-11-27 10:38:35 -0300835 break
836
garciadeblas4568a372021-03-24 09:19:48 +0100837 if (
838 vnfd_mgmt_cp
839 and vdu_iface.get("external-connection-point-ref")
840 == vnfd_mgmt_cp
841 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300842 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300843 vdu_iface["mgmt-interface"] = True
844
845 for ecp in vdu_mgmt_cp:
846 if vdu_iface.get("external-connection-point-ref") == ecp:
847 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300848
849 if iface.get("virtual-interface"):
850 vdu_iface.update(deepcopy(iface["virtual-interface"]))
851
852 # look for network where this interface is connected
853 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
854 if iface_ext_cp:
855 # TODO: Change for multiple df support
856 for df in get_iterable(nsd.get("df")):
857 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100858 for vlc_index, vlc in enumerate(
859 get_iterable(
860 vnf_profile.get("virtual-link-connectivity")
861 )
862 ):
863 for cpd in get_iterable(
864 vlc.get("constituent-cpd-id")
865 ):
866 if (
867 cpd.get("constituent-cpd-id")
868 == iface_ext_cp
869 ):
870 vdu_iface["ns-vld-id"] = vlc.get(
871 "virtual-link-profile-id"
872 )
garciadeblas61c95912021-02-12 11:23:50 +0000873 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100874 if vdu_iface.get("type") in (
875 "SR-IOV",
876 "PCI-PASSTHROUGH",
877 ):
878 nsr_descriptor["vld"][vlc_index][
879 "pci-interfaces"
880 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300881 break
882 elif vdu_iface.get("internal-connection-point-ref"):
883 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000884 # TODO: store fixed IP address in the record (if it exists in the ICP)
885 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
886 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100887 ivld_index = utils.find_index_in_list(
888 vnfd.get("int-virtual-link-desc", ()),
889 lambda ivld: ivld["id"]
890 == icp.get("int-virtual-link-desc"),
891 )
garciadeblas61c95912021-02-12 11:23:50 +0000892 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300893
894 vdur["interfaces"].append(vdu_iface)
895
896 if vdu.get("sw-image-desc"):
897 sw_image = utils.find_in_list(
898 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100899 lambda image: image["id"] == vdu.get("sw-image-desc"),
900 )
garciaale7cbd03c2020-11-27 10:38:35 -0300901 nsr_sw_image_data = utils.find_in_list(
902 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100903 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300904 )
905 vdur["ns-image-id"] = nsr_sw_image_data["id"]
906
lloretgalleg28c13b62021-02-08 11:48:48 +0000907 if vdu.get("alternative-sw-image-desc"):
908 alt_image_ids = []
909 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
910 sw_image = utils.find_in_list(
911 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100912 lambda image: image["id"] == alt_image_id,
913 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000914 nsr_sw_image_data = utils.find_in_list(
915 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100916 lambda nsr_image: (
917 nsr_image.get("image") == sw_image.get("image")
918 ),
lloretgalleg28c13b62021-02-08 11:48:48 +0000919 )
920 alt_image_ids.append(nsr_sw_image_data["id"])
921 vdur["alt-image-ids"] = alt_image_ids
922
garciaale7cbd03c2020-11-27 10:38:35 -0300923 flavor_data_name = vdu["id"][:56] + "-flv"
924 nsr_flavor_desc = utils.find_in_list(
925 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +0100926 lambda flavor: flavor["name"] == flavor_data_name,
927 )
garciaale7cbd03c2020-11-27 10:38:35 -0300928
929 if nsr_flavor_desc:
930 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
931
bravof4ca51522021-04-22 10:03:02 -0400932 if vdu_instantiation_level:
933 count = vdu_instantiation_level.get("number-of-instances")
934 else:
935 count = 1
936
garciaale7cbd03c2020-11-27 10:38:35 -0300937 for index in range(0, count):
938 vdur = deepcopy(vdur)
939 for iface in vdur["interfaces"]:
bravofe91ee2a2021-07-01 09:32:30 -0400940 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -0300941 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofe91ee2a2021-07-01 09:32:30 -0400942 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -0300943 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
944
945 vdur["_id"] = str(uuid4())
946 vdur["id"] = vdur["_id"]
947 vdur["count-index"] = index
948 vnfr_descriptor["vdur"].append(vdur)
949
950 return vnfr_descriptor
951
K Sai Kiran57589552021-01-27 21:38:34 +0530952 def vca_status_refresh(self, session, ns_instance_content, filter_q):
953 """
954 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
955 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
956 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
957 :param ns_instance_content: ns instance content
958 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
959 :return: None
960 """
961 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
962 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
963 threshold_reached = time_delta > 120
964 if force_refresh or threshold_reached:
965 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
966 ns_instance_content["_admin"]["modified"] = time_now
967 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
968 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
969 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
970 nslcmop_desc["_admin"].pop("nsState")
971 self.msg.write("ns", operation, nslcmop_desc)
972 return
973
974 def show(self, session, _id, filter_q=None, api_req=False):
975 """
976 Get complete information on an ns instance.
977 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
978 :param _id: string, ns instance id
979 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
980 :param api_req: True if this call is serving an external API request. False if serving internal request.
981 :return: dictionary, raise exception if not found.
982 """
983 ns_instance_content = super().show(session, _id, api_req)
984 self.vca_status_refresh(session, ns_instance_content, filter_q)
985 return ns_instance_content
986
tierno65ca36d2019-02-12 19:27:52 +0100987 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +0100988 raise EngineException(
989 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
990 )
tiernob24258a2018-10-04 18:39:49 +0200991
992
993class VnfrTopic(BaseTopic):
994 topic = "vnfrs"
995 topic_msg = None
996
delacruzramo32bab472019-09-13 12:24:22 +0200997 def __init__(self, db, fs, msg, auth):
998 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200999
tiernobee3bad2019-12-05 12:26:01 +00001000 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001001 raise EngineException(
1002 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1003 )
tiernob24258a2018-10-04 18:39:49 +02001004
tierno65ca36d2019-02-12 19:27:52 +01001005 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001006 raise EngineException(
1007 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1008 )
tiernob24258a2018-10-04 18:39:49 +02001009
tierno65ca36d2019-02-12 19:27:52 +01001010 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001011 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001012 raise EngineException(
1013 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1014 )
tiernob24258a2018-10-04 18:39:49 +02001015
1016
1017class NsLcmOpTopic(BaseTopic):
1018 topic = "nslcmops"
1019 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001020 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001021 "instantiate": ns_instantiate,
1022 "action": ns_action,
1023 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +00001024 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +02001025 }
1026
delacruzramo32bab472019-09-13 12:24:22 +02001027 def __init__(self, db, fs, msg, auth):
1028 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001029
tiernob24258a2018-10-04 18:39:49 +02001030 def _check_ns_operation(self, session, nsr, operation, indata):
1031 """
1032 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001033 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001034 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1035 :param indata: descriptor with the parameters of the operation
1036 :return: None
1037 """
garciaale7cbd03c2020-11-27 10:38:35 -03001038 if operation == "action":
1039 self._check_action_ns_operation(indata, nsr)
1040 elif operation == "scale":
1041 self._check_scale_ns_operation(indata, nsr)
1042 elif operation == "instantiate":
1043 self._check_instantiate_ns_operation(indata, nsr, session)
1044
1045 def _check_action_ns_operation(self, indata, nsr):
1046 nsd = nsr["nsd"]
1047 # check vnf_member_index
1048 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001049 indata["member_vnf_index"] = indata.pop(
1050 "vnf_member_index"
1051 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001052 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001053 vnfd = self._get_vnfd_from_vnf_member_index(
1054 indata["member_vnf_index"], nsr["_id"]
1055 )
bravof41a52052021-02-17 18:08:01 -03001056 try:
garciadeblas4568a372021-03-24 09:19:48 +01001057 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1058 "operate-vnf-op-config"
1059 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001060 except Exception:
1061 configs = []
1062
garciaale7cbd03c2020-11-27 10:38:35 -03001063 if indata.get("vdu_id"):
1064 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001065 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001066 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001067 )
garciaale7cbd03c2020-11-27 10:38:35 -03001068 elif indata.get("kdu_name"):
1069 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001070 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001071 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001072 )
garciaale7cbd03c2020-11-27 10:38:35 -03001073 else:
bravof41a52052021-02-17 18:08:01 -03001074 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001075 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001076 )
1077 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001078 descriptor_configuration = descriptor_configuration.get(
1079 "config-primitive"
1080 )
garciaale7cbd03c2020-11-27 10:38:35 -03001081 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001082 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1083 "config-primitive"
1084 )
garciaale7cbd03c2020-11-27 10:38:35 -03001085
1086 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001087 if indata.get("kdu_name") and indata["primitive"] in (
1088 "upgrade",
1089 "rollback",
1090 "status",
1091 "inspect",
1092 "readme",
1093 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001094 # TODO should be checked that rollback only can contains revsision_numbe????
1095 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001096 raise EngineException(
1097 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1098 indata["primitive"]
1099 )
1100 )
garciaale7cbd03c2020-11-27 10:38:35 -03001101 return
1102 # if not, check primitive
1103 for config_primitive in get_iterable(descriptor_configuration):
1104 if indata["primitive"] == config_primitive["name"]:
1105 # check needed primitive_params are provided
1106 if indata.get("primitive_params"):
1107 in_primitive_params_copy = copy(indata["primitive_params"])
1108 else:
1109 in_primitive_params_copy = {}
1110 for paramd in get_iterable(config_primitive.get("parameter")):
1111 if paramd["name"] in in_primitive_params_copy:
1112 del in_primitive_params_copy[paramd["name"]]
1113 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001114 raise EngineException(
1115 "Needed parameter {} not provided for primitive '{}'".format(
1116 paramd["name"], indata["primitive"]
1117 )
1118 )
garciaale7cbd03c2020-11-27 10:38:35 -03001119 # check no extra primitive params are provided
1120 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001121 raise EngineException(
1122 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1123 list(in_primitive_params_copy.keys()), indata["primitive"]
1124 )
1125 )
garciaale7cbd03c2020-11-27 10:38:35 -03001126 break
1127 else:
garciadeblas4568a372021-03-24 09:19:48 +01001128 raise EngineException(
1129 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1130 indata["primitive"]
1131 )
1132 )
garciaale7cbd03c2020-11-27 10:38:35 -03001133
1134 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001135 vnfd = self._get_vnfd_from_vnf_member_index(
1136 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1137 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001138 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001139 if (
1140 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1141 == scaling_aspect["id"]
1142 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001143 break
1144 else:
garciadeblas4568a372021-03-24 09:19:48 +01001145 raise EngineException(
1146 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1147 "present at vnfd:scaling-aspect".format(
1148 indata["scaleVnfData"]["scaleByStepData"][
1149 "scaling-group-descriptor"
1150 ]
1151 )
1152 )
garciaale7cbd03c2020-11-27 10:38:35 -03001153
1154 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001155 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001156 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001157 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001158 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001159 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1160 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1161 for in_vnf in get_iterable(indata.get("vnf")):
1162 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001163 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001164 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001165 else:
garciadeblas4568a372021-03-24 09:19:48 +01001166 vnfd = self._get_vnfd_from_vnf_member_index(
1167 member_vnf_index, nsr["_id"]
1168 )
1169 vnf_member_index_to_vnfd[
1170 member_vnf_index
1171 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001172 self._check_vnf_instantiation_params(in_vnf, vnfd)
1173 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001174 self._check_valid_vim_account(
1175 in_vnf["vimAccountId"], vim_accounts, session
1176 )
tierno260dd6f2019-09-02 10:48:56 +00001177
garciaale7cbd03c2020-11-27 10:38:35 -03001178 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001179 self._check_valid_wim_account(
1180 in_vld.get("wimAccountId"), wim_accounts, session
1181 )
garciaale7cbd03c2020-11-27 10:38:35 -03001182 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1183 if in_vld["name"] == vldd["id"]:
1184 break
tierno9cb7d672019-10-30 12:13:48 +00001185 else:
garciadeblas4568a372021-03-24 09:19:48 +01001186 raise EngineException(
1187 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1188 in_vld["name"]
1189 )
1190 )
tierno9cb7d672019-10-30 12:13:48 +00001191
garciaale7cbd03c2020-11-27 10:38:35 -03001192 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1193 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001194 vnfr = self.db.get_one(
1195 "vnfrs",
1196 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1197 fail_on_empty=False,
1198 )
garciaale7cbd03c2020-11-27 10:38:35 -03001199 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001200 raise EngineException(
1201 "Invalid parameter member_vnf_index='{}' is not one of the "
1202 "nsd:constituent-vnfd".format(member_vnf_index)
1203 )
garciaale7cbd03c2020-11-27 10:38:35 -03001204 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1205 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001206 raise EngineException(
1207 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1208 vnfr["vnfd-id"]
1209 )
1210 )
garciaale7cbd03c2020-11-27 10:38:35 -03001211 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001212
garciaale7cbd03c2020-11-27 10:38:35 -03001213 def _check_valid_vdu(self, vnfd, vdu_id):
1214 for vdud in get_iterable(vnfd.get("vdu")):
1215 if vdud["id"] == vdu_id:
1216 return vdud
1217 else:
garciadeblas4568a372021-03-24 09:19:48 +01001218 raise EngineException(
1219 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1220 vdu_id
1221 )
1222 )
garciaale7cbd03c2020-11-27 10:38:35 -03001223
1224 def _check_valid_kdu(self, vnfd, kdu_name):
1225 for kdud in get_iterable(vnfd.get("kdu")):
1226 if kdud["name"] == kdu_name:
1227 return kdud
1228 else:
garciadeblas4568a372021-03-24 09:19:48 +01001229 raise EngineException(
1230 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1231 kdu_name
1232 )
1233 )
garciaale7cbd03c2020-11-27 10:38:35 -03001234
1235 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1236 for in_vdu in get_iterable(in_vnf.get("vdu")):
1237 for vdu in get_iterable(vnfd.get("vdu")):
1238 if in_vdu["id"] == vdu["id"]:
1239 for volume in get_iterable(in_vdu.get("volume")):
1240 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1241 if volumed["id"] == volume["name"]:
1242 break
1243 else:
garciadeblas4568a372021-03-24 09:19:48 +01001244 raise EngineException(
1245 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1246 "volume:name='{}' is not present at "
1247 "vnfd:vdu:virtual-storage-desc list".format(
1248 in_vnf["member-vnf-index"],
1249 in_vdu["id"],
1250 volume["id"],
1251 )
1252 )
garciaale7cbd03c2020-11-27 10:38:35 -03001253
1254 vdu_if_names = set()
1255 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001256 for iface in get_iterable(
1257 cpd.get("virtual-network-interface-requirement")
1258 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001259 vdu_if_names.add(iface.get("name"))
1260
1261 for in_iface in get_iterable(in_vdu["interface"]):
1262 if in_iface["name"] in vdu_if_names:
1263 break
1264 else:
garciadeblas4568a372021-03-24 09:19:48 +01001265 raise EngineException(
1266 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1267 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1268 in_vnf["member-vnf-index"],
1269 in_vdu["id"],
1270 in_iface["name"],
1271 )
1272 )
garciaale7cbd03c2020-11-27 10:38:35 -03001273 break
1274
1275 else:
garciadeblas4568a372021-03-24 09:19:48 +01001276 raise EngineException(
1277 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1278 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1279 )
garciaale7cbd03c2020-11-27 10:38:35 -03001280
garciadeblas4568a372021-03-24 09:19:48 +01001281 vnfd_ivlds_cpds = {
1282 ivld.get("id"): set()
1283 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1284 }
garciaale7cbd03c2020-11-27 10:38:35 -03001285 for vdu in get_iterable(vnfd.get("vdu")):
1286 for cpd in get_iterable(vnfd.get("int-cpd")):
1287 if cpd.get("int-virtual-link-desc"):
1288 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1289
1290 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1291 if in_ivld.get("name") in vnfd_ivlds_cpds:
1292 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1293 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001294 break
tiernob24258a2018-10-04 18:39:49 +02001295 else:
garciadeblas4568a372021-03-24 09:19:48 +01001296 raise EngineException(
1297 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1298 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1299 "vnfd:internal-vld:name/id:internal-connection-point".format(
1300 in_vnf["member-vnf-index"],
1301 in_ivld["name"],
1302 in_icp["id-ref"],
1303 )
1304 )
tiernob24258a2018-10-04 18:39:49 +02001305 else:
garciadeblas4568a372021-03-24 09:19:48 +01001306 raise EngineException(
1307 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1308 " is not present at vnfd '{}'".format(
1309 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1310 )
1311 )
tiernob24258a2018-10-04 18:39:49 +02001312
garciaale7cbd03c2020-11-27 10:38:35 -03001313 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1314 if vim_account in vim_accounts:
1315 return
1316 try:
1317 db_filter = self._get_project_filter(session)
1318 db_filter["_id"] = vim_account
1319 self.db.get_one("vim_accounts", db_filter)
1320 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001321 raise EngineException(
1322 "Invalid vimAccountId='{}' not present for the project".format(
1323 vim_account
1324 )
1325 )
garciaale7cbd03c2020-11-27 10:38:35 -03001326 vim_accounts.append(vim_account)
1327
1328 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1329 if not isinstance(wim_account, str):
1330 return
1331 if wim_account in wim_accounts:
1332 return
1333 try:
1334 db_filter = self._get_project_filter(session, write=False, show_all=True)
1335 db_filter["_id"] = wim_account
1336 self.db.get_one("wim_accounts", db_filter)
1337 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001338 raise EngineException(
1339 "Invalid wimAccountId='{}' not present for the project".format(
1340 wim_account
1341 )
1342 )
garciaale7cbd03c2020-11-27 10:38:35 -03001343 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001344
garciadeblas4568a372021-03-24 09:19:48 +01001345 def _look_for_pdu(
1346 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1347 ):
tiernocc103432018-10-19 14:10:35 +02001348 """
tierno36ec8602018-11-02 17:27:11 +01001349 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1350 (ip_address, ...) information.
1351 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001352 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001353 :param rollback: list with the database modifications to rollback if needed
1354 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1355 :param vim_account: vim_account where this vnfr should be deployed
1356 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1357 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1358 of the changed vnfr is needed
1359
1360 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1361 "vim-network-name": used at VIM
1362 "name": interface name
1363 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1364 "ns-vld-id": NSD vld where this interface is connected.
1365 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 +02001366 """
tierno36ec8602018-11-02 17:27:11 +01001367
1368 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001369 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1370 if not vdur.get("pdu-type"):
1371 continue
1372 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001373 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001374 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001375 pdu_filter["type"] = pdu_type
1376 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001377 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001378 # TODO feature 1417: "shared": True,
1379
1380 available_pdus = self.db.get_list("pdus", pdu_filter)
1381 for pdu in available_pdus:
1382 # step 1 check if this pdu contains needed interfaces:
1383 match_interfaces = True
1384 for vdur_interface in vdur["interfaces"]:
1385 for pdu_interface in pdu["interfaces"]:
1386 if pdu_interface["name"] == vdur_interface["name"]:
1387 # TODO feature 1417: match per mgmt type
1388 break
1389 else: # no interface found for name
1390 match_interfaces = False
1391 break
1392 if match_interfaces:
1393 break
1394 else:
1395 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001396 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001397 "names".format(
1398 pdu_type,
1399 vim_account,
1400 vnfr["member-vnf-index-ref"],
1401 vdur["vdu-id-ref"],
1402 )
1403 )
tiernocc103432018-10-19 14:10:35 +02001404
1405 # step 2. Update pdu
1406 rollback_pdu = {
1407 "_admin.usageState": pdu["_admin"]["usageState"],
1408 "_admin.usage.vnfr_id": None,
1409 "_admin.usage.nsr_id": None,
1410 "_admin.usage.vdur": None,
1411 }
garciadeblas4568a372021-03-24 09:19:48 +01001412 self.db.set_one(
1413 "pdus",
1414 {"_id": pdu["_id"]},
1415 {
1416 "_admin.usageState": "IN_USE",
1417 "_admin.usage": {
1418 "vnfr_id": vnfr["_id"],
1419 "nsr_id": vnfr["nsr-id-ref"],
1420 "vdur": vdur["vdu-id-ref"],
1421 },
1422 },
1423 )
1424 rollback.append(
1425 {
1426 "topic": "pdus",
1427 "_id": pdu["_id"],
1428 "operation": "set",
1429 "content": rollback_pdu,
1430 }
1431 )
tiernocc103432018-10-19 14:10:35 +02001432
1433 # step 3. Fill vnfr info by filling vdur
1434 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001435 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001436 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1437 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1438 for pdu_interface in pdu["interfaces"]:
1439 if pdu_interface["name"] == vdur_interface["name"]:
1440 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1441 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001442 if k in (
1443 "ip-address",
1444 "mac-address",
1445 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001446 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001447 vnfr_update_rollback[
1448 iface_text + ".{}".format(k)
1449 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001450 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001451 if vdur_interface.get(
1452 "mgmt-interface"
1453 ) or vdur_interface.get("mgmt-vnf"):
1454 vnfr_update_rollback[
1455 vdu_text + ".ip-address"
1456 ] = vdur.get("ip-address")
1457 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1458 "ip-address"
1459 ]
tierno36ec8602018-11-02 17:27:11 +01001460 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001461 vnfr_update_rollback["ip-address"] = vnfr.get(
1462 "ip-address"
1463 )
tierno36ec8602018-11-02 17:27:11 +01001464 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001465 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1466 "ip-address"
1467 ]
1468 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1469 "vim-network-id"
1470 ):
1471 ifaces_forcing_vim_network.append(
1472 {
1473 "name": vdur_interface.get("vnf-vld-id")
1474 or vdur_interface.get("ns-vld-id"),
1475 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1476 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1477 }
1478 )
gcalvino17d5b732018-12-17 16:26:21 +01001479 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001480 ifaces_forcing_vim_network[-1][
1481 "vim-network-id"
1482 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001483 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001484 ifaces_forcing_vim_network[-1][
1485 "vim-network-name"
1486 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001487 break
1488
tierno36ec8602018-11-02 17:27:11 +01001489 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001490
garciadeblas4568a372021-03-24 09:19:48 +01001491 def _look_for_k8scluster(
1492 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1493 ):
tierno9cb7d672019-10-30 12:13:48 +00001494 """
1495 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1496 Fills vnfr.kdur with the selected k8scluster
1497
1498 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1499 :param rollback: list with the database modifications to rollback if needed
1500 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1501 :param vim_account: vim_account where this vnfr should be deployed
1502 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1503 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1504 of the changed vnfr is needed
1505
1506 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1507 "vim-network-name": used at VIM
1508 "name": interface name
1509 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1510 "ns-vld-id": NSD vld where this interface is connected.
1511 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1512 """
1513
1514 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001515 if not vnfr.get("kdur"):
1516 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001517
tiernoc67b0e92019-11-05 12:45:29 +00001518 kdu_filter = self._get_project_filter(session)
1519 kdu_filter["vim_account"] = vim_account
1520 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1521 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1522
1523 k8s_requirements = {} # just for logging
1524 for k8scluster in available_k8sclusters:
1525 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001526 break
tiernoc67b0e92019-11-05 12:45:29 +00001527 # restrict by cni
1528 if vnfr["k8s-cluster"].get("cni"):
1529 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001530 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1531 k8scluster.get("cni", ())
1532 ):
tiernoc67b0e92019-11-05 12:45:29 +00001533 continue
1534 # restrict by version
1535 if vnfr["k8s-cluster"].get("version"):
1536 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1537 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1538 continue
1539 # restrict by number of networks
1540 if vnfr["k8s-cluster"].get("nets"):
1541 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001542 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1543 vnfr["k8s-cluster"]["nets"]
1544 ):
tiernoc67b0e92019-11-05 12:45:29 +00001545 continue
1546 break
1547 else:
garciadeblas4568a372021-03-24 09:19:48 +01001548 raise EngineException(
1549 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1550 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1551 )
1552 )
tierno9cb7d672019-10-30 12:13:48 +00001553
tiernoc67b0e92019-11-05 12:45:29 +00001554 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001555 # step 3. Fill vnfr info by filling kdur
1556 kdu_text = "kdur.{}.".format(kdur_index)
1557 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1558 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1559
tiernoc67b0e92019-11-05 12:45:29 +00001560 # step 4. Check VIM networks that forces the selected k8s_cluster
1561 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1562 k8scluster_net_list = list(k8scluster.get("nets").keys())
1563 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1564 # get a network from k8s_cluster nets. If name matches use this, if not use other
1565 if kdur_net["id"] in k8scluster_net_list: # name matches
1566 vim_net = k8scluster["nets"][kdur_net["id"]]
1567 k8scluster_net_list.remove(kdur_net["id"])
1568 else:
1569 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1570 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001571 vnfr_update_rollback[
1572 "k8s-cluster.nets.{}.vim_net".format(net_index)
1573 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001574 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001575 if vim_net and (
1576 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1577 ):
1578 ifaces_forcing_vim_network.append(
1579 {
1580 "name": kdur_net.get("vnf-vld-id")
1581 or kdur_net.get("ns-vld-id"),
1582 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1583 "ns-vld-id": kdur_net.get("ns-vld-id"),
1584 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1585 }
1586 )
tiernoc67b0e92019-11-05 12:45:29 +00001587 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001588 return ifaces_forcing_vim_network
1589
tiernocc103432018-10-19 14:10:35 +02001590 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001591 # get vnfr
1592 nsr_id = nsr["_id"]
1593 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1594
1595 for vnfr in vnfrs:
1596 vnfr_update = {}
1597 vnfr_update_rollback = {}
1598 member_vnf_index = vnfr["member-vnf-index-ref"]
1599 # update vim-account-id
1600
1601 vim_account = indata["vimAccountId"]
David Garciaecb41322021-03-31 19:10:46 +02001602 vca_id = indata.get("vcaId")
tiernocc103432018-10-19 14:10:35 +02001603 # check instantiate parameters
1604 for vnf_inst_params in get_iterable(indata.get("vnf")):
1605 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1606 continue
1607 if vnf_inst_params.get("vimAccountId"):
1608 vim_account = vnf_inst_params.get("vimAccountId")
David Garciaecb41322021-03-31 19:10:46 +02001609 if vnf_inst_params.get("vcaId"):
1610 vca_id = vnf_inst_params.get("vcaId")
tiernocc103432018-10-19 14:10:35 +02001611
tiernocddb07d2020-10-06 08:28:00 +00001612 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1613 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1614 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1615 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1616 continue
garciadeblas4568a372021-03-24 09:19:48 +01001617 for iface_inst_param in get_iterable(
1618 vdu_inst_param.get("interface")
1619 ):
1620 iface_index, _ = next(
1621 i
1622 for i in enumerate(vdur["interfaces"])
1623 if i[1]["name"] == iface_inst_param["name"]
1624 )
1625 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1626 vdur_index, iface_index
1627 )
tiernocddb07d2020-10-06 08:28:00 +00001628 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001629 vnfr_update[
1630 vnfr_update_text + ".ip-address"
1631 ] = increment_ip_mac(
1632 iface_inst_param.get("ip-address"),
1633 vdur.get("count-index", 0),
1634 )
tierno1bd9d952020-11-13 15:56:51 +00001635 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001636 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001637 vnfr_update[
1638 vnfr_update_text + ".mac-address"
1639 ] = increment_ip_mac(
1640 iface_inst_param.get("mac-address"),
1641 vdur.get("count-index", 0),
1642 )
tierno1bd9d952020-11-13 15:56:51 +00001643 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001644 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001645 vnfr_update[
1646 vnfr_update_text + ".floating-ip-required"
1647 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001648 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1649 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001650 for ivld_inst_param in get_iterable(
1651 vnf_inst_params.get("internal-vld")
1652 ):
1653 for icp_inst_param in get_iterable(
1654 ivld_inst_param.get("internal-connection-point")
1655 ):
tiernocddb07d2020-10-06 08:28:00 +00001656 # look for iface
1657 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1658 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001659 if (
1660 iface.get("internal-connection-point-ref")
1661 == icp_inst_param["id-ref"]
1662 ):
1663 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1664 vdur_index, iface_index
1665 )
tiernocddb07d2020-10-06 08:28:00 +00001666 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001667 vnfr_update[
1668 vnfr_update_text + ".ip-address"
1669 ] = increment_ip_mac(
1670 icp_inst_param.get("ip-address"),
1671 vdur.get("count-index", 0),
1672 )
1673 vnfr_update[
1674 vnfr_update_text + ".fixed-ip"
1675 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001676 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001677 vnfr_update[
1678 vnfr_update_text + ".mac-address"
1679 ] = increment_ip_mac(
1680 icp_inst_param.get("mac-address"),
1681 vdur.get("count-index", 0),
1682 )
1683 vnfr_update[
1684 vnfr_update_text + ".fixed-mac"
1685 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001686 break
1687 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1688 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001689 for vnfcp_inst_param in get_iterable(
1690 vld_inst_param.get("vnfd-connection-point-ref")
1691 ):
tiernocddb07d2020-10-06 08:28:00 +00001692 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1693 continue
1694 # look for iface
1695 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1696 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001697 if (
1698 iface.get("external-connection-point-ref")
1699 == vnfcp_inst_param["vnfd-connection-point-ref"]
1700 ):
1701 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1702 vdur_index, iface_index
1703 )
tiernocddb07d2020-10-06 08:28:00 +00001704 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001705 vnfr_update[
1706 vnfr_update_text + ".ip-address"
1707 ] = increment_ip_mac(
1708 vnfcp_inst_param.get("ip-address"),
1709 vdur.get("count-index", 0),
1710 )
tierno1bd9d952020-11-13 15:56:51 +00001711 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001712 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001713 vnfr_update[
1714 vnfr_update_text + ".mac-address"
1715 ] = increment_ip_mac(
1716 vnfcp_inst_param.get("mac-address"),
1717 vdur.get("count-index", 0),
1718 )
tierno1bd9d952020-11-13 15:56:51 +00001719 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001720 break
1721
tiernocc103432018-10-19 14:10:35 +02001722 vnfr_update["vim-account-id"] = vim_account
1723 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1724
David Garciaecb41322021-03-31 19:10:46 +02001725 if vca_id:
1726 vnfr_update["vca-id"] = vca_id
1727 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1728
tiernocc103432018-10-19 14:10:35 +02001729 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01001730 ifaces_forcing_vim_network = self._look_for_pdu(
1731 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1732 )
tiernocc103432018-10-19 14:10:35 +02001733
tierno9cb7d672019-10-30 12:13:48 +00001734 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01001735 ifaces_forcing_vim_network += self._look_for_k8scluster(
1736 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1737 )
tierno9cb7d672019-10-30 12:13:48 +00001738 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001739 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01001740 rollback.append(
1741 {
1742 "topic": "vnfrs",
1743 "_id": vnfr["_id"],
1744 "operation": "set",
1745 "content": vnfr_update_rollback,
1746 }
1747 )
tierno36ec8602018-11-02 17:27:11 +01001748
1749 # Update indada in case pdu forces to use a concrete vim-network-name
1750 # TODO check if user has already insert a vim-network-name and raises an error
1751 if not ifaces_forcing_vim_network:
1752 continue
1753 for iface_info in ifaces_forcing_vim_network:
1754 if iface_info.get("ns-vld-id"):
1755 if "vld" not in indata:
1756 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001757 indata["vld"].append(
1758 {
1759 key: iface_info[key]
1760 for key in ("name", "vim-network-name", "vim-network-id")
1761 if iface_info.get(key)
1762 }
1763 )
tierno36ec8602018-11-02 17:27:11 +01001764
1765 elif iface_info.get("vnf-vld-id"):
1766 if "vnf" not in indata:
1767 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001768 indata["vnf"].append(
1769 {
1770 "member-vnf-index": member_vnf_index,
1771 "internal-vld": [
1772 {
1773 key: iface_info[key]
1774 for key in (
1775 "name",
1776 "vim-network-name",
1777 "vim-network-id",
1778 )
1779 if iface_info.get(key)
1780 }
1781 ],
1782 }
1783 )
tierno36ec8602018-11-02 17:27:11 +01001784
1785 @staticmethod
1786 def _create_nslcmop(nsr_id, operation, params):
1787 """
1788 Creates a ns-lcm-opp content to be stored at database.
1789 :param nsr_id: internal id of the instance
1790 :param operation: instantiate, terminate, scale, action, ...
1791 :param params: user parameters for the operation
1792 :return: dictionary following SOL005 format
1793 """
tiernob24258a2018-10-04 18:39:49 +02001794 now = time()
1795 _id = str(uuid4())
1796 nslcmop = {
1797 "id": _id,
1798 "_id": _id,
1799 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001800 "queuePosition": None,
1801 "stage": None,
1802 "errorMessage": None,
1803 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001804 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001805 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001806 "lcmOperationType": operation,
1807 "startTime": now,
1808 "isAutomaticInvocation": False,
1809 "operationParams": params,
1810 "isCancelPending": False,
1811 "links": {
1812 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001813 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01001814 },
tiernob24258a2018-10-04 18:39:49 +02001815 }
1816 return nslcmop
1817
magnussonlf318b302020-01-20 18:38:18 +01001818 def _get_enabled_vims(self, session):
1819 """
1820 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1821 :param session: current session with user information
1822 """
1823 db_filter = self._get_project_filter(session)
1824 db_filter["_admin.operationalState"] = "ENABLED"
1825 vims = self.db.get_list("vim_accounts", db_filter)
1826 vimAccounts = []
1827 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01001828 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01001829 return vimAccounts
1830
garciadeblas4568a372021-03-24 09:19:48 +01001831 def new(
1832 self,
1833 rollback,
1834 session,
1835 indata=None,
1836 kwargs=None,
1837 headers=None,
1838 slice_object=False,
1839 ):
tiernob24258a2018-10-04 18:39:49 +02001840 """
1841 Performs a new operation over a ns
1842 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001843 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001844 :param indata: descriptor with the parameters of the operation. It must contains among others
1845 nsInstanceId: _id of the nsr to perform the operation
1846 operation: it can be: instantiate, terminate, action, TODO: update, heal
1847 :param kwargs: used to override the indata descriptor
1848 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02001849 :return: id of the nslcmops
1850 """
garciadeblas4568a372021-03-24 09:19:48 +01001851
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001852 def check_if_nsr_is_not_slice_member(session, nsr_id):
1853 nsis = None
1854 db_filter = self._get_project_filter(session)
1855 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01001856 nsis = self.db.get_one(
1857 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
1858 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001859 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01001860 raise EngineException(
1861 "The NS instance {} cannot be terminated because is used by the slice {}".format(
1862 nsr_id, nsis["_id"]
1863 ),
1864 http_code=HTTPStatus.CONFLICT,
1865 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001866
tiernob24258a2018-10-04 18:39:49 +02001867 try:
1868 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00001869 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02001870 operation = indata["lcmOperationType"]
1871 nsInstanceId = indata["nsInstanceId"]
1872
1873 validate_input(indata, self.operation_schema[operation])
1874 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01001875 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02001876 _filter["_id"] = nsInstanceId
1877 nsr = self.db.get_one("nsrs", _filter)
1878
1879 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001880 if operation == "terminate" and slice_object is False:
1881 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01001882 if (
1883 not nsr["_admin"].get("nsState")
1884 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
1885 ):
tiernob24258a2018-10-04 18:39:49 +02001886 if operation == "terminate" and indata.get("autoremove"):
1887 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01001888 return (
1889 None,
1890 None,
1891 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02001892 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01001893 raise EngineException(
1894 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1895 nsInstanceId, operation
1896 ),
1897 HTTPStatus.CONFLICT,
1898 )
tiernob24258a2018-10-04 18:39:49 +02001899 else:
tierno65ca36d2019-02-12 19:27:52 +01001900 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01001901 raise EngineException(
1902 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1903 nsInstanceId, operation
1904 ),
1905 HTTPStatus.CONFLICT,
1906 )
tiernob24258a2018-10-04 18:39:49 +02001907 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +01001908
tiernocc103432018-10-19 14:10:35 +02001909 if operation == "instantiate":
1910 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01001911
1912 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00001913 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01001914 self.format_on_new(
1915 nslcmop_desc, session["project_id"], make_public=session["public"]
1916 )
magnussonlf318b302020-01-20 18:38:18 +01001917 if indata.get("placement-engine"):
1918 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01001919 nslcmop_desc["operationParams"][
1920 "validVimAccounts"
1921 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00001922 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02001923 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001924 if not slice_object:
1925 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001926 return _id, None
1927 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02001928 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1929 # except DbException as e:
1930 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1931
tiernobee3bad2019-12-05 12:26:01 +00001932 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001933 raise EngineException(
1934 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1935 )
tiernob24258a2018-10-04 18:39:49 +02001936
tierno65ca36d2019-02-12 19:27:52 +01001937 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001938 raise EngineException(
1939 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1940 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02001941
1942
1943class NsiTopic(BaseTopic):
1944 topic = "nsis"
1945 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00001946 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001947
delacruzramo32bab472019-09-13 12:24:22 +02001948 def __init__(self, db, fs, msg, auth):
1949 BaseTopic.__init__(self, db, fs, msg, auth)
1950 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001951
Felipe Vicensc37b3842019-01-12 12:24:42 +01001952 @staticmethod
1953 def _format_ns_request(ns_request):
1954 formated_request = copy(ns_request)
1955 # TODO: Add request params
1956 return formated_request
1957
1958 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001959 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001960 """
1961 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001962 :param slice_request: User instantiation additional parameters
1963 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001964 """
tiernofd160572019-01-21 10:41:37 +00001965 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1966 if additional_params:
1967 for k, v in additional_params.items():
1968 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01001969 raise EngineException(
1970 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
1971 k
1972 )
1973 )
tiernofd160572019-01-21 10:41:37 +00001974 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01001975 raise EngineException(
1976 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
1977 k
1978 )
1979 )
tiernofd160572019-01-21 10:41:37 +00001980 if isinstance(v, (dict, tuple, list)):
1981 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001982 return additional_params
1983
Felipe Vicensb57758d2018-10-16 16:00:20 +02001984 def _check_descriptor_dependencies(self, session, descriptor):
1985 """
1986 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001987 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001988 :param descriptor: descriptor to be inserted or edit
1989 :return: None or raises exception
1990 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001991 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001992 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001993 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001994 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
garciadeblas4568a372021-03-24 09:19:48 +01001995 raise EngineException(
1996 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
1997 nstd_id
1998 ),
1999 http_code=HTTPStatus.CONFLICT,
2000 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002001
tiernob4844ab2019-05-23 08:42:12 +00002002 def check_conflict_on_del(self, session, _id, db_content):
2003 """
2004 Check that NSI is not instantiated
2005 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2006 :param _id: nsi internal id
2007 :param db_content: The database content of the _id
2008 :return: None or raises EngineException with the conflict
2009 """
tierno65ca36d2019-02-12 19:27:52 +01002010 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002011 return
tiernob4844ab2019-05-23 08:42:12 +00002012 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002013 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002014 raise EngineException(
2015 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2016 "Launch 'terminate' operation first; or force deletion".format(_id),
2017 http_code=HTTPStatus.CONFLICT,
2018 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002019
tiernobee3bad2019-12-05 12:26:01 +00002020 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002021 """
tiernob4844ab2019-05-23 08:42:12 +00002022 Deletes associated nsilcmops from database. Deletes associated filesystem.
2023 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002024 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002025 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002026 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002027 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002028 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002029 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002030
Felipe Vicens09e65422019-01-22 15:06:46 +01002031 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002032 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002033 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2034 nsr_id = nsrs_detailed_item["nsrId"]
2035 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002036 _filter = {
2037 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2038 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2039 "_id.ne": nsir["_id"],
2040 }
2041 nsi = self.db.get_one(
2042 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2043 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002044 if nsi: # last one using nsr
2045 continue
2046 try:
garciadeblas4568a372021-03-24 09:19:48 +01002047 self.nsrTopic.delete(
2048 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2049 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002050 except (DbException, EngineException) as e:
2051 if e.http_code == HTTPStatus.NOT_FOUND:
2052 pass
2053 else:
2054 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002055
tiernob4844ab2019-05-23 08:42:12 +00002056 # delete related nsilcmops database entries
2057 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002058
tiernob4844ab2019-05-23 08:42:12 +00002059 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002060 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002061 if nsir_admin and nsir_admin.get("nst-id"):
2062 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002063 nsis_list = self.db.get_one(
2064 "nsis",
2065 {"nst-id": nsir_admin["nst-id"]},
2066 fail_on_empty=False,
2067 fail_on_more=False,
2068 )
tiernob4844ab2019-05-23 08:42:12 +00002069 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002070 self.db.set_one(
2071 "nsts",
2072 {"_id": nsir_admin["nst-id"]},
2073 {"_admin.usageState": "NOT_IN_USE"},
2074 )
tiernob4844ab2019-05-23 08:42:12 +00002075
tierno65ca36d2019-02-12 19:27:52 +01002076 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002077 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002078 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002079 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002080 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002081 :param indata: params to be used for the nsir
2082 :param kwargs: used to override the indata descriptor
2083 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002084 :return: the _id of nsi descriptor created at database
2085 """
2086
2087 try:
delacruzramo32bab472019-09-13 12:24:22 +02002088 step = "checking quotas"
2089 self.check_quota(session)
2090
tierno99d4b172019-07-02 09:28:40 +00002091 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002092 slice_request = self._remove_envelop(indata)
2093 # Override descriptor with query string kwargs
2094 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002095 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002096
Felipe Vicensb57758d2018-10-16 16:00:20 +02002097 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002098 step = "getting nstd id='{}' from database".format(
2099 slice_request.get("nstId")
2100 )
tiernob4844ab2019-05-23 08:42:12 +00002101 _filter = self._get_project_filter(session)
2102 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002103 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002104 # check NST is not disabled
2105 step = "checking NST operationalState"
2106 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002107 raise EngineException(
2108 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2109 "instance".format(slice_request["nstId"]),
2110 http_code=HTTPStatus.CONFLICT,
2111 )
tiernob4844ab2019-05-23 08:42:12 +00002112 del _filter["_id"]
2113
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002114 # check NSD is not disabled
2115 step = "checking operationalState"
2116 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002117 raise EngineException(
2118 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2119 "a network slice".format(slice_request["nstId"]),
2120 http_code=HTTPStatus.CONFLICT,
2121 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002122
Felipe Vicens07f31722018-10-29 15:16:44 +01002123 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002124 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002125 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002126 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002127
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002128 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002129 nsi_descriptor = {
2130 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002131 "name": slice_request["nsiName"],
2132 "description": slice_request.get("nsiDescription", ""),
2133 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002134 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002135 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002136 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002137 "nsr-ref-list": [],
2138 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002139 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002140 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002141 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002142
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002143 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002144 self.format_on_new(
2145 nsi_descriptor, session["project_id"], make_public=session["public"]
2146 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002147 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2148 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002149 nsi_descriptor["_admin"]["deployed"] = {}
2150 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2151 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2152
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002153 # Creating netslice-vld for the RO.
2154 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002155
2156 # Building the vlds list to be deployed
2157 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002158 nsi_vlds = []
2159
2160 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2161 # Getting template Instantiation parameters from NST
2162 nsi_vld = deepcopy(netslice_vlds)
2163 nsi_vld["shared-nsrs-list"] = []
2164 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2165 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002166
2167 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002168 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002169 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002170 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002171
Felipe Vicens09e65422019-01-22 15:06:46 +01002172 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002173 for member_ns in nstd["netslice-subnet"]:
2174 nsd_id = member_ns["nsd-ref"]
2175 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002176 member_ns["nsd-ref"], member_ns["id"]
2177 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002178 if nsd_id not in needed_nsds:
2179 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002180 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002181 nsd = self.db.get_one(
2182 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2183 )
tiernob4844ab2019-05-23 08:42:12 +00002184 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002185 nsd.pop("_admin")
2186 needed_nsds[nsd_id] = nsd
2187 else:
2188 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002189 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2190 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002191
Felipe Vicensb57758d2018-10-16 16:00:20 +02002192 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002193 member_ns["nsd-ref"], member_ns["id"]
2194 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002195
Felipe Vicens07f31722018-10-29 15:16:44 +01002196 # creates Network Services records (NSRs)
2197 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002198 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002199 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002200 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002201 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002202 # Check if the netslice-subnet is shared and if it is share if the nss exists
2203 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002204 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002205 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002206 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002207 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2208 "nsd-ref"
2209 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002210 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002211 nsi = self.db.get_one(
2212 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2213 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002214 if nsi and service.get("is-shared-nss"):
2215 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2216 for nsrs_detailed_item in nsrs_detailed_list:
2217 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002218 if nsrs_detailed_item["nss-id"] == service["id"]:
2219 _id_nsr = nsrs_detailed_item["nsrId"]
2220 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002221 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2222 if netslice_subnet["nss-id"] == service["id"]:
2223 indata_ns = netslice_subnet
2224 break
2225 else:
2226 indata_ns = {}
2227 if service.get("instantiation-parameters"):
2228 indata_ns = deepcopy(service["instantiation-parameters"])
2229 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002230
Felipe Vicens09e65422019-01-22 15:06:46 +01002231 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002232 indata_ns["nsName"] = (
2233 slice_request.get("nsiName") + "." + service["id"]
2234 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002235 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2236 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002237 if slice_request.get("ssh_keys"):
2238 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002239
Felipe Vicens09e65422019-01-22 15:06:46 +01002240 if ns_params:
2241 for ns_param in ns_params:
2242 if ns_param.get("id") == service["id"]:
2243 copy_ns_param = deepcopy(ns_param)
2244 del copy_ns_param["id"]
2245 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002246 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002247
2248 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002249 _id_nsr, _ = self.nsrTopic.new(
2250 rollback, session, indata_ns, kwargs, headers
2251 )
2252 nsrs_item = {
2253 "nsrId": _id_nsr,
2254 "shared": service.get("is-shared-nss"),
2255 "nsd-id": service["nsd-ref"],
2256 "nss-id": service["id"],
2257 "nslcmop_instantiate": None,
2258 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002259 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002260 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002261 nsi_netslice_subnet.append(indata_ns)
2262 nsr_ref = {"nsr-ref": _id_nsr}
2263 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002264
2265 # Adding the nsrs list to the nsi
2266 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002267 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002268 self.db.set_one(
2269 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2270 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002271
Felipe Vicens07f31722018-10-29 15:16:44 +01002272 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002273 self.db.create("nsis", nsi_descriptor)
2274 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002275 return nsi_id, None
garciadeblas4568a372021-03-24 09:19:48 +01002276 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2277 self.logger.exception(
2278 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2279 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002280 raise EngineException("Error {}: {}".format(step, e))
2281 except ValidationError as e:
2282 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2283
tierno65ca36d2019-02-12 19:27:52 +01002284 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002285 raise EngineException(
2286 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2287 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002288
2289
2290class NsiLcmOpTopic(BaseTopic):
2291 topic = "nsilcmops"
2292 topic_msg = "nsi"
2293 operation_schema = { # mapping between operation and jsonschema to validate
2294 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002295 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002296 }
garciadeblas4568a372021-03-24 09:19:48 +01002297
delacruzramo32bab472019-09-13 12:24:22 +02002298 def __init__(self, db, fs, msg, auth):
2299 BaseTopic.__init__(self, db, fs, msg, auth)
2300 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002301
2302 def _check_nsi_operation(self, session, nsir, operation, indata):
2303 """
2304 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002305 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002306 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2307 :param indata: descriptor with the parameters of the operation
2308 :return: None
2309 """
2310 nsds = {}
2311 nstd = nsir["network-slice-template"]
2312
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002313 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002314 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002315 for netslice_subnet in nstd["netslice-subnet"]:
2316 if nstId == netslice_subnet["id"]:
2317 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002318 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002319 _filter = self._get_project_filter(session)
2320 _filter["id"] = nsd_id
2321 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002322 return nsds[nsd_id]
2323 else:
garciadeblas4568a372021-03-24 09:19:48 +01002324 raise EngineException(
2325 "Invalid parameter nstId='{}' is not one of the "
2326 "nst:netslice-subnet".format(nstId)
2327 )
2328
Felipe Vicens07f31722018-10-29 15:16:44 +01002329 if operation == "instantiate":
2330 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002331 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002332 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002333
2334 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2335 now = time()
2336 _id = str(uuid4())
2337 nsilcmop = {
2338 "id": _id,
2339 "_id": _id,
2340 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2341 "statusEnteredTime": now,
2342 "netsliceInstanceId": netsliceInstanceId,
2343 "lcmOperationType": operation,
2344 "startTime": now,
2345 "isAutomaticInvocation": False,
2346 "operationParams": params,
2347 "isCancelPending": False,
2348 "links": {
2349 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002350 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2351 + netsliceInstanceId,
2352 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002353 }
2354 return nsilcmop
2355
Felipe Vicens09e65422019-01-22 15:06:46 +01002356 def add_shared_nsr_2vld(self, nsir, nsr_item):
2357 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2358 if nst_sb_item.get("is-shared-nss"):
2359 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2360 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2361 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002362 for admin_vld_nss_cp_ref_item in admin_vld_item[
2363 "nss-connection-point-ref"
2364 ]:
2365 if (
2366 admin_subnet_item["nss-id"]
2367 == admin_vld_nss_cp_ref_item["nss-ref"]
2368 ):
2369 if (
2370 not nsr_item["nsrId"]
2371 in admin_vld_item["shared-nsrs-list"]
2372 ):
2373 admin_vld_item["shared-nsrs-list"].append(
2374 nsr_item["nsrId"]
2375 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002376 break
2377 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002378 self.db.set_one(
2379 "nsis",
2380 {"_id": nsir["_id"]},
2381 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2382 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002383
tierno65ca36d2019-02-12 19:27:52 +01002384 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002385 """
2386 Performs a new operation over a ns
2387 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002388 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002389 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002390 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002391 operation: it can be: instantiate, terminate, action, TODO: update, heal
2392 :param kwargs: used to override the indata descriptor
2393 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002394 :return: id of the nslcmops
2395 """
2396 try:
2397 # Override descriptor with query string kwargs
2398 self._update_input_with_kwargs(indata, kwargs)
2399 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002400 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002401 validate_input(indata, self.operation_schema[operation])
2402
Felipe Vicens126af572019-06-05 19:13:04 +02002403 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002404 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002405 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002406 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002407 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002408 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002409
2410 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002411 if (
2412 not nsir["_admin"].get("nsiState")
2413 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2414 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002415 if operation == "terminate" and indata.get("autoremove"):
2416 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002417 return (
2418 None,
2419 None,
2420 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002421 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002422 raise EngineException(
2423 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2424 netsliceInstanceId, operation
2425 ),
2426 HTTPStatus.CONFLICT,
2427 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002428 else:
tierno65ca36d2019-02-12 19:27:52 +01002429 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002430 raise EngineException(
2431 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2432 netsliceInstanceId, operation
2433 ),
2434 HTTPStatus.CONFLICT,
2435 )
2436
Felipe Vicens07f31722018-10-29 15:16:44 +01002437 # Creating all the NS_operation (nslcmop)
2438 # Get service list from db
2439 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2440 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002441 # nslcmops_item = None
2442 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002443 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002444 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002445 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002446 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002447 _filter[
2448 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2449 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002450 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002451 nsi = self.db.get_one(
2452 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2453 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002454 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002455 _update = {
2456 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2457 index
2458 ): None
2459 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002460 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002461 if (
2462 nsi
2463 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002464 continue # do not create nsilcmop
2465 else: # instantiate
2466 # looks the first nsi fulfilling the conditions but not being the current NSIR
2467 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002468 nsi_nsr_item = next(
2469 n
2470 for n in nsi["_admin"]["nsrs-detailed-list"]
2471 if n["nsrId"] == nsr_id
2472 and n["shared"]
2473 and n["nslcmop_instantiate"]
2474 )
tierno40f742b2020-06-23 15:25:26 +00002475 self.add_shared_nsr_2vld(nsir, nsr_item)
2476 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002477 _update = {
2478 "_admin.nsrs-detailed-list.{}".format(
2479 index
2480 ): nsi_nsr_item
2481 }
tierno40f742b2020-06-23 15:25:26 +00002482 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2483 # continue to not create nslcmop since nsrs is shared and nsrs was created
2484 continue
2485 else:
2486 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002487
tierno40f742b2020-06-23 15:25:26 +00002488 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002489 try:
tierno0b8752f2020-05-12 09:42:02 +00002490 indata_ns = {
2491 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002492 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002493 # Including netslice_id in the ns instantiate Operation
2494 "netsliceInstanceId": netsliceInstanceId,
2495 }
2496 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002497 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002498 indata_ns.update(service["instantiate_params"])
2499
tierno99d4b172019-07-02 09:28:40 +00002500 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002501 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002502 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2503 rollback, session, indata_ns, None, headers, slice_object=True
2504 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002505 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002506 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002507 _update = {
2508 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2509 index
2510 ): nslcmop
2511 }
tierno40f742b2020-06-23 15:25:26 +00002512 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002513 except (DbException, EngineException) as e:
2514 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002515 self.logger.info(
2516 logging_prefix
2517 + "skipping NS={} because not found".format(nsr_id)
2518 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002519 pass
2520 else:
2521 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002522
2523 # Creates nsilcmop
2524 indata["nslcmops_ids"] = nslcmops
2525 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002526
garciadeblas4568a372021-03-24 09:19:48 +01002527 nsilcmop_desc = self._create_nsilcmop(
2528 session, netsliceInstanceId, operation, indata
2529 )
2530 self.format_on_new(
2531 nsilcmop_desc, session["project_id"], make_public=session["public"]
2532 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002533 _id = self.db.create("nsilcmops", nsilcmop_desc)
2534 rollback.append({"topic": "nsilcmops", "_id": _id})
2535 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002536 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002537 except ValidationError as e:
2538 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002539
tiernobee3bad2019-12-05 12:26:01 +00002540 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002541 raise EngineException(
2542 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2543 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002544
tierno65ca36d2019-02-12 19:27:52 +01002545 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002546 raise EngineException(
2547 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2548 )