blob: 09a8c1be6d795a29626c555e2a68194ce518d6d3 [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
tierno23acf402019-08-28 13:36:34 +000021from osm_nbi.validation import validate_input, ValidationError, ns_instantiate, ns_action, ns_scale, nsi_instantiate
tierno714954e2019-11-29 13:43:26 +000022from osm_nbi.base_topic import BaseTopic, EngineException, get_iterable, deep_get
tiernob4844ab2019-05-23 08:42:12 +000023# from descriptor_topics import DescriptorTopic
tiernobee085c2018-12-12 17:03:04 +000024from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010025from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000026from osm_common.msgbase import MsgException
27from osm_common.fsbase import FsException
delacruzramo36ffe552019-05-03 14:52:37 +020028from re import match # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020029
30__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
31
32
33class NsrTopic(BaseTopic):
34 topic = "nsrs"
35 topic_msg = "ns"
tiernod77ba6f2019-06-27 14:31:10 +000036 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020037
delacruzramo32bab472019-09-13 12:24:22 +020038 def __init__(self, db, fs, msg, auth):
39 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020040
41 def _check_descriptor_dependencies(self, session, descriptor):
42 """
43 Check that the dependent descriptors exist on a new descriptor or edition
44 :param session: client session information
45 :param descriptor: descriptor to be inserted or edit
46 :return: None or raises exception
47 """
48 if not descriptor.get("nsdId"):
49 return
50 nsd_id = descriptor["nsdId"]
51 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
52 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
53 http_code=HTTPStatus.CONFLICT)
54
55 @staticmethod
56 def format_on_new(content, project_id=None, make_public=False):
57 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
58 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000059 return None
tiernob24258a2018-10-04 18:39:49 +020060
tiernob4844ab2019-05-23 08:42:12 +000061 def check_conflict_on_del(self, session, _id, db_content):
62 """
63 Check that NSR is not instantiated
64 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
65 :param _id: nsr internal id
66 :param db_content: The database content of the nsr
67 :return: None or raises EngineException with the conflict
68 """
tierno65ca36d2019-02-12 19:27:52 +010069 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020070 return
tiernob4844ab2019-05-23 08:42:12 +000071 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020072 if nsr["_admin"].get("nsState") == "INSTANTIATED":
73 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
74 "Launch 'terminate' operation first; or force deletion".format(_id),
75 http_code=HTTPStatus.CONFLICT)
76
tiernobee3bad2019-12-05 12:26:01 +000077 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +000078 """
79 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
80 Set usageState of pdu, vnfd, nsd
81 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
82 :param _id: server internal id
83 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +000084 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +000085 :return: None if ok or raises EngineException with the problem
86 """
tiernobee085c2018-12-12 17:03:04 +000087 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +020088 self.db.del_list("nslcmops", {"nsInstanceId": _id})
89 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +000090
tiernob24258a2018-10-04 18:39:49 +020091 # set all used pdus as free
92 self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
tierno36ec8602018-11-02 17:27:11 +010093 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
tiernob24258a2018-10-04 18:39:49 +020094
tiernob4844ab2019-05-23 08:42:12 +000095 # Set NSD usageState
96 nsr = db_content
97 used_nsd_id = nsr.get("nsd-id")
98 if used_nsd_id:
99 # check if used by another NSR
100 nsrs_list = self.db.get_one("nsrs", {"nsd-id": used_nsd_id},
101 fail_on_empty=False, fail_on_more=False)
102 if not nsrs_list:
103 self.db.set_one("nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"})
104
105 # Set VNFD usageState
106 used_vnfd_id_list = nsr.get("vnfd-id")
107 if used_vnfd_id_list:
108 for used_vnfd_id in used_vnfd_id_list:
109 # check if used by another NSR
110 nsrs_list = self.db.get_one("nsrs", {"vnfd-id": used_vnfd_id},
111 fail_on_empty=False, fail_on_more=False)
112 if not nsrs_list:
113 self.db.set_one("vnfds", {"_id": used_vnfd_id}, {"_admin.usageState": "NOT_IN_USE"})
114
tiernobee085c2018-12-12 17:03:04 +0000115 @staticmethod
116 def _format_ns_request(ns_request):
117 formated_request = copy(ns_request)
118 formated_request.pop("additionalParamsForNs", None)
119 formated_request.pop("additionalParamsForVnf", None)
120 return formated_request
121
122 @staticmethod
tierno714954e2019-11-29 13:43:26 +0000123 def _format_addional_params(ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None):
tiernobee085c2018-12-12 17:03:04 +0000124 """
125 Get and format user additional params for NS or VNF
126 :param ns_request: User instantiation additional parameters
127 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
128 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno714954e2019-11-29 13:43:26 +0000129 :return: a formatted copy of additional params or None if not supplied
tiernobee085c2018-12-12 17:03:04 +0000130 """
131 additional_params = None
132 if not member_vnf_index:
133 additional_params = copy(ns_request.get("additionalParamsForNs"))
134 where_ = "additionalParamsForNs"
135 elif ns_request.get("additionalParamsForVnf"):
tierno714954e2019-11-29 13:43:26 +0000136 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index)
137 item = next((x for x in ns_request["additionalParamsForVnf"] if x["member-vnf-index"] == member_vnf_index),
138 None)
139 if item:
140 additional_params = copy(item.get("additionalParams")) or {}
141 if vdu_id and item.get("additionalParamsForVdu"):
142 item_vdu = next((x for x in item["additionalParamsForVdu"] if x["vdu_id"] == vdu_id), None)
143 if item_vdu and item_vdu.get("additionalParams"):
144 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000145 additional_params = item_vdu["additionalParams"]
146 if kdu_name:
147 additional_params = {}
148 if item.get("additionalParamsForKdu"):
149 item_kdu = next((x for x in item["additionalParamsForKdu"] if x["kdu_name"] == kdu_name), None)
150 if item_kdu and item_kdu.get("additionalParams"):
151 where_ += ".additionalParamsForKdu[kdu_name={}]".format(kdu_name)
152 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000153
tiernobee085c2018-12-12 17:03:04 +0000154 if additional_params:
155 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000156 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
157 if not kdu_name and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k):
delacruzramo36ffe552019-05-03 14:52:37 +0200158 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
159 "and underscores, and cannot start with a digit"
160 .format(where_, k))
161 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000162 if not isinstance(k, str):
163 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
164 if "." in k or "$" in k:
165 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
166 if isinstance(v, (dict, tuple, list)):
167 additional_params[k] = "!!yaml " + safe_dump(v)
168
169 if descriptor:
170 # check that enough parameters are supplied for the initial-config-primitive
171 # TODO: check for cloud-init
172 if member_vnf_index:
tierno714954e2019-11-29 13:43:26 +0000173 if kdu_name:
174 initial_primitives = None
175 elif vdu_id:
176 vdud = next(x for x in descriptor["vdu"] if x["id"] == vdu_id)
177 initial_primitives = deep_get(vdud, ("vdu-configuration", "initial-config-primitive"))
178 else:
179 initial_primitives = deep_get(descriptor, ("vnf-configuration", "initial-config-primitive"))
180 else:
181 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
tiernobee085c2018-12-12 17:03:04 +0000182
tierno714954e2019-11-29 13:43:26 +0000183 for initial_primitive in get_iterable(initial_primitives):
184 for param in get_iterable(initial_primitive.get("parameter")):
185 if param["value"].startswith("<") and param["value"].endswith(">"):
186 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
187 continue
188 if not additional_params or param["value"][1:-1] not in additional_params:
189 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
190 "initial-config-primitive[name={}] not supplied".
191 format(param["value"], descriptor["id"],
192 initial_primitive["name"]))
193
194 return additional_params or None
tiernobee085c2018-12-12 17:03:04 +0000195
tierno65ca36d2019-02-12 19:27:52 +0100196 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200197 """
198 Creates a new nsr into database. It also creates needed vnfrs
199 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100200 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200201 :param indata: params to be used for the nsr
202 :param kwargs: used to override the indata descriptor
203 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000204 :return: the _id of nsr descriptor created at database. Or an exception of type
205 EngineException, ValidationError, DbException, FsException, MsgException.
206 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200207 """
208
209 try:
delacruzramo32bab472019-09-13 12:24:22 +0200210 step = "checking quotas"
211 self.check_quota(session)
212
tierno99d4b172019-07-02 09:28:40 +0000213 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200214 ns_request = self._remove_envelop(indata)
215 # Override descriptor with query string kwargs
216 self._update_input_with_kwargs(ns_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100217 self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200218
tiernob24258a2018-10-04 18:39:49 +0200219 # look for nsr
220 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
tiernob4844ab2019-05-23 08:42:12 +0000221 _filter = self._get_project_filter(session)
222 _filter["_id"] = ns_request["nsdId"]
tiernob24258a2018-10-04 18:39:49 +0200223 nsd = self.db.get_one("nsds", _filter)
tiernob4844ab2019-05-23 08:42:12 +0000224 del _filter["_id"]
tiernob24258a2018-10-04 18:39:49 +0200225
226 nsr_id = str(uuid4())
tiernobee085c2018-12-12 17:03:04 +0000227
tiernob24258a2018-10-04 18:39:49 +0200228 now = time()
229 step = "filling nsr from input data"
230 nsr_descriptor = {
231 "name": ns_request["nsName"],
232 "name-ref": ns_request["nsName"],
233 "short-name": ns_request["nsName"],
234 "admin-status": "ENABLED",
tiernoecf94bd2020-01-09 12:40:45 +0000235 "nsState": "NOT_INSTANTIATED",
236 "currentOperation": "IDLE",
237 "currentOperationID": None,
238 "errorDescription": None,
239 "errorDetail": None,
240 "deploymentStatus": None,
241 "configurationStatus": None,
242 "vcaStatus": None,
tiernob24258a2018-10-04 18:39:49 +0200243 "nsd": nsd,
244 "datacenter": ns_request["vimAccountId"],
245 "resource-orchestrator": "osmopenmano",
246 "description": ns_request.get("nsDescription", ""),
247 "constituent-vnfr-ref": [],
248
249 "operational-status": "init", # typedef ns-operational-
250 "config-status": "init", # typedef config-states
251 "detailed-status": "scheduled",
252
253 "orchestration-progress": {},
254 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
255
tierno65ca36d2019-02-12 19:27:52 +0100256 "create-time": now,
tiernob24258a2018-10-04 18:39:49 +0200257 "nsd-name-ref": nsd["name"],
258 "operational-events": [], # "id", "timestamp", "description", "event",
259 "nsd-ref": nsd["id"],
tiernof0637052019-03-07 16:26:47 +0000260 "nsd-id": nsd["_id"],
tiernob4844ab2019-05-23 08:42:12 +0000261 "vnfd-id": [],
tiernobee085c2018-12-12 17:03:04 +0000262 "instantiate_params": self._format_ns_request(ns_request),
tierno714954e2019-11-29 13:43:26 +0000263 "additionalParamsForNs": self._format_addional_params(ns_request, descriptor=nsd),
tiernob24258a2018-10-04 18:39:49 +0200264 "ns-instance-config-ref": nsr_id,
265 "id": nsr_id,
266 "_id": nsr_id,
267 # "input-parameter": xpath, value,
tierno99d4b172019-07-02 09:28:40 +0000268 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
tiernob24258a2018-10-04 18:39:49 +0200269 }
270 ns_request["nsr_id"] = nsr_id
tierno36ec8602018-11-02 17:27:11 +0100271 # Create vld
272 if nsd.get("vld"):
273 nsr_descriptor["vld"] = []
274 for nsd_vld in nsd.get("vld"):
275 nsr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100276 {key: nsd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in nsd_vld})
tiernob24258a2018-10-04 18:39:49 +0200277
278 # Create VNFR
279 needed_vnfds = {}
gcalvino4f269dd2018-11-06 13:18:31 +0100280 for member_vnf in nsd.get("constituent-vnfd", ()):
tiernob24258a2018-10-04 18:39:49 +0200281 vnfd_id = member_vnf["vnfd-id-ref"]
282 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
283 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
284 if vnfd_id not in needed_vnfds:
285 # Obtain vnfd
tiernob4844ab2019-05-23 08:42:12 +0000286 _filter["id"] = vnfd_id
287 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
288 del _filter["id"]
tiernob24258a2018-10-04 18:39:49 +0200289 vnfd.pop("_admin")
290 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000291 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200292 else:
293 vnfd = needed_vnfds[vnfd_id]
294 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
295 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
296 vnfr_id = str(uuid4())
297 vnfr_descriptor = {
298 "id": vnfr_id,
299 "_id": vnfr_id,
300 "nsr-id-ref": nsr_id,
301 "member-vnf-index-ref": member_vnf["member-vnf-index"],
tiernobee085c2018-12-12 17:03:04 +0000302 "additionalParamsForVnf": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
tierno714954e2019-11-29 13:43:26 +0000303 descriptor=vnfd),
tiernob24258a2018-10-04 18:39:49 +0200304 "created-time": now,
305 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
306 "vnfd-ref": vnfd_id,
307 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
308 "vim-account-id": None,
309 "vdur": [],
310 "connection-point": [],
311 "ip-address": None, # mgmt-interface filled by LCM
312 }
tierno36ec8602018-11-02 17:27:11 +0100313
314 # Create vld
315 if vnfd.get("internal-vld"):
316 vnfr_descriptor["vld"] = []
317 for vnfd_vld in vnfd.get("internal-vld"):
318 vnfr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100319 {key: vnfd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in
320 vnfd_vld})
tierno36ec8602018-11-02 17:27:11 +0100321
322 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
tiernob24258a2018-10-04 18:39:49 +0200323 for cp in vnfd.get("connection-point", ()):
324 vnf_cp = {
325 "name": cp["name"],
326 "connection-point-id": cp.get("id"),
327 "id": cp.get("id"),
328 # "ip-address", "mac-address" # filled by LCM
329 # vim-id # TODO it would be nice having a vim port id
330 }
331 vnfr_descriptor["connection-point"].append(vnf_cp)
tierno9cb7d672019-10-30 12:13:48 +0000332
tiernoc67b0e92019-11-05 12:45:29 +0000333 # Create k8s-cluster information
334 if vnfd.get("k8s-cluster"):
335 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
336 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
337 if net.get("external-connection-point-ref"):
338 for nsd_vld in get_iterable(nsd.get("vld")):
339 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
340 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
341 net["external-connection-point-ref"] and \
342 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
343 net["ns-vld-id"] = nsd_vld["id"]
344 break
345 else:
346 continue
347 break
348 elif net.get("internal-connection-point-ref"):
349 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
350 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
351 if vnfd_ivld_icp.get("id-ref") == net["internal-connection-point-ref"]:
352 net["vnf-vld-id"] = vnfd_ivld["id"]
353 break
354 else:
355 continue
356 break
tierno9cb7d672019-10-30 12:13:48 +0000357 # update kdus
358 for kdu in get_iterable(vnfd.get("kdu")):
tierno714954e2019-11-29 13:43:26 +0000359 kdur = {x: kdu[x] for x in kdu if x in ("helm-chart", "juju-bundle")}
360 kdur["kdu-name"] = kdu["name"]
361 # TODO "name": "" Name of the VDU in the VIM
tierno3ffc7a42019-12-03 09:39:40 +0000362 kdur["ip-address"] = None # mgmt-interface filled by LCM
363 kdur["k8s-cluster"] = {}
tierno714954e2019-11-29 13:43:26 +0000364 kdur["additionalParams"] = self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
tierno3ffc7a42019-12-03 09:39:40 +0000365 kdu_name=kdu["name"], descriptor=vnfd)
tierno9cb7d672019-10-30 12:13:48 +0000366 if not vnfr_descriptor.get("kdur"):
367 vnfr_descriptor["kdur"] = []
368 vnfr_descriptor["kdur"].append(kdur)
369
gcalvinoe45aded2018-11-13 17:17:28 +0100370 for vdu in vnfd.get("vdu", ()):
tiernob24258a2018-10-04 18:39:49 +0200371 vdur = {
tiernob24258a2018-10-04 18:39:49 +0200372 "vdu-id-ref": vdu["id"],
373 # TODO "name": "" Name of the VDU in the VIM
374 "ip-address": None, # mgmt-interface filled by LCM
375 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
376 "internal-connection-point": [],
377 "interfaces": [],
tierno714954e2019-11-29 13:43:26 +0000378 "additionalParams": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
tierno3ffc7a42019-12-03 09:39:40 +0000379 vdu_id=vdu["id"], descriptor=vnfd)
tiernob24258a2018-10-04 18:39:49 +0200380 }
tiernocc103432018-10-19 14:10:35 +0200381 if vdu.get("pdu-type"):
382 vdur["pdu-type"] = vdu["pdu-type"]
tiernob24258a2018-10-04 18:39:49 +0200383 # TODO volumes: name, volume-id
384 for icp in vdu.get("internal-connection-point", ()):
385 vdu_icp = {
386 "id": icp["id"],
387 "connection-point-id": icp["id"],
388 "name": icp.get("name"),
389 # "ip-address", "mac-address" # filled by LCM
390 # vim-id # TODO it would be nice having a vim port id
391 }
392 vdur["internal-connection-point"].append(vdu_icp)
393 for iface in vdu.get("interface", ()):
394 vdu_iface = {
395 "name": iface.get("name"),
396 # "ip-address", "mac-address" # filled by LCM
397 # vim-id # TODO it would be nice having a vim port id
398 }
tierno36ec8602018-11-02 17:27:11 +0100399 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
400 vdu_iface["mgmt-vnf"] = True
tiernocc103432018-10-19 14:10:35 +0200401 if iface.get("mgmt-interface"):
tierno36ec8602018-11-02 17:27:11 +0100402 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
403
404 # look for network where this interface is connected
405 if iface.get("external-connection-point-ref"):
406 for nsd_vld in get_iterable(nsd.get("vld")):
407 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
408 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
409 iface["external-connection-point-ref"] and \
410 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
411 vdu_iface["ns-vld-id"] = nsd_vld["id"]
412 break
413 else:
414 continue
415 break
416 elif iface.get("internal-connection-point-ref"):
417 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
418 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
419 if vnfd_ivld_icp.get("id-ref") == iface["internal-connection-point-ref"]:
420 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
421 break
422 else:
423 continue
424 break
tiernocc103432018-10-19 14:10:35 +0200425
tiernob24258a2018-10-04 18:39:49 +0200426 vdur["interfaces"].append(vdu_iface)
tiernocc103432018-10-19 14:10:35 +0200427 count = vdu.get("count", 1)
428 if count is None:
429 count = 1
430 count = int(count) # TODO remove when descriptor serialized with payngbind
431 for index in range(0, count):
432 if index:
433 vdur = deepcopy(vdur)
434 vdur["_id"] = str(uuid4())
435 vdur["count-index"] = index
436 vnfr_descriptor["vdur"].append(vdur)
tiernob24258a2018-10-04 18:39:49 +0200437
438 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
439 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
440
441 # add at database
tiernobdebce92019-07-01 15:36:49 +0000442 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200443 self.db.create("vnfrs", vnfr_descriptor)
444 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
445 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
446
447 step = "creating nsr at database"
tierno65ca36d2019-02-12 19:27:52 +0100448 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200449 self.db.create("nsrs", nsr_descriptor)
450 rollback.append({"topic": "nsrs", "_id": nsr_id})
tiernobee085c2018-12-12 17:03:04 +0000451
452 step = "creating nsr temporal folder"
453 self.fs.mkdir(nsr_id)
454
tiernobdebce92019-07-01 15:36:49 +0000455 return nsr_id, None
tierno1bfe4e22019-09-02 16:03:25 +0000456 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
457 raise type(e)("{} while '{}".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200458
tierno65ca36d2019-02-12 19:27:52 +0100459 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200460 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
461
462
463class VnfrTopic(BaseTopic):
464 topic = "vnfrs"
465 topic_msg = None
466
delacruzramo32bab472019-09-13 12:24:22 +0200467 def __init__(self, db, fs, msg, auth):
468 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200469
tiernobee3bad2019-12-05 12:26:01 +0000470 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200471 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
472
tierno65ca36d2019-02-12 19:27:52 +0100473 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200474 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
475
tierno65ca36d2019-02-12 19:27:52 +0100476 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200477 # Not used because vnfrs are created and deleted by NsrTopic class directly
478 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
479
480
481class NsLcmOpTopic(BaseTopic):
482 topic = "nslcmops"
483 topic_msg = "ns"
484 operation_schema = { # mapping between operation and jsonschema to validate
485 "instantiate": ns_instantiate,
486 "action": ns_action,
487 "scale": ns_scale,
488 "terminate": None,
489 }
490
delacruzramo32bab472019-09-13 12:24:22 +0200491 def __init__(self, db, fs, msg, auth):
492 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200493
tiernob24258a2018-10-04 18:39:49 +0200494 def _check_ns_operation(self, session, nsr, operation, indata):
495 """
496 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100497 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200498 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
499 :param indata: descriptor with the parameters of the operation
500 :return: None
501 """
tierno982da4e2019-09-03 11:51:55 +0000502 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +0200503 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000504 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200505 nsd = nsr["nsd"]
506
507 def check_valid_vnf_member_index(member_vnf_index):
tierno982da4e2019-09-03 11:51:55 +0000508 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
509 if vnf_member_index_to_vnfd.get(member_vnf_index):
510 return vnf_member_index_to_vnfd[member_vnf_index]
511 vnfr = self.db.get_one("vnfrs",
512 {"nsr-id-ref": nsr["_id"], "member-vnf-index-ref": member_vnf_index},
513 fail_on_empty=False)
514 if not vnfr:
tiernob24258a2018-10-04 18:39:49 +0200515 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
516 "nsd:constituent-vnfd".format(member_vnf_index))
tierno982da4e2019-09-03 11:51:55 +0000517 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
518 if not vnfd:
519 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
520 format(vnfr["vnfd-id"]))
521 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
522 return vnfd
tiernob24258a2018-10-04 18:39:49 +0200523
tierno260dd6f2019-09-02 10:48:56 +0000524 def check_valid_vdu(vnfd, vdu_id):
525 for vdud in get_iterable(vnfd.get("vdu")):
526 if vdud["id"] == vdu_id:
527 return vdud
528 else:
529 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
530
tierno9cb7d672019-10-30 12:13:48 +0000531 def check_valid_kdu(vnfd, kdu_name):
532 for kdud in get_iterable(vnfd.get("kdu")):
533 if kdud["name"] == kdu_name:
534 return kdud
535 else:
536 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
537
gcalvino5e72d152018-10-23 11:46:57 +0200538 def _check_vnf_instantiation_params(in_vnfd, vnfd):
539
tierno40fbcad2018-10-26 10:58:15 +0200540 for in_vdu in get_iterable(in_vnfd.get("vdu")):
541 for vdu in get_iterable(vnfd.get("vdu")):
542 if in_vdu["id"] == vdu["id"]:
543 for volume in get_iterable(in_vdu.get("volume")):
544 for volumed in get_iterable(vdu.get("volumes")):
545 if volumed["name"] == volume["name"]:
546 break
547 else:
548 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
549 "volume:name='{}' is not present at vnfd:vdu:volumes list".
550 format(in_vnf["member-vnf-index"], in_vdu["id"],
551 volume["name"]))
552 for in_iface in get_iterable(in_vdu["interface"]):
553 for iface in get_iterable(vdu.get("interface")):
554 if in_iface["name"] == iface["name"]:
555 break
556 else:
557 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
558 "interface[name='{}'] is not present at vnfd:vdu:interface"
559 .format(in_vnf["member-vnf-index"], in_vdu["id"],
560 in_iface["name"]))
561 break
gcalvino5e72d152018-10-23 11:46:57 +0200562 else:
tierno40fbcad2018-10-26 10:58:15 +0200563 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
564 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200565
566 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
567 for ivld in get_iterable(vnfd.get("internal-vld")):
568 if in_ivld["name"] == ivld["name"] or in_ivld["name"] == ivld["id"]:
tierno1bfe4e22019-09-02 16:03:25 +0000569 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
gcalvino5e72d152018-10-23 11:46:57 +0200570 for icp in ivld["internal-connection-point"]:
571 if in_icp["id-ref"] == icp["id-ref"]:
572 break
573 else:
tierno40fbcad2018-10-26 10:58:15 +0200574 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
575 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
576 "vnfd:internal-vld:name/id:internal-connection-point"
577 .format(in_vnf["member-vnf-index"], in_ivld["name"],
578 in_icp["id-ref"], vnfd["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200579 break
580 else:
581 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
582 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
583 in_ivld["name"], vnfd["id"]))
584
tiernob24258a2018-10-04 18:39:49 +0200585 def check_valid_vim_account(vim_account):
586 if vim_account in vim_accounts:
587 return
588 try:
tierno65ca36d2019-02-12 19:27:52 +0100589 db_filter = self._get_project_filter(session)
tiernocc103432018-10-19 14:10:35 +0200590 db_filter["_id"] = vim_account
591 self.db.get_one("vim_accounts", db_filter)
tiernob24258a2018-10-04 18:39:49 +0200592 except Exception:
tiernocc103432018-10-19 14:10:35 +0200593 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
tiernob24258a2018-10-04 18:39:49 +0200594 vim_accounts.append(vim_account)
595
tierno4f9d4ae2019-03-20 17:24:11 +0000596 def check_valid_wim_account(wim_account):
597 if not isinstance(wim_account, str):
598 return
599 elif wim_account in wim_accounts:
600 return
601 try:
602 db_filter = self._get_project_filter(session, write=False, show_all=True)
603 db_filter["_id"] = wim_account
604 self.db.get_one("wim_accounts", db_filter)
605 except Exception:
606 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
607 wim_accounts.append(wim_account)
608
tiernob24258a2018-10-04 18:39:49 +0200609 if operation == "action":
610 # check vnf_member_index
611 if indata.get("vnf_member_index"):
612 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
tierno1ac7f462019-06-03 17:22:12 +0000613 if indata.get("member_vnf_index"):
614 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
tierno260dd6f2019-09-02 10:48:56 +0000615 if indata.get("vdu_id"):
616 vdud = check_valid_vdu(vnfd, indata["vdu_id"])
617 descriptor_configuration = vdud.get("vdu-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000618 elif indata.get("kdu_name"):
tiernoc67b0e92019-11-05 12:45:29 +0000619 kdud = check_valid_kdu(vnfd, indata["kdu_name"])
tierno9cb7d672019-10-30 12:13:48 +0000620 descriptor_configuration = kdud.get("kdu-configuration", {}).get("config-primitive")
tierno260dd6f2019-09-02 10:48:56 +0000621 else:
622 descriptor_configuration = vnfd.get("vnf-configuration", {}).get("config-primitive")
tierno1ac7f462019-06-03 17:22:12 +0000623 else: # use a NSD
624 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000625
626 # For k8s allows default primitives without validating the parameters
delacruzramo6ddff2e2019-11-28 11:24:09 +0100627 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
tierno9cb7d672019-10-30 12:13:48 +0000628 # TODO should be checked that rollback only can contains revsision_numbe????
delacruzramo6ddff2e2019-11-28 11:24:09 +0100629 if not indata.get("member_vnf_index"):
630 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
631 .format(indata["primitive"]))
tierno9cb7d672019-10-30 12:13:48 +0000632 return
633 # if not, check primitive
tierno1ac7f462019-06-03 17:22:12 +0000634 for config_primitive in get_iterable(descriptor_configuration):
tiernob24258a2018-10-04 18:39:49 +0200635 if indata["primitive"] == config_primitive["name"]:
636 # check needed primitive_params are provided
637 if indata.get("primitive_params"):
638 in_primitive_params_copy = copy(indata["primitive_params"])
639 else:
640 in_primitive_params_copy = {}
641 for paramd in get_iterable(config_primitive.get("parameter")):
642 if paramd["name"] in in_primitive_params_copy:
643 del in_primitive_params_copy[paramd["name"]]
644 elif not paramd.get("default-value"):
645 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
646 paramd["name"], indata["primitive"]))
647 # check no extra primitive params are provided
648 if in_primitive_params_copy:
tierno1ac7f462019-06-03 17:22:12 +0000649 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
tiernob24258a2018-10-04 18:39:49 +0200650 list(in_primitive_params_copy.keys()), indata["primitive"]))
651 break
652 else:
tierno1ac7f462019-06-03 17:22:12 +0000653 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
tiernob24258a2018-10-04 18:39:49 +0200654 if operation == "scale":
655 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
656 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
657 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
658 break
659 else:
660 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
661 "present at vnfd:scaling-group-descriptor".format(
662 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
663 if operation == "instantiate":
664 # check vim_account
665 check_valid_vim_account(indata["vimAccountId"])
tierno4f9d4ae2019-03-20 17:24:11 +0000666 check_valid_wim_account(indata.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200667 for in_vnf in get_iterable(indata.get("vnf")):
668 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
gcalvino5e72d152018-10-23 11:46:57 +0200669 _check_vnf_instantiation_params(in_vnf, vnfd)
tiernob24258a2018-10-04 18:39:49 +0200670 if in_vnf.get("vimAccountId"):
671 check_valid_vim_account(in_vnf["vimAccountId"])
tiernob24258a2018-10-04 18:39:49 +0200672
tiernob24258a2018-10-04 18:39:49 +0200673 for in_vld in get_iterable(indata.get("vld")):
tierno4f9d4ae2019-03-20 17:24:11 +0000674 check_valid_wim_account(in_vld.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200675 for vldd in get_iterable(nsd.get("vld")):
676 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
677 break
678 else:
679 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
680 in_vld["name"]))
681
tierno36ec8602018-11-02 17:27:11 +0100682 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200683 """
tierno36ec8602018-11-02 17:27:11 +0100684 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
685 (ip_address, ...) information.
686 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +0100687 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100688 :param rollback: list with the database modifications to rollback if needed
689 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
690 :param vim_account: vim_account where this vnfr should be deployed
691 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
692 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
693 of the changed vnfr is needed
694
695 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
696 "vim-network-name": used at VIM
697 "name": interface name
698 "vnf-vld-id": internal VNFD vld where this interface is connected, or
699 "ns-vld-id": NSD vld where this interface is connected.
700 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 +0200701 """
tierno36ec8602018-11-02 17:27:11 +0100702
703 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +0200704 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
705 if not vdur.get("pdu-type"):
706 continue
707 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +0100708 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +0100709 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +0200710 pdu_filter["type"] = pdu_type
711 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +0100712 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +0200713 # TODO feature 1417: "shared": True,
714
715 available_pdus = self.db.get_list("pdus", pdu_filter)
716 for pdu in available_pdus:
717 # step 1 check if this pdu contains needed interfaces:
718 match_interfaces = True
719 for vdur_interface in vdur["interfaces"]:
720 for pdu_interface in pdu["interfaces"]:
721 if pdu_interface["name"] == vdur_interface["name"]:
722 # TODO feature 1417: match per mgmt type
723 break
724 else: # no interface found for name
725 match_interfaces = False
726 break
727 if match_interfaces:
728 break
729 else:
730 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +0100731 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
732 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +0200733
734 # step 2. Update pdu
735 rollback_pdu = {
736 "_admin.usageState": pdu["_admin"]["usageState"],
737 "_admin.usage.vnfr_id": None,
738 "_admin.usage.nsr_id": None,
739 "_admin.usage.vdur": None,
740 }
741 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +0100742 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +0000743 "_admin.usage": {"vnfr_id": vnfr["_id"],
744 "nsr_id": vnfr["nsr-id-ref"],
745 "vdur": vdur["vdu-id-ref"]}
746 })
tiernocc103432018-10-19 14:10:35 +0200747 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
748
749 # step 3. Fill vnfr info by filling vdur
750 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +0100751 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +0200752 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
753 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
754 for pdu_interface in pdu["interfaces"]:
755 if pdu_interface["name"] == vdur_interface["name"]:
756 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
757 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +0100758 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
759 vnfr_update[iface_text + ".{}".format(k)] = v
760 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
761 if pdu_interface.get("ip-address"):
762 if vdur_interface.get("mgmt-interface"):
763 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
764 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
765 if vdur_interface.get("mgmt-vnf"):
766 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
767 vnfr_update["ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +0100768 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +0100769 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +0100770 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
771 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
772 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +0100773 if pdu_interface.get("vim-network-id"):
tiernoc67b0e92019-11-05 12:45:29 +0000774 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +0100775 if pdu_interface.get("vim-network-name"):
tiernoc67b0e92019-11-05 12:45:29 +0000776 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +0200777 break
778
tierno36ec8602018-11-02 17:27:11 +0100779 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +0200780
tierno9cb7d672019-10-30 12:13:48 +0000781 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
782 """
783 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
784 Fills vnfr.kdur with the selected k8scluster
785
786 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
787 :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 KDU 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
800 """
801
802 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +0000803 if not vnfr.get("kdur"):
804 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +0000805
tiernoc67b0e92019-11-05 12:45:29 +0000806 kdu_filter = self._get_project_filter(session)
807 kdu_filter["vim_account"] = vim_account
808 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
809 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
810
811 k8s_requirements = {} # just for logging
812 for k8scluster in available_k8sclusters:
813 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +0000814 break
tiernoc67b0e92019-11-05 12:45:29 +0000815 # restrict by cni
816 if vnfr["k8s-cluster"].get("cni"):
817 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
818 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
819 continue
820 # restrict by version
821 if vnfr["k8s-cluster"].get("version"):
822 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
823 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
824 continue
825 # restrict by number of networks
826 if vnfr["k8s-cluster"].get("nets"):
827 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
828 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
829 continue
830 break
831 else:
832 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
833 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
tierno9cb7d672019-10-30 12:13:48 +0000834
tiernoc67b0e92019-11-05 12:45:29 +0000835 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +0000836 # step 3. Fill vnfr info by filling kdur
837 kdu_text = "kdur.{}.".format(kdur_index)
838 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
839 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
840
tiernoc67b0e92019-11-05 12:45:29 +0000841 # step 4. Check VIM networks that forces the selected k8s_cluster
842 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
843 k8scluster_net_list = list(k8scluster.get("nets").keys())
844 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
845 # get a network from k8s_cluster nets. If name matches use this, if not use other
846 if kdur_net["id"] in k8scluster_net_list: # name matches
847 vim_net = k8scluster["nets"][kdur_net["id"]]
848 k8scluster_net_list.remove(kdur_net["id"])
849 else:
850 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
851 k8scluster_net_list.pop(0)
852 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
853 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
854 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
855 ifaces_forcing_vim_network.append({
856 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
857 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
858 "ns-vld-id": kdur_net.get("ns-vld-id"),
859 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
860 })
861 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +0000862 return ifaces_forcing_vim_network
863
tiernocc103432018-10-19 14:10:35 +0200864 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +0200865 # get vnfr
866 nsr_id = nsr["_id"]
867 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
868
869 for vnfr in vnfrs:
870 vnfr_update = {}
871 vnfr_update_rollback = {}
872 member_vnf_index = vnfr["member-vnf-index-ref"]
873 # update vim-account-id
874
875 vim_account = indata["vimAccountId"]
876 # check instantiate parameters
877 for vnf_inst_params in get_iterable(indata.get("vnf")):
878 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
879 continue
880 if vnf_inst_params.get("vimAccountId"):
881 vim_account = vnf_inst_params.get("vimAccountId")
882
883 vnfr_update["vim-account-id"] = vim_account
884 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
885
886 # get pdu
tierno36ec8602018-11-02 17:27:11 +0100887 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
888 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +0200889
tierno9cb7d672019-10-30 12:13:48 +0000890 # get kdus
891 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
892 vnfr_update_rollback)
893 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +0100894 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
895 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
896
897 # Update indada in case pdu forces to use a concrete vim-network-name
898 # TODO check if user has already insert a vim-network-name and raises an error
899 if not ifaces_forcing_vim_network:
900 continue
901 for iface_info in ifaces_forcing_vim_network:
902 if iface_info.get("ns-vld-id"):
903 if "vld" not in indata:
904 indata["vld"] = []
905 indata["vld"].append({key: iface_info[key] for key in
906 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
907
908 elif iface_info.get("vnf-vld-id"):
909 if "vnf" not in indata:
910 indata["vnf"] = []
911 indata["vnf"].append({
912 "member-vnf-index": member_vnf_index,
913 "internal-vld": [{key: iface_info[key] for key in
914 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
915 })
916
917 @staticmethod
918 def _create_nslcmop(nsr_id, operation, params):
919 """
920 Creates a ns-lcm-opp content to be stored at database.
921 :param nsr_id: internal id of the instance
922 :param operation: instantiate, terminate, scale, action, ...
923 :param params: user parameters for the operation
924 :return: dictionary following SOL005 format
925 """
tiernob24258a2018-10-04 18:39:49 +0200926 now = time()
927 _id = str(uuid4())
928 nslcmop = {
929 "id": _id,
930 "_id": _id,
931 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +0000932 "queuePosition": None,
933 "stage": None,
934 "errorMessage": None,
935 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +0200936 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +0100937 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200938 "lcmOperationType": operation,
939 "startTime": now,
940 "isAutomaticInvocation": False,
941 "operationParams": params,
942 "isCancelPending": False,
943 "links": {
944 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +0100945 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200946 }
947 }
948 return nslcmop
949
tierno65ca36d2019-02-12 19:27:52 +0100950 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +0200951 """
952 Performs a new operation over a ns
953 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100954 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200955 :param indata: descriptor with the parameters of the operation. It must contains among others
956 nsInstanceId: _id of the nsr to perform the operation
957 operation: it can be: instantiate, terminate, action, TODO: update, heal
958 :param kwargs: used to override the indata descriptor
959 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200960 :return: id of the nslcmops
961 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +0200962 def check_if_nsr_is_not_slice_member(session, nsr_id):
963 nsis = None
964 db_filter = self._get_project_filter(session)
965 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
966 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
967 if nsis:
968 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
969 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
970
tiernob24258a2018-10-04 18:39:49 +0200971 try:
972 # Override descriptor with query string kwargs
973 self._update_input_with_kwargs(indata, kwargs)
974 operation = indata["lcmOperationType"]
975 nsInstanceId = indata["nsInstanceId"]
976
977 validate_input(indata, self.operation_schema[operation])
978 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +0100979 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +0200980 _filter["_id"] = nsInstanceId
981 nsr = self.db.get_one("nsrs", _filter)
982
983 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +0200984 if operation == "terminate" and slice_object is False:
985 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +0200986 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
987 if operation == "terminate" and indata.get("autoremove"):
988 # NSR must be deleted
tierno586ae812019-10-17 13:56:53 +0000989 return None, None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +0200990 if operation != "instantiate":
991 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
992 nsInstanceId, operation), HTTPStatus.CONFLICT)
993 else:
tierno65ca36d2019-02-12 19:27:52 +0100994 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200995 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
996 nsInstanceId, operation), HTTPStatus.CONFLICT)
997 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +0100998
tiernocc103432018-10-19 14:10:35 +0200999 if operation == "instantiate":
1000 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01001001
1002 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00001003 _id = nslcmop_desc["_id"]
tierno65ca36d2019-02-12 19:27:52 +01001004 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
tierno1bfe4e22019-09-02 16:03:25 +00001005 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02001006 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001007 if not slice_object:
1008 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001009 return _id, None
1010 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02001011 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1012 # except DbException as e:
1013 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1014
tiernobee3bad2019-12-05 12:26:01 +00001015 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +02001016 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1017
tierno65ca36d2019-02-12 19:27:52 +01001018 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +02001019 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001020
1021
1022class NsiTopic(BaseTopic):
1023 topic = "nsis"
1024 topic_msg = "nsi"
1025
delacruzramo32bab472019-09-13 12:24:22 +02001026 def __init__(self, db, fs, msg, auth):
1027 BaseTopic.__init__(self, db, fs, msg, auth)
1028 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001029
Felipe Vicensc37b3842019-01-12 12:24:42 +01001030 @staticmethod
1031 def _format_ns_request(ns_request):
1032 formated_request = copy(ns_request)
1033 # TODO: Add request params
1034 return formated_request
1035
1036 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001037 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001038 """
1039 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001040 :param slice_request: User instantiation additional parameters
1041 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001042 """
tiernofd160572019-01-21 10:41:37 +00001043 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1044 if additional_params:
1045 for k, v in additional_params.items():
1046 if not isinstance(k, str):
1047 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1048 format(k))
1049 if "." in k or "$" in k:
1050 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1051 format(k))
1052 if isinstance(v, (dict, tuple, list)):
1053 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001054 return additional_params
1055
Felipe Vicensb57758d2018-10-16 16:00:20 +02001056 def _check_descriptor_dependencies(self, session, descriptor):
1057 """
1058 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001059 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001060 :param descriptor: descriptor to be inserted or edit
1061 :return: None or raises exception
1062 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001063 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001064 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001065 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001066 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +01001067 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +02001068 http_code=HTTPStatus.CONFLICT)
1069
tiernob4844ab2019-05-23 08:42:12 +00001070 def check_conflict_on_del(self, session, _id, db_content):
1071 """
1072 Check that NSI is not instantiated
1073 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1074 :param _id: nsi internal id
1075 :param db_content: The database content of the _id
1076 :return: None or raises EngineException with the conflict
1077 """
tierno65ca36d2019-02-12 19:27:52 +01001078 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02001079 return
tiernob4844ab2019-05-23 08:42:12 +00001080 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02001081 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1082 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1083 "Launch 'terminate' operation first; or force deletion".format(_id),
1084 http_code=HTTPStatus.CONFLICT)
1085
tiernobee3bad2019-12-05 12:26:01 +00001086 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001087 """
tiernob4844ab2019-05-23 08:42:12 +00001088 Deletes associated nsilcmops from database. Deletes associated filesystem.
1089 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01001090 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001091 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00001092 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00001093 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00001094 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02001095 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001096
Felipe Vicens09e65422019-01-22 15:06:46 +01001097 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00001098 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01001099 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1100 nsr_id = nsrs_detailed_item["nsrId"]
1101 if nsrs_detailed_item.get("shared"):
1102 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1103 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1104 "_id.ne": nsir["_id"]}
1105 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1106 if nsi: # last one using nsr
1107 continue
1108 try:
tiernobee3bad2019-12-05 12:26:01 +00001109 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
Felipe Vicens09e65422019-01-22 15:06:46 +01001110 except (DbException, EngineException) as e:
1111 if e.http_code == HTTPStatus.NOT_FOUND:
1112 pass
1113 else:
1114 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001115
tiernob4844ab2019-05-23 08:42:12 +00001116 # delete related nsilcmops database entries
1117 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001118
tiernob4844ab2019-05-23 08:42:12 +00001119 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01001120 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00001121 if nsir_admin and nsir_admin.get("nst-id"):
1122 # check if used by another NSI
1123 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1124 fail_on_empty=False, fail_on_more=False)
1125 if not nsis_list:
1126 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1127
1128 # def delete(self, session, _id, dry_run=False):
1129 # """
1130 # Delete item by its internal _id
1131 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1132 # :param _id: server internal id
1133 # :param dry_run: make checking but do not delete
1134 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1135 # """
1136 # # TODO add admin to filter, validate rights
1137 # BaseTopic.delete(self, session, _id, dry_run=True)
1138 # if dry_run:
1139 # return
1140 #
1141 # # Deleting the nsrs belonging to nsir
1142 # nsir = self.db.get_one("nsis", {"_id": _id})
1143 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1144 # nsr_id = nsrs_detailed_item["nsrId"]
1145 # if nsrs_detailed_item.get("shared"):
1146 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1147 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1148 # "_id.ne": nsir["_id"]}
1149 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1150 # if nsi: # last one using nsr
1151 # continue
1152 # try:
1153 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1154 # except (DbException, EngineException) as e:
1155 # if e.http_code == HTTPStatus.NOT_FOUND:
1156 # pass
1157 # else:
1158 # raise
1159 # # deletes NetSlice instance object
1160 # v = self.db.del_one("nsis", {"_id": _id})
1161 #
1162 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1163 # _filter = {"netsliceInstanceId": _id}
1164 # self.db.del_list("nsilcmops", _filter)
1165 #
1166 # # Search if nst is being used by other nsi
1167 # nsir_admin = nsir.get("_admin")
1168 # if nsir_admin:
1169 # if nsir_admin.get("nst-id"):
1170 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1171 # fail_on_empty=False, fail_on_more=False)
1172 # if not nsis_list:
1173 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1174 # return v
Felipe Vicensb57758d2018-10-16 16:00:20 +02001175
tierno65ca36d2019-02-12 19:27:52 +01001176 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001177 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001178 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02001179 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01001180 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001181 :param indata: params to be used for the nsir
1182 :param kwargs: used to override the indata descriptor
1183 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02001184 :return: the _id of nsi descriptor created at database
1185 """
1186
1187 try:
delacruzramo32bab472019-09-13 12:24:22 +02001188 step = "checking quotas"
1189 self.check_quota(session)
1190
tierno99d4b172019-07-02 09:28:40 +00001191 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02001192 slice_request = self._remove_envelop(indata)
1193 # Override descriptor with query string kwargs
1194 self._update_input_with_kwargs(slice_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001195 self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001196
Felipe Vicensb57758d2018-10-16 16:00:20 +02001197 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +00001198 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001199 _filter = self._get_project_filter(session)
1200 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001201 nstd = self.db.get_one("nsts", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001202 del _filter["_id"]
1203
Felipe Vicens07f31722018-10-29 15:16:44 +01001204 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001205 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001206 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001207 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001208
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001209 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001210 nsi_descriptor = {
1211 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001212 "name": slice_request["nsiName"],
1213 "description": slice_request.get("nsiDescription", ""),
1214 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001215 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001216 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001217 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001218 "nsr-ref-list": [],
1219 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001220 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001221 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001222 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001223
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001224 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001225 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001226 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1227 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001228 nsi_descriptor["_admin"]["deployed"] = {}
1229 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1230 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1231
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001232 # Creating netslice-vld for the RO.
1233 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001234
1235 # Building the vlds list to be deployed
1236 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001237 nsi_vlds = []
1238
1239 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1240 # Getting template Instantiation parameters from NST
1241 nsi_vld = deepcopy(netslice_vlds)
1242 nsi_vld["shared-nsrs-list"] = []
1243 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1244 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001245
1246 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00001247 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001248 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001249 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001250
Felipe Vicens09e65422019-01-22 15:06:46 +01001251 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001252 for member_ns in nstd["netslice-subnet"]:
1253 nsd_id = member_ns["nsd-ref"]
1254 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1255 member_ns["nsd-ref"], member_ns["id"])
1256 if nsd_id not in needed_nsds:
1257 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001258 _filter["id"] = nsd_id
1259 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1260 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001261 nsd.pop("_admin")
1262 needed_nsds[nsd_id] = nsd
1263 else:
1264 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001265 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1266 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001267
Felipe Vicensb57758d2018-10-16 16:00:20 +02001268 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1269 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001270
Felipe Vicens07f31722018-10-29 15:16:44 +01001271 # creates Network Services records (NSRs)
1272 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001273 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001274 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001275 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001276 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001277 # Check if the netslice-subnet is shared and if it is share if the nss exists
1278 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001279 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001280 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001281 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1282 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens08ddb142019-08-09 15:52:40 +02001283 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001284 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001285 if nsi and service.get("is-shared-nss"):
1286 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1287 for nsrs_detailed_item in nsrs_detailed_list:
1288 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02001289 if nsrs_detailed_item["nss-id"] == service["id"]:
1290 _id_nsr = nsrs_detailed_item["nsrId"]
1291 break
Felipe Vicens09e65422019-01-22 15:06:46 +01001292 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1293 if netslice_subnet["nss-id"] == service["id"]:
1294 indata_ns = netslice_subnet
1295 break
1296 else:
1297 indata_ns = {}
1298 if service.get("instantiation-parameters"):
1299 indata_ns = deepcopy(service["instantiation-parameters"])
1300 # del service["instantiation-parameters"]
1301
1302 indata_ns["nsdId"] = service["_id"]
1303 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1304 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1305 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001306 if slice_request.get("ssh_keys"):
1307 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001308
Felipe Vicens09e65422019-01-22 15:06:46 +01001309 if ns_params:
1310 for ns_param in ns_params:
1311 if ns_param.get("id") == service["id"]:
1312 copy_ns_param = deepcopy(ns_param)
1313 del copy_ns_param["id"]
1314 indata_ns.update(copy_ns_param)
1315 break
1316
1317 # Creates Nsr objects
tiernobdebce92019-07-01 15:36:49 +00001318 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001319 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
Felipe Vicens08ddb142019-08-09 15:52:40 +02001320 "nss-id": service["id"], "nslcmop_instantiate": None}
Felipe Vicens09e65422019-01-22 15:06:46 +01001321 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001322 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001323 nsi_netslice_subnet.append(indata_ns)
1324 nsr_ref = {"nsr-ref": _id_nsr}
1325 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001326
1327 # Adding the nsrs list to the nsi
1328 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001329 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001330 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1331
Felipe Vicens07f31722018-10-29 15:16:44 +01001332 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001333 self.db.create("nsis", nsi_descriptor)
1334 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00001335 return nsi_id, None
1336 except Exception as e: # TODO remove try Except, it is captured at nbi.py
Felipe Vicensb57758d2018-10-16 16:00:20 +02001337 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1338 raise EngineException("Error {}: {}".format(step, e))
1339 except ValidationError as e:
1340 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1341
tierno65ca36d2019-02-12 19:27:52 +01001342 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001343 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001344
1345
1346class NsiLcmOpTopic(BaseTopic):
1347 topic = "nsilcmops"
1348 topic_msg = "nsi"
1349 operation_schema = { # mapping between operation and jsonschema to validate
1350 "instantiate": nsi_instantiate,
1351 "terminate": None
1352 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001353
delacruzramo32bab472019-09-13 12:24:22 +02001354 def __init__(self, db, fs, msg, auth):
1355 BaseTopic.__init__(self, db, fs, msg, auth)
1356 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01001357
1358 def _check_nsi_operation(self, session, nsir, operation, indata):
1359 """
1360 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001361 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001362 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1363 :param indata: descriptor with the parameters of the operation
1364 :return: None
1365 """
1366 nsds = {}
1367 nstd = nsir["network-slice-template"]
1368
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001369 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001370 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001371 for netslice_subnet in nstd["netslice-subnet"]:
1372 if nstId == netslice_subnet["id"]:
1373 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001374 if nsd_id not in nsds:
1375 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1376 return nsds[nsd_id]
1377 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001378 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1379 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001380 if operation == "instantiate":
1381 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001382 for in_nst in get_iterable(indata.get("netslice-subnet")):
1383 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001384
1385 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1386 now = time()
1387 _id = str(uuid4())
1388 nsilcmop = {
1389 "id": _id,
1390 "_id": _id,
1391 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1392 "statusEnteredTime": now,
1393 "netsliceInstanceId": netsliceInstanceId,
1394 "lcmOperationType": operation,
1395 "startTime": now,
1396 "isAutomaticInvocation": False,
1397 "operationParams": params,
1398 "isCancelPending": False,
1399 "links": {
1400 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001401 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001402 }
1403 }
1404 return nsilcmop
1405
Felipe Vicens09e65422019-01-22 15:06:46 +01001406 def add_shared_nsr_2vld(self, nsir, nsr_item):
1407 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1408 if nst_sb_item.get("is-shared-nss"):
1409 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1410 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1411 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1412 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1413 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1414 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1415 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1416 break
1417 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1418 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1419
tierno65ca36d2019-02-12 19:27:52 +01001420 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001421 """
1422 Performs a new operation over a ns
1423 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001424 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001425 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001426 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001427 operation: it can be: instantiate, terminate, action, TODO: update, heal
1428 :param kwargs: used to override the indata descriptor
1429 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001430 :return: id of the nslcmops
1431 """
1432 try:
1433 # Override descriptor with query string kwargs
1434 self._update_input_with_kwargs(indata, kwargs)
1435 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001436 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001437 validate_input(indata, self.operation_schema[operation])
1438
Felipe Vicens126af572019-06-05 19:13:04 +02001439 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001440 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001441 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001442 nsir = self.db.get_one("nsis", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001443 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001444
1445 # initial checking
1446 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1447 if operation == "terminate" and indata.get("autoremove"):
1448 # NSIR must be deleted
tierno586ae812019-10-17 13:56:53 +00001449 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 +01001450 if operation != "instantiate":
1451 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001452 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001453 else:
tierno65ca36d2019-02-12 19:27:52 +01001454 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001455 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001456 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001457
1458 # Creating all the NS_operation (nslcmop)
1459 # Get service list from db
1460 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1461 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001462 # nslcmops_item = None
1463 for index, nsr_item in enumerate(nsrs_list):
1464 nsi = None
1465 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001466 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tiernob4844ab2019-05-23 08:42:12 +00001467 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1468 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001469 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001470 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001471 if operation == "terminate":
1472 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1473 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1474
Felipe Vicens09e65422019-01-22 15:06:46 +01001475 # looks the first nsi fulfilling the conditions but not being the current NSIR
1476 if nsi:
1477 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1478 for nsi_nsr_item in nsi_admin_shared:
1479 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1480 self.add_shared_nsr_2vld(nsir, nsr_item)
1481 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1482 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1483 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1484 break
1485 # continue to not create nslcmop since nsrs is shared and nsrs was created
1486 continue
1487 else:
1488 self.add_shared_nsr_2vld(nsir, nsr_item)
1489
1490 try:
1491 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1492 indata_ns = {}
1493 indata_ns = service["instantiate_params"]
1494 indata_ns["lcmOperationType"] = operation
1495 indata_ns["nsInstanceId"] = service["_id"]
1496 # Including netslice_id in the ns instantiate Operation
Felipe Vicens126af572019-06-05 19:13:04 +02001497 indata_ns["netsliceInstanceId"] = netsliceInstanceId
tierno99d4b172019-07-02 09:28:40 +00001498 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001499 # message via kafka bus
tiernobdebce92019-07-01 15:36:49 +00001500 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
1501 slice_object=True)
Felipe Vicens09e65422019-01-22 15:06:46 +01001502 nslcmops.append(nslcmop)
1503 if operation == "terminate":
1504 nslcmop = None
1505 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1506 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1507 except (DbException, EngineException) as e:
1508 if e.http_code == HTTPStatus.NOT_FOUND:
1509 self.logger.info("HTTPStatus.NOT_FOUND")
1510 pass
1511 else:
1512 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001513
1514 # Creates nsilcmop
1515 indata["nslcmops_ids"] = nslcmops
1516 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001517
Felipe Vicens126af572019-06-05 19:13:04 +02001518 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001519 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001520 _id = self.db.create("nsilcmops", nsilcmop_desc)
1521 rollback.append({"topic": "nsilcmops", "_id": _id})
1522 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001523 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01001524 except ValidationError as e:
1525 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001526
tiernobee3bad2019-12-05 12:26:01 +00001527 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001528 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1529
tierno65ca36d2019-02-12 19:27:52 +01001530 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001531 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)