blob: 4e516863e9767774cfff9718d15c583857c076d2 [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
tiernob4844ab2019-05-23 08:42:12 +000024# from descriptor_topics import DescriptorTopic
tiernobee085c2018-12-12 17:03:04 +000025from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010026from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000027from osm_common.msgbase import MsgException
28from osm_common.fsbase import FsException
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:
189 initial_primitives = deep_get(descriptor, ("vnf-configuration", "initial-config-primitive"))
190 else:
191 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
tiernobee085c2018-12-12 17:03:04 +0000192
tierno714954e2019-11-29 13:43:26 +0000193 for initial_primitive in get_iterable(initial_primitives):
194 for param in get_iterable(initial_primitive.get("parameter")):
195 if param["value"].startswith("<") and param["value"].endswith(">"):
196 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
197 continue
198 if not additional_params or param["value"][1:-1] not in additional_params:
199 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
200 "initial-config-primitive[name={}] not supplied".
201 format(param["value"], descriptor["id"],
202 initial_primitive["name"]))
203
tierno54db2e42020-04-06 15:29:42 +0000204 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000205
tierno65ca36d2019-02-12 19:27:52 +0100206 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200207 """
208 Creates a new nsr into database. It also creates needed vnfrs
209 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100210 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200211 :param indata: params to be used for the nsr
212 :param kwargs: used to override the indata descriptor
213 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000214 :return: the _id of nsr descriptor created at database. Or an exception of type
215 EngineException, ValidationError, DbException, FsException, MsgException.
216 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200217 """
218
219 try:
delacruzramo32bab472019-09-13 12:24:22 +0200220 step = "checking quotas"
221 self.check_quota(session)
222
tierno99d4b172019-07-02 09:28:40 +0000223 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200224 ns_request = self._remove_envelop(indata)
225 # Override descriptor with query string kwargs
226 self._update_input_with_kwargs(ns_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100227 self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200228
tierno54db2e42020-04-06 15:29:42 +0000229 # look for nsd
tiernob24258a2018-10-04 18:39:49 +0200230 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
tiernob4844ab2019-05-23 08:42:12 +0000231 _filter = self._get_project_filter(session)
232 _filter["_id"] = ns_request["nsdId"]
tiernob24258a2018-10-04 18:39:49 +0200233 nsd = self.db.get_one("nsds", _filter)
tiernob4844ab2019-05-23 08:42:12 +0000234 del _filter["_id"]
tiernob24258a2018-10-04 18:39:49 +0200235
Frank Bryden3c64ab62020-07-21 14:25:32 +0000236 # check NSD is not disabled
237 step = "checking nsdOperationalState"
238 if nsd["_admin"]["operationalState"] == "DISABLED":
239 raise EngineException("nsd with id '{}' is DISABLED, and thus cannot be used to create "
240 "a network service".format(ns_request["nsdId"]), http_code=HTTPStatus.CONFLICT)
241
tiernob24258a2018-10-04 18:39:49 +0200242 nsr_id = str(uuid4())
tiernobee085c2018-12-12 17:03:04 +0000243
tiernob24258a2018-10-04 18:39:49 +0200244 now = time()
245 step = "filling nsr from input data"
tiernoe19707b2020-04-21 13:08:04 +0000246 additional_params, _ = self._format_additional_params(ns_request, descriptor=nsd)
tierno54db2e42020-04-06 15:29:42 +0000247
248 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
249 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
250 if ns_request and ns_request.get("k8s-namespace"):
251 ns_k8s_namespace = ns_request["k8s-namespace"]
252 if additional_params and additional_params.get("k8s-namespace"):
253 ns_k8s_namespace = additional_params["k8s-namespace"]
254
tiernob24258a2018-10-04 18:39:49 +0200255 nsr_descriptor = {
256 "name": ns_request["nsName"],
257 "name-ref": ns_request["nsName"],
258 "short-name": ns_request["nsName"],
259 "admin-status": "ENABLED",
tiernoecf94bd2020-01-09 12:40:45 +0000260 "nsState": "NOT_INSTANTIATED",
261 "currentOperation": "IDLE",
262 "currentOperationID": None,
263 "errorDescription": None,
264 "errorDetail": None,
265 "deploymentStatus": None,
266 "configurationStatus": None,
267 "vcaStatus": None,
preethika.pee12aa02020-07-10 13:14:22 +0000268 "nsd": {k: v for k, v in nsd.items() if k in ("vld", "_id", "id", "constituent-vnfd", "name",
269 "ns-configuration")},
tiernob24258a2018-10-04 18:39:49 +0200270 "datacenter": ns_request["vimAccountId"],
271 "resource-orchestrator": "osmopenmano",
272 "description": ns_request.get("nsDescription", ""),
273 "constituent-vnfr-ref": [],
274
275 "operational-status": "init", # typedef ns-operational-
276 "config-status": "init", # typedef config-states
277 "detailed-status": "scheduled",
278
279 "orchestration-progress": {},
280 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
281
tierno65ca36d2019-02-12 19:27:52 +0100282 "create-time": now,
tiernob24258a2018-10-04 18:39:49 +0200283 "nsd-name-ref": nsd["name"],
284 "operational-events": [], # "id", "timestamp", "description", "event",
285 "nsd-ref": nsd["id"],
tiernof0637052019-03-07 16:26:47 +0000286 "nsd-id": nsd["_id"],
tiernob4844ab2019-05-23 08:42:12 +0000287 "vnfd-id": [],
tiernobee085c2018-12-12 17:03:04 +0000288 "instantiate_params": self._format_ns_request(ns_request),
tierno54db2e42020-04-06 15:29:42 +0000289 "additionalParamsForNs": additional_params,
tiernob24258a2018-10-04 18:39:49 +0200290 "ns-instance-config-ref": nsr_id,
291 "id": nsr_id,
292 "_id": nsr_id,
293 # "input-parameter": xpath, value,
tierno99d4b172019-07-02 09:28:40 +0000294 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
tiernof0441ea2020-05-26 15:39:18 +0000295 "vld": nsd.get("vld") or [],
296 "flavor": [],
297 "image": [],
tiernob24258a2018-10-04 18:39:49 +0200298 }
299 ns_request["nsr_id"] = nsr_id
tierno59338b12020-06-25 13:26:28 +0000300 if ns_request and ns_request.get("config-units"):
301 nsr_descriptor["config-units"] = ns_request["config-units"]
302
tierno36ec8602018-11-02 17:27:11 +0100303 # Create vld
304 if nsd.get("vld"):
tierno340df482020-04-03 10:09:06 +0000305 nsr_descriptor["vld"] = nsd["vld"]
tiernob24258a2018-10-04 18:39:49 +0200306
307 # Create VNFR
308 needed_vnfds = {}
gcalvino4f269dd2018-11-06 13:18:31 +0100309 for member_vnf in nsd.get("constituent-vnfd", ()):
tiernob24258a2018-10-04 18:39:49 +0200310 vnfd_id = member_vnf["vnfd-id-ref"]
311 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
312 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
313 if vnfd_id not in needed_vnfds:
314 # Obtain vnfd
tiernob4844ab2019-05-23 08:42:12 +0000315 _filter["id"] = vnfd_id
316 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
317 del _filter["id"]
tiernob24258a2018-10-04 18:39:49 +0200318 vnfd.pop("_admin")
319 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000320 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200321 else:
322 vnfd = needed_vnfds[vnfd_id]
323 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
324 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
325 vnfr_id = str(uuid4())
tiernoe19707b2020-04-21 13:08:04 +0000326 additional_params, vnf_params = self._format_additional_params(ns_request,
327 member_vnf["member-vnf-index"],
328 descriptor=vnfd)
tiernob24258a2018-10-04 18:39:49 +0200329 vnfr_descriptor = {
330 "id": vnfr_id,
331 "_id": vnfr_id,
332 "nsr-id-ref": nsr_id,
333 "member-vnf-index-ref": member_vnf["member-vnf-index"],
tierno54db2e42020-04-06 15:29:42 +0000334 "additionalParamsForVnf": additional_params,
tiernob24258a2018-10-04 18:39:49 +0200335 "created-time": now,
336 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
337 "vnfd-ref": vnfd_id,
338 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
339 "vim-account-id": None,
340 "vdur": [],
341 "connection-point": [],
342 "ip-address": None, # mgmt-interface filled by LCM
343 }
tierno59338b12020-06-25 13:26:28 +0000344 vnf_k8s_namespace = ns_k8s_namespace
345 if vnf_params:
346 if vnf_params.get("k8s-namespace"):
347 vnf_k8s_namespace = vnf_params["k8s-namespace"]
348 if vnf_params.get("config-units"):
349 vnfr_descriptor["config-units"] = vnf_params["config-units"]
tierno36ec8602018-11-02 17:27:11 +0100350
351 # Create vld
352 if vnfd.get("internal-vld"):
353 vnfr_descriptor["vld"] = []
354 for vnfd_vld in vnfd.get("internal-vld"):
355 vnfr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100356 {key: vnfd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in
357 vnfd_vld})
tierno36ec8602018-11-02 17:27:11 +0100358
359 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
tiernob24258a2018-10-04 18:39:49 +0200360 for cp in vnfd.get("connection-point", ()):
361 vnf_cp = {
362 "name": cp["name"],
363 "connection-point-id": cp.get("id"),
364 "id": cp.get("id"),
365 # "ip-address", "mac-address" # filled by LCM
366 # vim-id # TODO it would be nice having a vim port id
367 }
368 vnfr_descriptor["connection-point"].append(vnf_cp)
tierno9cb7d672019-10-30 12:13:48 +0000369
tiernoc67b0e92019-11-05 12:45:29 +0000370 # Create k8s-cluster information
371 if vnfd.get("k8s-cluster"):
372 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
373 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
374 if net.get("external-connection-point-ref"):
375 for nsd_vld in get_iterable(nsd.get("vld")):
376 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
377 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
378 net["external-connection-point-ref"] and \
379 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
380 net["ns-vld-id"] = nsd_vld["id"]
381 break
382 else:
383 continue
384 break
385 elif net.get("internal-connection-point-ref"):
386 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
387 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
388 if vnfd_ivld_icp.get("id-ref") == net["internal-connection-point-ref"]:
389 net["vnf-vld-id"] = vnfd_ivld["id"]
390 break
391 else:
392 continue
393 break
tierno9cb7d672019-10-30 12:13:48 +0000394 # update kdus
395 for kdu in get_iterable(vnfd.get("kdu")):
tiernoe19707b2020-04-21 13:08:04 +0000396 additional_params, kdu_params = self._format_additional_params(ns_request,
397 member_vnf["member-vnf-index"],
398 kdu_name=kdu["name"],
399 descriptor=vnfd)
tierno54db2e42020-04-06 15:29:42 +0000400 kdu_k8s_namespace = vnf_k8s_namespace
tiernobce98f02020-04-17 11:27:47 +0000401 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
tierno54db2e42020-04-06 15:29:42 +0000402 if kdu_params and kdu_params.get("k8s-namespace"):
403 kdu_k8s_namespace = kdu_params["k8s-namespace"]
404
405 kdur = {
406 "additionalParams": additional_params,
407 "k8s-namespace": kdu_k8s_namespace,
408 "kdu-name": kdu["name"],
409 # TODO "name": "" Name of the VDU in the VIM
410 "ip-address": None, # mgmt-interface filled by LCM
411 "k8s-cluster": {},
412 }
tierno59338b12020-06-25 13:26:28 +0000413 if kdu_params and kdu_params.get("config-units"):
414 kdur["config-units"] = kdu_params["config-units"]
tierno54db2e42020-04-06 15:29:42 +0000415 for k8s_type in ("helm-chart", "juju-bundle"):
416 if kdu.get(k8s_type):
417 kdur[k8s_type] = kdu_model or kdu[k8s_type]
tierno9cb7d672019-10-30 12:13:48 +0000418 if not vnfr_descriptor.get("kdur"):
419 vnfr_descriptor["kdur"] = []
420 vnfr_descriptor["kdur"].append(kdur)
421
gcalvinoe45aded2018-11-13 17:17:28 +0100422 for vdu in vnfd.get("vdu", ()):
tierno59338b12020-06-25 13:26:28 +0000423 additional_params, vdu_params = self._format_additional_params(
424 ns_request, member_vnf["member-vnf-index"], vdu_id=vdu["id"], descriptor=vnfd)
tiernob24258a2018-10-04 18:39:49 +0200425 vdur = {
tiernob24258a2018-10-04 18:39:49 +0200426 "vdu-id-ref": vdu["id"],
427 # TODO "name": "" Name of the VDU in the VIM
428 "ip-address": None, # mgmt-interface filled by LCM
429 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
430 "internal-connection-point": [],
431 "interfaces": [],
tiernof0441ea2020-05-26 15:39:18 +0000432 "additionalParams": additional_params,
433 "vdu-name": vdu["name"],
tiernob24258a2018-10-04 18:39:49 +0200434 }
tierno59338b12020-06-25 13:26:28 +0000435 if vdu_params and vdu_params.get("config-units"):
436 vdur["config-units"] = vdu_params["config-units"]
437 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
438 vdur["boot-data-drive"] = vdu["supplemental-boot-data"]["boot-data-drive"]
tiernocc103432018-10-19 14:10:35 +0200439 if vdu.get("pdu-type"):
440 vdur["pdu-type"] = vdu["pdu-type"]
tierno1d81bad2020-07-14 15:39:07 +0000441 vdur["name"] = vdu["pdu-type"]
tiernof0441ea2020-05-26 15:39:18 +0000442
443 # flavor
444 flavor_data = copy(vdu.get("vm-flavor", {}))
445 flavor_data["guest-epa"] = vdu.get("guest-epa")
446 f = next((f for f in nsr_descriptor["flavor"] if
447 all(f.get(k) == flavor_data[k] for k in flavor_data)), None)
448 if not f:
449 flavor_data["vim_info"] = []
450 flavor_data["name"] = vdu["id"][:56] + "-flv"
451 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
452 nsr_descriptor["flavor"].append(flavor_data)
453 f = flavor_data
454 vdur["ns-flavor-id"] = f["id"]
455
456 # image
457 if vdu.get("image"):
458 image_data = {"image": vdu["image"], "image_checksum": vdu.get("image_checksum")}
459 img = next((f for f in nsr_descriptor["image"] if
460 all(f.get(k) == image_data[k] for k in image_data)), None)
461 if not img:
462 image_data["vim_info"] = []
463 image_data["id"] = str(len(nsr_descriptor["image"]))
464 nsr_descriptor["image"].append(image_data)
465 img = image_data
466 vdur["ns-image-id"] = img["id"]
467
tiernob24258a2018-10-04 18:39:49 +0200468 # TODO volumes: name, volume-id
469 for icp in vdu.get("internal-connection-point", ()):
470 vdu_icp = {
471 "id": icp["id"],
472 "connection-point-id": icp["id"],
473 "name": icp.get("name"),
tiernob24258a2018-10-04 18:39:49 +0200474 }
475 vdur["internal-connection-point"].append(vdu_icp)
476 for iface in vdu.get("interface", ()):
477 vdu_iface = {
tiernocddb07d2020-10-06 08:28:00 +0000478 x: iface[x] for x in ("name", "ip-address", "mac-address", "internal-connection-point-ref",
479 "external-connection-point-ref") if iface.get(x) is not None}
tierno36ec8602018-11-02 17:27:11 +0100480 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
481 vdu_iface["mgmt-vnf"] = True
tiernocc103432018-10-19 14:10:35 +0200482 if iface.get("mgmt-interface"):
tierno36ec8602018-11-02 17:27:11 +0100483 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
tiernof0441ea2020-05-26 15:39:18 +0000484 if iface.get("virtual-interface"):
485 if iface["virtual-interface"].get("type"):
486 iface["type"] = iface["virtual-interface"]["type"]
487 if iface["virtual-interface"].get("vpci"):
488 iface["vpci"] = iface["virtual-interface"]["vpci"]
489 if iface["virtual-interface"].get("bandwidth"):
490 iface["bandwidth"] = iface["virtual-interface"]["bandwidth"]
tierno36ec8602018-11-02 17:27:11 +0100491
492 # look for network where this interface is connected
493 if iface.get("external-connection-point-ref"):
494 for nsd_vld in get_iterable(nsd.get("vld")):
495 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
496 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
497 iface["external-connection-point-ref"] and \
498 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
499 vdu_iface["ns-vld-id"] = nsd_vld["id"]
500 break
501 else:
502 continue
503 break
504 elif iface.get("internal-connection-point-ref"):
505 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
506 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
507 if vnfd_ivld_icp.get("id-ref") == iface["internal-connection-point-ref"]:
508 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
tiernocddb07d2020-10-06 08:28:00 +0000509 if vnfd_ivld_icp.get("ip-address"):
510 vdu_iface["ip-address"] = vnfd_ivld_icp["ip-address"]
tierno36ec8602018-11-02 17:27:11 +0100511 break
512 else:
513 continue
514 break
tiernof0441ea2020-05-26 15:39:18 +0000515 if iface.get("position") is not None:
516 vdur["interfaces"].insert(iface["position"], vdu_iface)
517 else:
518 vdur["interfaces"].append(vdu_iface)
tiernocc103432018-10-19 14:10:35 +0200519 count = vdu.get("count", 1)
520 if count is None:
521 count = 1
522 count = int(count) # TODO remove when descriptor serialized with payngbind
523 for index in range(0, count):
524 if index:
525 vdur = deepcopy(vdur)
tiernocddb07d2020-10-06 08:28:00 +0000526 for iface in vdur["interfaces"]:
527 if iface.get("ip-address"):
528 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
529 if iface.get("mac-address"):
530 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
531
tiernocc103432018-10-19 14:10:35 +0200532 vdur["_id"] = str(uuid4())
533 vdur["count-index"] = index
tiernof0441ea2020-05-26 15:39:18 +0000534 vdur["id"] = "{}-{}".format(vdur["vdu-id-ref"], index)
tiernocc103432018-10-19 14:10:35 +0200535 vnfr_descriptor["vdur"].append(vdur)
tiernob24258a2018-10-04 18:39:49 +0200536
537 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
538 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
539
540 # add at database
tiernobdebce92019-07-01 15:36:49 +0000541 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200542 self.db.create("vnfrs", vnfr_descriptor)
543 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
544 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
545
546 step = "creating nsr at database"
tierno65ca36d2019-02-12 19:27:52 +0100547 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200548 self.db.create("nsrs", nsr_descriptor)
549 rollback.append({"topic": "nsrs", "_id": nsr_id})
tiernobee085c2018-12-12 17:03:04 +0000550
551 step = "creating nsr temporal folder"
552 self.fs.mkdir(nsr_id)
553
tiernobdebce92019-07-01 15:36:49 +0000554 return nsr_id, None
tierno1bfe4e22019-09-02 16:03:25 +0000555 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
Frank Bryden3c64ab62020-07-21 14:25:32 +0000556 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200557
tierno65ca36d2019-02-12 19:27:52 +0100558 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200559 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
560
561
562class VnfrTopic(BaseTopic):
563 topic = "vnfrs"
564 topic_msg = None
565
delacruzramo32bab472019-09-13 12:24:22 +0200566 def __init__(self, db, fs, msg, auth):
567 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200568
tiernobee3bad2019-12-05 12:26:01 +0000569 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200570 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
571
tierno65ca36d2019-02-12 19:27:52 +0100572 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200573 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
574
tierno65ca36d2019-02-12 19:27:52 +0100575 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200576 # Not used because vnfrs are created and deleted by NsrTopic class directly
577 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
578
579
580class NsLcmOpTopic(BaseTopic):
581 topic = "nslcmops"
582 topic_msg = "ns"
583 operation_schema = { # mapping between operation and jsonschema to validate
584 "instantiate": ns_instantiate,
585 "action": ns_action,
586 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +0000587 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +0200588 }
589
delacruzramo32bab472019-09-13 12:24:22 +0200590 def __init__(self, db, fs, msg, auth):
591 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200592
tiernob24258a2018-10-04 18:39:49 +0200593 def _check_ns_operation(self, session, nsr, operation, indata):
594 """
595 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100596 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200597 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
598 :param indata: descriptor with the parameters of the operation
599 :return: None
600 """
tierno982da4e2019-09-03 11:51:55 +0000601 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +0200602 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000603 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200604 nsd = nsr["nsd"]
605
606 def check_valid_vnf_member_index(member_vnf_index):
tierno982da4e2019-09-03 11:51:55 +0000607 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
608 if vnf_member_index_to_vnfd.get(member_vnf_index):
609 return vnf_member_index_to_vnfd[member_vnf_index]
610 vnfr = self.db.get_one("vnfrs",
611 {"nsr-id-ref": nsr["_id"], "member-vnf-index-ref": member_vnf_index},
612 fail_on_empty=False)
613 if not vnfr:
tiernob24258a2018-10-04 18:39:49 +0200614 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
615 "nsd:constituent-vnfd".format(member_vnf_index))
tierno982da4e2019-09-03 11:51:55 +0000616 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
617 if not vnfd:
618 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
619 format(vnfr["vnfd-id"]))
620 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
621 return vnfd
tiernob24258a2018-10-04 18:39:49 +0200622
tierno260dd6f2019-09-02 10:48:56 +0000623 def check_valid_vdu(vnfd, vdu_id):
624 for vdud in get_iterable(vnfd.get("vdu")):
625 if vdud["id"] == vdu_id:
626 return vdud
627 else:
628 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
629
tierno9cb7d672019-10-30 12:13:48 +0000630 def check_valid_kdu(vnfd, kdu_name):
631 for kdud in get_iterable(vnfd.get("kdu")):
632 if kdud["name"] == kdu_name:
633 return kdud
634 else:
635 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
636
gcalvino5e72d152018-10-23 11:46:57 +0200637 def _check_vnf_instantiation_params(in_vnfd, vnfd):
638
tierno40fbcad2018-10-26 10:58:15 +0200639 for in_vdu in get_iterable(in_vnfd.get("vdu")):
640 for vdu in get_iterable(vnfd.get("vdu")):
641 if in_vdu["id"] == vdu["id"]:
642 for volume in get_iterable(in_vdu.get("volume")):
643 for volumed in get_iterable(vdu.get("volumes")):
644 if volumed["name"] == volume["name"]:
645 break
646 else:
647 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
648 "volume:name='{}' is not present at vnfd:vdu:volumes list".
649 format(in_vnf["member-vnf-index"], in_vdu["id"],
650 volume["name"]))
651 for in_iface in get_iterable(in_vdu["interface"]):
652 for iface in get_iterable(vdu.get("interface")):
653 if in_iface["name"] == iface["name"]:
654 break
655 else:
656 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
657 "interface[name='{}'] is not present at vnfd:vdu:interface"
658 .format(in_vnf["member-vnf-index"], in_vdu["id"],
659 in_iface["name"]))
660 break
gcalvino5e72d152018-10-23 11:46:57 +0200661 else:
tierno40fbcad2018-10-26 10:58:15 +0200662 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
663 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200664
665 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
666 for ivld in get_iterable(vnfd.get("internal-vld")):
tierno75d5a4e2020-05-21 15:09:22 +0000667 if in_ivld["name"] in (ivld["id"], ivld.get("name")):
tierno1bfe4e22019-09-02 16:03:25 +0000668 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
gcalvino5e72d152018-10-23 11:46:57 +0200669 for icp in ivld["internal-connection-point"]:
670 if in_icp["id-ref"] == icp["id-ref"]:
671 break
672 else:
tierno40fbcad2018-10-26 10:58:15 +0200673 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
674 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
675 "vnfd:internal-vld:name/id:internal-connection-point"
676 .format(in_vnf["member-vnf-index"], in_ivld["name"],
tierno670b0c62020-05-12 13:01:19 +0000677 in_icp["id-ref"]))
gcalvino5e72d152018-10-23 11:46:57 +0200678 break
679 else:
680 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
681 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
682 in_ivld["name"], vnfd["id"]))
683
tiernob24258a2018-10-04 18:39:49 +0200684 def check_valid_vim_account(vim_account):
685 if vim_account in vim_accounts:
686 return
687 try:
tierno65ca36d2019-02-12 19:27:52 +0100688 db_filter = self._get_project_filter(session)
tiernocc103432018-10-19 14:10:35 +0200689 db_filter["_id"] = vim_account
690 self.db.get_one("vim_accounts", db_filter)
tiernob24258a2018-10-04 18:39:49 +0200691 except Exception:
tiernocc103432018-10-19 14:10:35 +0200692 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
tiernob24258a2018-10-04 18:39:49 +0200693 vim_accounts.append(vim_account)
694
tierno4f9d4ae2019-03-20 17:24:11 +0000695 def check_valid_wim_account(wim_account):
696 if not isinstance(wim_account, str):
697 return
698 elif wim_account in wim_accounts:
699 return
700 try:
701 db_filter = self._get_project_filter(session, write=False, show_all=True)
702 db_filter["_id"] = wim_account
703 self.db.get_one("wim_accounts", db_filter)
704 except Exception:
705 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
706 wim_accounts.append(wim_account)
707
tiernob24258a2018-10-04 18:39:49 +0200708 if operation == "action":
709 # check vnf_member_index
710 if indata.get("vnf_member_index"):
711 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
tierno1ac7f462019-06-03 17:22:12 +0000712 if indata.get("member_vnf_index"):
713 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
tierno260dd6f2019-09-02 10:48:56 +0000714 if indata.get("vdu_id"):
715 vdud = check_valid_vdu(vnfd, indata["vdu_id"])
716 descriptor_configuration = vdud.get("vdu-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000717 elif indata.get("kdu_name"):
tiernoc67b0e92019-11-05 12:45:29 +0000718 kdud = check_valid_kdu(vnfd, indata["kdu_name"])
tierno9cb7d672019-10-30 12:13:48 +0000719 descriptor_configuration = kdud.get("kdu-configuration", {}).get("config-primitive")
tierno260dd6f2019-09-02 10:48:56 +0000720 else:
721 descriptor_configuration = vnfd.get("vnf-configuration", {}).get("config-primitive")
tierno1ac7f462019-06-03 17:22:12 +0000722 else: # use a NSD
723 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000724
725 # For k8s allows default primitives without validating the parameters
delacruzramo6ddff2e2019-11-28 11:24:09 +0100726 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
tierno9cb7d672019-10-30 12:13:48 +0000727 # TODO should be checked that rollback only can contains revsision_numbe????
delacruzramo6ddff2e2019-11-28 11:24:09 +0100728 if not indata.get("member_vnf_index"):
729 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
730 .format(indata["primitive"]))
tierno9cb7d672019-10-30 12:13:48 +0000731 return
732 # if not, check primitive
tierno1ac7f462019-06-03 17:22:12 +0000733 for config_primitive in get_iterable(descriptor_configuration):
tiernob24258a2018-10-04 18:39:49 +0200734 if indata["primitive"] == config_primitive["name"]:
735 # check needed primitive_params are provided
736 if indata.get("primitive_params"):
737 in_primitive_params_copy = copy(indata["primitive_params"])
738 else:
739 in_primitive_params_copy = {}
740 for paramd in get_iterable(config_primitive.get("parameter")):
741 if paramd["name"] in in_primitive_params_copy:
742 del in_primitive_params_copy[paramd["name"]]
743 elif not paramd.get("default-value"):
744 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
745 paramd["name"], indata["primitive"]))
746 # check no extra primitive params are provided
747 if in_primitive_params_copy:
tierno1ac7f462019-06-03 17:22:12 +0000748 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
tiernob24258a2018-10-04 18:39:49 +0200749 list(in_primitive_params_copy.keys()), indata["primitive"]))
750 break
751 else:
tierno1ac7f462019-06-03 17:22:12 +0000752 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
tiernob24258a2018-10-04 18:39:49 +0200753 if operation == "scale":
754 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
755 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
756 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
757 break
758 else:
759 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
760 "present at vnfd:scaling-group-descriptor".format(
761 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
762 if operation == "instantiate":
763 # check vim_account
764 check_valid_vim_account(indata["vimAccountId"])
tierno4f9d4ae2019-03-20 17:24:11 +0000765 check_valid_wim_account(indata.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200766 for in_vnf in get_iterable(indata.get("vnf")):
767 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
gcalvino5e72d152018-10-23 11:46:57 +0200768 _check_vnf_instantiation_params(in_vnf, vnfd)
tiernob24258a2018-10-04 18:39:49 +0200769 if in_vnf.get("vimAccountId"):
770 check_valid_vim_account(in_vnf["vimAccountId"])
tiernob24258a2018-10-04 18:39:49 +0200771
tiernob24258a2018-10-04 18:39:49 +0200772 for in_vld in get_iterable(indata.get("vld")):
tierno4f9d4ae2019-03-20 17:24:11 +0000773 check_valid_wim_account(in_vld.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200774 for vldd in get_iterable(nsd.get("vld")):
775 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
776 break
777 else:
778 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
779 in_vld["name"]))
780
tierno36ec8602018-11-02 17:27:11 +0100781 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200782 """
tierno36ec8602018-11-02 17:27:11 +0100783 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
784 (ip_address, ...) information.
785 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +0100786 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100787 :param rollback: list with the database modifications to rollback if needed
788 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
789 :param vim_account: vim_account where this vnfr should be deployed
790 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
791 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
792 of the changed vnfr is needed
793
794 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
795 "vim-network-name": used at VIM
796 "name": interface name
797 "vnf-vld-id": internal VNFD vld where this interface is connected, or
798 "ns-vld-id": NSD vld where this interface is connected.
799 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 +0200800 """
tierno36ec8602018-11-02 17:27:11 +0100801
802 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +0200803 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
804 if not vdur.get("pdu-type"):
805 continue
806 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +0100807 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +0100808 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +0200809 pdu_filter["type"] = pdu_type
810 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +0100811 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +0200812 # TODO feature 1417: "shared": True,
813
814 available_pdus = self.db.get_list("pdus", pdu_filter)
815 for pdu in available_pdus:
816 # step 1 check if this pdu contains needed interfaces:
817 match_interfaces = True
818 for vdur_interface in vdur["interfaces"]:
819 for pdu_interface in pdu["interfaces"]:
820 if pdu_interface["name"] == vdur_interface["name"]:
821 # TODO feature 1417: match per mgmt type
822 break
823 else: # no interface found for name
824 match_interfaces = False
825 break
826 if match_interfaces:
827 break
828 else:
829 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +0100830 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
831 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +0200832
833 # step 2. Update pdu
834 rollback_pdu = {
835 "_admin.usageState": pdu["_admin"]["usageState"],
836 "_admin.usage.vnfr_id": None,
837 "_admin.usage.nsr_id": None,
838 "_admin.usage.vdur": None,
839 }
840 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +0100841 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +0000842 "_admin.usage": {"vnfr_id": vnfr["_id"],
843 "nsr_id": vnfr["nsr-id-ref"],
844 "vdur": vdur["vdu-id-ref"]}
845 })
tiernocc103432018-10-19 14:10:35 +0200846 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
847
848 # step 3. Fill vnfr info by filling vdur
849 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +0100850 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +0200851 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
852 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
853 for pdu_interface in pdu["interfaces"]:
854 if pdu_interface["name"] == vdur_interface["name"]:
855 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
856 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +0100857 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
858 vnfr_update[iface_text + ".{}".format(k)] = v
859 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
860 if pdu_interface.get("ip-address"):
tiernoc88003e2020-03-12 17:31:42 +0000861 if vdur_interface.get("mgmt-interface") or vdur_interface.get("mgmt-vnf"):
tierno36ec8602018-11-02 17:27:11 +0100862 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
863 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
864 if vdur_interface.get("mgmt-vnf"):
865 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
866 vnfr_update["ip-address"] = pdu_interface["ip-address"]
tierno72b16e12020-03-18 09:49:43 +0000867 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +0100868 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +0100869 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +0100870 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
871 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
872 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +0100873 if pdu_interface.get("vim-network-id"):
tiernoc67b0e92019-11-05 12:45:29 +0000874 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +0100875 if pdu_interface.get("vim-network-name"):
tiernoc67b0e92019-11-05 12:45:29 +0000876 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +0200877 break
878
tierno36ec8602018-11-02 17:27:11 +0100879 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +0200880
tierno9cb7d672019-10-30 12:13:48 +0000881 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
882 """
883 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
884 Fills vnfr.kdur with the selected k8scluster
885
886 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
887 :param rollback: list with the database modifications to rollback if needed
888 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
889 :param vim_account: vim_account where this vnfr should be deployed
890 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
891 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
892 of the changed vnfr is needed
893
894 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
895 "vim-network-name": used at VIM
896 "name": interface name
897 "vnf-vld-id": internal VNFD vld where this interface is connected, or
898 "ns-vld-id": NSD vld where this interface is connected.
899 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
900 """
901
902 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +0000903 if not vnfr.get("kdur"):
904 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +0000905
tiernoc67b0e92019-11-05 12:45:29 +0000906 kdu_filter = self._get_project_filter(session)
907 kdu_filter["vim_account"] = vim_account
908 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
909 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
910
911 k8s_requirements = {} # just for logging
912 for k8scluster in available_k8sclusters:
913 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +0000914 break
tiernoc67b0e92019-11-05 12:45:29 +0000915 # restrict by cni
916 if vnfr["k8s-cluster"].get("cni"):
917 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
918 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
919 continue
920 # restrict by version
921 if vnfr["k8s-cluster"].get("version"):
922 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
923 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
924 continue
925 # restrict by number of networks
926 if vnfr["k8s-cluster"].get("nets"):
927 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
928 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
929 continue
930 break
931 else:
932 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
933 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
tierno9cb7d672019-10-30 12:13:48 +0000934
tiernoc67b0e92019-11-05 12:45:29 +0000935 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +0000936 # step 3. Fill vnfr info by filling kdur
937 kdu_text = "kdur.{}.".format(kdur_index)
938 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
939 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
940
tiernoc67b0e92019-11-05 12:45:29 +0000941 # step 4. Check VIM networks that forces the selected k8s_cluster
942 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
943 k8scluster_net_list = list(k8scluster.get("nets").keys())
944 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
945 # get a network from k8s_cluster nets. If name matches use this, if not use other
946 if kdur_net["id"] in k8scluster_net_list: # name matches
947 vim_net = k8scluster["nets"][kdur_net["id"]]
948 k8scluster_net_list.remove(kdur_net["id"])
949 else:
950 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
951 k8scluster_net_list.pop(0)
952 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
953 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
954 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
955 ifaces_forcing_vim_network.append({
956 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
957 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
958 "ns-vld-id": kdur_net.get("ns-vld-id"),
959 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
960 })
961 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +0000962 return ifaces_forcing_vim_network
963
tiernocc103432018-10-19 14:10:35 +0200964 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +0200965 # get vnfr
966 nsr_id = nsr["_id"]
967 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
968
969 for vnfr in vnfrs:
970 vnfr_update = {}
971 vnfr_update_rollback = {}
972 member_vnf_index = vnfr["member-vnf-index-ref"]
973 # update vim-account-id
974
975 vim_account = indata["vimAccountId"]
976 # check instantiate parameters
977 for vnf_inst_params in get_iterable(indata.get("vnf")):
978 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
979 continue
980 if vnf_inst_params.get("vimAccountId"):
981 vim_account = vnf_inst_params.get("vimAccountId")
982
tiernocddb07d2020-10-06 08:28:00 +0000983 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
984 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
985 for vdur_index, vdur in enumerate(vnfr["vdur"]):
986 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
987 continue
988 for iface_inst_param in get_iterable(vdu_inst_param.get("interface")):
989 iface_index, _ = next(i for i in enumerate(vdur["interfaces"])
990 if i[1]["name"] == iface_inst_param["name"])
991 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
992 if iface_inst_param.get("ip-address"):
993 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
994 iface_inst_param.get("ip-address"), vdur.get("count-index", 0))
995 if iface_inst_param.get("mac-address"):
996 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
997 iface_inst_param.get("mac-address"), vdur.get("count-index", 0))
998 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
999 # TODO update vld with the ip-profile
1000 for ivld_inst_param in get_iterable(vnf_inst_params.get("internal-vld")):
1001 for icp_inst_param in get_iterable(ivld_inst_param.get("internal-connection-point")):
1002 # look for iface
1003 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1004 for iface_index, iface in enumerate(vdur["interfaces"]):
1005 if iface.get("internal-connection-point-ref") == icp_inst_param["id-ref"]:
1006 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1007 if icp_inst_param.get("ip-address"):
1008 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1009 icp_inst_param.get("ip-address"), vdur.get("count-index", 0))
1010 if icp_inst_param.get("mac-address"):
1011 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1012 icp_inst_param.get("mac-address"), vdur.get("count-index", 0))
1013 break
1014 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1015 for vld_inst_param in get_iterable(indata.get("vld")):
1016 for vnfcp_inst_param in get_iterable(vld_inst_param.get("vnfd-connection-point-ref")):
1017 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1018 continue
1019 # look for iface
1020 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1021 for iface_index, iface in enumerate(vdur["interfaces"]):
1022 if iface.get("external-connection-point-ref") == \
1023 vnfcp_inst_param["vnfd-connection-point-ref"]:
1024 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1025 if vnfcp_inst_param.get("ip-address"):
1026 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1027 vnfcp_inst_param.get("ip-address"), vdur.get("count-index", 0))
1028 if vnfcp_inst_param.get("mac-address"):
1029 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1030 vnfcp_inst_param.get("mac-address"), vdur.get("count-index", 0))
1031 break
1032
tiernocc103432018-10-19 14:10:35 +02001033 vnfr_update["vim-account-id"] = vim_account
1034 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1035
1036 # get pdu
tierno36ec8602018-11-02 17:27:11 +01001037 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
1038 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +02001039
tierno9cb7d672019-10-30 12:13:48 +00001040 # get kdus
1041 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
1042 vnfr_update_rollback)
1043 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +01001044 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1045 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
1046
1047 # Update indada in case pdu forces to use a concrete vim-network-name
1048 # TODO check if user has already insert a vim-network-name and raises an error
1049 if not ifaces_forcing_vim_network:
1050 continue
1051 for iface_info in ifaces_forcing_vim_network:
1052 if iface_info.get("ns-vld-id"):
1053 if "vld" not in indata:
1054 indata["vld"] = []
1055 indata["vld"].append({key: iface_info[key] for key in
1056 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
1057
1058 elif iface_info.get("vnf-vld-id"):
1059 if "vnf" not in indata:
1060 indata["vnf"] = []
1061 indata["vnf"].append({
1062 "member-vnf-index": member_vnf_index,
1063 "internal-vld": [{key: iface_info[key] for key in
1064 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
1065 })
1066
1067 @staticmethod
1068 def _create_nslcmop(nsr_id, operation, params):
1069 """
1070 Creates a ns-lcm-opp content to be stored at database.
1071 :param nsr_id: internal id of the instance
1072 :param operation: instantiate, terminate, scale, action, ...
1073 :param params: user parameters for the operation
1074 :return: dictionary following SOL005 format
1075 """
tiernob24258a2018-10-04 18:39:49 +02001076 now = time()
1077 _id = str(uuid4())
1078 nslcmop = {
1079 "id": _id,
1080 "_id": _id,
1081 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +00001082 "queuePosition": None,
1083 "stage": None,
1084 "errorMessage": None,
1085 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +02001086 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +01001087 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001088 "lcmOperationType": operation,
1089 "startTime": now,
1090 "isAutomaticInvocation": False,
1091 "operationParams": params,
1092 "isCancelPending": False,
1093 "links": {
1094 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +01001095 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +02001096 }
1097 }
1098 return nslcmop
1099
magnussonlf318b302020-01-20 18:38:18 +01001100 def _get_enabled_vims(self, session):
1101 """
1102 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1103 :param session: current session with user information
1104 """
1105 db_filter = self._get_project_filter(session)
1106 db_filter["_admin.operationalState"] = "ENABLED"
1107 vims = self.db.get_list("vim_accounts", db_filter)
1108 vimAccounts = []
1109 for vim in vims:
1110 vimAccounts.append(vim['_id'])
1111 return vimAccounts
1112
tierno65ca36d2019-02-12 19:27:52 +01001113 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +02001114 """
1115 Performs a new operation over a ns
1116 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001117 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001118 :param indata: descriptor with the parameters of the operation. It must contains among others
1119 nsInstanceId: _id of the nsr to perform the operation
1120 operation: it can be: instantiate, terminate, action, TODO: update, heal
1121 :param kwargs: used to override the indata descriptor
1122 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02001123 :return: id of the nslcmops
1124 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001125 def check_if_nsr_is_not_slice_member(session, nsr_id):
1126 nsis = None
1127 db_filter = self._get_project_filter(session)
1128 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1129 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
1130 if nsis:
tierno40f742b2020-06-23 15:25:26 +00001131 raise EngineException("The NS instance {} cannot be terminated because is used by the slice {}".format(
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001132 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
1133
tiernob24258a2018-10-04 18:39:49 +02001134 try:
1135 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00001136 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02001137 operation = indata["lcmOperationType"]
1138 nsInstanceId = indata["nsInstanceId"]
1139
1140 validate_input(indata, self.operation_schema[operation])
1141 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01001142 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02001143 _filter["_id"] = nsInstanceId
1144 nsr = self.db.get_one("nsrs", _filter)
1145
1146 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001147 if operation == "terminate" and slice_object is False:
1148 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +02001149 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1150 if operation == "terminate" and indata.get("autoremove"):
1151 # NSR must be deleted
tierno586ae812019-10-17 13:56:53 +00001152 return None, None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02001153 if operation != "instantiate":
1154 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1155 nsInstanceId, operation), HTTPStatus.CONFLICT)
1156 else:
tierno65ca36d2019-02-12 19:27:52 +01001157 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +02001158 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1159 nsInstanceId, operation), HTTPStatus.CONFLICT)
1160 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +01001161
tiernocc103432018-10-19 14:10:35 +02001162 if operation == "instantiate":
1163 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01001164
1165 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00001166 _id = nslcmop_desc["_id"]
tierno65ca36d2019-02-12 19:27:52 +01001167 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
magnussonlf318b302020-01-20 18:38:18 +01001168 if indata.get("placement-engine"):
1169 # Save valid vim accounts in lcm operation descriptor
1170 nslcmop_desc['operationParams']['validVimAccounts'] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00001171 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02001172 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001173 if not slice_object:
1174 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001175 return _id, None
1176 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02001177 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1178 # except DbException as e:
1179 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1180
tiernobee3bad2019-12-05 12:26:01 +00001181 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +02001182 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1183
tierno65ca36d2019-02-12 19:27:52 +01001184 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +02001185 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001186
1187
1188class NsiTopic(BaseTopic):
1189 topic = "nsis"
1190 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00001191 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001192
delacruzramo32bab472019-09-13 12:24:22 +02001193 def __init__(self, db, fs, msg, auth):
1194 BaseTopic.__init__(self, db, fs, msg, auth)
1195 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001196
Felipe Vicensc37b3842019-01-12 12:24:42 +01001197 @staticmethod
1198 def _format_ns_request(ns_request):
1199 formated_request = copy(ns_request)
1200 # TODO: Add request params
1201 return formated_request
1202
1203 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001204 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001205 """
1206 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001207 :param slice_request: User instantiation additional parameters
1208 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001209 """
tiernofd160572019-01-21 10:41:37 +00001210 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1211 if additional_params:
1212 for k, v in additional_params.items():
1213 if not isinstance(k, str):
1214 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1215 format(k))
1216 if "." in k or "$" in k:
1217 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1218 format(k))
1219 if isinstance(v, (dict, tuple, list)):
1220 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001221 return additional_params
1222
Felipe Vicensb57758d2018-10-16 16:00:20 +02001223 def _check_descriptor_dependencies(self, session, descriptor):
1224 """
1225 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001227 :param descriptor: descriptor to be inserted or edit
1228 :return: None or raises exception
1229 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001230 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001231 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001232 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001233 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +01001234 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +02001235 http_code=HTTPStatus.CONFLICT)
1236
tiernob4844ab2019-05-23 08:42:12 +00001237 def check_conflict_on_del(self, session, _id, db_content):
1238 """
1239 Check that NSI is not instantiated
1240 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1241 :param _id: nsi internal id
1242 :param db_content: The database content of the _id
1243 :return: None or raises EngineException with the conflict
1244 """
tierno65ca36d2019-02-12 19:27:52 +01001245 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02001246 return
tiernob4844ab2019-05-23 08:42:12 +00001247 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02001248 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1249 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1250 "Launch 'terminate' operation first; or force deletion".format(_id),
1251 http_code=HTTPStatus.CONFLICT)
1252
tiernobee3bad2019-12-05 12:26:01 +00001253 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001254 """
tiernob4844ab2019-05-23 08:42:12 +00001255 Deletes associated nsilcmops from database. Deletes associated filesystem.
1256 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01001257 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001258 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00001259 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00001260 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00001261 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02001262 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001263
Felipe Vicens09e65422019-01-22 15:06:46 +01001264 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00001265 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01001266 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1267 nsr_id = nsrs_detailed_item["nsrId"]
1268 if nsrs_detailed_item.get("shared"):
1269 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1270 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1271 "_id.ne": nsir["_id"]}
1272 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1273 if nsi: # last one using nsr
1274 continue
1275 try:
tiernobee3bad2019-12-05 12:26:01 +00001276 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
Felipe Vicens09e65422019-01-22 15:06:46 +01001277 except (DbException, EngineException) as e:
1278 if e.http_code == HTTPStatus.NOT_FOUND:
1279 pass
1280 else:
1281 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001282
tiernob4844ab2019-05-23 08:42:12 +00001283 # delete related nsilcmops database entries
1284 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001285
tiernob4844ab2019-05-23 08:42:12 +00001286 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01001287 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00001288 if nsir_admin and nsir_admin.get("nst-id"):
1289 # check if used by another NSI
1290 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1291 fail_on_empty=False, fail_on_more=False)
1292 if not nsis_list:
1293 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1294
1295 # def delete(self, session, _id, dry_run=False):
1296 # """
1297 # Delete item by its internal _id
1298 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1299 # :param _id: server internal id
1300 # :param dry_run: make checking but do not delete
1301 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1302 # """
1303 # # TODO add admin to filter, validate rights
1304 # BaseTopic.delete(self, session, _id, dry_run=True)
1305 # if dry_run:
1306 # return
1307 #
1308 # # Deleting the nsrs belonging to nsir
1309 # nsir = self.db.get_one("nsis", {"_id": _id})
1310 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1311 # nsr_id = nsrs_detailed_item["nsrId"]
1312 # if nsrs_detailed_item.get("shared"):
1313 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1314 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1315 # "_id.ne": nsir["_id"]}
1316 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1317 # if nsi: # last one using nsr
1318 # continue
1319 # try:
1320 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1321 # except (DbException, EngineException) as e:
1322 # if e.http_code == HTTPStatus.NOT_FOUND:
1323 # pass
1324 # else:
1325 # raise
1326 # # deletes NetSlice instance object
1327 # v = self.db.del_one("nsis", {"_id": _id})
1328 #
1329 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1330 # _filter = {"netsliceInstanceId": _id}
1331 # self.db.del_list("nsilcmops", _filter)
1332 #
1333 # # Search if nst is being used by other nsi
1334 # nsir_admin = nsir.get("_admin")
1335 # if nsir_admin:
1336 # if nsir_admin.get("nst-id"):
1337 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1338 # fail_on_empty=False, fail_on_more=False)
1339 # if not nsis_list:
1340 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1341 # return v
Felipe Vicensb57758d2018-10-16 16:00:20 +02001342
tierno65ca36d2019-02-12 19:27:52 +01001343 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001344 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001345 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02001346 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01001347 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001348 :param indata: params to be used for the nsir
1349 :param kwargs: used to override the indata descriptor
1350 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02001351 :return: the _id of nsi descriptor created at database
1352 """
1353
1354 try:
delacruzramo32bab472019-09-13 12:24:22 +02001355 step = "checking quotas"
1356 self.check_quota(session)
1357
tierno99d4b172019-07-02 09:28:40 +00001358 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02001359 slice_request = self._remove_envelop(indata)
1360 # Override descriptor with query string kwargs
1361 self._update_input_with_kwargs(slice_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001362 self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001363
Felipe Vicensb57758d2018-10-16 16:00:20 +02001364 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +00001365 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001366 _filter = self._get_project_filter(session)
1367 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001368 nstd = self.db.get_one("nsts", _filter)
tierno40f742b2020-06-23 15:25:26 +00001369 # check NST is not disabled
1370 step = "checking NST operationalState"
1371 if nstd["_admin"]["operationalState"] == "DISABLED":
1372 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
1373 "instance".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
tiernob4844ab2019-05-23 08:42:12 +00001374 del _filter["_id"]
1375
Frank Brydenb5a2ead2020-07-28 12:50:23 +00001376 # check NSD is not disabled
1377 step = "checking operationalState"
1378 if nstd["_admin"]["operationalState"] == "DISABLED":
1379 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create "
1380 "a network slice".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
1381
Felipe Vicens07f31722018-10-29 15:16:44 +01001382 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001383 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001384 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001385 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001386
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001387 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001388 nsi_descriptor = {
1389 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001390 "name": slice_request["nsiName"],
1391 "description": slice_request.get("nsiDescription", ""),
1392 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001393 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001394 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001395 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001396 "nsr-ref-list": [],
1397 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001398 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001399 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001400 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001401
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001402 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001403 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001404 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1405 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001406 nsi_descriptor["_admin"]["deployed"] = {}
1407 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1408 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1409
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001410 # Creating netslice-vld for the RO.
1411 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001412
1413 # Building the vlds list to be deployed
1414 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001415 nsi_vlds = []
1416
1417 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1418 # Getting template Instantiation parameters from NST
1419 nsi_vld = deepcopy(netslice_vlds)
1420 nsi_vld["shared-nsrs-list"] = []
1421 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1422 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001423
1424 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00001425 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001426 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001427 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001428
Felipe Vicens09e65422019-01-22 15:06:46 +01001429 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001430 for member_ns in nstd["netslice-subnet"]:
1431 nsd_id = member_ns["nsd-ref"]
1432 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1433 member_ns["nsd-ref"], member_ns["id"])
1434 if nsd_id not in needed_nsds:
1435 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001436 _filter["id"] = nsd_id
1437 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1438 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001439 nsd.pop("_admin")
1440 needed_nsds[nsd_id] = nsd
1441 else:
1442 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001443 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1444 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001445
Felipe Vicensb57758d2018-10-16 16:00:20 +02001446 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1447 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001448
Felipe Vicens07f31722018-10-29 15:16:44 +01001449 # creates Network Services records (NSRs)
1450 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001451 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001452 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001453 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001454 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001455 # Check if the netslice-subnet is shared and if it is share if the nss exists
1456 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001457 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001458 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001459 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1460 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens08ddb142019-08-09 15:52:40 +02001461 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001462 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001463 if nsi and service.get("is-shared-nss"):
1464 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1465 for nsrs_detailed_item in nsrs_detailed_list:
1466 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02001467 if nsrs_detailed_item["nss-id"] == service["id"]:
1468 _id_nsr = nsrs_detailed_item["nsrId"]
1469 break
Felipe Vicens09e65422019-01-22 15:06:46 +01001470 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1471 if netslice_subnet["nss-id"] == service["id"]:
1472 indata_ns = netslice_subnet
1473 break
1474 else:
1475 indata_ns = {}
1476 if service.get("instantiation-parameters"):
1477 indata_ns = deepcopy(service["instantiation-parameters"])
1478 # del service["instantiation-parameters"]
1479
1480 indata_ns["nsdId"] = service["_id"]
1481 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1482 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1483 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001484 if slice_request.get("ssh_keys"):
1485 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001486
Felipe Vicens09e65422019-01-22 15:06:46 +01001487 if ns_params:
1488 for ns_param in ns_params:
1489 if ns_param.get("id") == service["id"]:
1490 copy_ns_param = deepcopy(ns_param)
1491 del copy_ns_param["id"]
1492 indata_ns.update(copy_ns_param)
1493 break
1494
1495 # Creates Nsr objects
tiernobdebce92019-07-01 15:36:49 +00001496 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001497 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
Felipe Vicens08ddb142019-08-09 15:52:40 +02001498 "nss-id": service["id"], "nslcmop_instantiate": None}
Felipe Vicens09e65422019-01-22 15:06:46 +01001499 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001500 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001501 nsi_netslice_subnet.append(indata_ns)
1502 nsr_ref = {"nsr-ref": _id_nsr}
1503 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001504
1505 # Adding the nsrs list to the nsi
1506 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001507 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001508 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1509
Felipe Vicens07f31722018-10-29 15:16:44 +01001510 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001511 self.db.create("nsis", nsi_descriptor)
1512 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00001513 return nsi_id, None
1514 except Exception as e: # TODO remove try Except, it is captured at nbi.py
Felipe Vicensb57758d2018-10-16 16:00:20 +02001515 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1516 raise EngineException("Error {}: {}".format(step, e))
1517 except ValidationError as e:
1518 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1519
tierno65ca36d2019-02-12 19:27:52 +01001520 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001521 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001522
1523
1524class NsiLcmOpTopic(BaseTopic):
1525 topic = "nsilcmops"
1526 topic_msg = "nsi"
1527 operation_schema = { # mapping between operation and jsonschema to validate
1528 "instantiate": nsi_instantiate,
1529 "terminate": None
1530 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001531
delacruzramo32bab472019-09-13 12:24:22 +02001532 def __init__(self, db, fs, msg, auth):
1533 BaseTopic.__init__(self, db, fs, msg, auth)
1534 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01001535
1536 def _check_nsi_operation(self, session, nsir, operation, indata):
1537 """
1538 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001539 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001540 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1541 :param indata: descriptor with the parameters of the operation
1542 :return: None
1543 """
1544 nsds = {}
1545 nstd = nsir["network-slice-template"]
1546
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001547 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001548 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001549 for netslice_subnet in nstd["netslice-subnet"]:
1550 if nstId == netslice_subnet["id"]:
1551 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001552 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02001553 _filter = self._get_project_filter(session)
1554 _filter["id"] = nsd_id
1555 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01001556 return nsds[nsd_id]
1557 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001558 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1559 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001560 if operation == "instantiate":
1561 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001562 for in_nst in get_iterable(indata.get("netslice-subnet")):
1563 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001564
1565 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1566 now = time()
1567 _id = str(uuid4())
1568 nsilcmop = {
1569 "id": _id,
1570 "_id": _id,
1571 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1572 "statusEnteredTime": now,
1573 "netsliceInstanceId": netsliceInstanceId,
1574 "lcmOperationType": operation,
1575 "startTime": now,
1576 "isAutomaticInvocation": False,
1577 "operationParams": params,
1578 "isCancelPending": False,
1579 "links": {
1580 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001581 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001582 }
1583 }
1584 return nsilcmop
1585
Felipe Vicens09e65422019-01-22 15:06:46 +01001586 def add_shared_nsr_2vld(self, nsir, nsr_item):
1587 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1588 if nst_sb_item.get("is-shared-nss"):
1589 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1590 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1591 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1592 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1593 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1594 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1595 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1596 break
1597 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1598 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1599
tierno65ca36d2019-02-12 19:27:52 +01001600 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001601 """
1602 Performs a new operation over a ns
1603 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001604 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001605 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001606 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001607 operation: it can be: instantiate, terminate, action, TODO: update, heal
1608 :param kwargs: used to override the indata descriptor
1609 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001610 :return: id of the nslcmops
1611 """
1612 try:
1613 # Override descriptor with query string kwargs
1614 self._update_input_with_kwargs(indata, kwargs)
1615 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001616 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001617 validate_input(indata, self.operation_schema[operation])
1618
Felipe Vicens126af572019-06-05 19:13:04 +02001619 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001620 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001621 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001622 nsir = self.db.get_one("nsis", _filter)
tierno40f742b2020-06-23 15:25:26 +00001623 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
tiernob4844ab2019-05-23 08:42:12 +00001624 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001625
1626 # initial checking
1627 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1628 if operation == "terminate" and indata.get("autoremove"):
1629 # NSIR must be deleted
tierno586ae812019-10-17 13:56:53 +00001630 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 +01001631 if operation != "instantiate":
1632 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001633 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001634 else:
tierno65ca36d2019-02-12 19:27:52 +01001635 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001636 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001637 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001638
1639 # Creating all the NS_operation (nslcmop)
1640 # Get service list from db
1641 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1642 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001643 # nslcmops_item = None
1644 for index, nsr_item in enumerate(nsrs_list):
tierno40f742b2020-06-23 15:25:26 +00001645 nsr_id = nsr_item["nsrId"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001646 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001647 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tierno40f742b2020-06-23 15:25:26 +00001648 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
tiernob4844ab2019-05-23 08:42:12 +00001649 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001650 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001651 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001652 if operation == "terminate":
1653 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1654 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
tierno40f742b2020-06-23 15:25:26 +00001655 if nsi: # other nsi is using this nsr and it needs this nsr instantiated
1656 continue # do not create nsilcmop
1657 else: # instantiate
1658 # looks the first nsi fulfilling the conditions but not being the current NSIR
1659 if nsi:
1660 nsi_nsr_item = next(n for n in nsi["_admin"]["nsrs-detailed-list"] if
1661 n["nsrId"] == nsr_id and n["shared"] and
1662 n["nslcmop_instantiate"])
1663 self.add_shared_nsr_2vld(nsir, nsr_item)
1664 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1665 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1666 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1667 # continue to not create nslcmop since nsrs is shared and nsrs was created
1668 continue
1669 else:
1670 self.add_shared_nsr_2vld(nsir, nsr_item)
Felipe Vicens09e65422019-01-22 15:06:46 +01001671
tierno40f742b2020-06-23 15:25:26 +00001672 # create operation
Felipe Vicens09e65422019-01-22 15:06:46 +01001673 try:
tierno0b8752f2020-05-12 09:42:02 +00001674 indata_ns = {
1675 "lcmOperationType": operation,
tierno40f742b2020-06-23 15:25:26 +00001676 "nsInstanceId": nsr_id,
tierno0b8752f2020-05-12 09:42:02 +00001677 # Including netslice_id in the ns instantiate Operation
1678 "netsliceInstanceId": netsliceInstanceId,
1679 }
1680 if operation == "instantiate":
tierno40f742b2020-06-23 15:25:26 +00001681 service = self.db.get_one("nsrs", {"_id": nsr_id})
tierno0b8752f2020-05-12 09:42:02 +00001682 indata_ns.update(service["instantiate_params"])
1683
tierno99d4b172019-07-02 09:28:40 +00001684 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001685 # message via kafka bus
tierno40f742b2020-06-23 15:25:26 +00001686 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, None, headers,
tiernobdebce92019-07-01 15:36:49 +00001687 slice_object=True)
Felipe Vicens09e65422019-01-22 15:06:46 +01001688 nslcmops.append(nslcmop)
tierno40f742b2020-06-23 15:25:26 +00001689 if operation == "instantiate":
1690 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1691 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
Felipe Vicens09e65422019-01-22 15:06:46 +01001692 except (DbException, EngineException) as e:
1693 if e.http_code == HTTPStatus.NOT_FOUND:
tierno40f742b2020-06-23 15:25:26 +00001694 self.logger.info(logging_prefix + "skipping NS={} because not found".format(nsr_id))
Felipe Vicens09e65422019-01-22 15:06:46 +01001695 pass
1696 else:
1697 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001698
1699 # Creates nsilcmop
1700 indata["nslcmops_ids"] = nslcmops
1701 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001702
Felipe Vicens126af572019-06-05 19:13:04 +02001703 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001704 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001705 _id = self.db.create("nsilcmops", nsilcmop_desc)
1706 rollback.append({"topic": "nsilcmops", "_id": _id})
1707 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001708 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01001709 except ValidationError as e:
1710 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001711
tiernobee3bad2019-12-05 12:26:01 +00001712 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001713 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1714
tierno65ca36d2019-02-12 19:27:52 +01001715 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001716 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)