blob: ece55b2d6aa47e4447622e976497e0bcf3561c74 [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"]
garciaale7cbd03c2020-11-27 10:38:35 -0300481 # Create vld
482 if nsd.get("virtual-link-desc"):
483 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
484 # Fill each vld with vnfd-connection-point-ref data
485 # TODO: Change for multiple df support
486 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
487 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
488 for vnf_profile in vnf_profiles:
489 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
490 for cpd in vlc.get("constituent-cpd-id", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100491 all_vld_connection_point_data[
492 vlc.get("virtual-link-profile-id")
493 ].append(
494 {
495 "member-vnf-index-ref": cpd.get(
496 "constituent-base-element-id"
497 ),
498 "vnfd-connection-point-ref": cpd.get(
499 "constituent-cpd-id"
500 ),
501 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
502 }
503 )
garciaale7cbd03c2020-11-27 10:38:35 -0300504
bravofe76b8822021-02-26 16:57:52 -0300505 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
garciaale7cbd03c2020-11-27 10:38:35 -0300506
507 for vdu in vnfd.get("vdu", ()):
508 flavor_data = {}
509 guest_epa = {}
510 # Find this vdu compute and storage descriptors
511 vdu_virtual_compute = {}
512 vdu_virtual_storage = {}
513 for vcd in vnfd.get("virtual-compute-desc", ()):
514 if vcd.get("id") == vdu.get("virtual-compute-desc"):
515 vdu_virtual_compute = vcd
516 for vsd in vnfd.get("virtual-storage-desc", ()):
517 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
518 vdu_virtual_storage = vsd
519 # Get this vdu vcpus, memory and storage info for flavor_data
garciadeblas4568a372021-03-24 09:19:48 +0100520 if vdu_virtual_compute.get("virtual-cpu", {}).get(
521 "num-virtual-cpu"
522 ):
523 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
524 "num-virtual-cpu"
525 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300526 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
garciadeblas4568a372021-03-24 09:19:48 +0100527 flavor_data["memory-mb"] = (
528 float(vdu_virtual_compute["virtual-memory"]["size"])
529 * 1024.0
530 )
garciaale7cbd03c2020-11-27 10:38:35 -0300531 if vdu_virtual_storage.get("size-of-storage"):
garciadeblas4568a372021-03-24 09:19:48 +0100532 flavor_data["storage-gb"] = vdu_virtual_storage[
533 "size-of-storage"
534 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300535 # Get this vdu EPA info for guest_epa
536 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100537 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
538 "cpu-quota"
539 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300540 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
541 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
542 if vcpu_pinning.get("thread-policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100543 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
544 "thread-policy"
545 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300546 if vcpu_pinning.get("policy"):
garciadeblas4568a372021-03-24 09:19:48 +0100547 cpu_policy = (
548 "SHARED"
549 if vcpu_pinning["policy"] == "dynamic"
550 else "DEDICATED"
551 )
garciaale7cbd03c2020-11-27 10:38:35 -0300552 guest_epa["cpu-pinning-policy"] = cpu_policy
553 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100554 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
555 "mem-quota"
556 ]
557 if vdu_virtual_compute.get("virtual-memory", {}).get(
558 "mempage-size"
559 ):
560 guest_epa["mempage-size"] = vdu_virtual_compute[
561 "virtual-memory"
562 ]["mempage-size"]
563 if vdu_virtual_compute.get("virtual-memory", {}).get(
564 "numa-node-policy"
565 ):
566 guest_epa["numa-node-policy"] = vdu_virtual_compute[
567 "virtual-memory"
568 ]["numa-node-policy"]
garciaale7cbd03c2020-11-27 10:38:35 -0300569 if vdu_virtual_storage.get("disk-io-quota"):
garciadeblas4568a372021-03-24 09:19:48 +0100570 guest_epa["disk-io-quota"] = vdu_virtual_storage[
571 "disk-io-quota"
572 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300573
574 if guest_epa:
575 flavor_data["guest-epa"] = guest_epa
576
577 flavor_data["name"] = vdu["id"][:56] + "-flv"
578 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
579 nsr_descriptor["flavor"].append(flavor_data)
580
581 sw_image_id = vdu.get("sw-image-desc")
582 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000583 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
584 self._add_image_to_nsr(nsr_descriptor, image_data)
585
586 # also add alternative images to the list of images
587 for alt_image in vdu.get("alternative-sw-image-desc", ()):
588 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
589 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300590
591 for vld in nsr_vld:
garciadeblas4568a372021-03-24 09:19:48 +0100592 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
593 vld.get("id"), []
594 )
garciaale7cbd03c2020-11-27 10:38:35 -0300595 vld["name"] = vld["id"]
596 nsr_descriptor["vld"] = nsr_vld
597
598 return nsr_descriptor
599
lloretgalleg28c13b62021-02-08 11:48:48 +0000600 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
garciadeblas4568a372021-03-24 09:19:48 +0100601 sw_image_desc = utils.find_in_list(
602 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
603 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000604 image_data = {}
605 if sw_image_desc.get("image"):
606 image_data["image"] = sw_image_desc["image"]
607 if sw_image_desc.get("checksum"):
608 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
609 if sw_image_desc.get("vim-type"):
610 image_data["vim-type"] = sw_image_desc["vim-type"]
611 return image_data
612
613 def _add_image_to_nsr(self, nsr_descriptor, image_data):
614 """
615 Adds image to nsr checking first it is not already added
616 """
garciadeblas4568a372021-03-24 09:19:48 +0100617 img = next(
618 (
619 f
620 for f in nsr_descriptor["image"]
621 if all(f.get(k) == image_data[k] for k in image_data)
622 ),
623 None,
624 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000625 if not img:
626 image_data["id"] = str(len(nsr_descriptor["image"]))
627 nsr_descriptor["image"].append(image_data)
628
garciadeblas4568a372021-03-24 09:19:48 +0100629 def _create_vnfr_descriptor_from_vnfd(
630 self,
631 nsd,
632 vnfd,
633 vnfd_id,
634 vnf_index,
635 nsr_descriptor,
636 ns_request,
637 ns_k8s_namespace,
638 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300639 vnfr_id = str(uuid4())
640 nsr_id = nsr_descriptor["id"]
641 now = time()
garciadeblas4568a372021-03-24 09:19:48 +0100642 additional_params, vnf_params = self._format_additional_params(
643 ns_request, vnf_index, descriptor=vnfd
644 )
garciaale7cbd03c2020-11-27 10:38:35 -0300645
646 vnfr_descriptor = {
647 "id": vnfr_id,
648 "_id": vnfr_id,
649 "nsr-id-ref": nsr_id,
650 "member-vnf-index-ref": vnf_index,
651 "additionalParamsForVnf": additional_params,
652 "created-time": now,
653 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
654 "vnfd-ref": vnfd_id,
655 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
656 "vim-account-id": None,
David Garciaecb41322021-03-31 19:10:46 +0200657 "vca-id": None,
garciaale7cbd03c2020-11-27 10:38:35 -0300658 "vdur": [],
659 "connection-point": [],
660 "ip-address": None, # mgmt-interface filled by LCM
661 }
662 vnf_k8s_namespace = ns_k8s_namespace
663 if vnf_params:
664 if vnf_params.get("k8s-namespace"):
665 vnf_k8s_namespace = vnf_params["k8s-namespace"]
666 if vnf_params.get("config-units"):
667 vnfr_descriptor["config-units"] = vnf_params["config-units"]
668
669 # Create vld
670 if vnfd.get("int-virtual-link-desc"):
671 vnfr_descriptor["vld"] = []
672 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
673 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
674
675 for cp in vnfd.get("ext-cpd", ()):
676 vnf_cp = {
677 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100678 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
679 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300680 "id": cp.get("id"),
681 # "ip-address", "mac-address" # filled by LCM
682 # vim-id # TODO it would be nice having a vim port id
683 }
684 vnfr_descriptor["connection-point"].append(vnf_cp)
685
686 # Create k8s-cluster information
687 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
688 if vnfd.get("k8s-cluster"):
689 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
690 all_k8s_cluster_nets_cpds = {}
691 for cpd in get_iterable(vnfd.get("ext-cpd")):
692 if cpd.get("k8s-cluster-net"):
garciadeblas4568a372021-03-24 09:19:48 +0100693 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
694 "id"
695 )
garciaale7cbd03c2020-11-27 10:38:35 -0300696 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
697 if net.get("id") in all_k8s_cluster_nets_cpds:
garciadeblas4568a372021-03-24 09:19:48 +0100698 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
699 net.get("id")
700 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300701
702 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300703 for kdu in get_iterable(vnfd.get("kdu")):
garciadeblas4568a372021-03-24 09:19:48 +0100704 additional_params, kdu_params = self._format_additional_params(
705 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
706 )
garciaale7cbd03c2020-11-27 10:38:35 -0300707 kdu_k8s_namespace = vnf_k8s_namespace
708 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
709 if kdu_params and kdu_params.get("k8s-namespace"):
710 kdu_k8s_namespace = kdu_params["k8s-namespace"]
romeromonserc47d0452021-05-28 11:44:53 +0200711 kdu_deployment_name = ""
712 if kdu_params and kdu_params.get("kdu-deployment-name"):
713 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
garciaale7cbd03c2020-11-27 10:38:35 -0300714
715 kdur = {
716 "additionalParams": additional_params,
717 "k8s-namespace": kdu_k8s_namespace,
romeromonserc47d0452021-05-28 11:44:53 +0200718 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000719 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300720 # TODO "name": "" Name of the VDU in the VIM
721 "ip-address": None, # mgmt-interface filled by LCM
722 "k8s-cluster": {},
723 }
724 if kdu_params and kdu_params.get("config-units"):
725 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000726 if kdu.get("helm-version"):
727 kdur["helm-version"] = kdu["helm-version"]
728 for k8s_type in ("helm-chart", "juju-bundle"):
729 if kdu.get(k8s_type):
730 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300731 if not vnfr_descriptor.get("kdur"):
732 vnfr_descriptor["kdur"] = []
733 vnfr_descriptor["kdur"].append(kdur)
734
735 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300736
garciaale7cbd03c2020-11-27 10:38:35 -0300737 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300738 vdu_mgmt_cp = []
739 try:
garciadeblas4568a372021-03-24 09:19:48 +0100740 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
741 "operate-vnf-op-config"
742 ]["day1-2"]
743 vdu_config = utils.find_in_list(
744 configs, lambda config: config["id"] == vdu["id"]
745 )
bravoff3c39552021-02-24 17:22:24 -0300746 except Exception:
747 vdu_config = None
bravof4ca51522021-04-22 10:03:02 -0400748
749 try:
750 vdu_instantiation_level = utils.find_in_list(
751 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
garciadeblas4568a372021-03-24 09:19:48 +0100752 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
bravof4ca51522021-04-22 10:03:02 -0400753 )
754 except Exception:
755 vdu_instantiation_level = None
756
bravoff3c39552021-02-24 17:22:24 -0300757 if vdu_config:
758 external_connection_ee = utils.filter_in_list(
759 vdu_config.get("execution-environment-list", []),
garciadeblas4568a372021-03-24 09:19:48 +0100760 lambda ee: "external-connection-point-ref" in ee,
bravoff3c39552021-02-24 17:22:24 -0300761 )
762 for ee in external_connection_ee:
763 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
764
garciaale7cbd03c2020-11-27 10:38:35 -0300765 additional_params, vdu_params = self._format_additional_params(
garciadeblas4568a372021-03-24 09:19:48 +0100766 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
767 )
bravof75fbedc2021-11-10 17:58:58 -0300768
769 try:
770 vdu_virtual_storage_descriptors = utils.filter_in_list(
771 vnfd.get("virtual-storage-desc", []),
772 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
773 )
774 except Exception:
775 vdu_virtual_storage_descriptors = []
garciaale7cbd03c2020-11-27 10:38:35 -0300776 vdur = {
777 "vdu-id-ref": vdu["id"],
778 # TODO "name": "" Name of the VDU in the VIM
779 "ip-address": None, # mgmt-interface filled by LCM
780 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
781 "internal-connection-point": [],
782 "interfaces": [],
783 "additionalParams": additional_params,
garciadeblas4568a372021-03-24 09:19:48 +0100784 "vdu-name": vdu["name"],
bravof75fbedc2021-11-10 17:58:58 -0300785 "virtual-storages": vdu_virtual_storage_descriptors
garciaale7cbd03c2020-11-27 10:38:35 -0300786 }
787 if vdu_params and vdu_params.get("config-units"):
788 vdur["config-units"] = vdu_params["config-units"]
789 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
garciadeblas4568a372021-03-24 09:19:48 +0100790 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
791 "boot-data-drive"
792 ]
garciaale7cbd03c2020-11-27 10:38:35 -0300793 if vdu.get("pdu-type"):
794 vdur["pdu-type"] = vdu["pdu-type"]
795 vdur["name"] = vdu["pdu-type"]
796 # TODO volumes: name, volume-id
797 for icp in vdu.get("int-cpd", ()):
798 vdu_icp = {
799 "id": icp["id"],
800 "connection-point-id": icp["id"],
801 "name": icp.get("id"),
802 }
bravof35766442021-02-04 14:58:04 -0300803
garciaale7cbd03c2020-11-27 10:38:35 -0300804 vdur["internal-connection-point"].append(vdu_icp)
805
806 for iface in icp.get("virtual-network-interface-requirement", ()):
807 iface_fields = ("name", "mac-address")
garciadeblas4568a372021-03-24 09:19:48 +0100808 vdu_iface = {
809 x: iface[x] for x in iface_fields if iface.get(x) is not None
810 }
garciaale7cbd03c2020-11-27 10:38:35 -0300811
812 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu003844e2021-03-02 00:19:15 +0100813 if "port-security-enabled" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100814 vdu_iface["port-security-enabled"] = icp[
815 "port-security-enabled"
816 ]
sousaedu003844e2021-03-02 00:19:15 +0100817
818 if "port-security-disable-strategy" in icp:
garciadeblas4568a372021-03-24 09:19:48 +0100819 vdu_iface["port-security-disable-strategy"] = icp[
820 "port-security-disable-strategy"
821 ]
sousaedu003844e2021-03-02 00:19:15 +0100822
garciaale7cbd03c2020-11-27 10:38:35 -0300823 for ext_cp in vnfd.get("ext-cpd", ()):
824 if not ext_cp.get("int-cpd"):
825 continue
826 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
827 continue
828 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
garciadeblas4568a372021-03-24 09:19:48 +0100829 vdu_iface["external-connection-point-ref"] = ext_cp.get(
830 "id"
831 )
sousaedu003844e2021-03-02 00:19:15 +0100832
833 if "port-security-enabled" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100834 vdu_iface["port-security-enabled"] = ext_cp[
835 "port-security-enabled"
836 ]
sousaedu003844e2021-03-02 00:19:15 +0100837
838 if "port-security-disable-strategy" in ext_cp:
garciadeblas4568a372021-03-24 09:19:48 +0100839 vdu_iface["port-security-disable-strategy"] = ext_cp[
840 "port-security-disable-strategy"
841 ]
sousaedu003844e2021-03-02 00:19:15 +0100842
garciaale7cbd03c2020-11-27 10:38:35 -0300843 break
844
garciadeblas4568a372021-03-24 09:19:48 +0100845 if (
846 vnfd_mgmt_cp
847 and vdu_iface.get("external-connection-point-ref")
848 == vnfd_mgmt_cp
849 ):
garciaale7cbd03c2020-11-27 10:38:35 -0300850 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300851 vdu_iface["mgmt-interface"] = True
852
853 for ecp in vdu_mgmt_cp:
854 if vdu_iface.get("external-connection-point-ref") == ecp:
855 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300856
857 if iface.get("virtual-interface"):
858 vdu_iface.update(deepcopy(iface["virtual-interface"]))
859
860 # look for network where this interface is connected
861 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
862 if iface_ext_cp:
863 # TODO: Change for multiple df support
864 for df in get_iterable(nsd.get("df")):
865 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas4568a372021-03-24 09:19:48 +0100866 for vlc_index, vlc in enumerate(
867 get_iterable(
868 vnf_profile.get("virtual-link-connectivity")
869 )
870 ):
871 for cpd in get_iterable(
872 vlc.get("constituent-cpd-id")
873 ):
874 if (
875 cpd.get("constituent-cpd-id")
876 == iface_ext_cp
877 ):
878 vdu_iface["ns-vld-id"] = vlc.get(
879 "virtual-link-profile-id"
880 )
garciadeblas61c95912021-02-12 11:23:50 +0000881 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
garciadeblas4568a372021-03-24 09:19:48 +0100882 if vdu_iface.get("type") in (
883 "SR-IOV",
884 "PCI-PASSTHROUGH",
885 ):
886 nsr_descriptor["vld"][vlc_index][
887 "pci-interfaces"
888 ] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300889 break
890 elif vdu_iface.get("internal-connection-point-ref"):
891 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000892 # TODO: store fixed IP address in the record (if it exists in the ICP)
893 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
894 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
garciadeblas4568a372021-03-24 09:19:48 +0100895 ivld_index = utils.find_index_in_list(
896 vnfd.get("int-virtual-link-desc", ()),
897 lambda ivld: ivld["id"]
898 == icp.get("int-virtual-link-desc"),
899 )
garciadeblas61c95912021-02-12 11:23:50 +0000900 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300901
902 vdur["interfaces"].append(vdu_iface)
903
904 if vdu.get("sw-image-desc"):
905 sw_image = utils.find_in_list(
906 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100907 lambda image: image["id"] == vdu.get("sw-image-desc"),
908 )
garciaale7cbd03c2020-11-27 10:38:35 -0300909 nsr_sw_image_data = utils.find_in_list(
910 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100911 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
garciaale7cbd03c2020-11-27 10:38:35 -0300912 )
913 vdur["ns-image-id"] = nsr_sw_image_data["id"]
914
lloretgalleg28c13b62021-02-08 11:48:48 +0000915 if vdu.get("alternative-sw-image-desc"):
916 alt_image_ids = []
917 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
918 sw_image = utils.find_in_list(
919 vnfd.get("sw-image-desc", ()),
garciadeblas4568a372021-03-24 09:19:48 +0100920 lambda image: image["id"] == alt_image_id,
921 )
lloretgalleg28c13b62021-02-08 11:48:48 +0000922 nsr_sw_image_data = utils.find_in_list(
923 nsr_descriptor["image"],
garciadeblas4568a372021-03-24 09:19:48 +0100924 lambda nsr_image: (
925 nsr_image.get("image") == sw_image.get("image")
926 ),
lloretgalleg28c13b62021-02-08 11:48:48 +0000927 )
928 alt_image_ids.append(nsr_sw_image_data["id"])
929 vdur["alt-image-ids"] = alt_image_ids
930
garciaale7cbd03c2020-11-27 10:38:35 -0300931 flavor_data_name = vdu["id"][:56] + "-flv"
932 nsr_flavor_desc = utils.find_in_list(
933 nsr_descriptor["flavor"],
garciadeblas4568a372021-03-24 09:19:48 +0100934 lambda flavor: flavor["name"] == flavor_data_name,
935 )
garciaale7cbd03c2020-11-27 10:38:35 -0300936
937 if nsr_flavor_desc:
938 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
939
bravof4ca51522021-04-22 10:03:02 -0400940 if vdu_instantiation_level:
941 count = vdu_instantiation_level.get("number-of-instances")
942 else:
943 count = 1
944
garciaale7cbd03c2020-11-27 10:38:35 -0300945 for index in range(0, count):
946 vdur = deepcopy(vdur)
947 for iface in vdur["interfaces"]:
bravofe91ee2a2021-07-01 09:32:30 -0400948 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -0300949 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofe91ee2a2021-07-01 09:32:30 -0400950 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -0300951 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
952
953 vdur["_id"] = str(uuid4())
954 vdur["id"] = vdur["_id"]
955 vdur["count-index"] = index
956 vnfr_descriptor["vdur"].append(vdur)
957
958 return vnfr_descriptor
959
K Sai Kiran57589552021-01-27 21:38:34 +0530960 def vca_status_refresh(self, session, ns_instance_content, filter_q):
961 """
962 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
963 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
964 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
965 :param ns_instance_content: ns instance content
966 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
967 :return: None
968 """
969 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
970 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
971 threshold_reached = time_delta > 120
972 if force_refresh or threshold_reached:
973 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
974 ns_instance_content["_admin"]["modified"] = time_now
975 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
976 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
977 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
978 nslcmop_desc["_admin"].pop("nsState")
979 self.msg.write("ns", operation, nslcmop_desc)
980 return
981
982 def show(self, session, _id, filter_q=None, api_req=False):
983 """
984 Get complete information on an ns instance.
985 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
986 :param _id: string, ns instance id
987 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
988 :param api_req: True if this call is serving an external API request. False if serving internal request.
989 :return: dictionary, raise exception if not found.
990 """
991 ns_instance_content = super().show(session, _id, api_req)
992 self.vca_status_refresh(session, ns_instance_content, filter_q)
993 return ns_instance_content
994
tierno65ca36d2019-02-12 19:27:52 +0100995 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +0100996 raise EngineException(
997 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
998 )
tiernob24258a2018-10-04 18:39:49 +0200999
1000
1001class VnfrTopic(BaseTopic):
1002 topic = "vnfrs"
1003 topic_msg = None
1004
delacruzramo32bab472019-09-13 12:24:22 +02001005 def __init__(self, db, fs, msg, auth):
1006 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001007
tiernobee3bad2019-12-05 12:26:01 +00001008 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01001009 raise EngineException(
1010 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1011 )
tiernob24258a2018-10-04 18:39:49 +02001012
tierno65ca36d2019-02-12 19:27:52 +01001013 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01001014 raise EngineException(
1015 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1016 )
tiernob24258a2018-10-04 18:39:49 +02001017
tierno65ca36d2019-02-12 19:27:52 +01001018 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +02001019 # Not used because vnfrs are created and deleted by NsrTopic class directly
garciadeblas4568a372021-03-24 09:19:48 +01001020 raise EngineException(
1021 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1022 )
tiernob24258a2018-10-04 18:39:49 +02001023
1024
1025class NsLcmOpTopic(BaseTopic):
1026 topic = "nslcmops"
1027 topic_msg = "ns"
garciadeblas4568a372021-03-24 09:19:48 +01001028 operation_schema = { # mapping between operation and jsonschema to validate
tiernob24258a2018-10-04 18:39:49 +02001029 "instantiate": ns_instantiate,
1030 "action": ns_action,
1031 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +00001032 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +02001033 }
1034
delacruzramo32bab472019-09-13 12:24:22 +02001035 def __init__(self, db, fs, msg, auth):
1036 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +02001037
tiernob24258a2018-10-04 18:39:49 +02001038 def _check_ns_operation(self, session, nsr, operation, indata):
1039 """
1040 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001041 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001042 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1043 :param indata: descriptor with the parameters of the operation
1044 :return: None
1045 """
garciaale7cbd03c2020-11-27 10:38:35 -03001046 if operation == "action":
1047 self._check_action_ns_operation(indata, nsr)
1048 elif operation == "scale":
1049 self._check_scale_ns_operation(indata, nsr)
1050 elif operation == "instantiate":
1051 self._check_instantiate_ns_operation(indata, nsr, session)
1052
1053 def _check_action_ns_operation(self, indata, nsr):
1054 nsd = nsr["nsd"]
1055 # check vnf_member_index
1056 if indata.get("vnf_member_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001057 indata["member_vnf_index"] = indata.pop(
1058 "vnf_member_index"
1059 ) # for backward compatibility
garciaale7cbd03c2020-11-27 10:38:35 -03001060 if indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001061 vnfd = self._get_vnfd_from_vnf_member_index(
1062 indata["member_vnf_index"], nsr["_id"]
1063 )
bravof41a52052021-02-17 18:08:01 -03001064 try:
garciadeblas4568a372021-03-24 09:19:48 +01001065 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1066 "operate-vnf-op-config"
1067 ]["day1-2"]
bravof41a52052021-02-17 18:08:01 -03001068 except Exception:
1069 configs = []
1070
garciaale7cbd03c2020-11-27 10:38:35 -03001071 if indata.get("vdu_id"):
1072 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -03001073 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001074 configs, lambda config: config["id"] == indata["vdu_id"]
limon9b33fa82021-03-17 13:24:00 +01001075 )
garciaale7cbd03c2020-11-27 10:38:35 -03001076 elif indata.get("kdu_name"):
1077 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -03001078 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001079 configs, lambda config: config["id"] == indata.get("kdu_name")
limon9b33fa82021-03-17 13:24:00 +01001080 )
garciaale7cbd03c2020-11-27 10:38:35 -03001081 else:
bravof41a52052021-02-17 18:08:01 -03001082 descriptor_configuration = utils.find_in_list(
garciadeblas4568a372021-03-24 09:19:48 +01001083 configs, lambda config: config["id"] == vnfd["id"]
limon9b33fa82021-03-17 13:24:00 +01001084 )
1085 if descriptor_configuration is not None:
garciadeblas4568a372021-03-24 09:19:48 +01001086 descriptor_configuration = descriptor_configuration.get(
1087 "config-primitive"
1088 )
garciaale7cbd03c2020-11-27 10:38:35 -03001089 else: # use a NSD
garciadeblas4568a372021-03-24 09:19:48 +01001090 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1091 "config-primitive"
1092 )
garciaale7cbd03c2020-11-27 10:38:35 -03001093
1094 # For k8s allows default primitives without validating the parameters
garciadeblas4568a372021-03-24 09:19:48 +01001095 if indata.get("kdu_name") and indata["primitive"] in (
1096 "upgrade",
1097 "rollback",
1098 "status",
1099 "inspect",
1100 "readme",
1101 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001102 # TODO should be checked that rollback only can contains revsision_numbe????
1103 if not indata.get("member_vnf_index"):
garciadeblas4568a372021-03-24 09:19:48 +01001104 raise EngineException(
1105 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1106 indata["primitive"]
1107 )
1108 )
garciaale7cbd03c2020-11-27 10:38:35 -03001109 return
1110 # if not, check primitive
1111 for config_primitive in get_iterable(descriptor_configuration):
1112 if indata["primitive"] == config_primitive["name"]:
1113 # check needed primitive_params are provided
1114 if indata.get("primitive_params"):
1115 in_primitive_params_copy = copy(indata["primitive_params"])
1116 else:
1117 in_primitive_params_copy = {}
1118 for paramd in get_iterable(config_primitive.get("parameter")):
1119 if paramd["name"] in in_primitive_params_copy:
1120 del in_primitive_params_copy[paramd["name"]]
1121 elif not paramd.get("default-value"):
garciadeblas4568a372021-03-24 09:19:48 +01001122 raise EngineException(
1123 "Needed parameter {} not provided for primitive '{}'".format(
1124 paramd["name"], indata["primitive"]
1125 )
1126 )
garciaale7cbd03c2020-11-27 10:38:35 -03001127 # check no extra primitive params are provided
1128 if in_primitive_params_copy:
garciadeblas4568a372021-03-24 09:19:48 +01001129 raise EngineException(
1130 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1131 list(in_primitive_params_copy.keys()), indata["primitive"]
1132 )
1133 )
garciaale7cbd03c2020-11-27 10:38:35 -03001134 break
1135 else:
garciadeblas4568a372021-03-24 09:19:48 +01001136 raise EngineException(
1137 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1138 indata["primitive"]
1139 )
1140 )
garciaale7cbd03c2020-11-27 10:38:35 -03001141
1142 def _check_scale_ns_operation(self, indata, nsr):
garciadeblas4568a372021-03-24 09:19:48 +01001143 vnfd = self._get_vnfd_from_vnf_member_index(
1144 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1145 )
lloretgallegdf9fd612020-12-01 12:51:52 +00001146 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
garciadeblas4568a372021-03-24 09:19:48 +01001147 if (
1148 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1149 == scaling_aspect["id"]
1150 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001151 break
1152 else:
garciadeblas4568a372021-03-24 09:19:48 +01001153 raise EngineException(
1154 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1155 "present at vnfd:scaling-aspect".format(
1156 indata["scaleVnfData"]["scaleByStepData"][
1157 "scaling-group-descriptor"
1158 ]
1159 )
1160 )
garciaale7cbd03c2020-11-27 10:38:35 -03001161
1162 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +00001163 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +02001164 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +00001165 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +02001166 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -03001167 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1168 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1169 for in_vnf in get_iterable(indata.get("vnf")):
1170 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +00001171 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -03001172 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +00001173 else:
garciadeblas4568a372021-03-24 09:19:48 +01001174 vnfd = self._get_vnfd_from_vnf_member_index(
1175 member_vnf_index, nsr["_id"]
1176 )
1177 vnf_member_index_to_vnfd[
1178 member_vnf_index
1179 ] = vnfd # add to cache, avoiding a later look for
garciaale7cbd03c2020-11-27 10:38:35 -03001180 self._check_vnf_instantiation_params(in_vnf, vnfd)
1181 if in_vnf.get("vimAccountId"):
garciadeblas4568a372021-03-24 09:19:48 +01001182 self._check_valid_vim_account(
1183 in_vnf["vimAccountId"], vim_accounts, session
1184 )
tierno260dd6f2019-09-02 10:48:56 +00001185
garciaale7cbd03c2020-11-27 10:38:35 -03001186 for in_vld in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001187 self._check_valid_wim_account(
1188 in_vld.get("wimAccountId"), wim_accounts, session
1189 )
garciaale7cbd03c2020-11-27 10:38:35 -03001190 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1191 if in_vld["name"] == vldd["id"]:
1192 break
tierno9cb7d672019-10-30 12:13:48 +00001193 else:
garciadeblas4568a372021-03-24 09:19:48 +01001194 raise EngineException(
1195 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1196 in_vld["name"]
1197 )
1198 )
tierno9cb7d672019-10-30 12:13:48 +00001199
garciaale7cbd03c2020-11-27 10:38:35 -03001200 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1201 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
garciadeblas4568a372021-03-24 09:19:48 +01001202 vnfr = self.db.get_one(
1203 "vnfrs",
1204 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1205 fail_on_empty=False,
1206 )
garciaale7cbd03c2020-11-27 10:38:35 -03001207 if not vnfr:
garciadeblas4568a372021-03-24 09:19:48 +01001208 raise EngineException(
1209 "Invalid parameter member_vnf_index='{}' is not one of the "
1210 "nsd:constituent-vnfd".format(member_vnf_index)
1211 )
garciaale7cbd03c2020-11-27 10:38:35 -03001212 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1213 if not vnfd:
garciadeblas4568a372021-03-24 09:19:48 +01001214 raise EngineException(
1215 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1216 vnfr["vnfd-id"]
1217 )
1218 )
garciaale7cbd03c2020-11-27 10:38:35 -03001219 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +02001220
garciaale7cbd03c2020-11-27 10:38:35 -03001221 def _check_valid_vdu(self, vnfd, vdu_id):
1222 for vdud in get_iterable(vnfd.get("vdu")):
1223 if vdud["id"] == vdu_id:
1224 return vdud
1225 else:
garciadeblas4568a372021-03-24 09:19:48 +01001226 raise EngineException(
1227 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1228 vdu_id
1229 )
1230 )
garciaale7cbd03c2020-11-27 10:38:35 -03001231
1232 def _check_valid_kdu(self, vnfd, kdu_name):
1233 for kdud in get_iterable(vnfd.get("kdu")):
1234 if kdud["name"] == kdu_name:
1235 return kdud
1236 else:
garciadeblas4568a372021-03-24 09:19:48 +01001237 raise EngineException(
1238 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1239 kdu_name
1240 )
1241 )
garciaale7cbd03c2020-11-27 10:38:35 -03001242
1243 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1244 for in_vdu in get_iterable(in_vnf.get("vdu")):
1245 for vdu in get_iterable(vnfd.get("vdu")):
1246 if in_vdu["id"] == vdu["id"]:
1247 for volume in get_iterable(in_vdu.get("volume")):
1248 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1249 if volumed["id"] == volume["name"]:
1250 break
1251 else:
garciadeblas4568a372021-03-24 09:19:48 +01001252 raise EngineException(
1253 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1254 "volume:name='{}' is not present at "
1255 "vnfd:vdu:virtual-storage-desc list".format(
1256 in_vnf["member-vnf-index"],
1257 in_vdu["id"],
1258 volume["id"],
1259 )
1260 )
garciaale7cbd03c2020-11-27 10:38:35 -03001261
1262 vdu_if_names = set()
1263 for cpd in get_iterable(vdu.get("int-cpd")):
garciadeblas4568a372021-03-24 09:19:48 +01001264 for iface in get_iterable(
1265 cpd.get("virtual-network-interface-requirement")
1266 ):
garciaale7cbd03c2020-11-27 10:38:35 -03001267 vdu_if_names.add(iface.get("name"))
1268
1269 for in_iface in get_iterable(in_vdu["interface"]):
1270 if in_iface["name"] in vdu_if_names:
1271 break
1272 else:
garciadeblas4568a372021-03-24 09:19:48 +01001273 raise EngineException(
1274 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1275 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1276 in_vnf["member-vnf-index"],
1277 in_vdu["id"],
1278 in_iface["name"],
1279 )
1280 )
garciaale7cbd03c2020-11-27 10:38:35 -03001281 break
1282
1283 else:
garciadeblas4568a372021-03-24 09:19:48 +01001284 raise EngineException(
1285 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1286 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1287 )
garciaale7cbd03c2020-11-27 10:38:35 -03001288
garciadeblas4568a372021-03-24 09:19:48 +01001289 vnfd_ivlds_cpds = {
1290 ivld.get("id"): set()
1291 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1292 }
garciaale7cbd03c2020-11-27 10:38:35 -03001293 for vdu in get_iterable(vnfd.get("vdu")):
1294 for cpd in get_iterable(vnfd.get("int-cpd")):
1295 if cpd.get("int-virtual-link-desc"):
1296 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1297
1298 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1299 if in_ivld.get("name") in vnfd_ivlds_cpds:
1300 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1301 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +02001302 break
tiernob24258a2018-10-04 18:39:49 +02001303 else:
garciadeblas4568a372021-03-24 09:19:48 +01001304 raise EngineException(
1305 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1306 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1307 "vnfd:internal-vld:name/id:internal-connection-point".format(
1308 in_vnf["member-vnf-index"],
1309 in_ivld["name"],
1310 in_icp["id-ref"],
1311 )
1312 )
tiernob24258a2018-10-04 18:39:49 +02001313 else:
garciadeblas4568a372021-03-24 09:19:48 +01001314 raise EngineException(
1315 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1316 " is not present at vnfd '{}'".format(
1317 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1318 )
1319 )
tiernob24258a2018-10-04 18:39:49 +02001320
garciaale7cbd03c2020-11-27 10:38:35 -03001321 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1322 if vim_account in vim_accounts:
1323 return
1324 try:
1325 db_filter = self._get_project_filter(session)
1326 db_filter["_id"] = vim_account
1327 self.db.get_one("vim_accounts", db_filter)
1328 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001329 raise EngineException(
1330 "Invalid vimAccountId='{}' not present for the project".format(
1331 vim_account
1332 )
1333 )
garciaale7cbd03c2020-11-27 10:38:35 -03001334 vim_accounts.append(vim_account)
1335
David Garcia510aafa2021-10-13 17:14:01 +02001336 def _get_vim_account(self, vim_id: str, session):
1337 try:
1338 db_filter = self._get_project_filter(session)
1339 db_filter["_id"] = vim_id
1340 return self.db.get_one("vim_accounts", db_filter)
1341 except Exception:
1342 raise EngineException(
1343 "Invalid vimAccountId='{}' not present for the project".format(
1344 vim_id
1345 )
1346 )
1347
garciaale7cbd03c2020-11-27 10:38:35 -03001348 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1349 if not isinstance(wim_account, str):
1350 return
1351 if wim_account in wim_accounts:
1352 return
1353 try:
1354 db_filter = self._get_project_filter(session, write=False, show_all=True)
1355 db_filter["_id"] = wim_account
1356 self.db.get_one("wim_accounts", db_filter)
1357 except Exception:
garciadeblas4568a372021-03-24 09:19:48 +01001358 raise EngineException(
1359 "Invalid wimAccountId='{}' not present for the project".format(
1360 wim_account
1361 )
1362 )
garciaale7cbd03c2020-11-27 10:38:35 -03001363 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +02001364
garciadeblas4568a372021-03-24 09:19:48 +01001365 def _look_for_pdu(
1366 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1367 ):
tiernocc103432018-10-19 14:10:35 +02001368 """
tierno36ec8602018-11-02 17:27:11 +01001369 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1370 (ip_address, ...) information.
1371 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +01001372 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +01001373 :param rollback: list with the database modifications to rollback if needed
1374 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1375 :param vim_account: vim_account where this vnfr should be deployed
1376 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1377 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1378 of the changed vnfr is needed
1379
1380 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1381 "vim-network-name": used at VIM
1382 "name": interface name
1383 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1384 "ns-vld-id": NSD vld where this interface is connected.
1385 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 +02001386 """
tierno36ec8602018-11-02 17:27:11 +01001387
1388 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001389 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1390 if not vdur.get("pdu-type"):
1391 continue
1392 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001393 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001394 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001395 pdu_filter["type"] = pdu_type
1396 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001397 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001398 # TODO feature 1417: "shared": True,
1399
1400 available_pdus = self.db.get_list("pdus", pdu_filter)
1401 for pdu in available_pdus:
1402 # step 1 check if this pdu contains needed interfaces:
1403 match_interfaces = True
1404 for vdur_interface in vdur["interfaces"]:
1405 for pdu_interface in pdu["interfaces"]:
1406 if pdu_interface["name"] == vdur_interface["name"]:
1407 # TODO feature 1417: match per mgmt type
1408 break
1409 else: # no interface found for name
1410 match_interfaces = False
1411 break
1412 if match_interfaces:
1413 break
1414 else:
1415 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001416 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
garciadeblas4568a372021-03-24 09:19:48 +01001417 "names".format(
1418 pdu_type,
1419 vim_account,
1420 vnfr["member-vnf-index-ref"],
1421 vdur["vdu-id-ref"],
1422 )
1423 )
tiernocc103432018-10-19 14:10:35 +02001424
1425 # step 2. Update pdu
1426 rollback_pdu = {
1427 "_admin.usageState": pdu["_admin"]["usageState"],
1428 "_admin.usage.vnfr_id": None,
1429 "_admin.usage.nsr_id": None,
1430 "_admin.usage.vdur": None,
1431 }
garciadeblas4568a372021-03-24 09:19:48 +01001432 self.db.set_one(
1433 "pdus",
1434 {"_id": pdu["_id"]},
1435 {
1436 "_admin.usageState": "IN_USE",
1437 "_admin.usage": {
1438 "vnfr_id": vnfr["_id"],
1439 "nsr_id": vnfr["nsr-id-ref"],
1440 "vdur": vdur["vdu-id-ref"],
1441 },
1442 },
1443 )
1444 rollback.append(
1445 {
1446 "topic": "pdus",
1447 "_id": pdu["_id"],
1448 "operation": "set",
1449 "content": rollback_pdu,
1450 }
1451 )
tiernocc103432018-10-19 14:10:35 +02001452
1453 # step 3. Fill vnfr info by filling vdur
1454 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001455 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001456 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1457 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1458 for pdu_interface in pdu["interfaces"]:
1459 if pdu_interface["name"] == vdur_interface["name"]:
1460 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1461 for k, v in pdu_interface.items():
garciadeblas4568a372021-03-24 09:19:48 +01001462 if k in (
1463 "ip-address",
1464 "mac-address",
1465 ): # TODO: switch-xxxxx must be inserted
tierno36ec8602018-11-02 17:27:11 +01001466 vnfr_update[iface_text + ".{}".format(k)] = v
garciadeblas4568a372021-03-24 09:19:48 +01001467 vnfr_update_rollback[
1468 iface_text + ".{}".format(k)
1469 ] = vdur_interface.get(v)
tierno36ec8602018-11-02 17:27:11 +01001470 if pdu_interface.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001471 if vdur_interface.get(
1472 "mgmt-interface"
1473 ) or vdur_interface.get("mgmt-vnf"):
1474 vnfr_update_rollback[
1475 vdu_text + ".ip-address"
1476 ] = vdur.get("ip-address")
1477 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1478 "ip-address"
1479 ]
tierno36ec8602018-11-02 17:27:11 +01001480 if vdur_interface.get("mgmt-vnf"):
garciadeblas4568a372021-03-24 09:19:48 +01001481 vnfr_update_rollback["ip-address"] = vnfr.get(
1482 "ip-address"
1483 )
tierno36ec8602018-11-02 17:27:11 +01001484 vnfr_update["ip-address"] = pdu_interface["ip-address"]
garciadeblas4568a372021-03-24 09:19:48 +01001485 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1486 "ip-address"
1487 ]
1488 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1489 "vim-network-id"
1490 ):
1491 ifaces_forcing_vim_network.append(
1492 {
1493 "name": vdur_interface.get("vnf-vld-id")
1494 or vdur_interface.get("ns-vld-id"),
1495 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1496 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1497 }
1498 )
gcalvino17d5b732018-12-17 16:26:21 +01001499 if pdu_interface.get("vim-network-id"):
garciadeblas4568a372021-03-24 09:19:48 +01001500 ifaces_forcing_vim_network[-1][
1501 "vim-network-id"
1502 ] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001503 if pdu_interface.get("vim-network-name"):
garciadeblas4568a372021-03-24 09:19:48 +01001504 ifaces_forcing_vim_network[-1][
1505 "vim-network-name"
1506 ] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001507 break
1508
tierno36ec8602018-11-02 17:27:11 +01001509 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001510
garciadeblas4568a372021-03-24 09:19:48 +01001511 def _look_for_k8scluster(
1512 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1513 ):
tierno9cb7d672019-10-30 12:13:48 +00001514 """
1515 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1516 Fills vnfr.kdur with the selected k8scluster
1517
1518 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1519 :param rollback: list with the database modifications to rollback if needed
1520 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1521 :param vim_account: vim_account where this vnfr should be deployed
1522 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1523 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1524 of the changed vnfr is needed
1525
1526 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1527 "vim-network-name": used at VIM
1528 "name": interface name
1529 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1530 "ns-vld-id": NSD vld where this interface is connected.
1531 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1532 """
1533
1534 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001535 if not vnfr.get("kdur"):
1536 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001537
tiernoc67b0e92019-11-05 12:45:29 +00001538 kdu_filter = self._get_project_filter(session)
1539 kdu_filter["vim_account"] = vim_account
1540 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1541 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1542
1543 k8s_requirements = {} # just for logging
1544 for k8scluster in available_k8sclusters:
1545 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001546 break
tiernoc67b0e92019-11-05 12:45:29 +00001547 # restrict by cni
1548 if vnfr["k8s-cluster"].get("cni"):
1549 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
garciadeblas4568a372021-03-24 09:19:48 +01001550 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1551 k8scluster.get("cni", ())
1552 ):
tiernoc67b0e92019-11-05 12:45:29 +00001553 continue
1554 # restrict by version
1555 if vnfr["k8s-cluster"].get("version"):
1556 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1557 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1558 continue
1559 # restrict by number of networks
1560 if vnfr["k8s-cluster"].get("nets"):
1561 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
garciadeblas4568a372021-03-24 09:19:48 +01001562 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1563 vnfr["k8s-cluster"]["nets"]
1564 ):
tiernoc67b0e92019-11-05 12:45:29 +00001565 continue
1566 break
1567 else:
garciadeblas4568a372021-03-24 09:19:48 +01001568 raise EngineException(
1569 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1570 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1571 )
1572 )
tierno9cb7d672019-10-30 12:13:48 +00001573
tiernoc67b0e92019-11-05 12:45:29 +00001574 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001575 # step 3. Fill vnfr info by filling kdur
1576 kdu_text = "kdur.{}.".format(kdur_index)
1577 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1578 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1579
tiernoc67b0e92019-11-05 12:45:29 +00001580 # step 4. Check VIM networks that forces the selected k8s_cluster
1581 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1582 k8scluster_net_list = list(k8scluster.get("nets").keys())
1583 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1584 # get a network from k8s_cluster nets. If name matches use this, if not use other
1585 if kdur_net["id"] in k8scluster_net_list: # name matches
1586 vim_net = k8scluster["nets"][kdur_net["id"]]
1587 k8scluster_net_list.remove(kdur_net["id"])
1588 else:
1589 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1590 k8scluster_net_list.pop(0)
garciadeblas4568a372021-03-24 09:19:48 +01001591 vnfr_update_rollback[
1592 "k8s-cluster.nets.{}.vim_net".format(net_index)
1593 ] = None
tiernoc67b0e92019-11-05 12:45:29 +00001594 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
garciadeblas4568a372021-03-24 09:19:48 +01001595 if vim_net and (
1596 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1597 ):
1598 ifaces_forcing_vim_network.append(
1599 {
1600 "name": kdur_net.get("vnf-vld-id")
1601 or kdur_net.get("ns-vld-id"),
1602 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1603 "ns-vld-id": kdur_net.get("ns-vld-id"),
1604 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1605 }
1606 )
tiernoc67b0e92019-11-05 12:45:29 +00001607 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001608 return ifaces_forcing_vim_network
1609
Gulsum Atici89af5202021-11-10 20:59:06 +03001610 def _update_vnfrs_from_nsd(self, nsr):
1611 try:
1612 nsr_id = nsr["_id"]
1613 nsd = nsr["nsd"]
1614
1615 step = "Getting vnf_profiles from nsd"
1616 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1617 vld_fixed_ip_connection_point_data = {}
1618
1619 step = "Getting ip-address info from vnf_profile if it exists"
1620 for vnfp in vnf_profiles:
1621 # Checking ip-address info from nsd.vnf_profile and storing
1622 for vlc in vnfp.get("virtual-link-connectivity", ()):
1623 for cpd in vlc.get("constituent-cpd-id", ()):
1624 if cpd.get("ip-address"):
1625 step = "Storing ip-address info"
1626 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1627 "vnfd-connection-point-ref": cpd.get(
1628 "constituent-cpd-id"),
1629 "ip-address": cpd.get(
1630 "ip-address")}})
1631
1632 # Inserting ip address to vnfr
1633 if len(vld_fixed_ip_connection_point_data) > 0:
1634 step = "Getting vnfrs"
1635 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1636 for item in vld_fixed_ip_connection_point_data.keys():
1637 step = "Filtering vnfrs"
1638 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1639 if vnfr:
1640 vnfr_update = {}
1641 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1642 for iface_index, iface in enumerate(vdur["interfaces"]):
1643 step = "Looking for matched interface"
1644 if (
1645 iface.get("external-connection-point-ref")
1646 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1647 iface.get("ns-vld-id") == item.split('.')[0]
1648
1649 ):
1650 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1651 vdur_index, iface_index
1652 )
1653 step = "Storing info in order to update vnfr"
1654 vnfr_update[
1655 vnfr_update_text + ".ip-address"
1656 ] = increment_ip_mac(
1657 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1658 vdur.get("count-index", 0), )
1659 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1660
1661 step = "updating vnfr at database"
1662 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1663 except (
1664 ValidationError,
1665 EngineException,
1666 DbException,
1667 MsgException,
1668 FsException,
1669 ) as e:
1670 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1671
tiernocc103432018-10-19 14:10:35 +02001672 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001673 # get vnfr
1674 nsr_id = nsr["_id"]
1675 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1676
1677 for vnfr in vnfrs:
1678 vnfr_update = {}
1679 vnfr_update_rollback = {}
1680 member_vnf_index = vnfr["member-vnf-index-ref"]
1681 # update vim-account-id
1682
1683 vim_account = indata["vimAccountId"]
David Garcia510aafa2021-10-13 17:14:01 +02001684 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001685 # check instantiate parameters
1686 for vnf_inst_params in get_iterable(indata.get("vnf")):
1687 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1688 continue
1689 if vnf_inst_params.get("vimAccountId"):
1690 vim_account = vnf_inst_params.get("vimAccountId")
David Garcia510aafa2021-10-13 17:14:01 +02001691 vca_id = self._get_vim_account(vim_account, session).get("vca")
tiernocc103432018-10-19 14:10:35 +02001692
tiernocddb07d2020-10-06 08:28:00 +00001693 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1694 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1695 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1696 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1697 continue
garciadeblas4568a372021-03-24 09:19:48 +01001698 for iface_inst_param in get_iterable(
1699 vdu_inst_param.get("interface")
1700 ):
1701 iface_index, _ = next(
1702 i
1703 for i in enumerate(vdur["interfaces"])
1704 if i[1]["name"] == iface_inst_param["name"]
1705 )
1706 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1707 vdur_index, iface_index
1708 )
tiernocddb07d2020-10-06 08:28:00 +00001709 if iface_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001710 vnfr_update[
1711 vnfr_update_text + ".ip-address"
1712 ] = increment_ip_mac(
1713 iface_inst_param.get("ip-address"),
1714 vdur.get("count-index", 0),
1715 )
tierno1bd9d952020-11-13 15:56:51 +00001716 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001717 if iface_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001718 vnfr_update[
1719 vnfr_update_text + ".mac-address"
1720 ] = increment_ip_mac(
1721 iface_inst_param.get("mac-address"),
1722 vdur.get("count-index", 0),
1723 )
tierno1bd9d952020-11-13 15:56:51 +00001724 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001725 if iface_inst_param.get("floating-ip-required"):
garciadeblas4568a372021-03-24 09:19:48 +01001726 vnfr_update[
1727 vnfr_update_text + ".floating-ip-required"
1728 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001729 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1730 # TODO update vld with the ip-profile
garciadeblas4568a372021-03-24 09:19:48 +01001731 for ivld_inst_param in get_iterable(
1732 vnf_inst_params.get("internal-vld")
1733 ):
1734 for icp_inst_param in get_iterable(
1735 ivld_inst_param.get("internal-connection-point")
1736 ):
tiernocddb07d2020-10-06 08:28:00 +00001737 # look for iface
1738 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1739 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001740 if (
1741 iface.get("internal-connection-point-ref")
1742 == icp_inst_param["id-ref"]
1743 ):
1744 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1745 vdur_index, iface_index
1746 )
tiernocddb07d2020-10-06 08:28:00 +00001747 if icp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001748 vnfr_update[
1749 vnfr_update_text + ".ip-address"
1750 ] = increment_ip_mac(
1751 icp_inst_param.get("ip-address"),
1752 vdur.get("count-index", 0),
1753 )
1754 vnfr_update[
1755 vnfr_update_text + ".fixed-ip"
1756 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001757 if icp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001758 vnfr_update[
1759 vnfr_update_text + ".mac-address"
1760 ] = increment_ip_mac(
1761 icp_inst_param.get("mac-address"),
1762 vdur.get("count-index", 0),
1763 )
1764 vnfr_update[
1765 vnfr_update_text + ".fixed-mac"
1766 ] = True
tiernocddb07d2020-10-06 08:28:00 +00001767 break
1768 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1769 for vld_inst_param in get_iterable(indata.get("vld")):
garciadeblas4568a372021-03-24 09:19:48 +01001770 for vnfcp_inst_param in get_iterable(
1771 vld_inst_param.get("vnfd-connection-point-ref")
1772 ):
tiernocddb07d2020-10-06 08:28:00 +00001773 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1774 continue
1775 # look for iface
1776 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1777 for iface_index, iface in enumerate(vdur["interfaces"]):
garciadeblas4568a372021-03-24 09:19:48 +01001778 if (
1779 iface.get("external-connection-point-ref")
1780 == vnfcp_inst_param["vnfd-connection-point-ref"]
1781 ):
1782 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1783 vdur_index, iface_index
1784 )
tiernocddb07d2020-10-06 08:28:00 +00001785 if vnfcp_inst_param.get("ip-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001786 vnfr_update[
1787 vnfr_update_text + ".ip-address"
1788 ] = increment_ip_mac(
1789 vnfcp_inst_param.get("ip-address"),
1790 vdur.get("count-index", 0),
1791 )
tierno1bd9d952020-11-13 15:56:51 +00001792 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001793 if vnfcp_inst_param.get("mac-address"):
garciadeblas4568a372021-03-24 09:19:48 +01001794 vnfr_update[
1795 vnfr_update_text + ".mac-address"
1796 ] = increment_ip_mac(
1797 vnfcp_inst_param.get("mac-address"),
1798 vdur.get("count-index", 0),
1799 )
tierno1bd9d952020-11-13 15:56:51 +00001800 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001801 break
1802
tiernocc103432018-10-19 14:10:35 +02001803 vnfr_update["vim-account-id"] = vim_account
1804 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1805
David Garciaecb41322021-03-31 19:10:46 +02001806 if vca_id:
1807 vnfr_update["vca-id"] = vca_id
1808 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1809
tiernocc103432018-10-19 14:10:35 +02001810 # get pdu
garciadeblas4568a372021-03-24 09:19:48 +01001811 ifaces_forcing_vim_network = self._look_for_pdu(
1812 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1813 )
tiernocc103432018-10-19 14:10:35 +02001814
tierno9cb7d672019-10-30 12:13:48 +00001815 # get kdus
garciadeblas4568a372021-03-24 09:19:48 +01001816 ifaces_forcing_vim_network += self._look_for_k8scluster(
1817 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1818 )
tierno9cb7d672019-10-30 12:13:48 +00001819 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001820 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
garciadeblas4568a372021-03-24 09:19:48 +01001821 rollback.append(
1822 {
1823 "topic": "vnfrs",
1824 "_id": vnfr["_id"],
1825 "operation": "set",
1826 "content": vnfr_update_rollback,
1827 }
1828 )
tierno36ec8602018-11-02 17:27:11 +01001829
1830 # Update indada in case pdu forces to use a concrete vim-network-name
1831 # TODO check if user has already insert a vim-network-name and raises an error
1832 if not ifaces_forcing_vim_network:
1833 continue
1834 for iface_info in ifaces_forcing_vim_network:
1835 if iface_info.get("ns-vld-id"):
1836 if "vld" not in indata:
1837 indata["vld"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001838 indata["vld"].append(
1839 {
1840 key: iface_info[key]
1841 for key in ("name", "vim-network-name", "vim-network-id")
1842 if iface_info.get(key)
1843 }
1844 )
tierno36ec8602018-11-02 17:27:11 +01001845
1846 elif iface_info.get("vnf-vld-id"):
1847 if "vnf" not in indata:
1848 indata["vnf"] = []
garciadeblas4568a372021-03-24 09:19:48 +01001849 indata["vnf"].append(
1850 {
1851 "member-vnf-index": member_vnf_index,
1852 "internal-vld": [
1853 {
1854 key: iface_info[key]
1855 for key in (
1856 "name",
1857 "vim-network-name",
1858 "vim-network-id",
1859 )
1860 if iface_info.get(key)
1861 }
1862 ],
1863 }
1864 )
tierno36ec8602018-11-02 17:27:11 +01001865
1866 @staticmethod
1867 def _create_nslcmop(nsr_id, operation, params):
1868 """
1869 Creates a ns-lcm-opp content to be stored at database.
1870 :param nsr_id: internal id of the instance
1871 :param operation: instantiate, terminate, scale, action, ...
1872 :param params: user parameters for the operation
1873 :return: dictionary following SOL005 format
1874 """
tiernob24258a2018-10-04 18:39:49 +02001875 now = time()
1876 _id = str(uuid4())
1877 nslcmop = {
1878 "id": _id,
1879 "_id": _id,
1880 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001881 "queuePosition": None,
1882 "stage": None,
1883 "errorMessage": None,
1884 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001885 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001886 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001887 "lcmOperationType": operation,
1888 "startTime": now,
1889 "isAutomaticInvocation": False,
1890 "operationParams": params,
1891 "isCancelPending": False,
1892 "links": {
1893 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001894 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas4568a372021-03-24 09:19:48 +01001895 },
tiernob24258a2018-10-04 18:39:49 +02001896 }
1897 return nslcmop
1898
magnussonlf318b302020-01-20 18:38:18 +01001899 def _get_enabled_vims(self, session):
1900 """
1901 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1902 :param session: current session with user information
1903 """
1904 db_filter = self._get_project_filter(session)
1905 db_filter["_admin.operationalState"] = "ENABLED"
1906 vims = self.db.get_list("vim_accounts", db_filter)
1907 vimAccounts = []
1908 for vim in vims:
garciadeblas4568a372021-03-24 09:19:48 +01001909 vimAccounts.append(vim["_id"])
magnussonlf318b302020-01-20 18:38:18 +01001910 return vimAccounts
1911
garciadeblas4568a372021-03-24 09:19:48 +01001912 def new(
1913 self,
1914 rollback,
1915 session,
1916 indata=None,
1917 kwargs=None,
1918 headers=None,
1919 slice_object=False,
1920 ):
tiernob24258a2018-10-04 18:39:49 +02001921 """
1922 Performs a new operation over a ns
1923 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001924 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001925 :param indata: descriptor with the parameters of the operation. It must contains among others
1926 nsInstanceId: _id of the nsr to perform the operation
1927 operation: it can be: instantiate, terminate, action, TODO: update, heal
1928 :param kwargs: used to override the indata descriptor
1929 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02001930 :return: id of the nslcmops
1931 """
garciadeblas4568a372021-03-24 09:19:48 +01001932
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001933 def check_if_nsr_is_not_slice_member(session, nsr_id):
1934 nsis = None
1935 db_filter = self._get_project_filter(session)
1936 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01001937 nsis = self.db.get_one(
1938 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
1939 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001940 if nsis:
garciadeblas4568a372021-03-24 09:19:48 +01001941 raise EngineException(
1942 "The NS instance {} cannot be terminated because is used by the slice {}".format(
1943 nsr_id, nsis["_id"]
1944 ),
1945 http_code=HTTPStatus.CONFLICT,
1946 )
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001947
tiernob24258a2018-10-04 18:39:49 +02001948 try:
1949 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00001950 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02001951 operation = indata["lcmOperationType"]
1952 nsInstanceId = indata["nsInstanceId"]
1953
1954 validate_input(indata, self.operation_schema[operation])
1955 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01001956 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02001957 _filter["_id"] = nsInstanceId
1958 nsr = self.db.get_one("nsrs", _filter)
1959
1960 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001961 if operation == "terminate" and slice_object is False:
1962 check_if_nsr_is_not_slice_member(session, nsr["_id"])
garciadeblas4568a372021-03-24 09:19:48 +01001963 if (
1964 not nsr["_admin"].get("nsState")
1965 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
1966 ):
tiernob24258a2018-10-04 18:39:49 +02001967 if operation == "terminate" and indata.get("autoremove"):
1968 # NSR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01001969 return (
1970 None,
1971 None,
1972 ) # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02001973 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01001974 raise EngineException(
1975 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1976 nsInstanceId, operation
1977 ),
1978 HTTPStatus.CONFLICT,
1979 )
tiernob24258a2018-10-04 18:39:49 +02001980 else:
tierno65ca36d2019-02-12 19:27:52 +01001981 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01001982 raise EngineException(
1983 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1984 nsInstanceId, operation
1985 ),
1986 HTTPStatus.CONFLICT,
1987 )
tiernob24258a2018-10-04 18:39:49 +02001988 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +01001989
tiernocc103432018-10-19 14:10:35 +02001990 if operation == "instantiate":
Gulsum Atici89af5202021-11-10 20:59:06 +03001991 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02001992 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01001993
1994 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00001995 _id = nslcmop_desc["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01001996 self.format_on_new(
1997 nslcmop_desc, session["project_id"], make_public=session["public"]
1998 )
magnussonlf318b302020-01-20 18:38:18 +01001999 if indata.get("placement-engine"):
2000 # Save valid vim accounts in lcm operation descriptor
garciadeblas4568a372021-03-24 09:19:48 +01002001 nslcmop_desc["operationParams"][
2002 "validVimAccounts"
2003 ] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00002004 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02002005 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002006 if not slice_object:
2007 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002008 return _id, None
2009 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02002010 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2011 # except DbException as e:
2012 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2013
tiernobee3bad2019-12-05 12:26:01 +00002014 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002015 raise EngineException(
2016 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2017 )
tiernob24258a2018-10-04 18:39:49 +02002018
tierno65ca36d2019-02-12 19:27:52 +01002019 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002020 raise EngineException(
2021 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2022 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002023
2024
2025class NsiTopic(BaseTopic):
2026 topic = "nsis"
2027 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00002028 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002029
delacruzramo32bab472019-09-13 12:24:22 +02002030 def __init__(self, db, fs, msg, auth):
2031 BaseTopic.__init__(self, db, fs, msg, auth)
2032 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002033
Felipe Vicensc37b3842019-01-12 12:24:42 +01002034 @staticmethod
2035 def _format_ns_request(ns_request):
2036 formated_request = copy(ns_request)
2037 # TODO: Add request params
2038 return formated_request
2039
2040 @staticmethod
tiernofd160572019-01-21 10:41:37 +00002041 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01002042 """
2043 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00002044 :param slice_request: User instantiation additional parameters
2045 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01002046 """
tiernofd160572019-01-21 10:41:37 +00002047 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2048 if additional_params:
2049 for k, v in additional_params.items():
2050 if not isinstance(k, str):
garciadeblas4568a372021-03-24 09:19:48 +01002051 raise EngineException(
2052 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2053 k
2054 )
2055 )
tiernofd160572019-01-21 10:41:37 +00002056 if "." in k or "$" in k:
garciadeblas4568a372021-03-24 09:19:48 +01002057 raise EngineException(
2058 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2059 k
2060 )
2061 )
tiernofd160572019-01-21 10:41:37 +00002062 if isinstance(v, (dict, tuple, list)):
2063 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01002064 return additional_params
2065
Felipe Vicensb57758d2018-10-16 16:00:20 +02002066 def _check_descriptor_dependencies(self, session, descriptor):
2067 """
2068 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01002069 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002070 :param descriptor: descriptor to be inserted or edit
2071 :return: None or raises exception
2072 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002073 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002074 return
Felipe Vicens07f31722018-10-29 15:16:44 +01002075 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002076 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
garciadeblas4568a372021-03-24 09:19:48 +01002077 raise EngineException(
2078 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2079 nstd_id
2080 ),
2081 http_code=HTTPStatus.CONFLICT,
2082 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002083
tiernob4844ab2019-05-23 08:42:12 +00002084 def check_conflict_on_del(self, session, _id, db_content):
2085 """
2086 Check that NSI is not instantiated
2087 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2088 :param _id: nsi internal id
2089 :param db_content: The database content of the _id
2090 :return: None or raises EngineException with the conflict
2091 """
tierno65ca36d2019-02-12 19:27:52 +01002092 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02002093 return
tiernob4844ab2019-05-23 08:42:12 +00002094 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02002095 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
garciadeblas4568a372021-03-24 09:19:48 +01002096 raise EngineException(
2097 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2098 "Launch 'terminate' operation first; or force deletion".format(_id),
2099 http_code=HTTPStatus.CONFLICT,
2100 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002101
tiernobee3bad2019-12-05 12:26:01 +00002102 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002103 """
tiernob4844ab2019-05-23 08:42:12 +00002104 Deletes associated nsilcmops from database. Deletes associated filesystem.
2105 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01002106 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002107 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00002108 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00002109 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00002110 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02002111 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002112
Felipe Vicens09e65422019-01-22 15:06:46 +01002113 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00002114 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01002115 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2116 nsr_id = nsrs_detailed_item["nsrId"]
2117 if nsrs_detailed_item.get("shared"):
garciadeblas4568a372021-03-24 09:19:48 +01002118 _filter = {
2119 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2120 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2121 "_id.ne": nsir["_id"],
2122 }
2123 nsi = self.db.get_one(
2124 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2125 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002126 if nsi: # last one using nsr
2127 continue
2128 try:
garciadeblas4568a372021-03-24 09:19:48 +01002129 self.nsrTopic.delete(
2130 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2131 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002132 except (DbException, EngineException) as e:
2133 if e.http_code == HTTPStatus.NOT_FOUND:
2134 pass
2135 else:
2136 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002137
tiernob4844ab2019-05-23 08:42:12 +00002138 # delete related nsilcmops database entries
2139 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01002140
tiernob4844ab2019-05-23 08:42:12 +00002141 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01002142 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00002143 if nsir_admin and nsir_admin.get("nst-id"):
2144 # check if used by another NSI
garciadeblas4568a372021-03-24 09:19:48 +01002145 nsis_list = self.db.get_one(
2146 "nsis",
2147 {"nst-id": nsir_admin["nst-id"]},
2148 fail_on_empty=False,
2149 fail_on_more=False,
2150 )
tiernob4844ab2019-05-23 08:42:12 +00002151 if not nsis_list:
garciadeblas4568a372021-03-24 09:19:48 +01002152 self.db.set_one(
2153 "nsts",
2154 {"_id": nsir_admin["nst-id"]},
2155 {"_admin.usageState": "NOT_IN_USE"},
2156 )
tiernob4844ab2019-05-23 08:42:12 +00002157
tierno65ca36d2019-02-12 19:27:52 +01002158 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02002159 """
Felipe Vicens07f31722018-10-29 15:16:44 +01002160 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02002161 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01002162 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02002163 :param indata: params to be used for the nsir
2164 :param kwargs: used to override the indata descriptor
2165 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02002166 :return: the _id of nsi descriptor created at database
2167 """
2168
2169 try:
delacruzramo32bab472019-09-13 12:24:22 +02002170 step = "checking quotas"
2171 self.check_quota(session)
2172
tierno99d4b172019-07-02 09:28:40 +00002173 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02002174 slice_request = self._remove_envelop(indata)
2175 # Override descriptor with query string kwargs
2176 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03002177 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02002178
Felipe Vicensb57758d2018-10-16 16:00:20 +02002179 # look for nstd
garciadeblas4568a372021-03-24 09:19:48 +01002180 step = "getting nstd id='{}' from database".format(
2181 slice_request.get("nstId")
2182 )
tiernob4844ab2019-05-23 08:42:12 +00002183 _filter = self._get_project_filter(session)
2184 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002185 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00002186 # check NST is not disabled
2187 step = "checking NST operationalState"
2188 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002189 raise EngineException(
2190 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2191 "instance".format(slice_request["nstId"]),
2192 http_code=HTTPStatus.CONFLICT,
2193 )
tiernob4844ab2019-05-23 08:42:12 +00002194 del _filter["_id"]
2195
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002196 # check NSD is not disabled
2197 step = "checking operationalState"
2198 if nstd["_admin"]["operationalState"] == "DISABLED":
garciadeblas4568a372021-03-24 09:19:48 +01002199 raise EngineException(
2200 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2201 "a network slice".format(slice_request["nstId"]),
2202 http_code=HTTPStatus.CONFLICT,
2203 )
Frank Brydenb5a2ead2020-07-28 12:50:23 +00002204
Felipe Vicens07f31722018-10-29 15:16:44 +01002205 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01002206 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02002207 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02002208 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01002209
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002210 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02002211 nsi_descriptor = {
2212 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01002213 "name": slice_request["nsiName"],
2214 "description": slice_request.get("nsiDescription", ""),
2215 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002216 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002217 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02002218 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002219 "nsr-ref-list": [],
2220 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02002221 "_id": nsi_id,
garciadeblas4568a372021-03-24 09:19:48 +01002222 "additionalParamsForNsi": self._format_addional_params(slice_request),
Felipe Vicensb57758d2018-10-16 16:00:20 +02002223 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02002224
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002225 step = "creating nsi at database"
garciadeblas4568a372021-03-24 09:19:48 +01002226 self.format_on_new(
2227 nsi_descriptor, session["project_id"], make_public=session["public"]
2228 )
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002229 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2230 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01002231 nsi_descriptor["_admin"]["deployed"] = {}
2232 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2233 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2234
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002235 # Creating netslice-vld for the RO.
2236 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002237
2238 # Building the vlds list to be deployed
2239 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01002240 nsi_vlds = []
2241
2242 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2243 # Getting template Instantiation parameters from NST
2244 nsi_vld = deepcopy(netslice_vlds)
2245 nsi_vld["shared-nsrs-list"] = []
2246 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2247 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002248
2249 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00002250 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02002251 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01002252 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002253
Felipe Vicens09e65422019-01-22 15:06:46 +01002254 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02002255 for member_ns in nstd["netslice-subnet"]:
2256 nsd_id = member_ns["nsd-ref"]
2257 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002258 member_ns["nsd-ref"], member_ns["id"]
2259 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002260 if nsd_id not in needed_nsds:
2261 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00002262 _filter["id"] = nsd_id
garciadeblas4568a372021-03-24 09:19:48 +01002263 nsd = self.db.get_one(
2264 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2265 )
tiernob4844ab2019-05-23 08:42:12 +00002266 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02002267 nsd.pop("_admin")
2268 needed_nsds[nsd_id] = nsd
2269 else:
2270 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01002271 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2272 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01002273
Felipe Vicensb57758d2018-10-16 16:00:20 +02002274 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
garciadeblas4568a372021-03-24 09:19:48 +01002275 member_ns["nsd-ref"], member_ns["id"]
2276 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002277
Felipe Vicens07f31722018-10-29 15:16:44 +01002278 # creates Network Services records (NSRs)
2279 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002280 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01002281 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002282 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01002283 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01002284 # Check if the netslice-subnet is shared and if it is share if the nss exists
2285 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01002286 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01002287 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00002288 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
garciadeblas4568a372021-03-24 09:19:48 +01002289 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2290 "nsd-ref"
2291 ]
Felipe Vicens08ddb142019-08-09 15:52:40 +02002292 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
garciadeblas4568a372021-03-24 09:19:48 +01002293 nsi = self.db.get_one(
2294 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2295 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002296 if nsi and service.get("is-shared-nss"):
2297 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2298 for nsrs_detailed_item in nsrs_detailed_list:
2299 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02002300 if nsrs_detailed_item["nss-id"] == service["id"]:
2301 _id_nsr = nsrs_detailed_item["nsrId"]
2302 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002303 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2304 if netslice_subnet["nss-id"] == service["id"]:
2305 indata_ns = netslice_subnet
2306 break
2307 else:
2308 indata_ns = {}
2309 if service.get("instantiation-parameters"):
2310 indata_ns = deepcopy(service["instantiation-parameters"])
2311 # del service["instantiation-parameters"]
garciadeblas4568a372021-03-24 09:19:48 +01002312
Felipe Vicens09e65422019-01-22 15:06:46 +01002313 indata_ns["nsdId"] = service["_id"]
garciadeblas4568a372021-03-24 09:19:48 +01002314 indata_ns["nsName"] = (
2315 slice_request.get("nsiName") + "." + service["id"]
2316 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002317 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2318 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00002319 if slice_request.get("ssh_keys"):
2320 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01002321
Felipe Vicens09e65422019-01-22 15:06:46 +01002322 if ns_params:
2323 for ns_param in ns_params:
2324 if ns_param.get("id") == service["id"]:
2325 copy_ns_param = deepcopy(ns_param)
2326 del copy_ns_param["id"]
2327 indata_ns.update(copy_ns_param)
garciadeblas4568a372021-03-24 09:19:48 +01002328 break
Felipe Vicens09e65422019-01-22 15:06:46 +01002329
2330 # Creates Nsr objects
garciadeblas4568a372021-03-24 09:19:48 +01002331 _id_nsr, _ = self.nsrTopic.new(
2332 rollback, session, indata_ns, kwargs, headers
2333 )
2334 nsrs_item = {
2335 "nsrId": _id_nsr,
2336 "shared": service.get("is-shared-nss"),
2337 "nsd-id": service["nsd-ref"],
2338 "nss-id": service["id"],
2339 "nslcmop_instantiate": None,
2340 }
Felipe Vicens09e65422019-01-22 15:06:46 +01002341 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002342 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002343 nsi_netslice_subnet.append(indata_ns)
2344 nsr_ref = {"nsr-ref": _id_nsr}
2345 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01002346
2347 # Adding the nsrs list to the nsi
2348 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002349 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
garciadeblas4568a372021-03-24 09:19:48 +01002350 self.db.set_one(
2351 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2352 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002353
Felipe Vicens07f31722018-10-29 15:16:44 +01002354 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02002355 self.db.create("nsis", nsi_descriptor)
2356 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00002357 return nsi_id, None
garciadeblas4568a372021-03-24 09:19:48 +01002358 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2359 self.logger.exception(
2360 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2361 )
Felipe Vicensb57758d2018-10-16 16:00:20 +02002362 raise EngineException("Error {}: {}".format(step, e))
2363 except ValidationError as e:
2364 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2365
tierno65ca36d2019-02-12 19:27:52 +01002366 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002367 raise EngineException(
2368 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2369 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002370
2371
2372class NsiLcmOpTopic(BaseTopic):
2373 topic = "nsilcmops"
2374 topic_msg = "nsi"
2375 operation_schema = { # mapping between operation and jsonschema to validate
2376 "instantiate": nsi_instantiate,
garciadeblas4568a372021-03-24 09:19:48 +01002377 "terminate": None,
Felipe Vicens07f31722018-10-29 15:16:44 +01002378 }
garciadeblas4568a372021-03-24 09:19:48 +01002379
delacruzramo32bab472019-09-13 12:24:22 +02002380 def __init__(self, db, fs, msg, auth):
2381 BaseTopic.__init__(self, db, fs, msg, auth)
2382 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01002383
2384 def _check_nsi_operation(self, session, nsir, operation, indata):
2385 """
2386 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01002387 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002388 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2389 :param indata: descriptor with the parameters of the operation
2390 :return: None
2391 """
2392 nsds = {}
2393 nstd = nsir["network-slice-template"]
2394
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002395 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01002396 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002397 for netslice_subnet in nstd["netslice-subnet"]:
2398 if nstId == netslice_subnet["id"]:
2399 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002400 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02002401 _filter = self._get_project_filter(session)
2402 _filter["id"] = nsd_id
2403 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01002404 return nsds[nsd_id]
2405 else:
garciadeblas4568a372021-03-24 09:19:48 +01002406 raise EngineException(
2407 "Invalid parameter nstId='{}' is not one of the "
2408 "nst:netslice-subnet".format(nstId)
2409 )
2410
Felipe Vicens07f31722018-10-29 15:16:44 +01002411 if operation == "instantiate":
2412 # check the existance of netslice-subnet items
garciadeblas4568a372021-03-24 09:19:48 +01002413 for in_nst in get_iterable(indata.get("netslice-subnet")):
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01002414 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01002415
2416 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2417 now = time()
2418 _id = str(uuid4())
2419 nsilcmop = {
2420 "id": _id,
2421 "_id": _id,
2422 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2423 "statusEnteredTime": now,
2424 "netsliceInstanceId": netsliceInstanceId,
2425 "lcmOperationType": operation,
2426 "startTime": now,
2427 "isAutomaticInvocation": False,
2428 "operationParams": params,
2429 "isCancelPending": False,
2430 "links": {
2431 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
garciadeblas4568a372021-03-24 09:19:48 +01002432 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2433 + netsliceInstanceId,
2434 },
Felipe Vicens07f31722018-10-29 15:16:44 +01002435 }
2436 return nsilcmop
2437
Felipe Vicens09e65422019-01-22 15:06:46 +01002438 def add_shared_nsr_2vld(self, nsir, nsr_item):
2439 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2440 if nst_sb_item.get("is-shared-nss"):
2441 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2442 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2443 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
garciadeblas4568a372021-03-24 09:19:48 +01002444 for admin_vld_nss_cp_ref_item in admin_vld_item[
2445 "nss-connection-point-ref"
2446 ]:
2447 if (
2448 admin_subnet_item["nss-id"]
2449 == admin_vld_nss_cp_ref_item["nss-ref"]
2450 ):
2451 if (
2452 not nsr_item["nsrId"]
2453 in admin_vld_item["shared-nsrs-list"]
2454 ):
2455 admin_vld_item["shared-nsrs-list"].append(
2456 nsr_item["nsrId"]
2457 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002458 break
2459 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
garciadeblas4568a372021-03-24 09:19:48 +01002460 self.db.set_one(
2461 "nsis",
2462 {"_id": nsir["_id"]},
2463 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2464 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002465
tierno65ca36d2019-02-12 19:27:52 +01002466 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01002467 """
2468 Performs a new operation over a ns
2469 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01002470 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01002471 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02002472 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01002473 operation: it can be: instantiate, terminate, action, TODO: update, heal
2474 :param kwargs: used to override the indata descriptor
2475 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01002476 :return: id of the nslcmops
2477 """
2478 try:
2479 # Override descriptor with query string kwargs
2480 self._update_input_with_kwargs(indata, kwargs)
2481 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02002482 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002483 validate_input(indata, self.operation_schema[operation])
2484
Felipe Vicens126af572019-06-05 19:13:04 +02002485 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00002486 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02002487 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01002488 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00002489 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00002490 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01002491
2492 # initial checking
garciadeblas4568a372021-03-24 09:19:48 +01002493 if (
2494 not nsir["_admin"].get("nsiState")
2495 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2496 ):
Felipe Vicens07f31722018-10-29 15:16:44 +01002497 if operation == "terminate" and indata.get("autoremove"):
2498 # NSIR must be deleted
garciadeblas4568a372021-03-24 09:19:48 +01002499 return (
2500 None,
2501 None,
2502 ) # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01002503 if operation != "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002504 raise EngineException(
2505 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2506 netsliceInstanceId, operation
2507 ),
2508 HTTPStatus.CONFLICT,
2509 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002510 else:
tierno65ca36d2019-02-12 19:27:52 +01002511 if operation == "instantiate" and not session["force"]:
garciadeblas4568a372021-03-24 09:19:48 +01002512 raise EngineException(
2513 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2514 netsliceInstanceId, operation
2515 ),
2516 HTTPStatus.CONFLICT,
2517 )
2518
Felipe Vicens07f31722018-10-29 15:16:44 +01002519 # Creating all the NS_operation (nslcmop)
2520 # Get service list from db
2521 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2522 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01002523 # nslcmops_item = None
2524 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00002525 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01002526 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002527 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00002528 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
garciadeblas4568a372021-03-24 09:19:48 +01002529 _filter[
2530 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2531 ] = None
Felipe Vicens126af572019-06-05 19:13:04 +02002532 _filter["_id.ne"] = netsliceInstanceId
garciadeblas4568a372021-03-24 09:19:48 +01002533 nsi = self.db.get_one(
2534 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2535 )
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002536 if operation == "terminate":
garciadeblas4568a372021-03-24 09:19:48 +01002537 _update = {
2538 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2539 index
2540 ): None
2541 }
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02002542 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
garciadeblas4568a372021-03-24 09:19:48 +01002543 if (
2544 nsi
2545 ): # other nsi is using this nsr and it needs this nsr instantiated
tierno40f742b2020-06-23 15:25:26 +00002546 continue # do not create nsilcmop
2547 else: # instantiate
2548 # looks the first nsi fulfilling the conditions but not being the current NSIR
2549 if nsi:
garciadeblas4568a372021-03-24 09:19:48 +01002550 nsi_nsr_item = next(
2551 n
2552 for n in nsi["_admin"]["nsrs-detailed-list"]
2553 if n["nsrId"] == nsr_id
2554 and n["shared"]
2555 and n["nslcmop_instantiate"]
2556 )
tierno40f742b2020-06-23 15:25:26 +00002557 self.add_shared_nsr_2vld(nsir, nsr_item)
2558 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
garciadeblas4568a372021-03-24 09:19:48 +01002559 _update = {
2560 "_admin.nsrs-detailed-list.{}".format(
2561 index
2562 ): nsi_nsr_item
2563 }
tierno40f742b2020-06-23 15:25:26 +00002564 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2565 # continue to not create nslcmop since nsrs is shared and nsrs was created
2566 continue
2567 else:
2568 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01002569
tierno40f742b2020-06-23 15:25:26 +00002570 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01002571 try:
tierno0b8752f2020-05-12 09:42:02 +00002572 indata_ns = {
2573 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00002574 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00002575 # Including netslice_id in the ns instantiate Operation
2576 "netsliceInstanceId": netsliceInstanceId,
2577 }
2578 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00002579 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00002580 indata_ns.update(service["instantiate_params"])
2581
tierno99d4b172019-07-02 09:28:40 +00002582 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01002583 # message via kafka bus
garciadeblas4568a372021-03-24 09:19:48 +01002584 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2585 rollback, session, indata_ns, None, headers, slice_object=True
2586 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002587 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00002588 if operation == "instantiate":
garciadeblas4568a372021-03-24 09:19:48 +01002589 _update = {
2590 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2591 index
2592 ): nslcmop
2593 }
tierno40f742b2020-06-23 15:25:26 +00002594 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01002595 except (DbException, EngineException) as e:
2596 if e.http_code == HTTPStatus.NOT_FOUND:
garciadeblas4568a372021-03-24 09:19:48 +01002597 self.logger.info(
2598 logging_prefix
2599 + "skipping NS={} because not found".format(nsr_id)
2600 )
Felipe Vicens09e65422019-01-22 15:06:46 +01002601 pass
2602 else:
2603 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01002604
2605 # Creates nsilcmop
2606 indata["nslcmops_ids"] = nslcmops
2607 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01002608
garciadeblas4568a372021-03-24 09:19:48 +01002609 nsilcmop_desc = self._create_nsilcmop(
2610 session, netsliceInstanceId, operation, indata
2611 )
2612 self.format_on_new(
2613 nsilcmop_desc, session["project_id"], make_public=session["public"]
2614 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002615 _id = self.db.create("nsilcmops", nsilcmop_desc)
2616 rollback.append({"topic": "nsilcmops", "_id": _id})
2617 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00002618 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01002619 except ValidationError as e:
2620 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01002621
tiernobee3bad2019-12-05 12:26:01 +00002622 def delete(self, session, _id, dry_run=False, not_send_msg=None):
garciadeblas4568a372021-03-24 09:19:48 +01002623 raise EngineException(
2624 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2625 )
Felipe Vicens07f31722018-10-29 15:16:44 +01002626
tierno65ca36d2019-02-12 19:27:52 +01002627 def edit(self, session, _id, indata=None, kwargs=None, content=None):
garciadeblas4568a372021-03-24 09:19:48 +01002628 raise EngineException(
2629 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2630 )