blob: 85e2c44869e6914e6aaec801c78ed82de8fb0a45 [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
garciaale9fa89992020-11-18 10:06:03 -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:
180 # check that enough parameters are supplied for the initial-config-primitive
181 # TODO: check for cloud-init
182 if member_vnf_index:
tierno714954e2019-11-29 13:43:26 +0000183 if kdu_name:
184 initial_primitives = None
185 elif vdu_id:
186 vdud = next(x for x in descriptor["vdu"] if x["id"] == vdu_id)
187 initial_primitives = deep_get(vdud, ("vdu-configuration", "initial-config-primitive"))
188 else:
garciaale9fa89992020-11-18 10:06:03 -0300189 vnf_configurations = get_iterable(descriptor.get("vnf-configuration"))
190 initial_primitives = []
191 for vnfc in vnf_configurations:
192 for primitive in get_iterable(vnfc.get("initial-config-primitive")):
193 initial_primitives.append(primitive)
tierno714954e2019-11-29 13:43:26 +0000194 else:
195 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
tiernobee085c2018-12-12 17:03:04 +0000196
tierno714954e2019-11-29 13:43:26 +0000197 for initial_primitive in get_iterable(initial_primitives):
198 for param in get_iterable(initial_primitive.get("parameter")):
199 if param["value"].startswith("<") and param["value"].endswith(">"):
200 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
201 continue
202 if not additional_params or param["value"][1:-1] not in additional_params:
203 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
204 "initial-config-primitive[name={}] not supplied".
205 format(param["value"], descriptor["id"],
206 initial_primitive["name"]))
207
tierno54db2e42020-04-06 15:29:42 +0000208 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000209
tierno65ca36d2019-02-12 19:27:52 +0100210 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200211 """
212 Creates a new nsr into database. It also creates needed vnfrs
213 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100214 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200215 :param indata: params to be used for the nsr
216 :param kwargs: used to override the indata descriptor
217 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000218 :return: the _id of nsr descriptor created at database. Or an exception of type
219 EngineException, ValidationError, DbException, FsException, MsgException.
220 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200221 """
tiernob24258a2018-10-04 18:39:49 +0200222 try:
delacruzramo32bab472019-09-13 12:24:22 +0200223 step = "checking quotas"
224 self.check_quota(session)
225
tierno99d4b172019-07-02 09:28:40 +0000226 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200227 ns_request = self._remove_envelop(indata)
tiernob24258a2018-10-04 18:39:49 +0200228 self._update_input_with_kwargs(ns_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100229 self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200230
tiernob24258a2018-10-04 18:39:49 +0200231 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
garciaale9fa89992020-11-18 10:06:03 -0300232 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
233 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
tiernob24258a2018-10-04 18:39:49 +0200234
Frank Bryden3c64ab62020-07-21 14:25:32 +0000235 step = "checking nsdOperationalState"
garciaale9fa89992020-11-18 10:06:03 -0300236 self._check_nsd_operational_state(nsd, ns_request)
Frank Bryden3c64ab62020-07-21 14:25:32 +0000237
tiernob24258a2018-10-04 18:39:49 +0200238 step = "filling nsr from input data"
garciaale9fa89992020-11-18 10:06:03 -0300239 nsr_id = str(uuid4())
240 nsr_descriptor = self._create_nsr_descriptor_from_nsd(nsd, ns_request, nsr_id)
tierno54db2e42020-04-06 15:29:42 +0000241
garciaale9fa89992020-11-18 10:06:03 -0300242 # Create VNFRs
tiernob24258a2018-10-04 18:39:49 +0200243 needed_vnfds = {}
garciaale9fa89992020-11-18 10:06:03 -0300244 # TODO: Change for multiple df support
245 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
246 for vnfp in vnf_profiles:
247 vnfd_id = vnfp.get("vnfd-id")
248 vnf_index = vnfp.get("id")
249 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(vnfd_id, vnf_index)
tiernob24258a2018-10-04 18:39:49 +0200250 if vnfd_id not in needed_vnfds:
garciaale9fa89992020-11-18 10:06:03 -0300251 vnfd = self._get_vnfd_from_db(vnfd_id, session)
tiernob24258a2018-10-04 18:39:49 +0200252 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000253 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200254 else:
255 vnfd = needed_vnfds[vnfd_id]
tierno36ec8602018-11-02 17:27:11 +0100256
garciaale9fa89992020-11-18 10:06:03 -0300257 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(vnfd_id, vnf_index)
258 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(nsd, vnfd, vnfd_id, vnf_index, nsr_descriptor,
259 ns_request, ns_k8s_namespace)
tierno36ec8602018-11-02 17:27:11 +0100260
garciaale9fa89992020-11-18 10:06:03 -0300261 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(vnfd_id, vnf_index)
262 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
263 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
tiernob24258a2018-10-04 18:39:49 +0200264
265 step = "creating nsr at database"
garciaale9fa89992020-11-18 10:06:03 -0300266 self._add_nsr_to_db(nsr_descriptor, rollback, session)
tiernobee085c2018-12-12 17:03:04 +0000267
268 step = "creating nsr temporal folder"
269 self.fs.mkdir(nsr_id)
270
tiernobdebce92019-07-01 15:36:49 +0000271 return nsr_id, None
tierno1bfe4e22019-09-02 16:03:25 +0000272 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000273 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200274
garciaale9fa89992020-11-18 10:06:03 -0300275 def _get_nsd_from_db(self, nsd_id, session):
276 _filter = self._get_project_filter(session)
277 _filter["_id"] = nsd_id
278 return self.db.get_one("nsds", _filter)
279
280 def _get_vnfd_from_db(self, vnfd_id, session):
281 _filter = self._get_project_filter(session)
282 _filter["id"] = vnfd_id
283 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
284 vnfd.pop("_admin")
285 return vnfd
286
287 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
288 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
289 self.db.create("nsrs", nsr_descriptor)
290 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
291
292 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
293 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
294 self.db.create("vnfrs", vnfr_descriptor)
295 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
296
297 def _check_nsd_operational_state(self, nsd, ns_request):
298 if nsd["_admin"]["operationalState"] == "DISABLED":
299 raise EngineException("nsd with id '{}' is DISABLED, and thus cannot be used to create "
300 "a network service".format(ns_request["nsdId"]), http_code=HTTPStatus.CONFLICT)
301
302 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
303 additional_params, _ = self._format_additional_params(ns_request, descriptor=nsd)
304 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
305 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
306 if ns_request and ns_request.get("k8s-namespace"):
307 ns_k8s_namespace = ns_request["k8s-namespace"]
308 if additional_params and additional_params.get("k8s-namespace"):
309 ns_k8s_namespace = additional_params["k8s-namespace"]
310
311 return ns_k8s_namespace
312
313 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id):
314 now = time()
315 additional_params, _ = self._format_additional_params(ns_request, descriptor=nsd)
316
317 nsr_descriptor = {
318 "name": ns_request["nsName"],
319 "name-ref": ns_request["nsName"],
320 "short-name": ns_request["nsName"],
321 "admin-status": "ENABLED",
322 "nsState": "NOT_INSTANTIATED",
323 "currentOperation": "IDLE",
324 "currentOperationID": None,
325 "errorDescription": None,
326 "errorDetail": None,
327 "deploymentStatus": None,
328 "configurationStatus": None,
329 "vcaStatus": None,
330 "nsd": {k: v for k, v in nsd.items()},
331 "datacenter": ns_request["vimAccountId"],
332 "resource-orchestrator": "osmopenmano",
333 "description": ns_request.get("nsDescription", ""),
334 "constituent-vnfr-ref": [],
335 "operational-status": "init", # typedef ns-operational-
336 "config-status": "init", # typedef config-states
337 "detailed-status": "scheduled",
338 "orchestration-progress": {},
339 "create-time": now,
340 "nsd-name-ref": nsd["name"],
341 "operational-events": [], # "id", "timestamp", "description", "event",
342 "nsd-ref": nsd["id"],
343 "nsd-id": nsd["_id"],
344 "vnfd-id": [],
345 "instantiate_params": self._format_ns_request(ns_request),
346 "additionalParamsForNs": additional_params,
347 "ns-instance-config-ref": nsr_id,
348 "id": nsr_id,
349 "_id": nsr_id,
350 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
351 "flavor": [],
352 "image": [],
353 }
354 ns_request["nsr_id"] = nsr_id
355 if ns_request and ns_request.get("config-units"):
356 nsr_descriptor["config-units"] = ns_request["config-units"]
357
358 # Create vld
359 if nsd.get("virtual-link-desc"):
360 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
361 # Fill each vld with vnfd-connection-point-ref data
362 # TODO: Change for multiple df support
363 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
364 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
365 for vnf_profile in vnf_profiles:
366 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
367 for cpd in vlc.get("constituent-cpd-id", ()):
368 all_vld_connection_point_data[vlc.get("virtual-link-profile-id")].append({
369 "member-vnf-index-ref": cpd.get("constituent-base-element-id"),
370 "vnfd-connection-point-ref": cpd.get("constituent-cpd-id"),
371 "vnfd-id-ref": vnf_profile.get("vnfd-id")
372 })
373
374 vnfd = self.db.get_one("vnfds",
375 {"id": vnf_profile.get("vnfd-id")},
376 fail_on_empty=True,
377 fail_on_more=True)
378
379 for vdu in vnfd.get("vdu", ()):
380 flavor_data = {}
381 guest_epa = {}
382 # Find this vdu compute and storage descriptors
383 vdu_virtual_compute = {}
384 vdu_virtual_storage = {}
385 for vcd in vnfd.get("virtual-compute-desc", ()):
386 if vcd.get("id") == vdu.get("virtual-compute-desc"):
387 vdu_virtual_compute = vcd
388 for vsd in vnfd.get("virtual-storage-desc", ()):
389 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
390 vdu_virtual_storage = vsd
391 # Get this vdu vcpus, memory and storage info for flavor_data
392 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
393 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"]["num-virtual-cpu"]
394 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
395 flavor_data["memory-mb"] = float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
396 if vdu_virtual_storage.get("size-of-storage"):
397 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
398 # Get this vdu EPA info for guest_epa
399 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
400 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
401 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
402 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
403 if vcpu_pinning.get("thread-policy"):
404 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
405 if vcpu_pinning.get("policy"):
406 cpu_policy = "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
407 guest_epa["cpu-pinning-policy"] = cpu_policy
408 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
409 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
410 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
411 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"]["mempage-size"]
412 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
413 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"]["numa-node-policy"]
414 if vdu_virtual_storage.get("disk-io-quota"):
415 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
416
417 if guest_epa:
418 flavor_data["guest-epa"] = guest_epa
garciaale9fa89992020-11-18 10:06:03 -0300419
garciaaleda48a122020-11-24 12:26:57 -0300420 flavor_data["vim_info"] = []
421 flavor_data["name"] = vdu["id"][:56] + "-flv"
422 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
423 nsr_descriptor["flavor"].append(flavor_data)
garciaale9fa89992020-11-18 10:06:03 -0300424
425 sw_image_id = vdu.get("sw-image-desc")
426 if sw_image_id:
427 sw_image_desc = utils.find_in_list(vnfd.get("sw-image-desc", ()),
428 lambda sw: sw["id"] == sw_image_id)
429 image_data = {}
430 if sw_image_desc.get("image"):
431 image_data["image"] = sw_image_desc["image"]
432 if sw_image_desc.get("checksum"):
433 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
434 img = next((f for f in nsr_descriptor["image"] if
435 all(f.get(k) == image_data[k] for k in image_data)), None)
436 if not img:
437 image_data["vim_info"] = []
438 image_data["id"] = str(len(nsr_descriptor["image"]))
439 nsr_descriptor["image"].append(image_data)
440
441 for vld in nsr_vld:
442 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(vld.get("id"), [])
443 vld["name"] = vld["id"]
444 nsr_descriptor["vld"] = nsr_vld
445
446 return nsr_descriptor
447
448 def _create_vnfr_descriptor_from_vnfd(self, nsd, vnfd, vnfd_id, vnf_index, nsr_descriptor,
449 ns_request, ns_k8s_namespace):
450 vnfr_id = str(uuid4())
451 nsr_id = nsr_descriptor["id"]
452 now = time()
453 additional_params, vnf_params = self._format_additional_params(ns_request, vnf_index, descriptor=vnfd)
454
455 vnfr_descriptor = {
456 "id": vnfr_id,
457 "_id": vnfr_id,
458 "nsr-id-ref": nsr_id,
459 "member-vnf-index-ref": vnf_index,
460 "additionalParamsForVnf": additional_params,
461 "created-time": now,
462 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
463 "vnfd-ref": vnfd_id,
464 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
465 "vim-account-id": None,
466 "vdur": [],
467 "connection-point": [],
468 "ip-address": None, # mgmt-interface filled by LCM
469 }
470 vnf_k8s_namespace = ns_k8s_namespace
471 if vnf_params:
472 if vnf_params.get("k8s-namespace"):
473 vnf_k8s_namespace = vnf_params["k8s-namespace"]
474 if vnf_params.get("config-units"):
475 vnfr_descriptor["config-units"] = vnf_params["config-units"]
476
477 # Create vld
478 if vnfd.get("int-virtual-link-desc"):
479 vnfr_descriptor["vld"] = []
480 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
481 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
482
483 for cp in vnfd.get("ext-cpd", ()):
484 vnf_cp = {
485 "name": cp.get("id"),
486 "connection-point-id": cp.get("int-cpd").get("cpd"),
487 "connection-point-vdu-id": cp.get("int-cpd").get("vdu-id"),
488 "id": cp.get("id"),
489 # "ip-address", "mac-address" # filled by LCM
490 # vim-id # TODO it would be nice having a vim port id
491 }
492 vnfr_descriptor["connection-point"].append(vnf_cp)
493
494 # Create k8s-cluster information
495 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
496 if vnfd.get("k8s-cluster"):
497 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
498 all_k8s_cluster_nets_cpds = {}
499 for cpd in get_iterable(vnfd.get("ext-cpd")):
500 if cpd.get("k8s-cluster-net"):
501 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get("id")
502 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
503 if net.get("id") in all_k8s_cluster_nets_cpds:
504 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[net.get("id")]
505
506 # update kdus
507 # TODO: Change for multiple df support
508 all_kdu_profiles = vnfd.get("df", [[]])[0].get("kdu-profile", ())
509 all_kdu_profiles_models = {profile.get("name"): profile.get("kdu-model-id") for profile in all_kdu_profiles}
510 all_kdu_models = vnfd.get("kdu-model", ())
511 all_kdu_models = {model.get("id"): model for model in all_kdu_models}
512 for kdu in get_iterable(vnfd.get("kdu")):
513 additional_params, kdu_params = self._format_additional_params(ns_request,
514 vnf_index,
515 kdu_name=kdu["name"],
516 descriptor=vnfd)
517 kdu_k8s_namespace = vnf_k8s_namespace
518 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
519 if kdu_params and kdu_params.get("k8s-namespace"):
520 kdu_k8s_namespace = kdu_params["k8s-namespace"]
521
522 kdur = {
523 "additionalParams": additional_params,
524 "k8s-namespace": kdu_k8s_namespace,
525 "kdu-name": kdu.get("name"),
526 # TODO "name": "" Name of the VDU in the VIM
527 "ip-address": None, # mgmt-interface filled by LCM
528 "k8s-cluster": {},
529 }
530 if kdu_params and kdu_params.get("config-units"):
531 kdur["config-units"] = kdu_params["config-units"]
532
533 kdu_model_data = all_kdu_models[all_kdu_profiles_models[kdur["name"]]]
534 kdur[kdu_model_data.get("kdu-model-type")] = kdu_model or kdu_model_data
535 if not vnfr_descriptor.get("kdur"):
536 vnfr_descriptor["kdur"] = []
537 vnfr_descriptor["kdur"].append(kdur)
538
539 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
540 for vdu in vnfd.get("vdu", ()):
541 additional_params, vdu_params = self._format_additional_params(
542 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd)
543 vdur = {
544 "vdu-id-ref": vdu["id"],
545 # TODO "name": "" Name of the VDU in the VIM
546 "ip-address": None, # mgmt-interface filled by LCM
547 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
548 "internal-connection-point": [],
549 "interfaces": [],
550 "additionalParams": additional_params,
551 "vdu-name": vdu["name"]
552 }
553 if vdu_params and vdu_params.get("config-units"):
554 vdur["config-units"] = vdu_params["config-units"]
555 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
556 vdur["boot-data-drive"] = vdu["supplemental-boot-data"]["boot-data-drive"]
557 if vdu.get("pdu-type"):
558 vdur["pdu-type"] = vdu["pdu-type"]
559 vdur["name"] = vdu["pdu-type"]
560 # TODO volumes: name, volume-id
561 for icp in vdu.get("int-cpd", ()):
562 vdu_icp = {
563 "id": icp["id"],
564 "connection-point-id": icp["id"],
565 "name": icp.get("id"),
566 }
567 vdur["internal-connection-point"].append(vdu_icp)
568
569 for iface in icp.get("virtual-network-interface-requirement", ()):
570 iface_fields = ("name", "mac-address")
571 vdu_iface = {x: iface[x] for x in iface_fields if iface.get(x) is not None}
572
573 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
574 for ext_cp in vnfd.get("ext-cpd", ()):
575 if not ext_cp.get("int-cpd"):
576 continue
577 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
578 continue
579 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
580 vdu_iface["external-connection-point-ref"] = ext_cp.get("id")
581 break
582
583 if vnfd_mgmt_cp and vdu_iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
584 vdu_iface["mgmt-vnf"] = True
585 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
586
garciaaleda48a122020-11-24 12:26:57 -0300587 if iface.get("virtual-interface"):
588 vdu_iface.update(deepcopy(iface["virtual-interface"]))
589
garciaale9fa89992020-11-18 10:06:03 -0300590 # look for network where this interface is connected
591 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
592 if iface_ext_cp:
593 # TODO: Change for multiple df support
594 for df in get_iterable(nsd.get("df")):
595 for vnf_profile in get_iterable(df.get("vnf-profile")):
596 for vlc in get_iterable(vnf_profile.get("virtual-link-connectivity")):
597 for cpd in get_iterable(vlc.get("constituent-cpd-id")):
598 if cpd.get("constituent-cpd-id") == iface_ext_cp:
599 vdu_iface["ns-vld-id"] = vlc.get("virtual-link-profile-id")
600 break
601 elif vdu_iface.get("internal-connection-point-ref"):
602 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
603
604 vdur["interfaces"].append(vdu_iface)
605
606 if vdu.get("sw-image-desc"):
607 sw_image = utils.find_in_list(
608 vnfd.get("sw-image-desc", ()),
609 lambda image: image["id"] == vdu.get("sw-image-desc"))
610 nsr_sw_image_data = utils.find_in_list(
611 nsr_descriptor["image"],
612 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image"))
613 )
614 vdur["ns-image-id"] = nsr_sw_image_data["id"]
615
616 flavor_data_name = vdu["id"][:56] + "-flv"
617 nsr_flavor_desc = utils.find_in_list(
618 nsr_descriptor["flavor"],
619 lambda flavor: flavor["name"] == flavor_data_name)
620
621 if nsr_flavor_desc:
622 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
623
624 count = int(vdu.get("count", 1))
625 for index in range(0, count):
626 vdur = deepcopy(vdur)
627 for iface in vdur["interfaces"]:
628 if iface.get("ip-address"):
629 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
630 if iface.get("mac-address"):
631 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
632
633 vdur["_id"] = str(uuid4())
634 vdur["id"] = vdur["_id"]
635 vdur["count-index"] = index
636 vnfr_descriptor["vdur"].append(vdur)
637
638 return vnfr_descriptor
639
tierno65ca36d2019-02-12 19:27:52 +0100640 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200641 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
642
643
644class VnfrTopic(BaseTopic):
645 topic = "vnfrs"
646 topic_msg = None
647
delacruzramo32bab472019-09-13 12:24:22 +0200648 def __init__(self, db, fs, msg, auth):
649 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200650
tiernobee3bad2019-12-05 12:26:01 +0000651 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200652 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
653
tierno65ca36d2019-02-12 19:27:52 +0100654 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200655 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
656
tierno65ca36d2019-02-12 19:27:52 +0100657 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200658 # Not used because vnfrs are created and deleted by NsrTopic class directly
659 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
660
661
662class NsLcmOpTopic(BaseTopic):
663 topic = "nslcmops"
664 topic_msg = "ns"
665 operation_schema = { # mapping between operation and jsonschema to validate
666 "instantiate": ns_instantiate,
667 "action": ns_action,
668 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +0000669 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +0200670 }
671
delacruzramo32bab472019-09-13 12:24:22 +0200672 def __init__(self, db, fs, msg, auth):
673 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200674
tiernob24258a2018-10-04 18:39:49 +0200675 def _check_ns_operation(self, session, nsr, operation, indata):
676 """
677 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100678 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200679 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
680 :param indata: descriptor with the parameters of the operation
681 :return: None
682 """
garciaale9fa89992020-11-18 10:06:03 -0300683 if operation == "action":
684 self._check_action_ns_operation(indata, nsr)
685 elif operation == "scale":
686 self._check_scale_ns_operation(indata, nsr)
687 elif operation == "instantiate":
688 self._check_instantiate_ns_operation(indata, nsr, session)
689
690 def _check_action_ns_operation(self, indata, nsr):
691 nsd = nsr["nsd"]
692 # check vnf_member_index
693 if indata.get("vnf_member_index"):
694 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
695 if indata.get("member_vnf_index"):
696 vnfd = self._get_vnfd_from_vnf_member_index(indata["member_vnf_index"], nsr["_id"])
697 if indata.get("vdu_id"):
garciaaleda48a122020-11-24 12:26:57 -0300698 self._check_valid_vdu(vnfd, indata["vdu_id"])
699 # TODO: Change the [0] as vdu-configuration is now a list
700 descriptor_configuration = vnfd.get("vdu-configuration", [{}])[0].get("config-primitive")
garciaale9fa89992020-11-18 10:06:03 -0300701 elif indata.get("kdu_name"):
garciaaleda48a122020-11-24 12:26:57 -0300702 self._check_valid_kdu(vnfd, indata["kdu_name"])
703 # TODO: Change the [0] as kdu-configuration is now a list
704 descriptor_configuration = vnfd.get("kdu-configuration", [{}])[0].get("config-primitive")
garciaale9fa89992020-11-18 10:06:03 -0300705 else:
garciaaleda48a122020-11-24 12:26:57 -0300706 # TODO: Change the [0] as vnf-configuration is now a list
707 descriptor_configuration = vnfd.get("vnf-configuration", [{}])[0].get("config-primitive")
garciaale9fa89992020-11-18 10:06:03 -0300708 else: # use a NSD
709 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
710
711 # For k8s allows default primitives without validating the parameters
712 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
713 # TODO should be checked that rollback only can contains revsision_numbe????
714 if not indata.get("member_vnf_index"):
715 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
716 .format(indata["primitive"]))
717 return
718 # if not, check primitive
719 for config_primitive in get_iterable(descriptor_configuration):
720 if indata["primitive"] == config_primitive["name"]:
721 # check needed primitive_params are provided
722 if indata.get("primitive_params"):
723 in_primitive_params_copy = copy(indata["primitive_params"])
724 else:
725 in_primitive_params_copy = {}
726 for paramd in get_iterable(config_primitive.get("parameter")):
727 if paramd["name"] in in_primitive_params_copy:
728 del in_primitive_params_copy[paramd["name"]]
729 elif not paramd.get("default-value"):
730 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
731 paramd["name"], indata["primitive"]))
732 # check no extra primitive params are provided
733 if in_primitive_params_copy:
734 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
735 list(in_primitive_params_copy.keys()), indata["primitive"]))
736 break
737 else:
738 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
739
740 def _check_scale_ns_operation(self, indata, nsr):
741 vnfd = self._get_vnfd_from_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"],
742 nsr["_id"])
743 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
744 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
745 break
746 else:
747 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
748 "present at vnfd:scaling-group-descriptor"
749 .format(indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
750
751 def _check_instantiate_ns_operation(self, indata, nsr, session):
tierno982da4e2019-09-03 11:51:55 +0000752 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +0200753 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000754 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200755 nsd = nsr["nsd"]
garciaale9fa89992020-11-18 10:06:03 -0300756 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
757 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
758 for in_vnf in get_iterable(indata.get("vnf")):
759 member_vnf_index = in_vnf["member-vnf-index"]
tierno982da4e2019-09-03 11:51:55 +0000760 if vnf_member_index_to_vnfd.get(member_vnf_index):
garciaale9fa89992020-11-18 10:06:03 -0300761 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
tierno260dd6f2019-09-02 10:48:56 +0000762 else:
garciaale9fa89992020-11-18 10:06:03 -0300763 vnfd = self._get_vnfd_from_vnf_member_index(member_vnf_index, nsr["_id"])
764 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
765 self._check_vnf_instantiation_params(in_vnf, vnfd)
766 if in_vnf.get("vimAccountId"):
767 self._check_valid_vim_account(in_vnf["vimAccountId"], vim_accounts, session)
tierno260dd6f2019-09-02 10:48:56 +0000768
garciaale9fa89992020-11-18 10:06:03 -0300769 for in_vld in get_iterable(indata.get("vld")):
770 self._check_valid_wim_account(in_vld.get("wimAccountId"), wim_accounts, session)
771 for vldd in get_iterable(nsd.get("virtual-link-desc")):
772 if in_vld["name"] == vldd["id"]:
773 break
tierno9cb7d672019-10-30 12:13:48 +0000774 else:
garciaale9fa89992020-11-18 10:06:03 -0300775 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
776 in_vld["name"]))
tierno9cb7d672019-10-30 12:13:48 +0000777
garciaale9fa89992020-11-18 10:06:03 -0300778 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
779 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
780 vnfr = self.db.get_one("vnfrs",
781 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
782 fail_on_empty=False)
783 if not vnfr:
784 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
785 "nsd:constituent-vnfd".format(member_vnf_index))
786 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
787 if not vnfd:
788 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
789 format(vnfr["vnfd-id"]))
790 return vnfd
gcalvino5e72d152018-10-23 11:46:57 +0200791
garciaale9fa89992020-11-18 10:06:03 -0300792 def _check_valid_vdu(self, vnfd, vdu_id):
793 for vdud in get_iterable(vnfd.get("vdu")):
794 if vdud["id"] == vdu_id:
795 return vdud
796 else:
797 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
798
799 def _check_valid_kdu(self, vnfd, kdu_name):
800 for kdud in get_iterable(vnfd.get("kdu")):
801 if kdud["name"] == kdu_name:
802 return kdud
803 else:
804 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
805
806 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
807 for in_vdu in get_iterable(in_vnf.get("vdu")):
808 for vdu in get_iterable(vnfd.get("vdu")):
809 if in_vdu["id"] == vdu["id"]:
810 for volume in get_iterable(in_vdu.get("volume")):
811 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
812 if volumed["id"] == volume["name"]:
813 break
814 else:
815 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
816 "volume:name='{}' is not present at "
817 "vnfd:vdu:virtual-storage-desc list".
818 format(in_vnf["member-vnf-index"], in_vdu["id"],
819 volume["id"]))
820
821 vdu_if_names = set()
822 for cpd in get_iterable(vdu.get("int-cpd")):
823 for iface in get_iterable(cpd.get("virtual-network-interface-requirement")):
824 vdu_if_names.add(iface.get("name"))
825
826 for in_iface in get_iterable(in_vdu["interface"]):
827 if in_iface["name"] in vdu_if_names:
828 break
829 else:
830 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
831 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd"
832 .format(in_vnf["member-vnf-index"], in_vdu["id"],
833 in_iface["name"]))
834 break
835
836 else:
837 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
838 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
839
840 vnfd_ivlds_cpds = {ivld.get("id"): set() for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))}
841 for vdu in get_iterable(vnfd.get("vdu")):
842 for cpd in get_iterable(vnfd.get("int-cpd")):
843 if cpd.get("int-virtual-link-desc"):
844 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
845
846 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
847 if in_ivld.get("name") in vnfd_ivlds_cpds:
848 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
849 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
tierno40fbcad2018-10-26 10:58:15 +0200850 break
tiernob24258a2018-10-04 18:39:49 +0200851 else:
garciaale9fa89992020-11-18 10:06:03 -0300852 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
853 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
854 "vnfd:internal-vld:name/id:internal-connection-point"
855 .format(in_vnf["member-vnf-index"], in_ivld["name"],
856 in_icp["id-ref"]))
tiernob24258a2018-10-04 18:39:49 +0200857 else:
garciaale9fa89992020-11-18 10:06:03 -0300858 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
859 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
860 in_ivld["name"], vnfd["id"]))
tiernob24258a2018-10-04 18:39:49 +0200861
garciaale9fa89992020-11-18 10:06:03 -0300862 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
863 if vim_account in vim_accounts:
864 return
865 try:
866 db_filter = self._get_project_filter(session)
867 db_filter["_id"] = vim_account
868 self.db.get_one("vim_accounts", db_filter)
869 except Exception:
870 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
871 vim_accounts.append(vim_account)
872
873 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
874 if not isinstance(wim_account, str):
875 return
876 if wim_account in wim_accounts:
877 return
878 try:
879 db_filter = self._get_project_filter(session, write=False, show_all=True)
880 db_filter["_id"] = wim_account
881 self.db.get_one("wim_accounts", db_filter)
882 except Exception:
883 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
884 wim_accounts.append(wim_account)
tiernob24258a2018-10-04 18:39:49 +0200885
tierno36ec8602018-11-02 17:27:11 +0100886 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200887 """
tierno36ec8602018-11-02 17:27:11 +0100888 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
889 (ip_address, ...) information.
890 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +0100891 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100892 :param rollback: list with the database modifications to rollback if needed
893 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
894 :param vim_account: vim_account where this vnfr should be deployed
895 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
896 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
897 of the changed vnfr is needed
898
899 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
900 "vim-network-name": used at VIM
901 "name": interface name
902 "vnf-vld-id": internal VNFD vld where this interface is connected, or
903 "ns-vld-id": NSD vld where this interface is connected.
904 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 +0200905 """
tierno36ec8602018-11-02 17:27:11 +0100906
907 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +0200908 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
909 if not vdur.get("pdu-type"):
910 continue
911 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +0100912 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +0100913 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +0200914 pdu_filter["type"] = pdu_type
915 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +0100916 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +0200917 # TODO feature 1417: "shared": True,
918
919 available_pdus = self.db.get_list("pdus", pdu_filter)
920 for pdu in available_pdus:
921 # step 1 check if this pdu contains needed interfaces:
922 match_interfaces = True
923 for vdur_interface in vdur["interfaces"]:
924 for pdu_interface in pdu["interfaces"]:
925 if pdu_interface["name"] == vdur_interface["name"]:
926 # TODO feature 1417: match per mgmt type
927 break
928 else: # no interface found for name
929 match_interfaces = False
930 break
931 if match_interfaces:
932 break
933 else:
934 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +0100935 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
936 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +0200937
938 # step 2. Update pdu
939 rollback_pdu = {
940 "_admin.usageState": pdu["_admin"]["usageState"],
941 "_admin.usage.vnfr_id": None,
942 "_admin.usage.nsr_id": None,
943 "_admin.usage.vdur": None,
944 }
945 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +0100946 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +0000947 "_admin.usage": {"vnfr_id": vnfr["_id"],
948 "nsr_id": vnfr["nsr-id-ref"],
949 "vdur": vdur["vdu-id-ref"]}
950 })
tiernocc103432018-10-19 14:10:35 +0200951 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
952
953 # step 3. Fill vnfr info by filling vdur
954 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +0100955 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +0200956 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
957 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
958 for pdu_interface in pdu["interfaces"]:
959 if pdu_interface["name"] == vdur_interface["name"]:
960 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
961 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +0100962 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
963 vnfr_update[iface_text + ".{}".format(k)] = v
964 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
965 if pdu_interface.get("ip-address"):
tiernoc88003e2020-03-12 17:31:42 +0000966 if vdur_interface.get("mgmt-interface") or vdur_interface.get("mgmt-vnf"):
tierno36ec8602018-11-02 17:27:11 +0100967 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
968 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
969 if vdur_interface.get("mgmt-vnf"):
970 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
971 vnfr_update["ip-address"] = pdu_interface["ip-address"]
tierno72b16e12020-03-18 09:49:43 +0000972 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +0100973 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +0100974 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +0100975 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
976 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
977 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +0100978 if pdu_interface.get("vim-network-id"):
tiernoc67b0e92019-11-05 12:45:29 +0000979 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +0100980 if pdu_interface.get("vim-network-name"):
tiernoc67b0e92019-11-05 12:45:29 +0000981 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +0200982 break
983
tierno36ec8602018-11-02 17:27:11 +0100984 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +0200985
tierno9cb7d672019-10-30 12:13:48 +0000986 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
987 """
988 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
989 Fills vnfr.kdur with the selected k8scluster
990
991 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
992 :param rollback: list with the database modifications to rollback if needed
993 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
994 :param vim_account: vim_account where this vnfr should be deployed
995 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
996 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
997 of the changed vnfr is needed
998
999 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1000 "vim-network-name": used at VIM
1001 "name": interface name
1002 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1003 "ns-vld-id": NSD vld where this interface is connected.
1004 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1005 """
1006
1007 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +00001008 if not vnfr.get("kdur"):
1009 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +00001010
tiernoc67b0e92019-11-05 12:45:29 +00001011 kdu_filter = self._get_project_filter(session)
1012 kdu_filter["vim_account"] = vim_account
1013 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1014 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1015
1016 k8s_requirements = {} # just for logging
1017 for k8scluster in available_k8sclusters:
1018 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +00001019 break
tiernoc67b0e92019-11-05 12:45:29 +00001020 # restrict by cni
1021 if vnfr["k8s-cluster"].get("cni"):
1022 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
1023 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
1024 continue
1025 # restrict by version
1026 if vnfr["k8s-cluster"].get("version"):
1027 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1028 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1029 continue
1030 # restrict by number of networks
1031 if vnfr["k8s-cluster"].get("nets"):
1032 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
1033 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
1034 continue
1035 break
1036 else:
1037 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
1038 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
tierno9cb7d672019-10-30 12:13:48 +00001039
tiernoc67b0e92019-11-05 12:45:29 +00001040 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +00001041 # step 3. Fill vnfr info by filling kdur
1042 kdu_text = "kdur.{}.".format(kdur_index)
1043 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1044 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1045
tiernoc67b0e92019-11-05 12:45:29 +00001046 # step 4. Check VIM networks that forces the selected k8s_cluster
1047 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1048 k8scluster_net_list = list(k8scluster.get("nets").keys())
1049 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1050 # get a network from k8s_cluster nets. If name matches use this, if not use other
1051 if kdur_net["id"] in k8scluster_net_list: # name matches
1052 vim_net = k8scluster["nets"][kdur_net["id"]]
1053 k8scluster_net_list.remove(kdur_net["id"])
1054 else:
1055 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1056 k8scluster_net_list.pop(0)
1057 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
1058 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
1059 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
1060 ifaces_forcing_vim_network.append({
1061 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
1062 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1063 "ns-vld-id": kdur_net.get("ns-vld-id"),
1064 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1065 })
1066 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +00001067 return ifaces_forcing_vim_network
1068
tiernocc103432018-10-19 14:10:35 +02001069 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +02001070 # get vnfr
1071 nsr_id = nsr["_id"]
1072 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1073
1074 for vnfr in vnfrs:
1075 vnfr_update = {}
1076 vnfr_update_rollback = {}
1077 member_vnf_index = vnfr["member-vnf-index-ref"]
1078 # update vim-account-id
1079
1080 vim_account = indata["vimAccountId"]
1081 # check instantiate parameters
1082 for vnf_inst_params in get_iterable(indata.get("vnf")):
1083 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1084 continue
1085 if vnf_inst_params.get("vimAccountId"):
1086 vim_account = vnf_inst_params.get("vimAccountId")
1087
tiernocddb07d2020-10-06 08:28:00 +00001088 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1089 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1090 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1091 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1092 continue
1093 for iface_inst_param in get_iterable(vdu_inst_param.get("interface")):
1094 iface_index, _ = next(i for i in enumerate(vdur["interfaces"])
1095 if i[1]["name"] == iface_inst_param["name"])
1096 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1097 if iface_inst_param.get("ip-address"):
1098 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1099 iface_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001100 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001101 if iface_inst_param.get("mac-address"):
1102 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1103 iface_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001104 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001105 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1106 # TODO update vld with the ip-profile
1107 for ivld_inst_param in get_iterable(vnf_inst_params.get("internal-vld")):
1108 for icp_inst_param in get_iterable(ivld_inst_param.get("internal-connection-point")):
1109 # look for iface
1110 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1111 for iface_index, iface in enumerate(vdur["interfaces"]):
1112 if iface.get("internal-connection-point-ref") == icp_inst_param["id-ref"]:
1113 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1114 if icp_inst_param.get("ip-address"):
1115 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1116 icp_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001117 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001118 if icp_inst_param.get("mac-address"):
1119 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1120 icp_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001121 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001122 break
1123 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1124 for vld_inst_param in get_iterable(indata.get("vld")):
1125 for vnfcp_inst_param in get_iterable(vld_inst_param.get("vnfd-connection-point-ref")):
1126 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1127 continue
1128 # look for iface
1129 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1130 for iface_index, iface in enumerate(vdur["interfaces"]):
1131 if iface.get("external-connection-point-ref") == \
1132 vnfcp_inst_param["vnfd-connection-point-ref"]:
1133 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1134 if vnfcp_inst_param.get("ip-address"):
1135 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1136 vnfcp_inst_param.get("ip-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001137 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
tiernocddb07d2020-10-06 08:28:00 +00001138 if vnfcp_inst_param.get("mac-address"):
1139 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1140 vnfcp_inst_param.get("mac-address"), vdur.get("count-index", 0))
tierno1bd9d952020-11-13 15:56:51 +00001141 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
tiernocddb07d2020-10-06 08:28:00 +00001142 break
1143
tiernocc103432018-10-19 14:10:35 +02001144 vnfr_update["vim-account-id"] = vim_account
1145 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1146
1147 # get pdu
tierno36ec8602018-11-02 17:27:11 +01001148 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
1149 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +02001150
tierno9cb7d672019-10-30 12:13:48 +00001151 # get kdus
1152 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
1153 vnfr_update_rollback)
1154 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001155 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1156 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
1157
1158 # Update indada in case pdu forces to use a concrete vim-network-name
1159 # TODO check if user has already insert a vim-network-name and raises an error
1160 if not ifaces_forcing_vim_network:
1161 continue
1162 for iface_info in ifaces_forcing_vim_network:
1163 if iface_info.get("ns-vld-id"):
1164 if "vld" not in indata:
1165 indata["vld"] = []
1166 indata["vld"].append({key: iface_info[key] for key in
1167 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
1168
1169 elif iface_info.get("vnf-vld-id"):
1170 if "vnf" not in indata:
1171 indata["vnf"] = []
1172 indata["vnf"].append({
1173 "member-vnf-index": member_vnf_index,
1174 "internal-vld": [{key: iface_info[key] for key in
1175 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
1176 })
1177
1178 @staticmethod
1179 def _create_nslcmop(nsr_id, operation, params):
1180 """
1181 Creates a ns-lcm-opp content to be stored at database.
1182 :param nsr_id: internal id of the instance
1183 :param operation: instantiate, terminate, scale, action, ...
1184 :param params: user parameters for the operation
1185 :return: dictionary following SOL005 format
1186 """
tiernob24258a2018-10-04 18:39:49 +02001187 now = time()
1188 _id = str(uuid4())
1189 nslcmop = {
1190 "id": _id,
1191 "_id": _id,
1192 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001193 "queuePosition": None,
1194 "stage": None,
1195 "errorMessage": None,
1196 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001197 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001198 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001199 "lcmOperationType": operation,
1200 "startTime": now,
1201 "isAutomaticInvocation": False,
1202 "operationParams": params,
1203 "isCancelPending": False,
1204 "links": {
1205 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001206 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001207 }
1208 }
1209 return nslcmop
1210
magnussonlf318b302020-01-20 18:38:18 +01001211 def _get_enabled_vims(self, session):
1212 """
1213 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1214 :param session: current session with user information
1215 """
1216 db_filter = self._get_project_filter(session)
1217 db_filter["_admin.operationalState"] = "ENABLED"
1218 vims = self.db.get_list("vim_accounts", db_filter)
1219 vimAccounts = []
1220 for vim in vims:
1221 vimAccounts.append(vim['_id'])
1222 return vimAccounts
1223
tierno65ca36d2019-02-12 19:27:52 +01001224 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +02001225 """
1226 Performs a new operation over a ns
1227 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001228 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001229 :param indata: descriptor with the parameters of the operation. It must contains among others
1230 nsInstanceId: _id of the nsr to perform the operation
1231 operation: it can be: instantiate, terminate, action, TODO: update, heal
1232 :param kwargs: used to override the indata descriptor
1233 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02001234 :return: id of the nslcmops
1235 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001236 def check_if_nsr_is_not_slice_member(session, nsr_id):
1237 nsis = None
1238 db_filter = self._get_project_filter(session)
1239 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1240 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
1241 if nsis:
tierno40f742b2020-06-23 15:25:26 +00001242 raise EngineException("The NS instance {} cannot be terminated because is used by the slice {}".format(
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001243 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
1244
tiernob24258a2018-10-04 18:39:49 +02001245 try:
1246 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00001247 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02001248 operation = indata["lcmOperationType"]
1249 nsInstanceId = indata["nsInstanceId"]
1250
1251 validate_input(indata, self.operation_schema[operation])
1252 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01001253 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02001254 _filter["_id"] = nsInstanceId
1255 nsr = self.db.get_one("nsrs", _filter)
1256
1257 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001258 if operation == "terminate" and slice_object is False:
1259 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +02001260 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1261 if operation == "terminate" and indata.get("autoremove"):
1262 # NSR must be deleted
tierno586ae812019-10-17 13:56:53 +00001263 return None, None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02001264 if operation != "instantiate":
1265 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1266 nsInstanceId, operation), HTTPStatus.CONFLICT)
1267 else:
tierno65ca36d2019-02-12 19:27:52 +01001268 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +02001269 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1270 nsInstanceId, operation), HTTPStatus.CONFLICT)
1271 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +01001272
tiernocc103432018-10-19 14:10:35 +02001273 if operation == "instantiate":
1274 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01001275
1276 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00001277 _id = nslcmop_desc["_id"]
tierno65ca36d2019-02-12 19:27:52 +01001278 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
magnussonlf318b302020-01-20 18:38:18 +01001279 if indata.get("placement-engine"):
1280 # Save valid vim accounts in lcm operation descriptor
1281 nslcmop_desc['operationParams']['validVimAccounts'] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00001282 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02001283 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001284 if not slice_object:
1285 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001286 return _id, None
1287 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02001288 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1289 # except DbException as e:
1290 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1291
tiernobee3bad2019-12-05 12:26:01 +00001292 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +02001293 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1294
tierno65ca36d2019-02-12 19:27:52 +01001295 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +02001296 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001297
1298
1299class NsiTopic(BaseTopic):
1300 topic = "nsis"
1301 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00001302 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001303
delacruzramo32bab472019-09-13 12:24:22 +02001304 def __init__(self, db, fs, msg, auth):
1305 BaseTopic.__init__(self, db, fs, msg, auth)
1306 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001307
Felipe Vicensc37b3842019-01-12 12:24:42 +01001308 @staticmethod
1309 def _format_ns_request(ns_request):
1310 formated_request = copy(ns_request)
1311 # TODO: Add request params
1312 return formated_request
1313
1314 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001315 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001316 """
1317 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001318 :param slice_request: User instantiation additional parameters
1319 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001320 """
tiernofd160572019-01-21 10:41:37 +00001321 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1322 if additional_params:
1323 for k, v in additional_params.items():
1324 if not isinstance(k, str):
1325 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1326 format(k))
1327 if "." in k or "$" in k:
1328 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1329 format(k))
1330 if isinstance(v, (dict, tuple, list)):
1331 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001332 return additional_params
1333
Felipe Vicensb57758d2018-10-16 16:00:20 +02001334 def _check_descriptor_dependencies(self, session, descriptor):
1335 """
1336 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001337 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001338 :param descriptor: descriptor to be inserted or edit
1339 :return: None or raises exception
1340 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001341 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001342 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001343 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001344 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +01001345 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +02001346 http_code=HTTPStatus.CONFLICT)
1347
tiernob4844ab2019-05-23 08:42:12 +00001348 def check_conflict_on_del(self, session, _id, db_content):
1349 """
1350 Check that NSI is not instantiated
1351 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1352 :param _id: nsi internal id
1353 :param db_content: The database content of the _id
1354 :return: None or raises EngineException with the conflict
1355 """
tierno65ca36d2019-02-12 19:27:52 +01001356 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02001357 return
tiernob4844ab2019-05-23 08:42:12 +00001358 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02001359 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1360 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1361 "Launch 'terminate' operation first; or force deletion".format(_id),
1362 http_code=HTTPStatus.CONFLICT)
1363
tiernobee3bad2019-12-05 12:26:01 +00001364 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001365 """
tiernob4844ab2019-05-23 08:42:12 +00001366 Deletes associated nsilcmops from database. Deletes associated filesystem.
1367 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01001368 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001369 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00001370 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00001371 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00001372 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02001373 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001374
Felipe Vicens09e65422019-01-22 15:06:46 +01001375 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00001376 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01001377 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1378 nsr_id = nsrs_detailed_item["nsrId"]
1379 if nsrs_detailed_item.get("shared"):
1380 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1381 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1382 "_id.ne": nsir["_id"]}
1383 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1384 if nsi: # last one using nsr
1385 continue
1386 try:
tiernobee3bad2019-12-05 12:26:01 +00001387 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
Felipe Vicens09e65422019-01-22 15:06:46 +01001388 except (DbException, EngineException) as e:
1389 if e.http_code == HTTPStatus.NOT_FOUND:
1390 pass
1391 else:
1392 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001393
tiernob4844ab2019-05-23 08:42:12 +00001394 # delete related nsilcmops database entries
1395 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001396
tiernob4844ab2019-05-23 08:42:12 +00001397 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01001398 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00001399 if nsir_admin and nsir_admin.get("nst-id"):
1400 # check if used by another NSI
1401 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1402 fail_on_empty=False, fail_on_more=False)
1403 if not nsis_list:
1404 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1405
tierno65ca36d2019-02-12 19:27:52 +01001406 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001407 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001408 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02001409 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01001410 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001411 :param indata: params to be used for the nsir
1412 :param kwargs: used to override the indata descriptor
1413 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02001414 :return: the _id of nsi descriptor created at database
1415 """
1416
1417 try:
delacruzramo32bab472019-09-13 12:24:22 +02001418 step = "checking quotas"
1419 self.check_quota(session)
1420
tierno99d4b172019-07-02 09:28:40 +00001421 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02001422 slice_request = self._remove_envelop(indata)
1423 # Override descriptor with query string kwargs
1424 self._update_input_with_kwargs(slice_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001425 self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001426
Felipe Vicensb57758d2018-10-16 16:00:20 +02001427 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +00001428 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001429 _filter = self._get_project_filter(session)
1430 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001431 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00001432 # check NST is not disabled
1433 step = "checking NST operationalState"
1434 if nstd["_admin"]["operationalState"] == "DISABLED":
1435 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
1436 "instance".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
tiernob4844ab2019-05-23 08:42:12 +00001437 del _filter["_id"]
1438
Frank Brydenb5a2ead2020-07-28 12:50:23 +00001439 # check NSD is not disabled
1440 step = "checking operationalState"
1441 if nstd["_admin"]["operationalState"] == "DISABLED":
1442 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create "
1443 "a network slice".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
1444
Felipe Vicens07f31722018-10-29 15:16:44 +01001445 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001446 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001447 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001448 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001449
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001450 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001451 nsi_descriptor = {
1452 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001453 "name": slice_request["nsiName"],
1454 "description": slice_request.get("nsiDescription", ""),
1455 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001456 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001457 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001458 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001459 "nsr-ref-list": [],
1460 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001461 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001462 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001463 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001464
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001465 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001466 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001467 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1468 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001469 nsi_descriptor["_admin"]["deployed"] = {}
1470 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1471 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1472
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001473 # Creating netslice-vld for the RO.
1474 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001475
1476 # Building the vlds list to be deployed
1477 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001478 nsi_vlds = []
1479
1480 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1481 # Getting template Instantiation parameters from NST
1482 nsi_vld = deepcopy(netslice_vlds)
1483 nsi_vld["shared-nsrs-list"] = []
1484 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1485 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001486
1487 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00001488 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001489 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001490 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001491
Felipe Vicens09e65422019-01-22 15:06:46 +01001492 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001493 for member_ns in nstd["netslice-subnet"]:
1494 nsd_id = member_ns["nsd-ref"]
1495 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1496 member_ns["nsd-ref"], member_ns["id"])
1497 if nsd_id not in needed_nsds:
1498 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001499 _filter["id"] = nsd_id
1500 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1501 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001502 nsd.pop("_admin")
1503 needed_nsds[nsd_id] = nsd
1504 else:
1505 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001506 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1507 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001508
Felipe Vicensb57758d2018-10-16 16:00:20 +02001509 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1510 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001511
Felipe Vicens07f31722018-10-29 15:16:44 +01001512 # creates Network Services records (NSRs)
1513 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001514 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001515 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001516 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001517 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001518 # Check if the netslice-subnet is shared and if it is share if the nss exists
1519 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001520 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001521 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001522 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1523 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens08ddb142019-08-09 15:52:40 +02001524 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001525 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001526 if nsi and service.get("is-shared-nss"):
1527 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1528 for nsrs_detailed_item in nsrs_detailed_list:
1529 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02001530 if nsrs_detailed_item["nss-id"] == service["id"]:
1531 _id_nsr = nsrs_detailed_item["nsrId"]
1532 break
Felipe Vicens09e65422019-01-22 15:06:46 +01001533 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1534 if netslice_subnet["nss-id"] == service["id"]:
1535 indata_ns = netslice_subnet
1536 break
1537 else:
1538 indata_ns = {}
1539 if service.get("instantiation-parameters"):
1540 indata_ns = deepcopy(service["instantiation-parameters"])
1541 # del service["instantiation-parameters"]
1542
1543 indata_ns["nsdId"] = service["_id"]
1544 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1545 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1546 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001547 if slice_request.get("ssh_keys"):
1548 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001549
Felipe Vicens09e65422019-01-22 15:06:46 +01001550 if ns_params:
1551 for ns_param in ns_params:
1552 if ns_param.get("id") == service["id"]:
1553 copy_ns_param = deepcopy(ns_param)
1554 del copy_ns_param["id"]
1555 indata_ns.update(copy_ns_param)
1556 break
1557
1558 # Creates Nsr objects
tiernobdebce92019-07-01 15:36:49 +00001559 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001560 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
Felipe Vicens08ddb142019-08-09 15:52:40 +02001561 "nss-id": service["id"], "nslcmop_instantiate": None}
Felipe Vicens09e65422019-01-22 15:06:46 +01001562 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001563 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001564 nsi_netslice_subnet.append(indata_ns)
1565 nsr_ref = {"nsr-ref": _id_nsr}
1566 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001567
1568 # Adding the nsrs list to the nsi
1569 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001570 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001571 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1572
Felipe Vicens07f31722018-10-29 15:16:44 +01001573 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001574 self.db.create("nsis", nsi_descriptor)
1575 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00001576 return nsi_id, None
1577 except Exception as e: # TODO remove try Except, it is captured at nbi.py
Felipe Vicensb57758d2018-10-16 16:00:20 +02001578 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1579 raise EngineException("Error {}: {}".format(step, e))
1580 except ValidationError as e:
1581 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1582
tierno65ca36d2019-02-12 19:27:52 +01001583 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001584 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001585
1586
1587class NsiLcmOpTopic(BaseTopic):
1588 topic = "nsilcmops"
1589 topic_msg = "nsi"
1590 operation_schema = { # mapping between operation and jsonschema to validate
1591 "instantiate": nsi_instantiate,
1592 "terminate": None
1593 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001594
delacruzramo32bab472019-09-13 12:24:22 +02001595 def __init__(self, db, fs, msg, auth):
1596 BaseTopic.__init__(self, db, fs, msg, auth)
1597 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01001598
1599 def _check_nsi_operation(self, session, nsir, operation, indata):
1600 """
1601 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001602 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001603 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1604 :param indata: descriptor with the parameters of the operation
1605 :return: None
1606 """
1607 nsds = {}
1608 nstd = nsir["network-slice-template"]
1609
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001610 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001611 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001612 for netslice_subnet in nstd["netslice-subnet"]:
1613 if nstId == netslice_subnet["id"]:
1614 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001615 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02001616 _filter = self._get_project_filter(session)
1617 _filter["id"] = nsd_id
1618 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01001619 return nsds[nsd_id]
1620 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001621 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1622 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001623 if operation == "instantiate":
1624 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001625 for in_nst in get_iterable(indata.get("netslice-subnet")):
1626 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001627
1628 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1629 now = time()
1630 _id = str(uuid4())
1631 nsilcmop = {
1632 "id": _id,
1633 "_id": _id,
1634 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1635 "statusEnteredTime": now,
1636 "netsliceInstanceId": netsliceInstanceId,
1637 "lcmOperationType": operation,
1638 "startTime": now,
1639 "isAutomaticInvocation": False,
1640 "operationParams": params,
1641 "isCancelPending": False,
1642 "links": {
1643 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001644 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001645 }
1646 }
1647 return nsilcmop
1648
Felipe Vicens09e65422019-01-22 15:06:46 +01001649 def add_shared_nsr_2vld(self, nsir, nsr_item):
1650 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1651 if nst_sb_item.get("is-shared-nss"):
1652 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1653 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1654 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1655 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1656 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1657 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1658 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1659 break
1660 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1661 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1662
tierno65ca36d2019-02-12 19:27:52 +01001663 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001664 """
1665 Performs a new operation over a ns
1666 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001667 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001668 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001669 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001670 operation: it can be: instantiate, terminate, action, TODO: update, heal
1671 :param kwargs: used to override the indata descriptor
1672 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001673 :return: id of the nslcmops
1674 """
1675 try:
1676 # Override descriptor with query string kwargs
1677 self._update_input_with_kwargs(indata, kwargs)
1678 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001679 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001680 validate_input(indata, self.operation_schema[operation])
1681
Felipe Vicens126af572019-06-05 19:13:04 +02001682 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001683 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001684 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001685 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00001686 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00001687 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001688
1689 # initial checking
1690 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1691 if operation == "terminate" and indata.get("autoremove"):
1692 # NSIR must be deleted
tierno586ae812019-10-17 13:56:53 +00001693 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 +01001694 if operation != "instantiate":
1695 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001696 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001697 else:
tierno65ca36d2019-02-12 19:27:52 +01001698 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001699 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001700 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001701
1702 # Creating all the NS_operation (nslcmop)
1703 # Get service list from db
1704 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1705 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001706 # nslcmops_item = None
1707 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00001708 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001709 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001710 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00001711 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
tiernob4844ab2019-05-23 08:42:12 +00001712 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001713 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001714 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001715 if operation == "terminate":
1716 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1717 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
tierno40f742b2020-06-23 15:25:26 +00001718 if nsi: # other nsi is using this nsr and it needs this nsr instantiated
1719 continue # do not create nsilcmop
1720 else: # instantiate
1721 # looks the first nsi fulfilling the conditions but not being the current NSIR
1722 if nsi:
1723 nsi_nsr_item = next(n for n in nsi["_admin"]["nsrs-detailed-list"] if
1724 n["nsrId"] == nsr_id and n["shared"] and
1725 n["nslcmop_instantiate"])
1726 self.add_shared_nsr_2vld(nsir, nsr_item)
1727 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1728 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1729 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1730 # continue to not create nslcmop since nsrs is shared and nsrs was created
1731 continue
1732 else:
1733 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01001734
tierno40f742b2020-06-23 15:25:26 +00001735 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01001736 try:
tierno0b8752f2020-05-12 09:42:02 +00001737 indata_ns = {
1738 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00001739 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00001740 # Including netslice_id in the ns instantiate Operation
1741 "netsliceInstanceId": netsliceInstanceId,
1742 }
1743 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00001744 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00001745 indata_ns.update(service["instantiate_params"])
1746
tierno99d4b172019-07-02 09:28:40 +00001747 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001748 # message via kafka bus
tierno40f742b2020-06-23 15:25:26 +00001749 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, None, headers,
tiernobdebce92019-07-01 15:36:49 +00001750 slice_object=True)
Felipe Vicens09e65422019-01-22 15:06:46 +01001751 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00001752 if operation == "instantiate":
1753 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1754 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01001755 except (DbException, EngineException) as e:
1756 if e.http_code == HTTPStatus.NOT_FOUND:
tierno40f742b2020-06-23 15:25:26 +00001757 self.logger.info(logging_prefix + "skipping NS={} because not found".format(nsr_id))
Felipe Vicens09e65422019-01-22 15:06:46 +01001758 pass
1759 else:
1760 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001761
1762 # Creates nsilcmop
1763 indata["nslcmops_ids"] = nslcmops
1764 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001765
Felipe Vicens126af572019-06-05 19:13:04 +02001766 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001767 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001768 _id = self.db.create("nsilcmops", nsilcmop_desc)
1769 rollback.append({"topic": "nsilcmops", "_id": _id})
1770 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001771 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01001772 except ValidationError as e:
1773 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001774
tiernobee3bad2019-12-05 12:26:01 +00001775 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001776 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1777
tierno65ca36d2019-02-12 19:27:52 +01001778 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001779 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)