blob: b3eca026bf5f216f7eb06fb10830cd274c0cb377 [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())
236 nsr_descriptor = self._create_nsr_descriptor_from_nsd(nsd, ns_request, nsr_id)
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
309 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id):
310 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
370 vnfd = self.db.get_one("vnfds",
371 {"id": vnf_profile.get("vnfd-id")},
372 fail_on_empty=True,
373 fail_on_more=True)
374
375 for vdu in vnfd.get("vdu", ()):
376 flavor_data = {}
377 guest_epa = {}
378 # Find this vdu compute and storage descriptors
379 vdu_virtual_compute = {}
380 vdu_virtual_storage = {}
381 for vcd in vnfd.get("virtual-compute-desc", ()):
382 if vcd.get("id") == vdu.get("virtual-compute-desc"):
383 vdu_virtual_compute = vcd
384 for vsd in vnfd.get("virtual-storage-desc", ()):
385 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
386 vdu_virtual_storage = vsd
387 # Get this vdu vcpus, memory and storage info for flavor_data
388 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
389 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"]["num-virtual-cpu"]
390 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
391 flavor_data["memory-mb"] = float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
392 if vdu_virtual_storage.get("size-of-storage"):
393 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
394 # Get this vdu EPA info for guest_epa
395 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
396 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
397 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
398 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
399 if vcpu_pinning.get("thread-policy"):
400 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
401 if vcpu_pinning.get("policy"):
402 cpu_policy = "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
403 guest_epa["cpu-pinning-policy"] = cpu_policy
404 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
405 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
406 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
407 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"]["mempage-size"]
408 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
409 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"]["numa-node-policy"]
410 if vdu_virtual_storage.get("disk-io-quota"):
411 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
412
413 if guest_epa:
414 flavor_data["guest-epa"] = guest_epa
415
416 flavor_data["name"] = vdu["id"][:56] + "-flv"
417 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
418 nsr_descriptor["flavor"].append(flavor_data)
419
420 sw_image_id = vdu.get("sw-image-desc")
421 if sw_image_id:
422 sw_image_desc = utils.find_in_list(vnfd.get("sw-image-desc", ()),
423 lambda sw: sw["id"] == sw_image_id)
424 image_data = {}
425 if sw_image_desc.get("image"):
426 image_data["image"] = sw_image_desc["image"]
427 if sw_image_desc.get("checksum"):
428 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
429 img = next((f for f in nsr_descriptor["image"] if
430 all(f.get(k) == image_data[k] for k in image_data)), None)
431 if not img:
432 image_data["id"] = str(len(nsr_descriptor["image"]))
433 nsr_descriptor["image"].append(image_data)
434
435 for vld in nsr_vld:
436 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(vld.get("id"), [])
437 vld["name"] = vld["id"]
438 nsr_descriptor["vld"] = nsr_vld
439
440 return nsr_descriptor
441
442 def _create_vnfr_descriptor_from_vnfd(self, nsd, vnfd, vnfd_id, vnf_index, nsr_descriptor,
443 ns_request, ns_k8s_namespace):
444 vnfr_id = str(uuid4())
445 nsr_id = nsr_descriptor["id"]
446 now = time()
447 additional_params, vnf_params = self._format_additional_params(ns_request, vnf_index, descriptor=vnfd)
448
449 vnfr_descriptor = {
450 "id": vnfr_id,
451 "_id": vnfr_id,
452 "nsr-id-ref": nsr_id,
453 "member-vnf-index-ref": vnf_index,
454 "additionalParamsForVnf": additional_params,
455 "created-time": now,
456 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
457 "vnfd-ref": vnfd_id,
458 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
459 "vim-account-id": None,
460 "vdur": [],
461 "connection-point": [],
462 "ip-address": None, # mgmt-interface filled by LCM
463 }
464 vnf_k8s_namespace = ns_k8s_namespace
465 if vnf_params:
466 if vnf_params.get("k8s-namespace"):
467 vnf_k8s_namespace = vnf_params["k8s-namespace"]
468 if vnf_params.get("config-units"):
469 vnfr_descriptor["config-units"] = vnf_params["config-units"]
470
471 # Create vld
472 if vnfd.get("int-virtual-link-desc"):
473 vnfr_descriptor["vld"] = []
474 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
475 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
476
477 for cp in vnfd.get("ext-cpd", ()):
478 vnf_cp = {
479 "name": cp.get("id"),
David Garcia1409c272020-12-02 15:47:46 +0100480 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
481 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
garciaale7cbd03c2020-11-27 10:38:35 -0300482 "id": cp.get("id"),
483 # "ip-address", "mac-address" # filled by LCM
484 # vim-id # TODO it would be nice having a vim port id
485 }
486 vnfr_descriptor["connection-point"].append(vnf_cp)
487
488 # Create k8s-cluster information
489 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
490 if vnfd.get("k8s-cluster"):
491 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
492 all_k8s_cluster_nets_cpds = {}
493 for cpd in get_iterable(vnfd.get("ext-cpd")):
494 if cpd.get("k8s-cluster-net"):
495 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get("id")
496 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
497 if net.get("id") in all_k8s_cluster_nets_cpds:
498 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[net.get("id")]
499
500 # update kdus
garciaale7cbd03c2020-11-27 10:38:35 -0300501 for kdu in get_iterable(vnfd.get("kdu")):
502 additional_params, kdu_params = self._format_additional_params(ns_request,
503 vnf_index,
504 kdu_name=kdu["name"],
505 descriptor=vnfd)
506 kdu_k8s_namespace = vnf_k8s_namespace
507 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
508 if kdu_params and kdu_params.get("k8s-namespace"):
509 kdu_k8s_namespace = kdu_params["k8s-namespace"]
510
511 kdur = {
512 "additionalParams": additional_params,
513 "k8s-namespace": kdu_k8s_namespace,
garciadeblas61e0c522020-12-15 10:33:40 +0000514 "kdu-name": kdu["name"],
garciaale7cbd03c2020-11-27 10:38:35 -0300515 # TODO "name": "" Name of the VDU in the VIM
516 "ip-address": None, # mgmt-interface filled by LCM
517 "k8s-cluster": {},
518 }
519 if kdu_params and kdu_params.get("config-units"):
520 kdur["config-units"] = kdu_params["config-units"]
garciadeblas61e0c522020-12-15 10:33:40 +0000521 if kdu.get("helm-version"):
522 kdur["helm-version"] = kdu["helm-version"]
523 for k8s_type in ("helm-chart", "juju-bundle"):
524 if kdu.get(k8s_type):
525 kdur[k8s_type] = kdu_model or kdu[k8s_type]
garciaale7cbd03c2020-11-27 10:38:35 -0300526 if not vnfr_descriptor.get("kdur"):
527 vnfr_descriptor["kdur"] = []
528 vnfr_descriptor["kdur"].append(kdur)
529
530 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
bravof41a52052021-02-17 18:08:01 -0300531
garciaale7cbd03c2020-11-27 10:38:35 -0300532 for vdu in vnfd.get("vdu", ()):
533 additional_params, vdu_params = self._format_additional_params(
534 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd)
535 vdur = {
536 "vdu-id-ref": vdu["id"],
537 # TODO "name": "" Name of the VDU in the VIM
538 "ip-address": None, # mgmt-interface filled by LCM
539 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
540 "internal-connection-point": [],
541 "interfaces": [],
542 "additionalParams": additional_params,
543 "vdu-name": vdu["name"]
544 }
545 if vdu_params and vdu_params.get("config-units"):
546 vdur["config-units"] = vdu_params["config-units"]
547 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
548 vdur["boot-data-drive"] = vdu["supplemental-boot-data"]["boot-data-drive"]
549 if vdu.get("pdu-type"):
550 vdur["pdu-type"] = vdu["pdu-type"]
551 vdur["name"] = vdu["pdu-type"]
552 # TODO volumes: name, volume-id
553 for icp in vdu.get("int-cpd", ()):
554 vdu_icp = {
555 "id": icp["id"],
556 "connection-point-id": icp["id"],
557 "name": icp.get("id"),
558 }
bravof35766442021-02-04 14:58:04 -0300559
560 if "port-security-enabled" in icp:
561 vdu_icp["port-security-enabled"] = icp["port-security-enabled"]
562
563 if "port-security-disable-strategy" in icp:
564 vdu_icp["port-security-disable-strategy"] = icp["port-security-disable-strategy"]
565
garciaale7cbd03c2020-11-27 10:38:35 -0300566 vdur["internal-connection-point"].append(vdu_icp)
567
568 for iface in icp.get("virtual-network-interface-requirement", ()):
569 iface_fields = ("name", "mac-address")
570 vdu_iface = {x: iface[x] for x in iface_fields if iface.get(x) is not None}
571
572 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
573 for ext_cp in vnfd.get("ext-cpd", ()):
574 if not ext_cp.get("int-cpd"):
575 continue
576 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
577 continue
578 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
579 vdu_iface["external-connection-point-ref"] = ext_cp.get("id")
580 break
581
582 if vnfd_mgmt_cp and vdu_iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
583 vdu_iface["mgmt-vnf"] = True
584 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
585
586 if iface.get("virtual-interface"):
587 vdu_iface.update(deepcopy(iface["virtual-interface"]))
588
589 # look for network where this interface is connected
590 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
591 if iface_ext_cp:
592 # TODO: Change for multiple df support
593 for df in get_iterable(nsd.get("df")):
594 for vnf_profile in get_iterable(df.get("vnf-profile")):
595 for vlc in get_iterable(vnf_profile.get("virtual-link-connectivity")):
596 for cpd in get_iterable(vlc.get("constituent-cpd-id")):
597 if cpd.get("constituent-cpd-id") == iface_ext_cp:
598 vdu_iface["ns-vld-id"] = vlc.get("virtual-link-profile-id")
599 break
600 elif vdu_iface.get("internal-connection-point-ref"):
601 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
602
603 vdur["interfaces"].append(vdu_iface)
604
605 if vdu.get("sw-image-desc"):
606 sw_image = utils.find_in_list(
607 vnfd.get("sw-image-desc", ()),
608 lambda image: image["id"] == vdu.get("sw-image-desc"))
609 nsr_sw_image_data = utils.find_in_list(
610 nsr_descriptor["image"],
611 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image"))
612 )
613 vdur["ns-image-id"] = nsr_sw_image_data["id"]
614
615 flavor_data_name = vdu["id"][:56] + "-flv"
616 nsr_flavor_desc = utils.find_in_list(
617 nsr_descriptor["flavor"],
618 lambda flavor: flavor["name"] == flavor_data_name)
619
620 if nsr_flavor_desc:
621 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
622
623 count = int(vdu.get("count", 1))
624 for index in range(0, count):
625 vdur = deepcopy(vdur)
626 for iface in vdur["interfaces"]:
627 if iface.get("ip-address"):
628 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
629 if iface.get("mac-address"):
630 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
631
632 vdur["_id"] = str(uuid4())
633 vdur["id"] = vdur["_id"]
634 vdur["count-index"] = index
635 vnfr_descriptor["vdur"].append(vdur)
636
637 return vnfr_descriptor
638
tierno65ca36d2019-02-12 19:27:52 +0100639 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200640 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
641
642
643class VnfrTopic(BaseTopic):
644 topic = "vnfrs"
645 topic_msg = None
646
delacruzramo32bab472019-09-13 12:24:22 +0200647 def __init__(self, db, fs, msg, auth):
648 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200649
tiernobee3bad2019-12-05 12:26:01 +0000650 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200651 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
652
tierno65ca36d2019-02-12 19:27:52 +0100653 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200654 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
655
tierno65ca36d2019-02-12 19:27:52 +0100656 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200657 # Not used because vnfrs are created and deleted by NsrTopic class directly
658 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
659
660
661class NsLcmOpTopic(BaseTopic):
662 topic = "nslcmops"
663 topic_msg = "ns"
664 operation_schema = { # mapping between operation and jsonschema to validate
665 "instantiate": ns_instantiate,
666 "action": ns_action,
667 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +0000668 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +0200669 }
670
delacruzramo32bab472019-09-13 12:24:22 +0200671 def __init__(self, db, fs, msg, auth):
672 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200673
tiernob24258a2018-10-04 18:39:49 +0200674 def _check_ns_operation(self, session, nsr, operation, indata):
675 """
676 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100677 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200678 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
679 :param indata: descriptor with the parameters of the operation
680 :return: None
681 """
garciaale7cbd03c2020-11-27 10:38:35 -0300682 if operation == "action":
683 self._check_action_ns_operation(indata, nsr)
684 elif operation == "scale":
685 self._check_scale_ns_operation(indata, nsr)
686 elif operation == "instantiate":
687 self._check_instantiate_ns_operation(indata, nsr, session)
688
689 def _check_action_ns_operation(self, indata, nsr):
690 nsd = nsr["nsd"]
691 # check vnf_member_index
692 if indata.get("vnf_member_index"):
693 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
694 if indata.get("member_vnf_index"):
695 vnfd = self._get_vnfd_from_vnf_member_index(indata["member_vnf_index"], nsr["_id"])
bravof41a52052021-02-17 18:08:01 -0300696 try:
697 configs = vnfd.get("df")[0]["lcm-operations-configuration"]["operate-vnf-op-config"]["day1-2"]
698 except Exception:
699 configs = []
700
garciaale7cbd03c2020-11-27 10:38:35 -0300701 if indata.get("vdu_id"):
702 self._check_valid_vdu(vnfd, indata["vdu_id"])
bravof41a52052021-02-17 18:08:01 -0300703 descriptor_configuration = utils.find_in_list(
704 configs,
705 lambda config: config["id"] == indata["vdu_id"]
706 ).get("config-primitive")
garciaale7cbd03c2020-11-27 10:38:35 -0300707 elif indata.get("kdu_name"):
708 self._check_valid_kdu(vnfd, indata["kdu_name"])
bravof41a52052021-02-17 18:08:01 -0300709 descriptor_configuration = utils.find_in_list(
710 configs,
711 lambda config: config["id"] == indata.get("kdu_name")
712 ).get("config-primitive")
garciaale7cbd03c2020-11-27 10:38:35 -0300713 else:
bravof41a52052021-02-17 18:08:01 -0300714 descriptor_configuration = utils.find_in_list(
715 configs,
716 lambda config: config["id"] == vnfd["id"]
717 ).get("config-primitive")
garciaale7cbd03c2020-11-27 10:38:35 -0300718 else: # use a NSD
719 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
720
721 # For k8s allows default primitives without validating the parameters
722 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
723 # TODO should be checked that rollback only can contains revsision_numbe????
724 if not indata.get("member_vnf_index"):
725 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
726 .format(indata["primitive"]))
727 return
728 # if not, check primitive
729 for config_primitive in get_iterable(descriptor_configuration):
730 if indata["primitive"] == config_primitive["name"]:
731 # check needed primitive_params are provided
732 if indata.get("primitive_params"):
733 in_primitive_params_copy = copy(indata["primitive_params"])
734 else:
735 in_primitive_params_copy = {}
736 for paramd in get_iterable(config_primitive.get("parameter")):
737 if paramd["name"] in in_primitive_params_copy:
738 del in_primitive_params_copy[paramd["name"]]
739 elif not paramd.get("default-value"):
740 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
741 paramd["name"], indata["primitive"]))
742 # check no extra primitive params are provided
743 if in_primitive_params_copy:
744 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
745 list(in_primitive_params_copy.keys()), indata["primitive"]))
746 break
747 else:
748 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
749
750 def _check_scale_ns_operation(self, indata, nsr):
751 vnfd = self._get_vnfd_from_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"],
752 nsr["_id"])
lloretgallegdf9fd612020-12-01 12:51:52 +0000753 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
754 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_aspect["id"]:
garciaale7cbd03c2020-11-27 10:38:35 -0300755 break
756 else:
757 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
lloretgallegdf9fd612020-12-01 12:51:52 +0000758 "present at vnfd:scaling-aspect"
garciaale7cbd03c2020-11-27 10:38:35 -0300759 .format(indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
760
761 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +0000762 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +0200763 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000764 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200765 nsd = nsr["nsd"]
garciaale7cbd03c2020-11-27 10:38:35 -0300766 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
767 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
768 for in_vnf in get_iterable(indata.get("vnf")):
769 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +0000770 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale7cbd03c2020-11-27 10:38:35 -0300771 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +0000772 else:
garciaale7cbd03c2020-11-27 10:38:35 -0300773 vnfd = self._get_vnfd_from_vnf_member_index(member_vnf_index, nsr["_id"])
774 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
775 self._check_vnf_instantiation_params(in_vnf, vnfd)
776 if in_vnf.get("vimAccountId"):
777 self._check_valid_vim_account(in_vnf["vimAccountId"], vim_accounts, session)
tierno260dd6f2019-09-02 10:48:56 +0000778
garciaale7cbd03c2020-11-27 10:38:35 -0300779 for in_vld in get_iterable(indata.get("vld")):
780 self._check_valid_wim_account(in_vld.get("wimAccountId"), wim_accounts, session)
781 for vldd in get_iterable(nsd.get("virtual-link-desc")):
782 if in_vld["name"] == vldd["id"]:
783 break
tierno9cb7d672019-10-30 12:13:48 +0000784 else:
garciaale7cbd03c2020-11-27 10:38:35 -0300785 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
786 in_vld["name"]))
tierno9cb7d672019-10-30 12:13:48 +0000787
garciaale7cbd03c2020-11-27 10:38:35 -0300788 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
789 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
790 vnfr = self.db.get_one("vnfrs",
791 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
792 fail_on_empty=False)
793 if not vnfr:
794 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
795 "nsd:constituent-vnfd".format(member_vnf_index))
796 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
797 if not vnfd:
798 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
799 format(vnfr["vnfd-id"]))
800 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +0200801
garciaale7cbd03c2020-11-27 10:38:35 -0300802 def _check_valid_vdu(self, vnfd, vdu_id):
803 for vdud in get_iterable(vnfd.get("vdu")):
804 if vdud["id"] == vdu_id:
805 return vdud
806 else:
807 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
808
809 def _check_valid_kdu(self, vnfd, kdu_name):
810 for kdud in get_iterable(vnfd.get("kdu")):
811 if kdud["name"] == kdu_name:
812 return kdud
813 else:
814 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
815
816 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
817 for in_vdu in get_iterable(in_vnf.get("vdu")):
818 for vdu in get_iterable(vnfd.get("vdu")):
819 if in_vdu["id"] == vdu["id"]:
820 for volume in get_iterable(in_vdu.get("volume")):
821 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
822 if volumed["id"] == volume["name"]:
823 break
824 else:
825 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
826 "volume:name='{}' is not present at "
827 "vnfd:vdu:virtual-storage-desc list".
828 format(in_vnf["member-vnf-index"], in_vdu["id"],
829 volume["id"]))
830
831 vdu_if_names = set()
832 for cpd in get_iterable(vdu.get("int-cpd")):
833 for iface in get_iterable(cpd.get("virtual-network-interface-requirement")):
834 vdu_if_names.add(iface.get("name"))
835
836 for in_iface in get_iterable(in_vdu["interface"]):
837 if in_iface["name"] in vdu_if_names:
838 break
839 else:
840 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
841 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd"
842 .format(in_vnf["member-vnf-index"], in_vdu["id"],
843 in_iface["name"]))
844 break
845
846 else:
847 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
848 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
849
850 vnfd_ivlds_cpds = {ivld.get("id"): set() for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))}
851 for vdu in get_iterable(vnfd.get("vdu")):
852 for cpd in get_iterable(vnfd.get("int-cpd")):
853 if cpd.get("int-virtual-link-desc"):
854 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
855
856 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
857 if in_ivld.get("name") in vnfd_ivlds_cpds:
858 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
859 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +0200860 break
tiernob24258a2018-10-04 18:39:49 +0200861 else:
garciaale7cbd03c2020-11-27 10:38:35 -0300862 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
863 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
864 "vnfd:internal-vld:name/id:internal-connection-point"
865 .format(in_vnf["member-vnf-index"], in_ivld["name"],
866 in_icp["id-ref"]))
tiernob24258a2018-10-04 18:39:49 +0200867 else:
garciaale7cbd03c2020-11-27 10:38:35 -0300868 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
869 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
870 in_ivld["name"], vnfd["id"]))
tiernob24258a2018-10-04 18:39:49 +0200871
garciaale7cbd03c2020-11-27 10:38:35 -0300872 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
873 if vim_account in vim_accounts:
874 return
875 try:
876 db_filter = self._get_project_filter(session)
877 db_filter["_id"] = vim_account
878 self.db.get_one("vim_accounts", db_filter)
879 except Exception:
880 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
881 vim_accounts.append(vim_account)
882
883 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
884 if not isinstance(wim_account, str):
885 return
886 if wim_account in wim_accounts:
887 return
888 try:
889 db_filter = self._get_project_filter(session, write=False, show_all=True)
890 db_filter["_id"] = wim_account
891 self.db.get_one("wim_accounts", db_filter)
892 except Exception:
893 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
894 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +0200895
tierno36ec8602018-11-02 17:27:11 +0100896 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200897 """
tierno36ec8602018-11-02 17:27:11 +0100898 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
899 (ip_address, ...) information.
900 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +0100901 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100902 :param rollback: list with the database modifications to rollback if needed
903 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
904 :param vim_account: vim_account where this vnfr should be deployed
905 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
906 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
907 of the changed vnfr is needed
908
909 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
910 "vim-network-name": used at VIM
911 "name": interface name
912 "vnf-vld-id": internal VNFD vld where this interface is connected, or
913 "ns-vld-id": NSD vld where this interface is connected.
914 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 +0200915 """
tierno36ec8602018-11-02 17:27:11 +0100916
917 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +0200918 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
919 if not vdur.get("pdu-type"):
920 continue
921 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +0100922 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +0100923 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +0200924 pdu_filter["type"] = pdu_type
925 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +0100926 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +0200927 # TODO feature 1417: "shared": True,
928
929 available_pdus = self.db.get_list("pdus", pdu_filter)
930 for pdu in available_pdus:
931 # step 1 check if this pdu contains needed interfaces:
932 match_interfaces = True
933 for vdur_interface in vdur["interfaces"]:
934 for pdu_interface in pdu["interfaces"]:
935 if pdu_interface["name"] == vdur_interface["name"]:
936 # TODO feature 1417: match per mgmt type
937 break
938 else: # no interface found for name
939 match_interfaces = False
940 break
941 if match_interfaces:
942 break
943 else:
944 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +0100945 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
946 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +0200947
948 # step 2. Update pdu
949 rollback_pdu = {
950 "_admin.usageState": pdu["_admin"]["usageState"],
951 "_admin.usage.vnfr_id": None,
952 "_admin.usage.nsr_id": None,
953 "_admin.usage.vdur": None,
954 }
955 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +0100956 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +0000957 "_admin.usage": {"vnfr_id": vnfr["_id"],
958 "nsr_id": vnfr["nsr-id-ref"],
959 "vdur": vdur["vdu-id-ref"]}
960 })
tiernocc103432018-10-19 14:10:35 +0200961 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
962
963 # step 3. Fill vnfr info by filling vdur
964 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +0100965 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +0200966 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
967 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
968 for pdu_interface in pdu["interfaces"]:
969 if pdu_interface["name"] == vdur_interface["name"]:
970 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
971 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +0100972 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
973 vnfr_update[iface_text + ".{}".format(k)] = v
974 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
975 if pdu_interface.get("ip-address"):
tiernoc88003e2020-03-12 17:31:42 +0000976 if vdur_interface.get("mgmt-interface") or vdur_interface.get("mgmt-vnf"):
tierno36ec8602018-11-02 17:27:11 +0100977 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
978 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
979 if vdur_interface.get("mgmt-vnf"):
980 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
981 vnfr_update["ip-address"] = pdu_interface["ip-address"]
tierno72b16e12020-03-18 09:49:43 +0000982 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +0100983 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +0100984 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +0100985 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
986 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
987 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +0100988 if pdu_interface.get("vim-network-id"):
tiernoc67b0e92019-11-05 12:45:29 +0000989 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +0100990 if pdu_interface.get("vim-network-name"):
tiernoc67b0e92019-11-05 12:45:29 +0000991 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +0200992 break
993
tierno36ec8602018-11-02 17:27:11 +0100994 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +0200995
tierno9cb7d672019-10-30 12:13:48 +0000996 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
997 """
998 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
999 Fills vnfr.kdur with the selected k8scluster
1000
1001 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1002 :param rollback: list with the database modifications to rollback if needed
1003 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1004 :param vim_account: vim_account where this vnfr should be deployed
1005 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1006 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1007 of the changed vnfr is needed
1008
1009 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1010 "vim-network-name": used at VIM
1011 "name": interface name
1012 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1013 "ns-vld-id": NSD vld where this interface is connected.
1014 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1015 """
1016
1017 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001018 if not vnfr.get("kdur"):
1019 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001020
tiernoc67b0e92019-11-05 12:45:29 +00001021 kdu_filter = self._get_project_filter(session)
1022 kdu_filter["vim_account"] = vim_account
1023 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1024 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1025
1026 k8s_requirements = {} # just for logging
1027 for k8scluster in available_k8sclusters:
1028 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001029 break
tiernoc67b0e92019-11-05 12:45:29 +00001030 # restrict by cni
1031 if vnfr["k8s-cluster"].get("cni"):
1032 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
1033 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
1034 continue
1035 # restrict by version
1036 if vnfr["k8s-cluster"].get("version"):
1037 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1038 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1039 continue
1040 # restrict by number of networks
1041 if vnfr["k8s-cluster"].get("nets"):
1042 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
1043 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
1044 continue
1045 break
1046 else:
1047 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
1048 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
tierno9cb7d672019-10-30 12:13:48 +00001049
tiernoc67b0e92019-11-05 12:45:29 +00001050 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001051 # step 3. Fill vnfr info by filling kdur
1052 kdu_text = "kdur.{}.".format(kdur_index)
1053 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1054 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1055
tiernoc67b0e92019-11-05 12:45:29 +00001056 # step 4. Check VIM networks that forces the selected k8s_cluster
1057 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1058 k8scluster_net_list = list(k8scluster.get("nets").keys())
1059 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1060 # get a network from k8s_cluster nets. If name matches use this, if not use other
1061 if kdur_net["id"] in k8scluster_net_list: # name matches
1062 vim_net = k8scluster["nets"][kdur_net["id"]]
1063 k8scluster_net_list.remove(kdur_net["id"])
1064 else:
1065 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1066 k8scluster_net_list.pop(0)
1067 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
1068 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
1069 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
1070 ifaces_forcing_vim_network.append({
1071 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
1072 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1073 "ns-vld-id": kdur_net.get("ns-vld-id"),
1074 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1075 })
1076 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001077 return ifaces_forcing_vim_network
1078
tiernocc103432018-10-19 14:10:35 +02001079 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001080 # get vnfr
1081 nsr_id = nsr["_id"]
1082 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1083
1084 for vnfr in vnfrs:
1085 vnfr_update = {}
1086 vnfr_update_rollback = {}
1087 member_vnf_index = vnfr["member-vnf-index-ref"]
1088 # update vim-account-id
1089
1090 vim_account = indata["vimAccountId"]
1091 # check instantiate parameters
1092 for vnf_inst_params in get_iterable(indata.get("vnf")):
1093 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1094 continue
1095 if vnf_inst_params.get("vimAccountId"):
1096 vim_account = vnf_inst_params.get("vimAccountId")
1097
tiernocddb07d2020-10-06 08:28:00 +00001098 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1099 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1100 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1101 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1102 continue
1103 for iface_inst_param in get_iterable(vdu_inst_param.get("interface")):
1104 iface_index, _ = next(i for i in enumerate(vdur["interfaces"])
1105 if i[1]["name"] == iface_inst_param["name"])
1106 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1107 if iface_inst_param.get("ip-address"):
1108 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1109 iface_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001110 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001111 if iface_inst_param.get("mac-address"):
1112 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1113 iface_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001114 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
bravofe4254fd2021-02-03 15:22:06 -03001115 if iface_inst_param.get("floating-ip-required"):
1116 vnfr_update[vnfr_update_text + ".floating-ip-required"] = True
tiernocddb07d2020-10-06 08:28:00 +00001117 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1118 # TODO update vld with the ip-profile
1119 for ivld_inst_param in get_iterable(vnf_inst_params.get("internal-vld")):
1120 for icp_inst_param in get_iterable(ivld_inst_param.get("internal-connection-point")):
1121 # look for iface
1122 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1123 for iface_index, iface in enumerate(vdur["interfaces"]):
1124 if iface.get("internal-connection-point-ref") == icp_inst_param["id-ref"]:
1125 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1126 if icp_inst_param.get("ip-address"):
1127 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1128 icp_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001129 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001130 if icp_inst_param.get("mac-address"):
1131 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1132 icp_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001133 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001134 break
1135 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1136 for vld_inst_param in get_iterable(indata.get("vld")):
1137 for vnfcp_inst_param in get_iterable(vld_inst_param.get("vnfd-connection-point-ref")):
1138 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1139 continue
1140 # look for iface
1141 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1142 for iface_index, iface in enumerate(vdur["interfaces"]):
1143 if iface.get("external-connection-point-ref") == \
1144 vnfcp_inst_param["vnfd-connection-point-ref"]:
1145 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1146 if vnfcp_inst_param.get("ip-address"):
1147 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1148 vnfcp_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001149 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001150 if vnfcp_inst_param.get("mac-address"):
1151 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1152 vnfcp_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001153 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001154 break
1155
tiernocc103432018-10-19 14:10:35 +02001156 vnfr_update["vim-account-id"] = vim_account
1157 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1158
1159 # get pdu
tierno36ec8602018-11-02 17:27:11 +01001160 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
1161 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +02001162
tierno9cb7d672019-10-30 12:13:48 +00001163 # get kdus
1164 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
1165 vnfr_update_rollback)
1166 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001167 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1168 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
1169
1170 # Update indada in case pdu forces to use a concrete vim-network-name
1171 # TODO check if user has already insert a vim-network-name and raises an error
1172 if not ifaces_forcing_vim_network:
1173 continue
1174 for iface_info in ifaces_forcing_vim_network:
1175 if iface_info.get("ns-vld-id"):
1176 if "vld" not in indata:
1177 indata["vld"] = []
1178 indata["vld"].append({key: iface_info[key] for key in
1179 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
1180
1181 elif iface_info.get("vnf-vld-id"):
1182 if "vnf" not in indata:
1183 indata["vnf"] = []
1184 indata["vnf"].append({
1185 "member-vnf-index": member_vnf_index,
1186 "internal-vld": [{key: iface_info[key] for key in
1187 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
1188 })
1189
1190 @staticmethod
1191 def _create_nslcmop(nsr_id, operation, params):
1192 """
1193 Creates a ns-lcm-opp content to be stored at database.
1194 :param nsr_id: internal id of the instance
1195 :param operation: instantiate, terminate, scale, action, ...
1196 :param params: user parameters for the operation
1197 :return: dictionary following SOL005 format
1198 """
tiernob24258a2018-10-04 18:39:49 +02001199 now = time()
1200 _id = str(uuid4())
1201 nslcmop = {
1202 "id": _id,
1203 "_id": _id,
1204 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001205 "queuePosition": None,
1206 "stage": None,
1207 "errorMessage": None,
1208 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001209 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001210 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001211 "lcmOperationType": operation,
1212 "startTime": now,
1213 "isAutomaticInvocation": False,
1214 "operationParams": params,
1215 "isCancelPending": False,
1216 "links": {
1217 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001218 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001219 }
1220 }
1221 return nslcmop
1222
magnussonlf318b302020-01-20 18:38:18 +01001223 def _get_enabled_vims(self, session):
1224 """
1225 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1226 :param session: current session with user information
1227 """
1228 db_filter = self._get_project_filter(session)
1229 db_filter["_admin.operationalState"] = "ENABLED"
1230 vims = self.db.get_list("vim_accounts", db_filter)
1231 vimAccounts = []
1232 for vim in vims:
1233 vimAccounts.append(vim['_id'])
1234 return vimAccounts
1235
tierno65ca36d2019-02-12 19:27:52 +01001236 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +02001237 """
1238 Performs a new operation over a ns
1239 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001240 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001241 :param indata: descriptor with the parameters of the operation. It must contains among others
1242 nsInstanceId: _id of the nsr to perform the operation
1243 operation: it can be: instantiate, terminate, action, TODO: update, heal
1244 :param kwargs: used to override the indata descriptor
1245 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02001246 :return: id of the nslcmops
1247 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001248 def check_if_nsr_is_not_slice_member(session, nsr_id):
1249 nsis = None
1250 db_filter = self._get_project_filter(session)
1251 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1252 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
1253 if nsis:
tierno40f742b2020-06-23 15:25:26 +00001254 raise EngineException("The NS instance {} cannot be terminated because is used by the slice {}".format(
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001255 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
1256
tiernob24258a2018-10-04 18:39:49 +02001257 try:
1258 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00001259 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02001260 operation = indata["lcmOperationType"]
1261 nsInstanceId = indata["nsInstanceId"]
1262
1263 validate_input(indata, self.operation_schema[operation])
1264 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01001265 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02001266 _filter["_id"] = nsInstanceId
1267 nsr = self.db.get_one("nsrs", _filter)
1268
1269 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001270 if operation == "terminate" and slice_object is False:
1271 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +02001272 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1273 if operation == "terminate" and indata.get("autoremove"):
1274 # NSR must be deleted
tierno586ae812019-10-17 13:56:53 +00001275 return None, None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02001276 if operation != "instantiate":
1277 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1278 nsInstanceId, operation), HTTPStatus.CONFLICT)
1279 else:
tierno65ca36d2019-02-12 19:27:52 +01001280 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +02001281 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1282 nsInstanceId, operation), HTTPStatus.CONFLICT)
1283 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +01001284
tiernocc103432018-10-19 14:10:35 +02001285 if operation == "instantiate":
1286 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01001287
1288 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00001289 _id = nslcmop_desc["_id"]
tierno65ca36d2019-02-12 19:27:52 +01001290 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
magnussonlf318b302020-01-20 18:38:18 +01001291 if indata.get("placement-engine"):
1292 # Save valid vim accounts in lcm operation descriptor
1293 nslcmop_desc['operationParams']['validVimAccounts'] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00001294 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02001295 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001296 if not slice_object:
1297 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001298 return _id, None
1299 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02001300 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1301 # except DbException as e:
1302 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1303
tiernobee3bad2019-12-05 12:26:01 +00001304 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +02001305 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1306
tierno65ca36d2019-02-12 19:27:52 +01001307 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +02001308 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001309
1310
1311class NsiTopic(BaseTopic):
1312 topic = "nsis"
1313 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00001314 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001315
delacruzramo32bab472019-09-13 12:24:22 +02001316 def __init__(self, db, fs, msg, auth):
1317 BaseTopic.__init__(self, db, fs, msg, auth)
1318 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001319
Felipe Vicensc37b3842019-01-12 12:24:42 +01001320 @staticmethod
1321 def _format_ns_request(ns_request):
1322 formated_request = copy(ns_request)
1323 # TODO: Add request params
1324 return formated_request
1325
1326 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001327 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001328 """
1329 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001330 :param slice_request: User instantiation additional parameters
1331 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001332 """
tiernofd160572019-01-21 10:41:37 +00001333 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1334 if additional_params:
1335 for k, v in additional_params.items():
1336 if not isinstance(k, str):
1337 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1338 format(k))
1339 if "." in k or "$" in k:
1340 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1341 format(k))
1342 if isinstance(v, (dict, tuple, list)):
1343 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001344 return additional_params
1345
Felipe Vicensb57758d2018-10-16 16:00:20 +02001346 def _check_descriptor_dependencies(self, session, descriptor):
1347 """
1348 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001349 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001350 :param descriptor: descriptor to be inserted or edit
1351 :return: None or raises exception
1352 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001353 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001354 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001355 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001356 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +01001357 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +02001358 http_code=HTTPStatus.CONFLICT)
1359
tiernob4844ab2019-05-23 08:42:12 +00001360 def check_conflict_on_del(self, session, _id, db_content):
1361 """
1362 Check that NSI is not instantiated
1363 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1364 :param _id: nsi internal id
1365 :param db_content: The database content of the _id
1366 :return: None or raises EngineException with the conflict
1367 """
tierno65ca36d2019-02-12 19:27:52 +01001368 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02001369 return
tiernob4844ab2019-05-23 08:42:12 +00001370 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02001371 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1372 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1373 "Launch 'terminate' operation first; or force deletion".format(_id),
1374 http_code=HTTPStatus.CONFLICT)
1375
tiernobee3bad2019-12-05 12:26:01 +00001376 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001377 """
tiernob4844ab2019-05-23 08:42:12 +00001378 Deletes associated nsilcmops from database. Deletes associated filesystem.
1379 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01001380 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001381 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00001382 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00001383 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00001384 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02001385 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001386
Felipe Vicens09e65422019-01-22 15:06:46 +01001387 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00001388 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01001389 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1390 nsr_id = nsrs_detailed_item["nsrId"]
1391 if nsrs_detailed_item.get("shared"):
1392 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1393 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1394 "_id.ne": nsir["_id"]}
1395 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1396 if nsi: # last one using nsr
1397 continue
1398 try:
tiernobee3bad2019-12-05 12:26:01 +00001399 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
Felipe Vicens09e65422019-01-22 15:06:46 +01001400 except (DbException, EngineException) as e:
1401 if e.http_code == HTTPStatus.NOT_FOUND:
1402 pass
1403 else:
1404 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001405
tiernob4844ab2019-05-23 08:42:12 +00001406 # delete related nsilcmops database entries
1407 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001408
tiernob4844ab2019-05-23 08:42:12 +00001409 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01001410 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00001411 if nsir_admin and nsir_admin.get("nst-id"):
1412 # check if used by another NSI
1413 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1414 fail_on_empty=False, fail_on_more=False)
1415 if not nsis_list:
1416 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1417
tierno65ca36d2019-02-12 19:27:52 +01001418 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001419 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001420 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02001421 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01001422 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001423 :param indata: params to be used for the nsir
1424 :param kwargs: used to override the indata descriptor
1425 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02001426 :return: the _id of nsi descriptor created at database
1427 """
1428
1429 try:
delacruzramo32bab472019-09-13 12:24:22 +02001430 step = "checking quotas"
1431 self.check_quota(session)
1432
tierno99d4b172019-07-02 09:28:40 +00001433 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02001434 slice_request = self._remove_envelop(indata)
1435 # Override descriptor with query string kwargs
1436 self._update_input_with_kwargs(slice_request, kwargs)
bravofb995ea22021-02-10 10:57:52 -03001437 slice_request = self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001438
Felipe Vicensb57758d2018-10-16 16:00:20 +02001439 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +00001440 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001441 _filter = self._get_project_filter(session)
1442 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001443 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00001444 # check NST is not disabled
1445 step = "checking NST operationalState"
1446 if nstd["_admin"]["operationalState"] == "DISABLED":
1447 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
1448 "instance".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
tiernob4844ab2019-05-23 08:42:12 +00001449 del _filter["_id"]
1450
Frank Brydenb5a2ead2020-07-28 12:50:23 +00001451 # check NSD is not disabled
1452 step = "checking operationalState"
1453 if nstd["_admin"]["operationalState"] == "DISABLED":
1454 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create "
1455 "a network slice".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
1456
Felipe Vicens07f31722018-10-29 15:16:44 +01001457 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001458 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001459 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001460 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001461
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001462 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001463 nsi_descriptor = {
1464 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001465 "name": slice_request["nsiName"],
1466 "description": slice_request.get("nsiDescription", ""),
1467 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001468 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001469 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001470 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001471 "nsr-ref-list": [],
1472 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001473 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001474 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001475 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001476
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001477 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001478 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001479 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1480 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001481 nsi_descriptor["_admin"]["deployed"] = {}
1482 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1483 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1484
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001485 # Creating netslice-vld for the RO.
1486 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001487
1488 # Building the vlds list to be deployed
1489 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001490 nsi_vlds = []
1491
1492 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1493 # Getting template Instantiation parameters from NST
1494 nsi_vld = deepcopy(netslice_vlds)
1495 nsi_vld["shared-nsrs-list"] = []
1496 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1497 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001498
1499 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00001500 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001501 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001502 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001503
Felipe Vicens09e65422019-01-22 15:06:46 +01001504 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001505 for member_ns in nstd["netslice-subnet"]:
1506 nsd_id = member_ns["nsd-ref"]
1507 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1508 member_ns["nsd-ref"], member_ns["id"])
1509 if nsd_id not in needed_nsds:
1510 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001511 _filter["id"] = nsd_id
1512 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1513 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001514 nsd.pop("_admin")
1515 needed_nsds[nsd_id] = nsd
1516 else:
1517 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001518 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1519 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001520
Felipe Vicensb57758d2018-10-16 16:00:20 +02001521 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1522 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001523
Felipe Vicens07f31722018-10-29 15:16:44 +01001524 # creates Network Services records (NSRs)
1525 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001526 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001527 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001528 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001529 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001530 # Check if the netslice-subnet is shared and if it is share if the nss exists
1531 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001532 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001533 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001534 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1535 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens08ddb142019-08-09 15:52:40 +02001536 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001537 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001538 if nsi and service.get("is-shared-nss"):
1539 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1540 for nsrs_detailed_item in nsrs_detailed_list:
1541 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02001542 if nsrs_detailed_item["nss-id"] == service["id"]:
1543 _id_nsr = nsrs_detailed_item["nsrId"]
1544 break
Felipe Vicens09e65422019-01-22 15:06:46 +01001545 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1546 if netslice_subnet["nss-id"] == service["id"]:
1547 indata_ns = netslice_subnet
1548 break
1549 else:
1550 indata_ns = {}
1551 if service.get("instantiation-parameters"):
1552 indata_ns = deepcopy(service["instantiation-parameters"])
1553 # del service["instantiation-parameters"]
1554
1555 indata_ns["nsdId"] = service["_id"]
1556 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1557 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1558 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001559 if slice_request.get("ssh_keys"):
1560 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001561
Felipe Vicens09e65422019-01-22 15:06:46 +01001562 if ns_params:
1563 for ns_param in ns_params:
1564 if ns_param.get("id") == service["id"]:
1565 copy_ns_param = deepcopy(ns_param)
1566 del copy_ns_param["id"]
1567 indata_ns.update(copy_ns_param)
1568 break
1569
1570 # Creates Nsr objects
tiernobdebce92019-07-01 15:36:49 +00001571 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001572 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
Felipe Vicens08ddb142019-08-09 15:52:40 +02001573 "nss-id": service["id"], "nslcmop_instantiate": None}
Felipe Vicens09e65422019-01-22 15:06:46 +01001574 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001575 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001576 nsi_netslice_subnet.append(indata_ns)
1577 nsr_ref = {"nsr-ref": _id_nsr}
1578 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001579
1580 # Adding the nsrs list to the nsi
1581 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001582 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001583 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1584
Felipe Vicens07f31722018-10-29 15:16:44 +01001585 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001586 self.db.create("nsis", nsi_descriptor)
1587 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00001588 return nsi_id, None
1589 except Exception as e: # TODO remove try Except, it is captured at nbi.py
Felipe Vicensb57758d2018-10-16 16:00:20 +02001590 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1591 raise EngineException("Error {}: {}".format(step, e))
1592 except ValidationError as e:
1593 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1594
tierno65ca36d2019-02-12 19:27:52 +01001595 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001596 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001597
1598
1599class NsiLcmOpTopic(BaseTopic):
1600 topic = "nsilcmops"
1601 topic_msg = "nsi"
1602 operation_schema = { # mapping between operation and jsonschema to validate
1603 "instantiate": nsi_instantiate,
1604 "terminate": None
1605 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001606
delacruzramo32bab472019-09-13 12:24:22 +02001607 def __init__(self, db, fs, msg, auth):
1608 BaseTopic.__init__(self, db, fs, msg, auth)
1609 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01001610
1611 def _check_nsi_operation(self, session, nsir, operation, indata):
1612 """
1613 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001614 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001615 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1616 :param indata: descriptor with the parameters of the operation
1617 :return: None
1618 """
1619 nsds = {}
1620 nstd = nsir["network-slice-template"]
1621
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001622 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001623 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001624 for netslice_subnet in nstd["netslice-subnet"]:
1625 if nstId == netslice_subnet["id"]:
1626 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001627 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02001628 _filter = self._get_project_filter(session)
1629 _filter["id"] = nsd_id
1630 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01001631 return nsds[nsd_id]
1632 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001633 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1634 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001635 if operation == "instantiate":
1636 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001637 for in_nst in get_iterable(indata.get("netslice-subnet")):
1638 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001639
1640 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1641 now = time()
1642 _id = str(uuid4())
1643 nsilcmop = {
1644 "id": _id,
1645 "_id": _id,
1646 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1647 "statusEnteredTime": now,
1648 "netsliceInstanceId": netsliceInstanceId,
1649 "lcmOperationType": operation,
1650 "startTime": now,
1651 "isAutomaticInvocation": False,
1652 "operationParams": params,
1653 "isCancelPending": False,
1654 "links": {
1655 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001656 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001657 }
1658 }
1659 return nsilcmop
1660
Felipe Vicens09e65422019-01-22 15:06:46 +01001661 def add_shared_nsr_2vld(self, nsir, nsr_item):
1662 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1663 if nst_sb_item.get("is-shared-nss"):
1664 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1665 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1666 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1667 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1668 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1669 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1670 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1671 break
1672 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1673 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1674
tierno65ca36d2019-02-12 19:27:52 +01001675 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001676 """
1677 Performs a new operation over a ns
1678 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001679 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001680 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001681 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001682 operation: it can be: instantiate, terminate, action, TODO: update, heal
1683 :param kwargs: used to override the indata descriptor
1684 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001685 :return: id of the nslcmops
1686 """
1687 try:
1688 # Override descriptor with query string kwargs
1689 self._update_input_with_kwargs(indata, kwargs)
1690 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001691 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001692 validate_input(indata, self.operation_schema[operation])
1693
Felipe Vicens126af572019-06-05 19:13:04 +02001694 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001695 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001696 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001697 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00001698 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00001699 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001700
1701 # initial checking
1702 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1703 if operation == "terminate" and indata.get("autoremove"):
1704 # NSIR must be deleted
tierno586ae812019-10-17 13:56:53 +00001705 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 +01001706 if operation != "instantiate":
1707 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001708 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001709 else:
tierno65ca36d2019-02-12 19:27:52 +01001710 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001711 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001712 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001713
1714 # Creating all the NS_operation (nslcmop)
1715 # Get service list from db
1716 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1717 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001718 # nslcmops_item = None
1719 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00001720 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001721 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001722 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00001723 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
tiernob4844ab2019-05-23 08:42:12 +00001724 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001725 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001726 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001727 if operation == "terminate":
1728 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1729 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
tierno40f742b2020-06-23 15:25:26 +00001730 if nsi: # other nsi is using this nsr and it needs this nsr instantiated
1731 continue # do not create nsilcmop
1732 else: # instantiate
1733 # looks the first nsi fulfilling the conditions but not being the current NSIR
1734 if nsi:
1735 nsi_nsr_item = next(n for n in nsi["_admin"]["nsrs-detailed-list"] if
1736 n["nsrId"] == nsr_id and n["shared"] and
1737 n["nslcmop_instantiate"])
1738 self.add_shared_nsr_2vld(nsir, nsr_item)
1739 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1740 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1741 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1742 # continue to not create nslcmop since nsrs is shared and nsrs was created
1743 continue
1744 else:
1745 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01001746
tierno40f742b2020-06-23 15:25:26 +00001747 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01001748 try:
tierno0b8752f2020-05-12 09:42:02 +00001749 indata_ns = {
1750 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00001751 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00001752 # Including netslice_id in the ns instantiate Operation
1753 "netsliceInstanceId": netsliceInstanceId,
1754 }
1755 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00001756 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00001757 indata_ns.update(service["instantiate_params"])
1758
tierno99d4b172019-07-02 09:28:40 +00001759 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001760 # message via kafka bus
tierno40f742b2020-06-23 15:25:26 +00001761 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, None, headers,
tiernobdebce92019-07-01 15:36:49 +00001762 slice_object=True)
Felipe Vicens09e65422019-01-22 15:06:46 +01001763 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00001764 if operation == "instantiate":
1765 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1766 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01001767 except (DbException, EngineException) as e:
1768 if e.http_code == HTTPStatus.NOT_FOUND:
tierno40f742b2020-06-23 15:25:26 +00001769 self.logger.info(logging_prefix + "skipping NS={} because not found".format(nsr_id))
Felipe Vicens09e65422019-01-22 15:06:46 +01001770 pass
1771 else:
1772 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001773
1774 # Creates nsilcmop
1775 indata["nslcmops_ids"] = nslcmops
1776 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001777
Felipe Vicens126af572019-06-05 19:13:04 +02001778 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001779 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001780 _id = self.db.create("nsilcmops", nsilcmop_desc)
1781 rollback.append({"topic": "nsilcmops", "_id": _id})
1782 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001783 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01001784 except ValidationError as e:
1785 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001786
tiernobee3bad2019-12-05 12:26:01 +00001787 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001788 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1789
tierno65ca36d2019-02-12 19:27:52 +01001790 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001791 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)