blob: 3626e537474ce44b654299423fd56fb6dc44170c [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
tierno1c38f2f2020-03-24 11:51:39 +000021from osm_nbi.validation import validate_input, ValidationError, ns_instantiate, ns_terminate, ns_action, ns_scale,\
22 nsi_instantiate
tiernocddb07d2020-10-06 08:28:00 +000023from osm_nbi.base_topic import BaseTopic, EngineException, get_iterable, deep_get, increment_ip_mac
tiernobee085c2018-12-12 17:03:04 +000024from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010025from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000026from osm_common.msgbase import MsgException
27from osm_common.fsbase import FsException
garciaale7cbd03c2020-11-27 10:38:35 -030028from osm_nbi import utils
delacruzramo36ffe552019-05-03 14:52:37 +020029from re import match # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020030
31__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
32
33
34class NsrTopic(BaseTopic):
35 topic = "nsrs"
36 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000037 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000038 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020039
delacruzramo32bab472019-09-13 12:24:22 +020040 def __init__(self, db, fs, msg, auth):
41 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020042
43 def _check_descriptor_dependencies(self, session, descriptor):
44 """
45 Check that the dependent descriptors exist on a new descriptor or edition
46 :param session: client session information
47 :param descriptor: descriptor to be inserted or edit
48 :return: None or raises exception
49 """
50 if not descriptor.get("nsdId"):
51 return
52 nsd_id = descriptor["nsdId"]
53 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
54 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
55 http_code=HTTPStatus.CONFLICT)
56
57 @staticmethod
58 def format_on_new(content, project_id=None, make_public=False):
59 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
60 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000061 return None
tiernob24258a2018-10-04 18:39:49 +020062
tiernob4844ab2019-05-23 08:42:12 +000063 def check_conflict_on_del(self, session, _id, db_content):
64 """
65 Check that NSR is not instantiated
66 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
67 :param _id: nsr internal id
68 :param db_content: The database content of the nsr
69 :return: None or raises EngineException with the conflict
70 """
tierno65ca36d2019-02-12 19:27:52 +010071 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020072 return
tiernob4844ab2019-05-23 08:42:12 +000073 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020074 if nsr["_admin"].get("nsState") == "INSTANTIATED":
75 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
76 "Launch 'terminate' operation first; or force deletion".format(_id),
77 http_code=HTTPStatus.CONFLICT)
78
tiernobee3bad2019-12-05 12:26:01 +000079 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +000080 """
81 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
82 Set usageState of pdu, vnfd, nsd
83 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
84 :param _id: server internal id
85 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +000086 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +000087 :return: None if ok or raises EngineException with the problem
88 """
tiernobee085c2018-12-12 17:03:04 +000089 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +020090 self.db.del_list("nslcmops", {"nsInstanceId": _id})
91 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +000092
tiernob24258a2018-10-04 18:39:49 +020093 # set all used pdus as free
94 self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
tierno36ec8602018-11-02 17:27:11 +010095 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
tiernob24258a2018-10-04 18:39:49 +020096
tiernob4844ab2019-05-23 08:42:12 +000097 # Set NSD usageState
98 nsr = db_content
99 used_nsd_id = nsr.get("nsd-id")
100 if used_nsd_id:
101 # check if used by another NSR
102 nsrs_list = self.db.get_one("nsrs", {"nsd-id": used_nsd_id},
103 fail_on_empty=False, fail_on_more=False)
104 if not nsrs_list:
105 self.db.set_one("nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"})
106
107 # Set VNFD usageState
108 used_vnfd_id_list = nsr.get("vnfd-id")
109 if used_vnfd_id_list:
110 for used_vnfd_id in used_vnfd_id_list:
111 # check if used by another NSR
112 nsrs_list = self.db.get_one("nsrs", {"vnfd-id": used_vnfd_id},
113 fail_on_empty=False, fail_on_more=False)
114 if not nsrs_list:
115 self.db.set_one("vnfds", {"_id": used_vnfd_id}, {"_admin.usageState": "NOT_IN_USE"})
116
tiernof0441ea2020-05-26 15:39:18 +0000117 # delete extra ro_nsrs used for internal RO module
118 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
119
tiernobee085c2018-12-12 17:03:04 +0000120 @staticmethod
121 def _format_ns_request(ns_request):
122 formated_request = copy(ns_request)
123 formated_request.pop("additionalParamsForNs", None)
124 formated_request.pop("additionalParamsForVnf", None)
125 return formated_request
126
127 @staticmethod
tiernoe19707b2020-04-21 13:08:04 +0000128 def _format_additional_params(ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None):
tiernobee085c2018-12-12 17:03:04 +0000129 """
130 Get and format user additional params for NS or VNF
131 :param ns_request: User instantiation additional parameters
132 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
133 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000134 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000135 """
136 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000137 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000138 if not member_vnf_index:
139 additional_params = copy(ns_request.get("additionalParamsForNs"))
140 where_ = "additionalParamsForNs"
141 elif ns_request.get("additionalParamsForVnf"):
tierno714954e2019-11-29 13:43:26 +0000142 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index)
143 item = next((x for x in ns_request["additionalParamsForVnf"] if x["member-vnf-index"] == member_vnf_index),
144 None)
145 if item:
tierno54db2e42020-04-06 15:29:42 +0000146 if not vdu_id and not kdu_name:
147 other_params = item
tierno714954e2019-11-29 13:43:26 +0000148 additional_params = copy(item.get("additionalParams")) or {}
149 if vdu_id and item.get("additionalParamsForVdu"):
150 item_vdu = next((x for x in item["additionalParamsForVdu"] if x["vdu_id"] == vdu_id), None)
tiernobce98f02020-04-17 11:27:47 +0000151 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000152 if item_vdu and item_vdu.get("additionalParams"):
153 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000154 additional_params = item_vdu["additionalParams"]
155 if kdu_name:
156 additional_params = {}
157 if item.get("additionalParamsForKdu"):
158 item_kdu = next((x for x in item["additionalParamsForKdu"] if x["kdu_name"] == kdu_name), None)
tiernobce98f02020-04-17 11:27:47 +0000159 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000160 if item_kdu and item_kdu.get("additionalParams"):
161 where_ += ".additionalParamsForKdu[kdu_name={}]".format(kdu_name)
162 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000163
tiernobee085c2018-12-12 17:03:04 +0000164 if additional_params:
165 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000166 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
167 if not kdu_name and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k):
delacruzramo36ffe552019-05-03 14:52:37 +0200168 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
169 "and underscores, and cannot start with a digit"
170 .format(where_, k))
171 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000172 if not isinstance(k, str):
173 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
174 if "." in k or "$" in k:
175 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
176 if isinstance(v, (dict, tuple, list)):
177 additional_params[k] = "!!yaml " + safe_dump(v)
178
179 if descriptor:
bravof41a52052021-02-17 18:08:01 -0300180 for df in descriptor.get("df", []):
181 # check that enough parameters are supplied for the initial-config-primitive
182 # TODO: check for cloud-init
183 if member_vnf_index:
garciaale7cbd03c2020-11-27 10:38:35 -0300184 initial_primitives = []
bravof41a52052021-02-17 18:08:01 -0300185 if "lcm-operations-configuration" in df \
186 and "operate-vnf-op-config" in df["lcm-operations-configuration"]:
187 for config in df["lcm-operations-configuration"]["operate-vnf-op-config"].get("day1-2", []):
188 for primitive in get_iterable(config.get("initial-config-primitive")):
189 initial_primitives.append(primitive)
190 else:
191 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
tiernobee085c2018-12-12 17:03:04 +0000192
bravof41a52052021-02-17 18:08:01 -0300193 for initial_primitive in get_iterable(initial_primitives):
194 for param in get_iterable(initial_primitive.get("parameter")):
195 if param["value"].startswith("<") and param["value"].endswith(">"):
196 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
197 continue
198 if not additional_params or param["value"][1:-1] not in additional_params:
199 raise EngineException("Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
200 "initial-config-primitive[name={}] not supplied".
201 format(param["value"], descriptor["id"],
202 initial_primitive["name"]))
tierno714954e2019-11-29 13:43:26 +0000203
tierno54db2e42020-04-06 15:29:42 +0000204 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000205
tierno65ca36d2019-02-12 19:27:52 +0100206 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200207 """
208 Creates a new nsr into database. It also creates needed vnfrs
209 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100210 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200211 :param indata: params to be used for the nsr
212 :param kwargs: used to override the indata descriptor
213 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000214 :return: the _id of nsr descriptor created at database. Or an exception of type
215 EngineException, ValidationError, DbException, FsException, MsgException.
216 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200217 """
tiernob24258a2018-10-04 18:39:49 +0200218 try:
delacruzramo32bab472019-09-13 12:24:22 +0200219 step = "checking quotas"
220 self.check_quota(session)
221
tierno99d4b172019-07-02 09:28:40 +0000222 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200223 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200224 self._update_input_with_kwargs(ns_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -0300225 ns_request = self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200226
tiernob24258a2018-10-04 18:39:49 +0200227 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale7cbd03c2020-11-27 10:38:35 -0300228 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
229 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200230
Frank Bryden3c64ab62020-07-21 14:25:32 +0000231 step = "checking nsdOperationalState"
garciaale7cbd03c2020-11-27 10:38:35 -0300232 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000233
tiernob24258a2018-10-04 18:39:49 +0200234 step = "filling nsr from input data"
garciaale7cbd03c2020-11-27 10:38:35 -0300235 nsr_id = str(uuid4())
bravof1eee0e22021-02-26 16:57:52 -0300236 nsr_descriptor = self._create_nsr_descriptor_from_nsd(nsd, ns_request, nsr_id, session)
tierno54db2e42020-04-06 15:29:42 +0000237
garciaale7cbd03c2020-11-27 10:38:35 -0300238 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200239 needed_vnfds = {}
garciaale7cbd03c2020-11-27 10:38:35 -0300240 # TODO: Change for multiple df support
241 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
242 for vnfp in vnf_profiles:
243 vnfd_id = vnfp.get("vnfd-id")
244 vnf_index = vnfp.get("id")
245 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(vnfd_id, vnf_index)
tiernob24258a2018-10-04 18:39:49 +0200246 if vnfd_id not in needed_vnfds:
garciaale7cbd03c2020-11-27 10:38:35 -0300247 vnfd = self._get_vnfd_from_db(vnfd_id, session)
tiernob24258a2018-10-04 18:39:49 +0200248 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000249 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200250 else:
251 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100252
garciaale7cbd03c2020-11-27 10:38:35 -0300253 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(vnfd_id, vnf_index)
254 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(nsd, vnfd, vnfd_id, vnf_index, nsr_descriptor,
255 ns_request, ns_k8s_namespace)
tierno36ec8602018-11-02 17:27:11 +0100256
garciaale7cbd03c2020-11-27 10:38:35 -0300257 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(vnfd_id, vnf_index)
258 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
259 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
tiernob24258a2018-10-04 18:39:49 +0200260
261 step = "creating nsr at database"
garciaale7cbd03c2020-11-27 10:38:35 -0300262 self._add_nsr_to_db(nsr_descriptor, rollback, session)
tiernobee085c2018-12-12 17:03:04 +0000263
264 step = "creating nsr temporal folder"
265 self.fs.mkdir(nsr_id)
266
tiernobdebce92019-07-01 15:36:49 +0000267 return nsr_id, None
tierno1bfe4e22019-09-02 16:03:25 +0000268 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000269 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200270
garciaale7cbd03c2020-11-27 10:38:35 -0300271 def _get_nsd_from_db(self, nsd_id, session):
272 _filter = self._get_project_filter(session)
273 _filter["_id"] = nsd_id
274 return self.db.get_one("nsds", _filter)
275
276 def _get_vnfd_from_db(self, vnfd_id, session):
277 _filter = self._get_project_filter(session)
278 _filter["id"] = vnfd_id
279 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
280 vnfd.pop("_admin")
281 return vnfd
282
283 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
284 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
285 self.db.create("nsrs", nsr_descriptor)
286 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
287
288 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
289 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
290 self.db.create("vnfrs", vnfr_descriptor)
291 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
292
293 def _check_nsd_operational_state(self, nsd, ns_request):
294 if nsd["_admin"]["operationalState"] == "DISABLED":
295 raise EngineException("nsd with id '{}' is DISABLED, and thus cannot be used to create "
296 "a network service".format(ns_request["nsdId"]), http_code=HTTPStatus.CONFLICT)
297
298 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
299 additional_params, _ = self._format_additional_params(ns_request, descriptor=nsd)
300 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
301 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
302 if ns_request and ns_request.get("k8s-namespace"):
303 ns_k8s_namespace = ns_request["k8s-namespace"]
304 if additional_params and additional_params.get("k8s-namespace"):
305 ns_k8s_namespace = additional_params["k8s-namespace"]
306
307 return ns_k8s_namespace
308
bravof1eee0e22021-02-26 16:57:52 -0300309 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
garciaale7cbd03c2020-11-27 10:38:35 -0300310 now = time()
311 additional_params, _ = self._format_additional_params(ns_request, descriptor=nsd)
312
313 nsr_descriptor = {
314 "name": ns_request["nsName"],
315 "name-ref": ns_request["nsName"],
316 "short-name": ns_request["nsName"],
317 "admin-status": "ENABLED",
318 "nsState": "NOT_INSTANTIATED",
319 "currentOperation": "IDLE",
320 "currentOperationID": None,
321 "errorDescription": None,
322 "errorDetail": None,
323 "deploymentStatus": None,
324 "configurationStatus": None,
325 "vcaStatus": None,
326 "nsd": {k: v for k, v in nsd.items()},
327 "datacenter": ns_request["vimAccountId"],
328 "resource-orchestrator": "osmopenmano",
329 "description": ns_request.get("nsDescription", ""),
330 "constituent-vnfr-ref": [],
331 "operational-status": "init", # typedef ns-operational-
332 "config-status": "init", # typedef config-states
333 "detailed-status": "scheduled",
334 "orchestration-progress": {},
335 "create-time": now,
336 "nsd-name-ref": nsd["name"],
337 "operational-events": [], # "id", "timestamp", "description", "event",
338 "nsd-ref": nsd["id"],
339 "nsd-id": nsd["_id"],
340 "vnfd-id": [],
341 "instantiate_params": self._format_ns_request(ns_request),
342 "additionalParamsForNs": additional_params,
343 "ns-instance-config-ref": nsr_id,
344 "id": nsr_id,
345 "_id": nsr_id,
346 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
347 "flavor": [],
348 "image": [],
349 }
350 ns_request["nsr_id"] = nsr_id
351 if ns_request and ns_request.get("config-units"):
352 nsr_descriptor["config-units"] = ns_request["config-units"]
353
354 # Create vld
355 if nsd.get("virtual-link-desc"):
356 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
357 # Fill each vld with vnfd-connection-point-ref data
358 # TODO: Change for multiple df support
359 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
360 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
361 for vnf_profile in vnf_profiles:
362 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
363 for cpd in vlc.get("constituent-cpd-id", ()):
364 all_vld_connection_point_data[vlc.get("virtual-link-profile-id")].append({
365 "member-vnf-index-ref": cpd.get("constituent-base-element-id"),
366 "vnfd-connection-point-ref": cpd.get("constituent-cpd-id"),
367 "vnfd-id-ref": vnf_profile.get("vnfd-id")
368 })
369
bravof1eee0e22021-02-26 16:57:52 -0300370 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
garciaale7cbd03c2020-11-27 10:38:35 -0300371
372 for vdu in vnfd.get("vdu", ()):
373 flavor_data = {}
374 guest_epa = {}
375 # Find this vdu compute and storage descriptors
376 vdu_virtual_compute = {}
377 vdu_virtual_storage = {}
378 for vcd in vnfd.get("virtual-compute-desc", ()):
379 if vcd.get("id") == vdu.get("virtual-compute-desc"):
380 vdu_virtual_compute = vcd
381 for vsd in vnfd.get("virtual-storage-desc", ()):
382 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
383 vdu_virtual_storage = vsd
384 # Get this vdu vcpus, memory and storage info for flavor_data
385 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
386 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"]["num-virtual-cpu"]
387 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
388 flavor_data["memory-mb"] = float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
389 if vdu_virtual_storage.get("size-of-storage"):
390 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
391 # Get this vdu EPA info for guest_epa
392 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
393 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
394 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
395 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
396 if vcpu_pinning.get("thread-policy"):
397 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
398 if vcpu_pinning.get("policy"):
399 cpu_policy = "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
400 guest_epa["cpu-pinning-policy"] = cpu_policy
401 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
402 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
403 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
404 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"]["mempage-size"]
405 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
406 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"]["numa-node-policy"]
407 if vdu_virtual_storage.get("disk-io-quota"):
408 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
409
410 if guest_epa:
411 flavor_data["guest-epa"] = guest_epa
412
413 flavor_data["name"] = vdu["id"][:56] + "-flv"
414 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
415 nsr_descriptor["flavor"].append(flavor_data)
416
417 sw_image_id = vdu.get("sw-image-desc")
418 if sw_image_id:
lloretgalleg28c13b62021-02-08 11:48:48 +0000419 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
420 self._add_image_to_nsr(nsr_descriptor, image_data)
421
422 # also add alternative images to the list of images
423 for alt_image in vdu.get("alternative-sw-image-desc", ()):
424 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
425 self._add_image_to_nsr(nsr_descriptor, image_data)
garciaale7cbd03c2020-11-27 10:38:35 -0300426
427 for vld in nsr_vld:
428 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(vld.get("id"), [])
429 vld["name"] = vld["id"]
430 nsr_descriptor["vld"] = nsr_vld
431
432 return nsr_descriptor
433
lloretgalleg28c13b62021-02-08 11:48:48 +0000434 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
435 sw_image_desc = utils.find_in_list(vnfd.get("sw-image-desc", ()),
436 lambda sw: sw["id"] == sw_image_id)
437 image_data = {}
438 if sw_image_desc.get("image"):
439 image_data["image"] = sw_image_desc["image"]
440 if sw_image_desc.get("checksum"):
441 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
442 if sw_image_desc.get("vim-type"):
443 image_data["vim-type"] = sw_image_desc["vim-type"]
444 return image_data
445
446 def _add_image_to_nsr(self, nsr_descriptor, image_data):
447 """
448 Adds image to nsr checking first it is not already added
449 """
450 img = next((f for f in nsr_descriptor["image"] if
451 all(f.get(k) == image_data[k] for k in image_data)), None)
452 if not img:
453 image_data["id"] = str(len(nsr_descriptor["image"]))
454 nsr_descriptor["image"].append(image_data)
455
garciaale7cbd03c2020-11-27 10:38:35 -0300456 def _create_vnfr_descriptor_from_vnfd(self, nsd, vnfd, vnfd_id, vnf_index, nsr_descriptor,
457 ns_request, ns_k8s_namespace):
458 vnfr_id = str(uuid4())
459 nsr_id = nsr_descriptor["id"]
460 now = time()
461 additional_params, vnf_params = self._format_additional_params(ns_request, vnf_index, descriptor=vnfd)
462
463 vnfr_descriptor = {
464 "id": vnfr_id,
465 "_id": vnfr_id,
466 "nsr-id-ref": nsr_id,
467 "member-vnf-index-ref": vnf_index,
468 "additionalParamsForVnf": additional_params,
469 "created-time": now,
470 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
471 "vnfd-ref": vnfd_id,
472 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
473 "vim-account-id": None,
474 "vdur": [],
475 "connection-point": [],
476 "ip-address": None, # mgmt-interface filled by LCM
477 }
478 vnf_k8s_namespace = ns_k8s_namespace
479 if vnf_params:
480 if vnf_params.get("k8s-namespace"):
481 vnf_k8s_namespace = vnf_params["k8s-namespace"]
482 if vnf_params.get("config-units"):
483 vnfr_descriptor["config-units"] = vnf_params["config-units"]
484
485 # Create vld
486 if vnfd.get("int-virtual-link-desc"):
487 vnfr_descriptor["vld"] = []
488 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
489 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
490
491 for cp in vnfd.get("ext-cpd", ()):
492 vnf_cp = {
493 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100494 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
495 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300496 "id": cp.get("id"),
497 # "ip-address", "mac-address" # filled by LCM
498 # vim-id # TODO it would be nice having a vim port id
499 }
500 vnfr_descriptor["connection-point"].append(vnf_cp)
501
502 # Create k8s-cluster information
503 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
504 if vnfd.get("k8s-cluster"):
505 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
506 all_k8s_cluster_nets_cpds = {}
507 for cpd in get_iterable(vnfd.get("ext-cpd")):
508 if cpd.get("k8s-cluster-net"):
509 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get("id")
510 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
511 if net.get("id") in all_k8s_cluster_nets_cpds:
512 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[net.get("id")]
513
514 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300515 for kdu in get_iterable(vnfd.get("kdu")):
516 additional_params, kdu_params = self._format_additional_params(ns_request,
517 vnf_index,
518 kdu_name=kdu["name"],
519 descriptor=vnfd)
520 kdu_k8s_namespace = vnf_k8s_namespace
521 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
522 if kdu_params and kdu_params.get("k8s-namespace"):
523 kdu_k8s_namespace = kdu_params["k8s-namespace"]
524
romeromonserf949db62021-05-28 10:59:05 +0200525 kdu_deployment_name = ""
526 if kdu_params and kdu_params.get("kdu-deployment-name"):
527 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
528
garciaale7cbd03c2020-11-27 10:38:35 -0300529 kdur = {
530 "additionalParams": additional_params,
531 "k8s-namespace": kdu_k8s_namespace,
romeromonserf949db62021-05-28 10:59:05 +0200532 "kdu-deployment-name": kdu_deployment_name,
garciadeblas61e0c522020-12-15 10:33:40 +0000533 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300534 # TODO "name": "" Name of the VDU in the VIM
535 "ip-address": None, # mgmt-interface filled by LCM
536 "k8s-cluster": {},
537 }
538 if kdu_params and kdu_params.get("config-units"):
539 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000540 if kdu.get("helm-version"):
541 kdur["helm-version"] = kdu["helm-version"]
542 for k8s_type in ("helm-chart", "juju-bundle"):
543 if kdu.get(k8s_type):
544 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300545 if not vnfr_descriptor.get("kdur"):
546 vnfr_descriptor["kdur"] = []
547 vnfr_descriptor["kdur"].append(kdur)
548
549 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300550
garciaale7cbd03c2020-11-27 10:38:35 -0300551 for vdu in vnfd.get("vdu", ()):
bravoff3c39552021-02-24 17:22:24 -0300552 vdu_mgmt_cp = []
553 try:
554 configs = vnfd.get("df")[0]["lcm-operations-configuration"]["operate-vnf-op-config"]["day1-2"]
555 vdu_config = utils.find_in_list(configs, lambda config: config["id"] == vdu["id"])
556 except Exception:
557 vdu_config = None
bravof5cfc4b32021-04-22 10:03:02 -0400558
559 try:
560 vdu_instantiation_level = utils.find_in_list(
561 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
562 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"]
563 )
564 except Exception:
565 vdu_instantiation_level = None
566
bravoff3c39552021-02-24 17:22:24 -0300567 if vdu_config:
568 external_connection_ee = utils.filter_in_list(
569 vdu_config.get("execution-environment-list", []),
570 lambda ee: "external-connection-point-ref" in ee
571 )
572 for ee in external_connection_ee:
573 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
574
garciaale7cbd03c2020-11-27 10:38:35 -0300575 additional_params, vdu_params = self._format_additional_params(
576 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd)
577 vdur = {
578 "vdu-id-ref": vdu["id"],
579 # TODO "name": "" Name of the VDU in the VIM
580 "ip-address": None, # mgmt-interface filled by LCM
581 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
582 "internal-connection-point": [],
583 "interfaces": [],
584 "additionalParams": additional_params,
585 "vdu-name": vdu["name"]
586 }
587 if vdu_params and vdu_params.get("config-units"):
588 vdur["config-units"] = vdu_params["config-units"]
589 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
590 vdur["boot-data-drive"] = vdu["supplemental-boot-data"]["boot-data-drive"]
591 if vdu.get("pdu-type"):
592 vdur["pdu-type"] = vdu["pdu-type"]
593 vdur["name"] = vdu["pdu-type"]
594 # TODO volumes: name, volume-id
595 for icp in vdu.get("int-cpd", ()):
596 vdu_icp = {
597 "id": icp["id"],
598 "connection-point-id": icp["id"],
599 "name": icp.get("id"),
600 }
bravof35766442021-02-04 14:58:04 -0300601
garciaale7cbd03c2020-11-27 10:38:35 -0300602 vdur["internal-connection-point"].append(vdu_icp)
603
604 for iface in icp.get("virtual-network-interface-requirement", ()):
605 iface_fields = ("name", "mac-address")
606 vdu_iface = {x: iface[x] for x in iface_fields if iface.get(x) is not None}
607
608 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
sousaedu510da532021-03-02 00:19:15 +0100609 if "port-security-enabled" in icp:
610 vdu_iface["port-security-enabled"] = icp["port-security-enabled"]
611
612 if "port-security-disable-strategy" in icp:
613 vdu_iface["port-security-disable-strategy"] = icp["port-security-disable-strategy"]
614
garciaale7cbd03c2020-11-27 10:38:35 -0300615 for ext_cp in vnfd.get("ext-cpd", ()):
616 if not ext_cp.get("int-cpd"):
617 continue
618 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
619 continue
620 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
621 vdu_iface["external-connection-point-ref"] = ext_cp.get("id")
sousaedu510da532021-03-02 00:19:15 +0100622
623 if "port-security-enabled" in ext_cp:
624 vdu_iface["port-security-enabled"] = (
625 ext_cp["port-security-enabled"]
626 )
627
628 if "port-security-disable-strategy" in ext_cp:
629 vdu_iface["port-security-disable-strategy"] = (
630 ext_cp["port-security-disable-strategy"]
631 )
632
garciaale7cbd03c2020-11-27 10:38:35 -0300633 break
634
635 if vnfd_mgmt_cp and vdu_iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
636 vdu_iface["mgmt-vnf"] = True
bravoff3c39552021-02-24 17:22:24 -0300637 vdu_iface["mgmt-interface"] = True
638
639 for ecp in vdu_mgmt_cp:
640 if vdu_iface.get("external-connection-point-ref") == ecp:
641 vdu_iface["mgmt-interface"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300642
643 if iface.get("virtual-interface"):
644 vdu_iface.update(deepcopy(iface["virtual-interface"]))
645
646 # look for network where this interface is connected
647 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
648 if iface_ext_cp:
649 # TODO: Change for multiple df support
650 for df in get_iterable(nsd.get("df")):
651 for vnf_profile in get_iterable(df.get("vnf-profile")):
garciadeblas61c95912021-02-12 11:23:50 +0000652 for vlc_index, vlc in \
653 enumerate(get_iterable(vnf_profile.get("virtual-link-connectivity"))):
garciaale7cbd03c2020-11-27 10:38:35 -0300654 for cpd in get_iterable(vlc.get("constituent-cpd-id")):
655 if cpd.get("constituent-cpd-id") == iface_ext_cp:
656 vdu_iface["ns-vld-id"] = vlc.get("virtual-link-profile-id")
garciadeblas61c95912021-02-12 11:23:50 +0000657 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
658 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
659 nsr_descriptor["vld"][vlc_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300660 break
661 elif vdu_iface.get("internal-connection-point-ref"):
662 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
garciadeblas61c95912021-02-12 11:23:50 +0000663 # TODO: store fixed IP address in the record (if it exists in the ICP)
664 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
665 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
666 ivld_index = utils.find_index_in_list(vnfd.get("int-virtual-link-desc", ()),
667 lambda ivld:
668 ivld["id"] == icp.get("int-virtual-link-desc")
669 )
670 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
garciaale7cbd03c2020-11-27 10:38:35 -0300671
672 vdur["interfaces"].append(vdu_iface)
673
674 if vdu.get("sw-image-desc"):
675 sw_image = utils.find_in_list(
676 vnfd.get("sw-image-desc", ()),
677 lambda image: image["id"] == vdu.get("sw-image-desc"))
678 nsr_sw_image_data = utils.find_in_list(
679 nsr_descriptor["image"],
680 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image"))
681 )
682 vdur["ns-image-id"] = nsr_sw_image_data["id"]
683
lloretgalleg28c13b62021-02-08 11:48:48 +0000684 if vdu.get("alternative-sw-image-desc"):
685 alt_image_ids = []
686 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
687 sw_image = utils.find_in_list(
688 vnfd.get("sw-image-desc", ()),
689 lambda image: image["id"] == alt_image_id)
690 nsr_sw_image_data = utils.find_in_list(
691 nsr_descriptor["image"],
692 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image"))
693 )
694 alt_image_ids.append(nsr_sw_image_data["id"])
695 vdur["alt-image-ids"] = alt_image_ids
696
garciaale7cbd03c2020-11-27 10:38:35 -0300697 flavor_data_name = vdu["id"][:56] + "-flv"
698 nsr_flavor_desc = utils.find_in_list(
699 nsr_descriptor["flavor"],
700 lambda flavor: flavor["name"] == flavor_data_name)
701
702 if nsr_flavor_desc:
703 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
704
bravof5cfc4b32021-04-22 10:03:02 -0400705 if vdu_instantiation_level:
706 count = vdu_instantiation_level.get("number-of-instances")
707 else:
708 count = 1
709
garciaale7cbd03c2020-11-27 10:38:35 -0300710 for index in range(0, count):
711 vdur = deepcopy(vdur)
712 for iface in vdur["interfaces"]:
bravofa8ba45a2021-07-01 09:32:30 -0400713 if iface.get("ip-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -0300714 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
bravofa8ba45a2021-07-01 09:32:30 -0400715 if iface.get("mac-address") and index != 0:
garciaale7cbd03c2020-11-27 10:38:35 -0300716 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
717
718 vdur["_id"] = str(uuid4())
719 vdur["id"] = vdur["_id"]
720 vdur["count-index"] = index
721 vnfr_descriptor["vdur"].append(vdur)
722
723 return vnfr_descriptor
724
tierno65ca36d2019-02-12 19:27:52 +0100725 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200726 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
727
728
729class VnfrTopic(BaseTopic):
730 topic = "vnfrs"
731 topic_msg = None
732
delacruzramo32bab472019-09-13 12:24:22 +0200733 def __init__(self, db, fs, msg, auth):
734 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200735
tiernobee3bad2019-12-05 12:26:01 +0000736 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200737 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
738
tierno65ca36d2019-02-12 19:27:52 +0100739 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200740 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
741
tierno65ca36d2019-02-12 19:27:52 +0100742 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200743 # Not used because vnfrs are created and deleted by NsrTopic class directly
744 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
745
746
747class NsLcmOpTopic(BaseTopic):
748 topic = "nslcmops"
749 topic_msg = "ns"
750 operation_schema = { # mapping between operation and jsonschema to validate
751 "instantiate": ns_instantiate,
752 "action": ns_action,
753 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +0000754 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +0200755 }
756
delacruzramo32bab472019-09-13 12:24:22 +0200757 def __init__(self, db, fs, msg, auth):
758 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200759
tiernob24258a2018-10-04 18:39:49 +0200760 def _check_ns_operation(self, session, nsr, operation, indata):
761 """
762 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100763 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200764 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
765 :param indata: descriptor with the parameters of the operation
766 :return: None
767 """
garciaale7cbd03c2020-11-27 10:38:35 -0300768 if operation == "action":
769 self._check_action_ns_operation(indata, nsr)
770 elif operation == "scale":
771 self._check_scale_ns_operation(indata, nsr)
772 elif operation == "instantiate":
773 self._check_instantiate_ns_operation(indata, nsr, session)
774
775 def _check_action_ns_operation(self, indata, nsr):
776 nsd = nsr["nsd"]
777 # check vnf_member_index
778 if indata.get("vnf_member_index"):
779 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
780 if indata.get("member_vnf_index"):
781 vnfd = self._get_vnfd_from_vnf_member_index(indata["member_vnf_index"], nsr["_id"])
bravof41a52052021-02-17 18:08:01 -0300782 try:
783 configs = vnfd.get("df")[0]["lcm-operations-configuration"]["operate-vnf-op-config"]["day1-2"]
784 except Exception:
785 configs = []
786
garciaale7cbd03c2020-11-27 10:38:35 -0300787 if indata.get("vdu_id"):
788 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -0300789 descriptor_configuration = utils.find_in_list(
790 configs,
791 lambda config: config["id"] == indata["vdu_id"]
limon4b3aa172021-03-17 13:24:00 +0100792 )
garciaale7cbd03c2020-11-27 10:38:35 -0300793 elif indata.get("kdu_name"):
794 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -0300795 descriptor_configuration = utils.find_in_list(
796 configs,
797 lambda config: config["id"] == indata.get("kdu_name")
limon4b3aa172021-03-17 13:24:00 +0100798 )
garciaale7cbd03c2020-11-27 10:38:35 -0300799 else:
bravof41a52052021-02-17 18:08:01 -0300800 descriptor_configuration = utils.find_in_list(
801 configs,
802 lambda config: config["id"] == vnfd["id"]
limon4b3aa172021-03-17 13:24:00 +0100803 )
804 if descriptor_configuration is not None:
805 descriptor_configuration = descriptor_configuration.get("config-primitive")
garciaale7cbd03c2020-11-27 10:38:35 -0300806 else: # use a NSD
807 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
808
809 # For k8s allows default primitives without validating the parameters
810 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
811 # TODO should be checked that rollback only can contains revsision_numbe????
812 if not indata.get("member_vnf_index"):
813 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
814 .format(indata["primitive"]))
815 return
816 # if not, check primitive
817 for config_primitive in get_iterable(descriptor_configuration):
818 if indata["primitive"] == config_primitive["name"]:
819 # check needed primitive_params are provided
820 if indata.get("primitive_params"):
821 in_primitive_params_copy = copy(indata["primitive_params"])
822 else:
823 in_primitive_params_copy = {}
824 for paramd in get_iterable(config_primitive.get("parameter")):
825 if paramd["name"] in in_primitive_params_copy:
826 del in_primitive_params_copy[paramd["name"]]
827 elif not paramd.get("default-value"):
828 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
829 paramd["name"], indata["primitive"]))
830 # check no extra primitive params are provided
831 if in_primitive_params_copy:
832 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
833 list(in_primitive_params_copy.keys()), indata["primitive"]))
834 break
835 else:
836 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
837
838 def _check_scale_ns_operation(self, indata, nsr):
839 vnfd = self._get_vnfd_from_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"],
840 nsr["_id"])
lloretgallegdf9fd612020-12-01 12:51:52 +0000841 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
842 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_aspect["id"]:
garciaale7cbd03c2020-11-27 10:38:35 -0300843 break
844 else:
845 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
lloretgallegdf9fd612020-12-01 12:51:52 +0000846 "present at vnfd:scaling-aspect"
garciaale7cbd03c2020-11-27 10:38:35 -0300847 .format(indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
848
849 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +0000850 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +0200851 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000852 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200853 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -0300854 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
855 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
856 for in_vnf in get_iterable(indata.get("vnf")):
857 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +0000858 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -0300859 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +0000860 else:
garciaale7cbd03c2020-11-27 10:38:35 -0300861 vnfd = self._get_vnfd_from_vnf_member_index(member_vnf_index, nsr["_id"])
862 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
863 self._check_vnf_instantiation_params(in_vnf, vnfd)
864 if in_vnf.get("vimAccountId"):
865 self._check_valid_vim_account(in_vnf["vimAccountId"], vim_accounts, session)
tierno260dd6f2019-09-02 10:48:56 +0000866
garciaale7cbd03c2020-11-27 10:38:35 -0300867 for in_vld in get_iterable(indata.get("vld")):
868 self._check_valid_wim_account(in_vld.get("wimAccountId"), wim_accounts, session)
869 for vldd in get_iterable(nsd.get("virtual-link-desc")):
870 if in_vld["name"] == vldd["id"]:
871 break
tierno9cb7d672019-10-30 12:13:48 +0000872 else:
garciaale7cbd03c2020-11-27 10:38:35 -0300873 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
874 in_vld["name"]))
tierno9cb7d672019-10-30 12:13:48 +0000875
garciaale7cbd03c2020-11-27 10:38:35 -0300876 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
877 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
878 vnfr = self.db.get_one("vnfrs",
879 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
880 fail_on_empty=False)
881 if not vnfr:
882 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
883 "nsd:constituent-vnfd".format(member_vnf_index))
884 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
885 if not vnfd:
886 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
887 format(vnfr["vnfd-id"]))
888 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +0200889
garciaale7cbd03c2020-11-27 10:38:35 -0300890 def _check_valid_vdu(self, vnfd, vdu_id):
891 for vdud in get_iterable(vnfd.get("vdu")):
892 if vdud["id"] == vdu_id:
893 return vdud
894 else:
895 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
896
897 def _check_valid_kdu(self, vnfd, kdu_name):
898 for kdud in get_iterable(vnfd.get("kdu")):
899 if kdud["name"] == kdu_name:
900 return kdud
901 else:
902 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
903
904 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
905 for in_vdu in get_iterable(in_vnf.get("vdu")):
906 for vdu in get_iterable(vnfd.get("vdu")):
907 if in_vdu["id"] == vdu["id"]:
908 for volume in get_iterable(in_vdu.get("volume")):
909 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
910 if volumed["id"] == volume["name"]:
911 break
912 else:
913 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
914 "volume:name='{}' is not present at "
915 "vnfd:vdu:virtual-storage-desc list".
916 format(in_vnf["member-vnf-index"], in_vdu["id"],
917 volume["id"]))
918
919 vdu_if_names = set()
920 for cpd in get_iterable(vdu.get("int-cpd")):
921 for iface in get_iterable(cpd.get("virtual-network-interface-requirement")):
922 vdu_if_names.add(iface.get("name"))
923
924 for in_iface in get_iterable(in_vdu["interface"]):
925 if in_iface["name"] in vdu_if_names:
926 break
927 else:
928 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
929 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd"
930 .format(in_vnf["member-vnf-index"], in_vdu["id"],
931 in_iface["name"]))
932 break
933
934 else:
935 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
936 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
937
938 vnfd_ivlds_cpds = {ivld.get("id"): set() for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))}
939 for vdu in get_iterable(vnfd.get("vdu")):
940 for cpd in get_iterable(vnfd.get("int-cpd")):
941 if cpd.get("int-virtual-link-desc"):
942 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
943
944 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
945 if in_ivld.get("name") in vnfd_ivlds_cpds:
946 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
947 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +0200948 break
tiernob24258a2018-10-04 18:39:49 +0200949 else:
garciaale7cbd03c2020-11-27 10:38:35 -0300950 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
951 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
952 "vnfd:internal-vld:name/id:internal-connection-point"
953 .format(in_vnf["member-vnf-index"], in_ivld["name"],
954 in_icp["id-ref"]))
tiernob24258a2018-10-04 18:39:49 +0200955 else:
garciaale7cbd03c2020-11-27 10:38:35 -0300956 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
957 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
958 in_ivld["name"], vnfd["id"]))
tiernob24258a2018-10-04 18:39:49 +0200959
garciaale7cbd03c2020-11-27 10:38:35 -0300960 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
961 if vim_account in vim_accounts:
962 return
963 try:
964 db_filter = self._get_project_filter(session)
965 db_filter["_id"] = vim_account
966 self.db.get_one("vim_accounts", db_filter)
967 except Exception:
968 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
969 vim_accounts.append(vim_account)
970
971 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
972 if not isinstance(wim_account, str):
973 return
974 if wim_account in wim_accounts:
975 return
976 try:
977 db_filter = self._get_project_filter(session, write=False, show_all=True)
978 db_filter["_id"] = wim_account
979 self.db.get_one("wim_accounts", db_filter)
980 except Exception:
981 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
982 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +0200983
tierno36ec8602018-11-02 17:27:11 +0100984 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200985 """
tierno36ec8602018-11-02 17:27:11 +0100986 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
987 (ip_address, ...) information.
988 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +0100989 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100990 :param rollback: list with the database modifications to rollback if needed
991 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
992 :param vim_account: vim_account where this vnfr should be deployed
993 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
994 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
995 of the changed vnfr is needed
996
997 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
998 "vim-network-name": used at VIM
999 "name": interface name
1000 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1001 "ns-vld-id": NSD vld where this interface is connected.
1002 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 +02001003 """
tierno36ec8602018-11-02 17:27:11 +01001004
1005 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +02001006 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1007 if not vdur.get("pdu-type"):
1008 continue
1009 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +01001010 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +01001011 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +02001012 pdu_filter["type"] = pdu_type
1013 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +01001014 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +02001015 # TODO feature 1417: "shared": True,
1016
1017 available_pdus = self.db.get_list("pdus", pdu_filter)
1018 for pdu in available_pdus:
1019 # step 1 check if this pdu contains needed interfaces:
1020 match_interfaces = True
1021 for vdur_interface in vdur["interfaces"]:
1022 for pdu_interface in pdu["interfaces"]:
1023 if pdu_interface["name"] == vdur_interface["name"]:
1024 # TODO feature 1417: match per mgmt type
1025 break
1026 else: # no interface found for name
1027 match_interfaces = False
1028 break
1029 if match_interfaces:
1030 break
1031 else:
1032 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +01001033 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1034 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +02001035
1036 # step 2. Update pdu
1037 rollback_pdu = {
1038 "_admin.usageState": pdu["_admin"]["usageState"],
1039 "_admin.usage.vnfr_id": None,
1040 "_admin.usage.nsr_id": None,
1041 "_admin.usage.vdur": None,
1042 }
1043 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +01001044 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +00001045 "_admin.usage": {"vnfr_id": vnfr["_id"],
1046 "nsr_id": vnfr["nsr-id-ref"],
1047 "vdur": vdur["vdu-id-ref"]}
1048 })
tiernocc103432018-10-19 14:10:35 +02001049 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
1050
1051 # step 3. Fill vnfr info by filling vdur
1052 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +01001053 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +02001054 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1055 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1056 for pdu_interface in pdu["interfaces"]:
1057 if pdu_interface["name"] == vdur_interface["name"]:
1058 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1059 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +01001060 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
1061 vnfr_update[iface_text + ".{}".format(k)] = v
1062 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
1063 if pdu_interface.get("ip-address"):
tiernoc88003e2020-03-12 17:31:42 +00001064 if vdur_interface.get("mgmt-interface") or vdur_interface.get("mgmt-vnf"):
tierno36ec8602018-11-02 17:27:11 +01001065 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
1066 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
1067 if vdur_interface.get("mgmt-vnf"):
1068 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
1069 vnfr_update["ip-address"] = pdu_interface["ip-address"]
tierno72b16e12020-03-18 09:49:43 +00001070 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +01001071 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +01001072 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +01001073 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
1074 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1075 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +01001076 if pdu_interface.get("vim-network-id"):
tiernoc67b0e92019-11-05 12:45:29 +00001077 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +01001078 if pdu_interface.get("vim-network-name"):
tiernoc67b0e92019-11-05 12:45:29 +00001079 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +02001080 break
1081
tierno36ec8602018-11-02 17:27:11 +01001082 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +02001083
tierno9cb7d672019-10-30 12:13:48 +00001084 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
1085 """
1086 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1087 Fills vnfr.kdur with the selected k8scluster
1088
1089 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1090 :param rollback: list with the database modifications to rollback if needed
1091 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1092 :param vim_account: vim_account where this vnfr should be deployed
1093 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1094 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1095 of the changed vnfr is needed
1096
1097 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1098 "vim-network-name": used at VIM
1099 "name": interface name
1100 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1101 "ns-vld-id": NSD vld where this interface is connected.
1102 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1103 """
1104
1105 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001106 if not vnfr.get("kdur"):
1107 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001108
tiernoc67b0e92019-11-05 12:45:29 +00001109 kdu_filter = self._get_project_filter(session)
1110 kdu_filter["vim_account"] = vim_account
1111 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1112 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1113
1114 k8s_requirements = {} # just for logging
1115 for k8scluster in available_k8sclusters:
1116 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001117 break
tiernoc67b0e92019-11-05 12:45:29 +00001118 # restrict by cni
1119 if vnfr["k8s-cluster"].get("cni"):
1120 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
1121 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
1122 continue
1123 # restrict by version
1124 if vnfr["k8s-cluster"].get("version"):
1125 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1126 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1127 continue
1128 # restrict by number of networks
1129 if vnfr["k8s-cluster"].get("nets"):
1130 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
1131 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
1132 continue
1133 break
1134 else:
1135 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
1136 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
tierno9cb7d672019-10-30 12:13:48 +00001137
tiernoc67b0e92019-11-05 12:45:29 +00001138 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001139 # step 3. Fill vnfr info by filling kdur
1140 kdu_text = "kdur.{}.".format(kdur_index)
1141 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1142 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1143
tiernoc67b0e92019-11-05 12:45:29 +00001144 # step 4. Check VIM networks that forces the selected k8s_cluster
1145 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1146 k8scluster_net_list = list(k8scluster.get("nets").keys())
1147 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1148 # get a network from k8s_cluster nets. If name matches use this, if not use other
1149 if kdur_net["id"] in k8scluster_net_list: # name matches
1150 vim_net = k8scluster["nets"][kdur_net["id"]]
1151 k8scluster_net_list.remove(kdur_net["id"])
1152 else:
1153 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1154 k8scluster_net_list.pop(0)
1155 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
1156 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
1157 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
1158 ifaces_forcing_vim_network.append({
1159 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
1160 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1161 "ns-vld-id": kdur_net.get("ns-vld-id"),
1162 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1163 })
1164 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001165 return ifaces_forcing_vim_network
1166
Gulsum Atici25e2b352021-11-10 20:59:06 +03001167 def _update_vnfrs_from_nsd(self, nsr):
1168 try:
1169 nsr_id = nsr["_id"]
1170 nsd = nsr["nsd"]
1171
1172 step = "Getting vnf_profiles from nsd"
1173 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1174 vld_fixed_ip_connection_point_data = {}
1175
1176 step = "Getting ip-address info from vnf_profile if it exists"
1177 for vnfp in vnf_profiles:
1178 # Checking ip-address info from nsd.vnf_profile and storing
1179 for vlc in vnfp.get("virtual-link-connectivity", ()):
1180 for cpd in vlc.get("constituent-cpd-id", ()):
1181 if cpd.get("ip-address"):
1182 step = "Storing ip-address info"
1183 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1184 "vnfd-connection-point-ref": cpd.get(
1185 "constituent-cpd-id"),
1186 "ip-address": cpd.get(
1187 "ip-address")}})
1188
1189 # Inserting ip address to vnfr
1190 if len(vld_fixed_ip_connection_point_data) > 0:
1191 step = "Getting vnfrs"
1192 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1193 for item in vld_fixed_ip_connection_point_data.keys():
1194 step = "Filtering vnfrs"
1195 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1196 if vnfr:
1197 vnfr_update = {}
1198 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1199 for iface_index, iface in enumerate(vdur["interfaces"]):
1200 step = "Looking for matched interface"
1201 if (
1202 iface.get("external-connection-point-ref")
1203 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1204 iface.get("ns-vld-id") == item.split('.')[0]
1205
1206 ):
1207 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1208 vdur_index, iface_index
1209 )
1210 step = "Storing info in order to update vnfr"
1211 vnfr_update[
1212 vnfr_update_text + ".ip-address"
1213 ] = increment_ip_mac(
1214 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1215 vdur.get("count-index", 0), )
1216 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1217
1218 step = "updating vnfr at database"
1219 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1220 except (
1221 ValidationError,
1222 EngineException,
1223 DbException,
1224 MsgException,
1225 FsException,
1226 ) as e:
1227 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1228
tiernocc103432018-10-19 14:10:35 +02001229 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001230 # get vnfr
1231 nsr_id = nsr["_id"]
1232 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1233
1234 for vnfr in vnfrs:
1235 vnfr_update = {}
1236 vnfr_update_rollback = {}
1237 member_vnf_index = vnfr["member-vnf-index-ref"]
1238 # update vim-account-id
1239
1240 vim_account = indata["vimAccountId"]
1241 # check instantiate parameters
1242 for vnf_inst_params in get_iterable(indata.get("vnf")):
1243 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1244 continue
1245 if vnf_inst_params.get("vimAccountId"):
1246 vim_account = vnf_inst_params.get("vimAccountId")
1247
tiernocddb07d2020-10-06 08:28:00 +00001248 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1249 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1250 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1251 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1252 continue
1253 for iface_inst_param in get_iterable(vdu_inst_param.get("interface")):
1254 iface_index, _ = next(i for i in enumerate(vdur["interfaces"])
1255 if i[1]["name"] == iface_inst_param["name"])
1256 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1257 if iface_inst_param.get("ip-address"):
1258 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1259 iface_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001260 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001261 if iface_inst_param.get("mac-address"):
1262 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1263 iface_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001264 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001265 if iface_inst_param.get("floating-ip-required"):
1266 vnfr_update[vnfr_update_text + ".floating-ip-required"] = True
tiernocddb07d2020-10-06 08:28:00 +00001267 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1268 # TODO update vld with the ip-profile
1269 for ivld_inst_param in get_iterable(vnf_inst_params.get("internal-vld")):
1270 for icp_inst_param in get_iterable(ivld_inst_param.get("internal-connection-point")):
1271 # look for iface
1272 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1273 for iface_index, iface in enumerate(vdur["interfaces"]):
1274 if iface.get("internal-connection-point-ref") == icp_inst_param["id-ref"]:
1275 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1276 if icp_inst_param.get("ip-address"):
1277 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1278 icp_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001279 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001280 if icp_inst_param.get("mac-address"):
1281 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1282 icp_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001283 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001284 break
1285 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1286 for vld_inst_param in get_iterable(indata.get("vld")):
1287 for vnfcp_inst_param in get_iterable(vld_inst_param.get("vnfd-connection-point-ref")):
1288 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1289 continue
1290 # look for iface
1291 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1292 for iface_index, iface in enumerate(vdur["interfaces"]):
1293 if iface.get("external-connection-point-ref") == \
1294 vnfcp_inst_param["vnfd-connection-point-ref"]:
1295 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1296 if vnfcp_inst_param.get("ip-address"):
1297 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1298 vnfcp_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001299 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001300 if vnfcp_inst_param.get("mac-address"):
1301 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1302 vnfcp_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001303 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001304 break
1305
tiernocc103432018-10-19 14:10:35 +02001306 vnfr_update["vim-account-id"] = vim_account
1307 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1308
1309 # get pdu
tierno36ec8602018-11-02 17:27:11 +01001310 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
1311 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +02001312
tierno9cb7d672019-10-30 12:13:48 +00001313 # get kdus
1314 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
1315 vnfr_update_rollback)
1316 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001317 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1318 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
1319
1320 # Update indada in case pdu forces to use a concrete vim-network-name
1321 # TODO check if user has already insert a vim-network-name and raises an error
1322 if not ifaces_forcing_vim_network:
1323 continue
1324 for iface_info in ifaces_forcing_vim_network:
1325 if iface_info.get("ns-vld-id"):
1326 if "vld" not in indata:
1327 indata["vld"] = []
1328 indata["vld"].append({key: iface_info[key] for key in
1329 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
1330
1331 elif iface_info.get("vnf-vld-id"):
1332 if "vnf" not in indata:
1333 indata["vnf"] = []
1334 indata["vnf"].append({
1335 "member-vnf-index": member_vnf_index,
1336 "internal-vld": [{key: iface_info[key] for key in
1337 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
1338 })
1339
1340 @staticmethod
1341 def _create_nslcmop(nsr_id, operation, params):
1342 """
1343 Creates a ns-lcm-opp content to be stored at database.
1344 :param nsr_id: internal id of the instance
1345 :param operation: instantiate, terminate, scale, action, ...
1346 :param params: user parameters for the operation
1347 :return: dictionary following SOL005 format
1348 """
tiernob24258a2018-10-04 18:39:49 +02001349 now = time()
1350 _id = str(uuid4())
1351 nslcmop = {
1352 "id": _id,
1353 "_id": _id,
1354 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001355 "queuePosition": None,
1356 "stage": None,
1357 "errorMessage": None,
1358 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001359 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001360 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001361 "lcmOperationType": operation,
1362 "startTime": now,
1363 "isAutomaticInvocation": False,
1364 "operationParams": params,
1365 "isCancelPending": False,
1366 "links": {
1367 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001368 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001369 }
1370 }
1371 return nslcmop
1372
magnussonlf318b302020-01-20 18:38:18 +01001373 def _get_enabled_vims(self, session):
1374 """
1375 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1376 :param session: current session with user information
1377 """
1378 db_filter = self._get_project_filter(session)
1379 db_filter["_admin.operationalState"] = "ENABLED"
1380 vims = self.db.get_list("vim_accounts", db_filter)
1381 vimAccounts = []
1382 for vim in vims:
1383 vimAccounts.append(vim['_id'])
1384 return vimAccounts
1385
tierno65ca36d2019-02-12 19:27:52 +01001386 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +02001387 """
1388 Performs a new operation over a ns
1389 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001390 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001391 :param indata: descriptor with the parameters of the operation. It must contains among others
1392 nsInstanceId: _id of the nsr to perform the operation
1393 operation: it can be: instantiate, terminate, action, TODO: update, heal
1394 :param kwargs: used to override the indata descriptor
1395 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02001396 :return: id of the nslcmops
1397 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001398 def check_if_nsr_is_not_slice_member(session, nsr_id):
1399 nsis = None
1400 db_filter = self._get_project_filter(session)
1401 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1402 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
1403 if nsis:
tierno40f742b2020-06-23 15:25:26 +00001404 raise EngineException("The NS instance {} cannot be terminated because is used by the slice {}".format(
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001405 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
1406
tiernob24258a2018-10-04 18:39:49 +02001407 try:
1408 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00001409 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02001410 operation = indata["lcmOperationType"]
1411 nsInstanceId = indata["nsInstanceId"]
1412
1413 validate_input(indata, self.operation_schema[operation])
1414 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01001415 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02001416 _filter["_id"] = nsInstanceId
1417 nsr = self.db.get_one("nsrs", _filter)
1418
1419 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001420 if operation == "terminate" and slice_object is False:
1421 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +02001422 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1423 if operation == "terminate" and indata.get("autoremove"):
1424 # NSR must be deleted
tierno586ae812019-10-17 13:56:53 +00001425 return None, None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02001426 if operation != "instantiate":
1427 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1428 nsInstanceId, operation), HTTPStatus.CONFLICT)
1429 else:
tierno65ca36d2019-02-12 19:27:52 +01001430 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +02001431 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1432 nsInstanceId, operation), HTTPStatus.CONFLICT)
1433 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +01001434
tiernocc103432018-10-19 14:10:35 +02001435 if operation == "instantiate":
Gulsum Atici25e2b352021-11-10 20:59:06 +03001436 self._update_vnfrs_from_nsd(nsr)
tiernocc103432018-10-19 14:10:35 +02001437 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01001438
1439 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00001440 _id = nslcmop_desc["_id"]
tierno65ca36d2019-02-12 19:27:52 +01001441 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
magnussonlf318b302020-01-20 18:38:18 +01001442 if indata.get("placement-engine"):
1443 # Save valid vim accounts in lcm operation descriptor
1444 nslcmop_desc['operationParams']['validVimAccounts'] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00001445 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02001446 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001447 if not slice_object:
1448 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001449 return _id, None
1450 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02001451 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1452 # except DbException as e:
1453 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1454
tiernobee3bad2019-12-05 12:26:01 +00001455 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +02001456 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1457
tierno65ca36d2019-02-12 19:27:52 +01001458 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +02001459 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001460
1461
1462class NsiTopic(BaseTopic):
1463 topic = "nsis"
1464 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00001465 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001466
delacruzramo32bab472019-09-13 12:24:22 +02001467 def __init__(self, db, fs, msg, auth):
1468 BaseTopic.__init__(self, db, fs, msg, auth)
1469 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001470
Felipe Vicensc37b3842019-01-12 12:24:42 +01001471 @staticmethod
1472 def _format_ns_request(ns_request):
1473 formated_request = copy(ns_request)
1474 # TODO: Add request params
1475 return formated_request
1476
1477 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001478 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001479 """
1480 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001481 :param slice_request: User instantiation additional parameters
1482 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001483 """
tiernofd160572019-01-21 10:41:37 +00001484 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1485 if additional_params:
1486 for k, v in additional_params.items():
1487 if not isinstance(k, str):
1488 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1489 format(k))
1490 if "." in k or "$" in k:
1491 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1492 format(k))
1493 if isinstance(v, (dict, tuple, list)):
1494 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001495 return additional_params
1496
Felipe Vicensb57758d2018-10-16 16:00:20 +02001497 def _check_descriptor_dependencies(self, session, descriptor):
1498 """
1499 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001500 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001501 :param descriptor: descriptor to be inserted or edit
1502 :return: None or raises exception
1503 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001504 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001505 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001506 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001507 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +01001508 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +02001509 http_code=HTTPStatus.CONFLICT)
1510
tiernob4844ab2019-05-23 08:42:12 +00001511 def check_conflict_on_del(self, session, _id, db_content):
1512 """
1513 Check that NSI is not instantiated
1514 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1515 :param _id: nsi internal id
1516 :param db_content: The database content of the _id
1517 :return: None or raises EngineException with the conflict
1518 """
tierno65ca36d2019-02-12 19:27:52 +01001519 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02001520 return
tiernob4844ab2019-05-23 08:42:12 +00001521 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02001522 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1523 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1524 "Launch 'terminate' operation first; or force deletion".format(_id),
1525 http_code=HTTPStatus.CONFLICT)
1526
tiernobee3bad2019-12-05 12:26:01 +00001527 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001528 """
tiernob4844ab2019-05-23 08:42:12 +00001529 Deletes associated nsilcmops from database. Deletes associated filesystem.
1530 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01001531 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001532 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00001533 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00001534 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00001535 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02001536 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001537
Felipe Vicens09e65422019-01-22 15:06:46 +01001538 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00001539 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01001540 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1541 nsr_id = nsrs_detailed_item["nsrId"]
1542 if nsrs_detailed_item.get("shared"):
1543 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1544 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1545 "_id.ne": nsir["_id"]}
1546 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1547 if nsi: # last one using nsr
1548 continue
1549 try:
tiernobee3bad2019-12-05 12:26:01 +00001550 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
Felipe Vicens09e65422019-01-22 15:06:46 +01001551 except (DbException, EngineException) as e:
1552 if e.http_code == HTTPStatus.NOT_FOUND:
1553 pass
1554 else:
1555 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001556
tiernob4844ab2019-05-23 08:42:12 +00001557 # delete related nsilcmops database entries
1558 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001559
tiernob4844ab2019-05-23 08:42:12 +00001560 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01001561 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00001562 if nsir_admin and nsir_admin.get("nst-id"):
1563 # check if used by another NSI
1564 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1565 fail_on_empty=False, fail_on_more=False)
1566 if not nsis_list:
1567 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1568
tierno65ca36d2019-02-12 19:27:52 +01001569 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001570 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001571 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02001572 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01001573 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001574 :param indata: params to be used for the nsir
1575 :param kwargs: used to override the indata descriptor
1576 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02001577 :return: the _id of nsi descriptor created at database
1578 """
1579
1580 try:
delacruzramo32bab472019-09-13 12:24:22 +02001581 step = "checking quotas"
1582 self.check_quota(session)
1583
tierno99d4b172019-07-02 09:28:40 +00001584 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02001585 slice_request = self._remove_envelop(indata)
1586 # Override descriptor with query string kwargs
1587 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03001588 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001589
Felipe Vicensb57758d2018-10-16 16:00:20 +02001590 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +00001591 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001592 _filter = self._get_project_filter(session)
1593 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001594 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00001595 # check NST is not disabled
1596 step = "checking NST operationalState"
1597 if nstd["_admin"]["operationalState"] == "DISABLED":
1598 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
1599 "instance".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
tiernob4844ab2019-05-23 08:42:12 +00001600 del _filter["_id"]
1601
Frank Brydenb5a2ead2020-07-28 12:50:23 +00001602 # check NSD is not disabled
1603 step = "checking operationalState"
1604 if nstd["_admin"]["operationalState"] == "DISABLED":
1605 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create "
1606 "a network slice".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
1607
Felipe Vicens07f31722018-10-29 15:16:44 +01001608 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001609 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001610 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001611 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001612
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001613 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001614 nsi_descriptor = {
1615 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001616 "name": slice_request["nsiName"],
1617 "description": slice_request.get("nsiDescription", ""),
1618 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001619 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001620 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001621 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001622 "nsr-ref-list": [],
1623 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001624 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001625 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001626 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001627
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001628 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001629 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001630 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1631 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001632 nsi_descriptor["_admin"]["deployed"] = {}
1633 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1634 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1635
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001636 # Creating netslice-vld for the RO.
1637 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001638
1639 # Building the vlds list to be deployed
1640 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001641 nsi_vlds = []
1642
1643 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1644 # Getting template Instantiation parameters from NST
1645 nsi_vld = deepcopy(netslice_vlds)
1646 nsi_vld["shared-nsrs-list"] = []
1647 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1648 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001649
1650 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00001651 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001652 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001653 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001654
Felipe Vicens09e65422019-01-22 15:06:46 +01001655 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001656 for member_ns in nstd["netslice-subnet"]:
1657 nsd_id = member_ns["nsd-ref"]
1658 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1659 member_ns["nsd-ref"], member_ns["id"])
1660 if nsd_id not in needed_nsds:
1661 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001662 _filter["id"] = nsd_id
1663 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1664 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001665 nsd.pop("_admin")
1666 needed_nsds[nsd_id] = nsd
1667 else:
1668 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001669 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1670 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001671
Felipe Vicensb57758d2018-10-16 16:00:20 +02001672 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1673 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001674
Felipe Vicens07f31722018-10-29 15:16:44 +01001675 # creates Network Services records (NSRs)
1676 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001677 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001678 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001679 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001680 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001681 # Check if the netslice-subnet is shared and if it is share if the nss exists
1682 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001683 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001684 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001685 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1686 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens08ddb142019-08-09 15:52:40 +02001687 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001688 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001689 if nsi and service.get("is-shared-nss"):
1690 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1691 for nsrs_detailed_item in nsrs_detailed_list:
1692 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02001693 if nsrs_detailed_item["nss-id"] == service["id"]:
1694 _id_nsr = nsrs_detailed_item["nsrId"]
1695 break
Felipe Vicens09e65422019-01-22 15:06:46 +01001696 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1697 if netslice_subnet["nss-id"] == service["id"]:
1698 indata_ns = netslice_subnet
1699 break
1700 else:
1701 indata_ns = {}
1702 if service.get("instantiation-parameters"):
1703 indata_ns = deepcopy(service["instantiation-parameters"])
1704 # del service["instantiation-parameters"]
1705
1706 indata_ns["nsdId"] = service["_id"]
1707 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1708 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1709 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001710 if slice_request.get("ssh_keys"):
1711 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001712
Felipe Vicens09e65422019-01-22 15:06:46 +01001713 if ns_params:
1714 for ns_param in ns_params:
1715 if ns_param.get("id") == service["id"]:
1716 copy_ns_param = deepcopy(ns_param)
1717 del copy_ns_param["id"]
1718 indata_ns.update(copy_ns_param)
1719 break
1720
1721 # Creates Nsr objects
tiernobdebce92019-07-01 15:36:49 +00001722 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001723 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
Felipe Vicens08ddb142019-08-09 15:52:40 +02001724 "nss-id": service["id"], "nslcmop_instantiate": None}
Felipe Vicens09e65422019-01-22 15:06:46 +01001725 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001726 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001727 nsi_netslice_subnet.append(indata_ns)
1728 nsr_ref = {"nsr-ref": _id_nsr}
1729 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001730
1731 # Adding the nsrs list to the nsi
1732 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001733 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001734 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1735
Felipe Vicens07f31722018-10-29 15:16:44 +01001736 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001737 self.db.create("nsis", nsi_descriptor)
1738 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00001739 return nsi_id, None
1740 except Exception as e: # TODO remove try Except, it is captured at nbi.py
Felipe Vicensb57758d2018-10-16 16:00:20 +02001741 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1742 raise EngineException("Error {}: {}".format(step, e))
1743 except ValidationError as e:
1744 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1745
tierno65ca36d2019-02-12 19:27:52 +01001746 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001747 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001748
1749
1750class NsiLcmOpTopic(BaseTopic):
1751 topic = "nsilcmops"
1752 topic_msg = "nsi"
1753 operation_schema = { # mapping between operation and jsonschema to validate
1754 "instantiate": nsi_instantiate,
1755 "terminate": None
1756 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001757
delacruzramo32bab472019-09-13 12:24:22 +02001758 def __init__(self, db, fs, msg, auth):
1759 BaseTopic.__init__(self, db, fs, msg, auth)
1760 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01001761
1762 def _check_nsi_operation(self, session, nsir, operation, indata):
1763 """
1764 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001765 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001766 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1767 :param indata: descriptor with the parameters of the operation
1768 :return: None
1769 """
1770 nsds = {}
1771 nstd = nsir["network-slice-template"]
1772
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001773 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001774 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001775 for netslice_subnet in nstd["netslice-subnet"]:
1776 if nstId == netslice_subnet["id"]:
1777 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001778 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02001779 _filter = self._get_project_filter(session)
1780 _filter["id"] = nsd_id
1781 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01001782 return nsds[nsd_id]
1783 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001784 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1785 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001786 if operation == "instantiate":
1787 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001788 for in_nst in get_iterable(indata.get("netslice-subnet")):
1789 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001790
1791 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1792 now = time()
1793 _id = str(uuid4())
1794 nsilcmop = {
1795 "id": _id,
1796 "_id": _id,
1797 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1798 "statusEnteredTime": now,
1799 "netsliceInstanceId": netsliceInstanceId,
1800 "lcmOperationType": operation,
1801 "startTime": now,
1802 "isAutomaticInvocation": False,
1803 "operationParams": params,
1804 "isCancelPending": False,
1805 "links": {
1806 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001807 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001808 }
1809 }
1810 return nsilcmop
1811
Felipe Vicens09e65422019-01-22 15:06:46 +01001812 def add_shared_nsr_2vld(self, nsir, nsr_item):
1813 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1814 if nst_sb_item.get("is-shared-nss"):
1815 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1816 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1817 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1818 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1819 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1820 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1821 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1822 break
1823 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1824 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1825
tierno65ca36d2019-02-12 19:27:52 +01001826 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001827 """
1828 Performs a new operation over a ns
1829 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001830 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001831 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001832 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001833 operation: it can be: instantiate, terminate, action, TODO: update, heal
1834 :param kwargs: used to override the indata descriptor
1835 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001836 :return: id of the nslcmops
1837 """
1838 try:
1839 # Override descriptor with query string kwargs
1840 self._update_input_with_kwargs(indata, kwargs)
1841 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001842 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001843 validate_input(indata, self.operation_schema[operation])
1844
Felipe Vicens126af572019-06-05 19:13:04 +02001845 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001846 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001847 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001848 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00001849 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00001850 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001851
1852 # initial checking
1853 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1854 if operation == "terminate" and indata.get("autoremove"):
1855 # NSIR must be deleted
tierno586ae812019-10-17 13:56:53 +00001856 return None, None # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01001857 if operation != "instantiate":
1858 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001859 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001860 else:
tierno65ca36d2019-02-12 19:27:52 +01001861 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001862 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001863 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001864
1865 # Creating all the NS_operation (nslcmop)
1866 # Get service list from db
1867 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1868 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001869 # nslcmops_item = None
1870 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00001871 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001872 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001873 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00001874 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
tiernob4844ab2019-05-23 08:42:12 +00001875 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001876 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001877 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001878 if operation == "terminate":
1879 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1880 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
tierno40f742b2020-06-23 15:25:26 +00001881 if nsi: # other nsi is using this nsr and it needs this nsr instantiated
1882 continue # do not create nsilcmop
1883 else: # instantiate
1884 # looks the first nsi fulfilling the conditions but not being the current NSIR
1885 if nsi:
1886 nsi_nsr_item = next(n for n in nsi["_admin"]["nsrs-detailed-list"] if
1887 n["nsrId"] == nsr_id and n["shared"] and
1888 n["nslcmop_instantiate"])
1889 self.add_shared_nsr_2vld(nsir, nsr_item)
1890 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1891 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1892 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1893 # continue to not create nslcmop since nsrs is shared and nsrs was created
1894 continue
1895 else:
1896 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01001897
tierno40f742b2020-06-23 15:25:26 +00001898 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01001899 try:
tierno0b8752f2020-05-12 09:42:02 +00001900 indata_ns = {
1901 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00001902 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00001903 # Including netslice_id in the ns instantiate Operation
1904 "netsliceInstanceId": netsliceInstanceId,
1905 }
1906 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00001907 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00001908 indata_ns.update(service["instantiate_params"])
1909
tierno99d4b172019-07-02 09:28:40 +00001910 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001911 # message via kafka bus
tierno40f742b2020-06-23 15:25:26 +00001912 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, None, headers,
tiernobdebce92019-07-01 15:36:49 +00001913 slice_object=True)
Felipe Vicens09e65422019-01-22 15:06:46 +01001914 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00001915 if operation == "instantiate":
1916 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1917 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01001918 except (DbException, EngineException) as e:
1919 if e.http_code == HTTPStatus.NOT_FOUND:
tierno40f742b2020-06-23 15:25:26 +00001920 self.logger.info(logging_prefix + "skipping NS={} because not found".format(nsr_id))
Felipe Vicens09e65422019-01-22 15:06:46 +01001921 pass
1922 else:
1923 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001924
1925 # Creates nsilcmop
1926 indata["nslcmops_ids"] = nslcmops
1927 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001928
Felipe Vicens126af572019-06-05 19:13:04 +02001929 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001930 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001931 _id = self.db.create("nsilcmops", nsilcmop_desc)
1932 rollback.append({"topic": "nsilcmops", "_id": _id})
1933 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001934 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01001935 except ValidationError as e:
1936 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001937
tiernobee3bad2019-12-05 12:26:01 +00001938 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001939 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1940
tierno65ca36d2019-02-12 19:27:52 +01001941 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001942 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)