blob: decb9c7da788fe0ba4a3d68590703fcb85b451d7 [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
tiernob4844ab2019-05-23 08:42:12 +000077 def delete_extra(self, session, _id, db_content):
78 """
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
84 :return: None if ok or raises EngineException with the problem
85 """
tiernobee085c2018-12-12 17:03:04 +000086 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +020087 self.db.del_list("nslcmops", {"nsInstanceId": _id})
88 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +000089
tiernob24258a2018-10-04 18:39:49 +020090 # set all used pdus as free
91 self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
tierno36ec8602018-11-02 17:27:11 +010092 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
tiernob24258a2018-10-04 18:39:49 +020093
tiernob4844ab2019-05-23 08:42:12 +000094 # Set NSD usageState
95 nsr = db_content
96 used_nsd_id = nsr.get("nsd-id")
97 if used_nsd_id:
98 # check if used by another NSR
99 nsrs_list = self.db.get_one("nsrs", {"nsd-id": used_nsd_id},
100 fail_on_empty=False, fail_on_more=False)
101 if not nsrs_list:
102 self.db.set_one("nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"})
103
104 # Set VNFD usageState
105 used_vnfd_id_list = nsr.get("vnfd-id")
106 if used_vnfd_id_list:
107 for used_vnfd_id in used_vnfd_id_list:
108 # check if used by another NSR
109 nsrs_list = self.db.get_one("nsrs", {"vnfd-id": used_vnfd_id},
110 fail_on_empty=False, fail_on_more=False)
111 if not nsrs_list:
112 self.db.set_one("vnfds", {"_id": used_vnfd_id}, {"_admin.usageState": "NOT_IN_USE"})
113
tiernobee085c2018-12-12 17:03:04 +0000114 @staticmethod
115 def _format_ns_request(ns_request):
116 formated_request = copy(ns_request)
117 formated_request.pop("additionalParamsForNs", None)
118 formated_request.pop("additionalParamsForVnf", None)
119 return formated_request
120
121 @staticmethod
tierno714954e2019-11-29 13:43:26 +0000122 def _format_addional_params(ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None):
tiernobee085c2018-12-12 17:03:04 +0000123 """
124 Get and format user additional params for NS or VNF
125 :param ns_request: User instantiation additional parameters
126 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
127 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno714954e2019-11-29 13:43:26 +0000128 :return: a formatted copy of additional params or None if not supplied
tiernobee085c2018-12-12 17:03:04 +0000129 """
130 additional_params = None
131 if not member_vnf_index:
132 additional_params = copy(ns_request.get("additionalParamsForNs"))
133 where_ = "additionalParamsForNs"
134 elif ns_request.get("additionalParamsForVnf"):
tierno714954e2019-11-29 13:43:26 +0000135 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index)
136 item = next((x for x in ns_request["additionalParamsForVnf"] if x["member-vnf-index"] == member_vnf_index),
137 None)
138 if item:
139 additional_params = copy(item.get("additionalParams")) or {}
140 if vdu_id and item.get("additionalParamsForVdu"):
141 item_vdu = next((x for x in item["additionalParamsForVdu"] if x["vdu_id"] == vdu_id), None)
142 if item_vdu and item_vdu.get("additionalParams"):
143 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000144 additional_params = item_vdu["additionalParams"]
145 if kdu_name:
146 additional_params = {}
147 if item.get("additionalParamsForKdu"):
148 item_kdu = next((x for x in item["additionalParamsForKdu"] if x["kdu_name"] == kdu_name), None)
149 if item_kdu and item_kdu.get("additionalParams"):
150 where_ += ".additionalParamsForKdu[kdu_name={}]".format(kdu_name)
151 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000152
tiernobee085c2018-12-12 17:03:04 +0000153 if additional_params:
154 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000155 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
156 if not kdu_name and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k):
delacruzramo36ffe552019-05-03 14:52:37 +0200157 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
158 "and underscores, and cannot start with a digit"
159 .format(where_, k))
160 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000161 if not isinstance(k, str):
162 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
163 if "." in k or "$" in k:
164 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
165 if isinstance(v, (dict, tuple, list)):
166 additional_params[k] = "!!yaml " + safe_dump(v)
167
168 if descriptor:
169 # check that enough parameters are supplied for the initial-config-primitive
170 # TODO: check for cloud-init
171 if member_vnf_index:
tierno714954e2019-11-29 13:43:26 +0000172 if kdu_name:
173 initial_primitives = None
174 elif vdu_id:
175 vdud = next(x for x in descriptor["vdu"] if x["id"] == vdu_id)
176 initial_primitives = deep_get(vdud, ("vdu-configuration", "initial-config-primitive"))
177 else:
178 initial_primitives = deep_get(descriptor, ("vnf-configuration", "initial-config-primitive"))
179 else:
180 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
tiernobee085c2018-12-12 17:03:04 +0000181
tierno714954e2019-11-29 13:43:26 +0000182 for initial_primitive in get_iterable(initial_primitives):
183 for param in get_iterable(initial_primitive.get("parameter")):
184 if param["value"].startswith("<") and param["value"].endswith(">"):
185 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
186 continue
187 if not additional_params or param["value"][1:-1] not in additional_params:
188 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
189 "initial-config-primitive[name={}] not supplied".
190 format(param["value"], descriptor["id"],
191 initial_primitive["name"]))
192
193 return additional_params or None
tiernobee085c2018-12-12 17:03:04 +0000194
tierno65ca36d2019-02-12 19:27:52 +0100195 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200196 """
197 Creates a new nsr into database. It also creates needed vnfrs
198 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100199 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200200 :param indata: params to be used for the nsr
201 :param kwargs: used to override the indata descriptor
202 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000203 :return: the _id of nsr descriptor created at database. Or an exception of type
204 EngineException, ValidationError, DbException, FsException, MsgException.
205 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200206 """
207
208 try:
delacruzramo32bab472019-09-13 12:24:22 +0200209 step = "checking quotas"
210 self.check_quota(session)
211
tierno99d4b172019-07-02 09:28:40 +0000212 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200213 ns_request = self._remove_envelop(indata)
214 # Override descriptor with query string kwargs
215 self._update_input_with_kwargs(ns_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100216 self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200217
tiernob24258a2018-10-04 18:39:49 +0200218 # look for nsr
219 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
tiernob4844ab2019-05-23 08:42:12 +0000220 _filter = self._get_project_filter(session)
221 _filter["_id"] = ns_request["nsdId"]
tiernob24258a2018-10-04 18:39:49 +0200222 nsd = self.db.get_one("nsds", _filter)
tiernob4844ab2019-05-23 08:42:12 +0000223 del _filter["_id"]
tiernob24258a2018-10-04 18:39:49 +0200224
225 nsr_id = str(uuid4())
tiernobee085c2018-12-12 17:03:04 +0000226
tiernob24258a2018-10-04 18:39:49 +0200227 now = time()
228 step = "filling nsr from input data"
229 nsr_descriptor = {
230 "name": ns_request["nsName"],
231 "name-ref": ns_request["nsName"],
232 "short-name": ns_request["nsName"],
233 "admin-status": "ENABLED",
234 "nsd": nsd,
235 "datacenter": ns_request["vimAccountId"],
236 "resource-orchestrator": "osmopenmano",
237 "description": ns_request.get("nsDescription", ""),
238 "constituent-vnfr-ref": [],
239
240 "operational-status": "init", # typedef ns-operational-
241 "config-status": "init", # typedef config-states
242 "detailed-status": "scheduled",
243
244 "orchestration-progress": {},
245 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
246
tierno65ca36d2019-02-12 19:27:52 +0100247 "create-time": now,
tiernob24258a2018-10-04 18:39:49 +0200248 "nsd-name-ref": nsd["name"],
249 "operational-events": [], # "id", "timestamp", "description", "event",
250 "nsd-ref": nsd["id"],
tiernof0637052019-03-07 16:26:47 +0000251 "nsd-id": nsd["_id"],
tiernob4844ab2019-05-23 08:42:12 +0000252 "vnfd-id": [],
tiernobee085c2018-12-12 17:03:04 +0000253 "instantiate_params": self._format_ns_request(ns_request),
tierno714954e2019-11-29 13:43:26 +0000254 "additionalParamsForNs": self._format_addional_params(ns_request, descriptor=nsd),
tiernob24258a2018-10-04 18:39:49 +0200255 "ns-instance-config-ref": nsr_id,
256 "id": nsr_id,
257 "_id": nsr_id,
258 # "input-parameter": xpath, value,
tierno99d4b172019-07-02 09:28:40 +0000259 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
tiernob24258a2018-10-04 18:39:49 +0200260 }
261 ns_request["nsr_id"] = nsr_id
tierno36ec8602018-11-02 17:27:11 +0100262 # Create vld
263 if nsd.get("vld"):
264 nsr_descriptor["vld"] = []
265 for nsd_vld in nsd.get("vld"):
266 nsr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100267 {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 +0200268
269 # Create VNFR
270 needed_vnfds = {}
gcalvino4f269dd2018-11-06 13:18:31 +0100271 for member_vnf in nsd.get("constituent-vnfd", ()):
tiernob24258a2018-10-04 18:39:49 +0200272 vnfd_id = member_vnf["vnfd-id-ref"]
273 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
274 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
275 if vnfd_id not in needed_vnfds:
276 # Obtain vnfd
tiernob4844ab2019-05-23 08:42:12 +0000277 _filter["id"] = vnfd_id
278 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
279 del _filter["id"]
tiernob24258a2018-10-04 18:39:49 +0200280 vnfd.pop("_admin")
281 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000282 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200283 else:
284 vnfd = needed_vnfds[vnfd_id]
285 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
286 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
287 vnfr_id = str(uuid4())
288 vnfr_descriptor = {
289 "id": vnfr_id,
290 "_id": vnfr_id,
291 "nsr-id-ref": nsr_id,
292 "member-vnf-index-ref": member_vnf["member-vnf-index"],
tiernobee085c2018-12-12 17:03:04 +0000293 "additionalParamsForVnf": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
tierno714954e2019-11-29 13:43:26 +0000294 descriptor=vnfd),
tiernob24258a2018-10-04 18:39:49 +0200295 "created-time": now,
296 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
297 "vnfd-ref": vnfd_id,
298 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
299 "vim-account-id": None,
300 "vdur": [],
301 "connection-point": [],
302 "ip-address": None, # mgmt-interface filled by LCM
303 }
tierno36ec8602018-11-02 17:27:11 +0100304
305 # Create vld
306 if vnfd.get("internal-vld"):
307 vnfr_descriptor["vld"] = []
308 for vnfd_vld in vnfd.get("internal-vld"):
309 vnfr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100310 {key: vnfd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in
311 vnfd_vld})
tierno36ec8602018-11-02 17:27:11 +0100312
313 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
tiernob24258a2018-10-04 18:39:49 +0200314 for cp in vnfd.get("connection-point", ()):
315 vnf_cp = {
316 "name": cp["name"],
317 "connection-point-id": cp.get("id"),
318 "id": cp.get("id"),
319 # "ip-address", "mac-address" # filled by LCM
320 # vim-id # TODO it would be nice having a vim port id
321 }
322 vnfr_descriptor["connection-point"].append(vnf_cp)
tierno9cb7d672019-10-30 12:13:48 +0000323
tiernoc67b0e92019-11-05 12:45:29 +0000324 # Create k8s-cluster information
325 if vnfd.get("k8s-cluster"):
326 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
327 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
328 if net.get("external-connection-point-ref"):
329 for nsd_vld in get_iterable(nsd.get("vld")):
330 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
331 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
332 net["external-connection-point-ref"] and \
333 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
334 net["ns-vld-id"] = nsd_vld["id"]
335 break
336 else:
337 continue
338 break
339 elif net.get("internal-connection-point-ref"):
340 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
341 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
342 if vnfd_ivld_icp.get("id-ref") == net["internal-connection-point-ref"]:
343 net["vnf-vld-id"] = vnfd_ivld["id"]
344 break
345 else:
346 continue
347 break
tierno9cb7d672019-10-30 12:13:48 +0000348 # update kdus
349 for kdu in get_iterable(vnfd.get("kdu")):
tierno714954e2019-11-29 13:43:26 +0000350 kdur = {x: kdu[x] for x in kdu if x in ("helm-chart", "juju-bundle")}
351 kdur["kdu-name"] = kdu["name"]
352 # TODO "name": "" Name of the VDU in the VIM
tierno3ffc7a42019-12-03 09:39:40 +0000353 kdur["ip-address"] = None # mgmt-interface filled by LCM
354 kdur["k8s-cluster"] = {}
tierno714954e2019-11-29 13:43:26 +0000355 kdur["additionalParams"] = self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
tierno3ffc7a42019-12-03 09:39:40 +0000356 kdu_name=kdu["name"], descriptor=vnfd)
tierno9cb7d672019-10-30 12:13:48 +0000357 if not vnfr_descriptor.get("kdur"):
358 vnfr_descriptor["kdur"] = []
359 vnfr_descriptor["kdur"].append(kdur)
360
gcalvinoe45aded2018-11-13 17:17:28 +0100361 for vdu in vnfd.get("vdu", ()):
tiernob24258a2018-10-04 18:39:49 +0200362 vdur = {
tiernob24258a2018-10-04 18:39:49 +0200363 "vdu-id-ref": vdu["id"],
364 # TODO "name": "" Name of the VDU in the VIM
365 "ip-address": None, # mgmt-interface filled by LCM
366 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
367 "internal-connection-point": [],
368 "interfaces": [],
tierno714954e2019-11-29 13:43:26 +0000369 "additionalParams": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
tierno3ffc7a42019-12-03 09:39:40 +0000370 vdu_id=vdu["id"], descriptor=vnfd)
tiernob24258a2018-10-04 18:39:49 +0200371 }
tiernocc103432018-10-19 14:10:35 +0200372 if vdu.get("pdu-type"):
373 vdur["pdu-type"] = vdu["pdu-type"]
tiernob24258a2018-10-04 18:39:49 +0200374 # TODO volumes: name, volume-id
375 for icp in vdu.get("internal-connection-point", ()):
376 vdu_icp = {
377 "id": icp["id"],
378 "connection-point-id": icp["id"],
379 "name": icp.get("name"),
380 # "ip-address", "mac-address" # filled by LCM
381 # vim-id # TODO it would be nice having a vim port id
382 }
383 vdur["internal-connection-point"].append(vdu_icp)
384 for iface in vdu.get("interface", ()):
385 vdu_iface = {
386 "name": iface.get("name"),
387 # "ip-address", "mac-address" # filled by LCM
388 # vim-id # TODO it would be nice having a vim port id
389 }
tierno36ec8602018-11-02 17:27:11 +0100390 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
391 vdu_iface["mgmt-vnf"] = True
tiernocc103432018-10-19 14:10:35 +0200392 if iface.get("mgmt-interface"):
tierno36ec8602018-11-02 17:27:11 +0100393 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
394
395 # look for network where this interface is connected
396 if iface.get("external-connection-point-ref"):
397 for nsd_vld in get_iterable(nsd.get("vld")):
398 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
399 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
400 iface["external-connection-point-ref"] and \
401 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
402 vdu_iface["ns-vld-id"] = nsd_vld["id"]
403 break
404 else:
405 continue
406 break
407 elif iface.get("internal-connection-point-ref"):
408 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
409 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
410 if vnfd_ivld_icp.get("id-ref") == iface["internal-connection-point-ref"]:
411 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
412 break
413 else:
414 continue
415 break
tiernocc103432018-10-19 14:10:35 +0200416
tiernob24258a2018-10-04 18:39:49 +0200417 vdur["interfaces"].append(vdu_iface)
tiernocc103432018-10-19 14:10:35 +0200418 count = vdu.get("count", 1)
419 if count is None:
420 count = 1
421 count = int(count) # TODO remove when descriptor serialized with payngbind
422 for index in range(0, count):
423 if index:
424 vdur = deepcopy(vdur)
425 vdur["_id"] = str(uuid4())
426 vdur["count-index"] = index
427 vnfr_descriptor["vdur"].append(vdur)
tiernob24258a2018-10-04 18:39:49 +0200428
429 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
430 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
431
432 # add at database
tiernobdebce92019-07-01 15:36:49 +0000433 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200434 self.db.create("vnfrs", vnfr_descriptor)
435 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
436 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
437
438 step = "creating nsr at database"
tierno65ca36d2019-02-12 19:27:52 +0100439 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200440 self.db.create("nsrs", nsr_descriptor)
441 rollback.append({"topic": "nsrs", "_id": nsr_id})
tiernobee085c2018-12-12 17:03:04 +0000442
443 step = "creating nsr temporal folder"
444 self.fs.mkdir(nsr_id)
445
tiernobdebce92019-07-01 15:36:49 +0000446 return nsr_id, None
tierno1bfe4e22019-09-02 16:03:25 +0000447 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
448 raise type(e)("{} while '{}".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200449
tierno65ca36d2019-02-12 19:27:52 +0100450 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200451 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
452
453
454class VnfrTopic(BaseTopic):
455 topic = "vnfrs"
456 topic_msg = None
457
delacruzramo32bab472019-09-13 12:24:22 +0200458 def __init__(self, db, fs, msg, auth):
459 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200460
tierno65ca36d2019-02-12 19:27:52 +0100461 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200462 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
463
tierno65ca36d2019-02-12 19:27:52 +0100464 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200465 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
466
tierno65ca36d2019-02-12 19:27:52 +0100467 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200468 # Not used because vnfrs are created and deleted by NsrTopic class directly
469 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
470
471
472class NsLcmOpTopic(BaseTopic):
473 topic = "nslcmops"
474 topic_msg = "ns"
475 operation_schema = { # mapping between operation and jsonschema to validate
476 "instantiate": ns_instantiate,
477 "action": ns_action,
478 "scale": ns_scale,
479 "terminate": None,
480 }
481
delacruzramo32bab472019-09-13 12:24:22 +0200482 def __init__(self, db, fs, msg, auth):
483 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200484
tiernob24258a2018-10-04 18:39:49 +0200485 def _check_ns_operation(self, session, nsr, operation, indata):
486 """
487 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100488 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200489 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
490 :param indata: descriptor with the parameters of the operation
491 :return: None
492 """
tierno982da4e2019-09-03 11:51:55 +0000493 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +0200494 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000495 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200496 nsd = nsr["nsd"]
497
498 def check_valid_vnf_member_index(member_vnf_index):
tierno982da4e2019-09-03 11:51:55 +0000499 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
500 if vnf_member_index_to_vnfd.get(member_vnf_index):
501 return vnf_member_index_to_vnfd[member_vnf_index]
502 vnfr = self.db.get_one("vnfrs",
503 {"nsr-id-ref": nsr["_id"], "member-vnf-index-ref": member_vnf_index},
504 fail_on_empty=False)
505 if not vnfr:
tiernob24258a2018-10-04 18:39:49 +0200506 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
507 "nsd:constituent-vnfd".format(member_vnf_index))
tierno982da4e2019-09-03 11:51:55 +0000508 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
509 if not vnfd:
510 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
511 format(vnfr["vnfd-id"]))
512 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
513 return vnfd
tiernob24258a2018-10-04 18:39:49 +0200514
tierno260dd6f2019-09-02 10:48:56 +0000515 def check_valid_vdu(vnfd, vdu_id):
516 for vdud in get_iterable(vnfd.get("vdu")):
517 if vdud["id"] == vdu_id:
518 return vdud
519 else:
520 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
521
tierno9cb7d672019-10-30 12:13:48 +0000522 def check_valid_kdu(vnfd, kdu_name):
523 for kdud in get_iterable(vnfd.get("kdu")):
524 if kdud["name"] == kdu_name:
525 return kdud
526 else:
527 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
528
gcalvino5e72d152018-10-23 11:46:57 +0200529 def _check_vnf_instantiation_params(in_vnfd, vnfd):
530
tierno40fbcad2018-10-26 10:58:15 +0200531 for in_vdu in get_iterable(in_vnfd.get("vdu")):
532 for vdu in get_iterable(vnfd.get("vdu")):
533 if in_vdu["id"] == vdu["id"]:
534 for volume in get_iterable(in_vdu.get("volume")):
535 for volumed in get_iterable(vdu.get("volumes")):
536 if volumed["name"] == volume["name"]:
537 break
538 else:
539 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
540 "volume:name='{}' is not present at vnfd:vdu:volumes list".
541 format(in_vnf["member-vnf-index"], in_vdu["id"],
542 volume["name"]))
543 for in_iface in get_iterable(in_vdu["interface"]):
544 for iface in get_iterable(vdu.get("interface")):
545 if in_iface["name"] == iface["name"]:
546 break
547 else:
548 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
549 "interface[name='{}'] is not present at vnfd:vdu:interface"
550 .format(in_vnf["member-vnf-index"], in_vdu["id"],
551 in_iface["name"]))
552 break
gcalvino5e72d152018-10-23 11:46:57 +0200553 else:
tierno40fbcad2018-10-26 10:58:15 +0200554 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
555 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200556
557 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
558 for ivld in get_iterable(vnfd.get("internal-vld")):
559 if in_ivld["name"] == ivld["name"] or in_ivld["name"] == ivld["id"]:
tierno1bfe4e22019-09-02 16:03:25 +0000560 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
gcalvino5e72d152018-10-23 11:46:57 +0200561 for icp in ivld["internal-connection-point"]:
562 if in_icp["id-ref"] == icp["id-ref"]:
563 break
564 else:
tierno40fbcad2018-10-26 10:58:15 +0200565 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
566 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
567 "vnfd:internal-vld:name/id:internal-connection-point"
568 .format(in_vnf["member-vnf-index"], in_ivld["name"],
569 in_icp["id-ref"], vnfd["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200570 break
571 else:
572 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
573 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
574 in_ivld["name"], vnfd["id"]))
575
tiernob24258a2018-10-04 18:39:49 +0200576 def check_valid_vim_account(vim_account):
577 if vim_account in vim_accounts:
578 return
579 try:
tierno65ca36d2019-02-12 19:27:52 +0100580 db_filter = self._get_project_filter(session)
tiernocc103432018-10-19 14:10:35 +0200581 db_filter["_id"] = vim_account
582 self.db.get_one("vim_accounts", db_filter)
tiernob24258a2018-10-04 18:39:49 +0200583 except Exception:
tiernocc103432018-10-19 14:10:35 +0200584 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
tiernob24258a2018-10-04 18:39:49 +0200585 vim_accounts.append(vim_account)
586
tierno4f9d4ae2019-03-20 17:24:11 +0000587 def check_valid_wim_account(wim_account):
588 if not isinstance(wim_account, str):
589 return
590 elif wim_account in wim_accounts:
591 return
592 try:
593 db_filter = self._get_project_filter(session, write=False, show_all=True)
594 db_filter["_id"] = wim_account
595 self.db.get_one("wim_accounts", db_filter)
596 except Exception:
597 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
598 wim_accounts.append(wim_account)
599
tiernob24258a2018-10-04 18:39:49 +0200600 if operation == "action":
601 # check vnf_member_index
602 if indata.get("vnf_member_index"):
603 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
tierno1ac7f462019-06-03 17:22:12 +0000604 if indata.get("member_vnf_index"):
605 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
tierno260dd6f2019-09-02 10:48:56 +0000606 if indata.get("vdu_id"):
607 vdud = check_valid_vdu(vnfd, indata["vdu_id"])
608 descriptor_configuration = vdud.get("vdu-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000609 elif indata.get("kdu_name"):
tiernoc67b0e92019-11-05 12:45:29 +0000610 kdud = check_valid_kdu(vnfd, indata["kdu_name"])
tierno9cb7d672019-10-30 12:13:48 +0000611 descriptor_configuration = kdud.get("kdu-configuration", {}).get("config-primitive")
tierno260dd6f2019-09-02 10:48:56 +0000612 else:
613 descriptor_configuration = vnfd.get("vnf-configuration", {}).get("config-primitive")
tierno1ac7f462019-06-03 17:22:12 +0000614 else: # use a NSD
615 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000616
617 # For k8s allows default primitives without validating the parameters
delacruzramo6ddff2e2019-11-28 11:24:09 +0100618 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
tierno9cb7d672019-10-30 12:13:48 +0000619 # TODO should be checked that rollback only can contains revsision_numbe????
delacruzramo6ddff2e2019-11-28 11:24:09 +0100620 if not indata.get("member_vnf_index"):
621 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
622 .format(indata["primitive"]))
tierno9cb7d672019-10-30 12:13:48 +0000623 return
624 # if not, check primitive
tierno1ac7f462019-06-03 17:22:12 +0000625 for config_primitive in get_iterable(descriptor_configuration):
tiernob24258a2018-10-04 18:39:49 +0200626 if indata["primitive"] == config_primitive["name"]:
627 # check needed primitive_params are provided
628 if indata.get("primitive_params"):
629 in_primitive_params_copy = copy(indata["primitive_params"])
630 else:
631 in_primitive_params_copy = {}
632 for paramd in get_iterable(config_primitive.get("parameter")):
633 if paramd["name"] in in_primitive_params_copy:
634 del in_primitive_params_copy[paramd["name"]]
635 elif not paramd.get("default-value"):
636 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
637 paramd["name"], indata["primitive"]))
638 # check no extra primitive params are provided
639 if in_primitive_params_copy:
tierno1ac7f462019-06-03 17:22:12 +0000640 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
tiernob24258a2018-10-04 18:39:49 +0200641 list(in_primitive_params_copy.keys()), indata["primitive"]))
642 break
643 else:
tierno1ac7f462019-06-03 17:22:12 +0000644 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
tiernob24258a2018-10-04 18:39:49 +0200645 if operation == "scale":
646 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
647 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
648 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
649 break
650 else:
651 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
652 "present at vnfd:scaling-group-descriptor".format(
653 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
654 if operation == "instantiate":
655 # check vim_account
656 check_valid_vim_account(indata["vimAccountId"])
tierno4f9d4ae2019-03-20 17:24:11 +0000657 check_valid_wim_account(indata.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200658 for in_vnf in get_iterable(indata.get("vnf")):
659 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
gcalvino5e72d152018-10-23 11:46:57 +0200660 _check_vnf_instantiation_params(in_vnf, vnfd)
tiernob24258a2018-10-04 18:39:49 +0200661 if in_vnf.get("vimAccountId"):
662 check_valid_vim_account(in_vnf["vimAccountId"])
tiernob24258a2018-10-04 18:39:49 +0200663
tiernob24258a2018-10-04 18:39:49 +0200664 for in_vld in get_iterable(indata.get("vld")):
tierno4f9d4ae2019-03-20 17:24:11 +0000665 check_valid_wim_account(in_vld.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200666 for vldd in get_iterable(nsd.get("vld")):
667 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
668 break
669 else:
670 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
671 in_vld["name"]))
672
tierno36ec8602018-11-02 17:27:11 +0100673 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200674 """
tierno36ec8602018-11-02 17:27:11 +0100675 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
676 (ip_address, ...) information.
677 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +0100678 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100679 :param rollback: list with the database modifications to rollback if needed
680 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
681 :param vim_account: vim_account where this vnfr should be deployed
682 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
683 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
684 of the changed vnfr is needed
685
686 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
687 "vim-network-name": used at VIM
688 "name": interface name
689 "vnf-vld-id": internal VNFD vld where this interface is connected, or
690 "ns-vld-id": NSD vld where this interface is connected.
691 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 +0200692 """
tierno36ec8602018-11-02 17:27:11 +0100693
694 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +0200695 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
696 if not vdur.get("pdu-type"):
697 continue
698 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +0100699 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +0100700 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +0200701 pdu_filter["type"] = pdu_type
702 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +0100703 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +0200704 # TODO feature 1417: "shared": True,
705
706 available_pdus = self.db.get_list("pdus", pdu_filter)
707 for pdu in available_pdus:
708 # step 1 check if this pdu contains needed interfaces:
709 match_interfaces = True
710 for vdur_interface in vdur["interfaces"]:
711 for pdu_interface in pdu["interfaces"]:
712 if pdu_interface["name"] == vdur_interface["name"]:
713 # TODO feature 1417: match per mgmt type
714 break
715 else: # no interface found for name
716 match_interfaces = False
717 break
718 if match_interfaces:
719 break
720 else:
721 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +0100722 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
723 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +0200724
725 # step 2. Update pdu
726 rollback_pdu = {
727 "_admin.usageState": pdu["_admin"]["usageState"],
728 "_admin.usage.vnfr_id": None,
729 "_admin.usage.nsr_id": None,
730 "_admin.usage.vdur": None,
731 }
732 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +0100733 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +0000734 "_admin.usage": {"vnfr_id": vnfr["_id"],
735 "nsr_id": vnfr["nsr-id-ref"],
736 "vdur": vdur["vdu-id-ref"]}
737 })
tiernocc103432018-10-19 14:10:35 +0200738 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
739
740 # step 3. Fill vnfr info by filling vdur
741 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +0100742 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +0200743 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
744 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
745 for pdu_interface in pdu["interfaces"]:
746 if pdu_interface["name"] == vdur_interface["name"]:
747 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
748 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +0100749 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
750 vnfr_update[iface_text + ".{}".format(k)] = v
751 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
752 if pdu_interface.get("ip-address"):
753 if vdur_interface.get("mgmt-interface"):
754 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
755 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
756 if vdur_interface.get("mgmt-vnf"):
757 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
758 vnfr_update["ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +0100759 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +0100760 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +0100761 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
762 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
763 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +0100764 if pdu_interface.get("vim-network-id"):
tiernoc67b0e92019-11-05 12:45:29 +0000765 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +0100766 if pdu_interface.get("vim-network-name"):
tiernoc67b0e92019-11-05 12:45:29 +0000767 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +0200768 break
769
tierno36ec8602018-11-02 17:27:11 +0100770 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +0200771
tierno9cb7d672019-10-30 12:13:48 +0000772 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
773 """
774 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
775 Fills vnfr.kdur with the selected k8scluster
776
777 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
778 :param rollback: list with the database modifications to rollback if needed
779 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
780 :param vim_account: vim_account where this vnfr should be deployed
781 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
782 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
783 of the changed vnfr is needed
784
785 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
786 "vim-network-name": used at VIM
787 "name": interface name
788 "vnf-vld-id": internal VNFD vld where this interface is connected, or
789 "ns-vld-id": NSD vld where this interface is connected.
790 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
791 """
792
793 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +0000794 if not vnfr.get("kdur"):
795 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +0000796
tiernoc67b0e92019-11-05 12:45:29 +0000797 kdu_filter = self._get_project_filter(session)
798 kdu_filter["vim_account"] = vim_account
799 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
800 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
801
802 k8s_requirements = {} # just for logging
803 for k8scluster in available_k8sclusters:
804 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +0000805 break
tiernoc67b0e92019-11-05 12:45:29 +0000806 # restrict by cni
807 if vnfr["k8s-cluster"].get("cni"):
808 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
809 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
810 continue
811 # restrict by version
812 if vnfr["k8s-cluster"].get("version"):
813 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
814 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
815 continue
816 # restrict by number of networks
817 if vnfr["k8s-cluster"].get("nets"):
818 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
819 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
820 continue
821 break
822 else:
823 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
824 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
tierno9cb7d672019-10-30 12:13:48 +0000825
tiernoc67b0e92019-11-05 12:45:29 +0000826 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +0000827 # step 3. Fill vnfr info by filling kdur
828 kdu_text = "kdur.{}.".format(kdur_index)
829 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
830 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
831
tiernoc67b0e92019-11-05 12:45:29 +0000832 # step 4. Check VIM networks that forces the selected k8s_cluster
833 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
834 k8scluster_net_list = list(k8scluster.get("nets").keys())
835 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
836 # get a network from k8s_cluster nets. If name matches use this, if not use other
837 if kdur_net["id"] in k8scluster_net_list: # name matches
838 vim_net = k8scluster["nets"][kdur_net["id"]]
839 k8scluster_net_list.remove(kdur_net["id"])
840 else:
841 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
842 k8scluster_net_list.pop(0)
843 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
844 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
845 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
846 ifaces_forcing_vim_network.append({
847 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
848 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
849 "ns-vld-id": kdur_net.get("ns-vld-id"),
850 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
851 })
852 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +0000853 return ifaces_forcing_vim_network
854
tiernocc103432018-10-19 14:10:35 +0200855 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +0200856 # get vnfr
857 nsr_id = nsr["_id"]
858 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
859
860 for vnfr in vnfrs:
861 vnfr_update = {}
862 vnfr_update_rollback = {}
863 member_vnf_index = vnfr["member-vnf-index-ref"]
864 # update vim-account-id
865
866 vim_account = indata["vimAccountId"]
867 # check instantiate parameters
868 for vnf_inst_params in get_iterable(indata.get("vnf")):
869 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
870 continue
871 if vnf_inst_params.get("vimAccountId"):
872 vim_account = vnf_inst_params.get("vimAccountId")
873
874 vnfr_update["vim-account-id"] = vim_account
875 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
876
877 # get pdu
tierno36ec8602018-11-02 17:27:11 +0100878 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
879 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +0200880
tierno9cb7d672019-10-30 12:13:48 +0000881 # get kdus
882 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
883 vnfr_update_rollback)
884 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +0100885 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
886 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
887
888 # Update indada in case pdu forces to use a concrete vim-network-name
889 # TODO check if user has already insert a vim-network-name and raises an error
890 if not ifaces_forcing_vim_network:
891 continue
892 for iface_info in ifaces_forcing_vim_network:
893 if iface_info.get("ns-vld-id"):
894 if "vld" not in indata:
895 indata["vld"] = []
896 indata["vld"].append({key: iface_info[key] for key in
897 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
898
899 elif iface_info.get("vnf-vld-id"):
900 if "vnf" not in indata:
901 indata["vnf"] = []
902 indata["vnf"].append({
903 "member-vnf-index": member_vnf_index,
904 "internal-vld": [{key: iface_info[key] for key in
905 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
906 })
907
908 @staticmethod
909 def _create_nslcmop(nsr_id, operation, params):
910 """
911 Creates a ns-lcm-opp content to be stored at database.
912 :param nsr_id: internal id of the instance
913 :param operation: instantiate, terminate, scale, action, ...
914 :param params: user parameters for the operation
915 :return: dictionary following SOL005 format
916 """
tiernob24258a2018-10-04 18:39:49 +0200917 now = time()
918 _id = str(uuid4())
919 nslcmop = {
920 "id": _id,
921 "_id": _id,
922 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
923 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +0100924 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200925 "lcmOperationType": operation,
926 "startTime": now,
927 "isAutomaticInvocation": False,
928 "operationParams": params,
929 "isCancelPending": False,
930 "links": {
931 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +0100932 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200933 }
934 }
935 return nslcmop
936
tierno65ca36d2019-02-12 19:27:52 +0100937 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +0200938 """
939 Performs a new operation over a ns
940 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100941 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200942 :param indata: descriptor with the parameters of the operation. It must contains among others
943 nsInstanceId: _id of the nsr to perform the operation
944 operation: it can be: instantiate, terminate, action, TODO: update, heal
945 :param kwargs: used to override the indata descriptor
946 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200947 :return: id of the nslcmops
948 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +0200949 def check_if_nsr_is_not_slice_member(session, nsr_id):
950 nsis = None
951 db_filter = self._get_project_filter(session)
952 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
953 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
954 if nsis:
955 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
956 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
957
tiernob24258a2018-10-04 18:39:49 +0200958 try:
959 # Override descriptor with query string kwargs
960 self._update_input_with_kwargs(indata, kwargs)
961 operation = indata["lcmOperationType"]
962 nsInstanceId = indata["nsInstanceId"]
963
964 validate_input(indata, self.operation_schema[operation])
965 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +0100966 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +0200967 _filter["_id"] = nsInstanceId
968 nsr = self.db.get_one("nsrs", _filter)
969
970 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +0200971 if operation == "terminate" and slice_object is False:
972 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +0200973 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
974 if operation == "terminate" and indata.get("autoremove"):
975 # NSR must be deleted
tierno586ae812019-10-17 13:56:53 +0000976 return None, None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +0200977 if operation != "instantiate":
978 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
979 nsInstanceId, operation), HTTPStatus.CONFLICT)
980 else:
tierno65ca36d2019-02-12 19:27:52 +0100981 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200982 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
983 nsInstanceId, operation), HTTPStatus.CONFLICT)
984 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +0100985
tiernocc103432018-10-19 14:10:35 +0200986 if operation == "instantiate":
987 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +0100988
989 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +0000990 _id = nslcmop_desc["_id"]
tierno65ca36d2019-02-12 19:27:52 +0100991 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
tierno1bfe4e22019-09-02 16:03:25 +0000992 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +0200993 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +0100994 if not slice_object:
995 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +0000996 return _id, None
997 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +0200998 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
999 # except DbException as e:
1000 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1001
tierno65ca36d2019-02-12 19:27:52 +01001002 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +02001003 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1004
tierno65ca36d2019-02-12 19:27:52 +01001005 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +02001006 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001007
1008
1009class NsiTopic(BaseTopic):
1010 topic = "nsis"
1011 topic_msg = "nsi"
1012
delacruzramo32bab472019-09-13 12:24:22 +02001013 def __init__(self, db, fs, msg, auth):
1014 BaseTopic.__init__(self, db, fs, msg, auth)
1015 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001016
Felipe Vicensc37b3842019-01-12 12:24:42 +01001017 @staticmethod
1018 def _format_ns_request(ns_request):
1019 formated_request = copy(ns_request)
1020 # TODO: Add request params
1021 return formated_request
1022
1023 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001024 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001025 """
1026 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001027 :param slice_request: User instantiation additional parameters
1028 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001029 """
tiernofd160572019-01-21 10:41:37 +00001030 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1031 if additional_params:
1032 for k, v in additional_params.items():
1033 if not isinstance(k, str):
1034 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1035 format(k))
1036 if "." in k or "$" in k:
1037 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1038 format(k))
1039 if isinstance(v, (dict, tuple, list)):
1040 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001041 return additional_params
1042
Felipe Vicensb57758d2018-10-16 16:00:20 +02001043 def _check_descriptor_dependencies(self, session, descriptor):
1044 """
1045 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001046 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001047 :param descriptor: descriptor to be inserted or edit
1048 :return: None or raises exception
1049 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001050 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001051 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001052 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001053 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +01001054 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +02001055 http_code=HTTPStatus.CONFLICT)
1056
tiernob4844ab2019-05-23 08:42:12 +00001057 def check_conflict_on_del(self, session, _id, db_content):
1058 """
1059 Check that NSI is not instantiated
1060 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1061 :param _id: nsi internal id
1062 :param db_content: The database content of the _id
1063 :return: None or raises EngineException with the conflict
1064 """
tierno65ca36d2019-02-12 19:27:52 +01001065 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02001066 return
tiernob4844ab2019-05-23 08:42:12 +00001067 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02001068 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1069 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1070 "Launch 'terminate' operation first; or force deletion".format(_id),
1071 http_code=HTTPStatus.CONFLICT)
1072
tiernob4844ab2019-05-23 08:42:12 +00001073 def delete_extra(self, session, _id, db_content):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001074 """
tiernob4844ab2019-05-23 08:42:12 +00001075 Deletes associated nsilcmops from database. Deletes associated filesystem.
1076 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01001077 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001078 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00001079 :param db_content: The database content of the descriptor
1080 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02001081 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001082
Felipe Vicens09e65422019-01-22 15:06:46 +01001083 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00001084 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01001085 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1086 nsr_id = nsrs_detailed_item["nsrId"]
1087 if nsrs_detailed_item.get("shared"):
1088 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1089 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1090 "_id.ne": nsir["_id"]}
1091 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1092 if nsi: # last one using nsr
1093 continue
1094 try:
tierno65ca36d2019-02-12 19:27:52 +01001095 self.nsrTopic.delete(session, nsr_id, dry_run=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001096 except (DbException, EngineException) as e:
1097 if e.http_code == HTTPStatus.NOT_FOUND:
1098 pass
1099 else:
1100 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001101
tiernob4844ab2019-05-23 08:42:12 +00001102 # delete related nsilcmops database entries
1103 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001104
tiernob4844ab2019-05-23 08:42:12 +00001105 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01001106 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00001107 if nsir_admin and nsir_admin.get("nst-id"):
1108 # check if used by another NSI
1109 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1110 fail_on_empty=False, fail_on_more=False)
1111 if not nsis_list:
1112 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1113
1114 # def delete(self, session, _id, dry_run=False):
1115 # """
1116 # Delete item by its internal _id
1117 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1118 # :param _id: server internal id
1119 # :param dry_run: make checking but do not delete
1120 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1121 # """
1122 # # TODO add admin to filter, validate rights
1123 # BaseTopic.delete(self, session, _id, dry_run=True)
1124 # if dry_run:
1125 # return
1126 #
1127 # # Deleting the nsrs belonging to nsir
1128 # nsir = self.db.get_one("nsis", {"_id": _id})
1129 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1130 # nsr_id = nsrs_detailed_item["nsrId"]
1131 # if nsrs_detailed_item.get("shared"):
1132 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1133 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1134 # "_id.ne": nsir["_id"]}
1135 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1136 # if nsi: # last one using nsr
1137 # continue
1138 # try:
1139 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1140 # except (DbException, EngineException) as e:
1141 # if e.http_code == HTTPStatus.NOT_FOUND:
1142 # pass
1143 # else:
1144 # raise
1145 # # deletes NetSlice instance object
1146 # v = self.db.del_one("nsis", {"_id": _id})
1147 #
1148 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1149 # _filter = {"netsliceInstanceId": _id}
1150 # self.db.del_list("nsilcmops", _filter)
1151 #
1152 # # Search if nst is being used by other nsi
1153 # nsir_admin = nsir.get("_admin")
1154 # if nsir_admin:
1155 # if nsir_admin.get("nst-id"):
1156 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1157 # fail_on_empty=False, fail_on_more=False)
1158 # if not nsis_list:
1159 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1160 # return v
Felipe Vicensb57758d2018-10-16 16:00:20 +02001161
tierno65ca36d2019-02-12 19:27:52 +01001162 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001163 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001164 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02001165 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01001166 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001167 :param indata: params to be used for the nsir
1168 :param kwargs: used to override the indata descriptor
1169 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02001170 :return: the _id of nsi descriptor created at database
1171 """
1172
1173 try:
delacruzramo32bab472019-09-13 12:24:22 +02001174 step = "checking quotas"
1175 self.check_quota(session)
1176
tierno99d4b172019-07-02 09:28:40 +00001177 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02001178 slice_request = self._remove_envelop(indata)
1179 # Override descriptor with query string kwargs
1180 self._update_input_with_kwargs(slice_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001181 self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001182
Felipe Vicensb57758d2018-10-16 16:00:20 +02001183 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +00001184 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001185 _filter = self._get_project_filter(session)
1186 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001187 nstd = self.db.get_one("nsts", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001188 del _filter["_id"]
1189
Felipe Vicens07f31722018-10-29 15:16:44 +01001190 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001191 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001192 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001193 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001194
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001195 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001196 nsi_descriptor = {
1197 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001198 "name": slice_request["nsiName"],
1199 "description": slice_request.get("nsiDescription", ""),
1200 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001201 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001202 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001203 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001204 "nsr-ref-list": [],
1205 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001206 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001207 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001208 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001209
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001210 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001211 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001212 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1213 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001214 nsi_descriptor["_admin"]["deployed"] = {}
1215 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1216 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1217
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001218 # Creating netslice-vld for the RO.
1219 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001220
1221 # Building the vlds list to be deployed
1222 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001223 nsi_vlds = []
1224
1225 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1226 # Getting template Instantiation parameters from NST
1227 nsi_vld = deepcopy(netslice_vlds)
1228 nsi_vld["shared-nsrs-list"] = []
1229 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1230 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001231
1232 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00001233 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001234 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001235 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001236
Felipe Vicens09e65422019-01-22 15:06:46 +01001237 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001238 for member_ns in nstd["netslice-subnet"]:
1239 nsd_id = member_ns["nsd-ref"]
1240 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1241 member_ns["nsd-ref"], member_ns["id"])
1242 if nsd_id not in needed_nsds:
1243 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001244 _filter["id"] = nsd_id
1245 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1246 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001247 nsd.pop("_admin")
1248 needed_nsds[nsd_id] = nsd
1249 else:
1250 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001251 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1252 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001253
Felipe Vicensb57758d2018-10-16 16:00:20 +02001254 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1255 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001256
Felipe Vicens07f31722018-10-29 15:16:44 +01001257 # creates Network Services records (NSRs)
1258 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001259 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001260 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001261 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001262 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001263 # Check if the netslice-subnet is shared and if it is share if the nss exists
1264 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001265 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001266 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001267 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1268 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens08ddb142019-08-09 15:52:40 +02001269 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001270 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001271 if nsi and service.get("is-shared-nss"):
1272 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1273 for nsrs_detailed_item in nsrs_detailed_list:
1274 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02001275 if nsrs_detailed_item["nss-id"] == service["id"]:
1276 _id_nsr = nsrs_detailed_item["nsrId"]
1277 break
Felipe Vicens09e65422019-01-22 15:06:46 +01001278 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1279 if netslice_subnet["nss-id"] == service["id"]:
1280 indata_ns = netslice_subnet
1281 break
1282 else:
1283 indata_ns = {}
1284 if service.get("instantiation-parameters"):
1285 indata_ns = deepcopy(service["instantiation-parameters"])
1286 # del service["instantiation-parameters"]
1287
1288 indata_ns["nsdId"] = service["_id"]
1289 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1290 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1291 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001292 if slice_request.get("ssh_keys"):
1293 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001294
Felipe Vicens09e65422019-01-22 15:06:46 +01001295 if ns_params:
1296 for ns_param in ns_params:
1297 if ns_param.get("id") == service["id"]:
1298 copy_ns_param = deepcopy(ns_param)
1299 del copy_ns_param["id"]
1300 indata_ns.update(copy_ns_param)
1301 break
1302
1303 # Creates Nsr objects
tiernobdebce92019-07-01 15:36:49 +00001304 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001305 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
Felipe Vicens08ddb142019-08-09 15:52:40 +02001306 "nss-id": service["id"], "nslcmop_instantiate": None}
Felipe Vicens09e65422019-01-22 15:06:46 +01001307 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001308 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001309 nsi_netslice_subnet.append(indata_ns)
1310 nsr_ref = {"nsr-ref": _id_nsr}
1311 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001312
1313 # Adding the nsrs list to the nsi
1314 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001315 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001316 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1317
Felipe Vicens07f31722018-10-29 15:16:44 +01001318 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001319 self.db.create("nsis", nsi_descriptor)
1320 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00001321 return nsi_id, None
1322 except Exception as e: # TODO remove try Except, it is captured at nbi.py
Felipe Vicensb57758d2018-10-16 16:00:20 +02001323 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1324 raise EngineException("Error {}: {}".format(step, e))
1325 except ValidationError as e:
1326 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1327
tierno65ca36d2019-02-12 19:27:52 +01001328 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001329 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001330
1331
1332class NsiLcmOpTopic(BaseTopic):
1333 topic = "nsilcmops"
1334 topic_msg = "nsi"
1335 operation_schema = { # mapping between operation and jsonschema to validate
1336 "instantiate": nsi_instantiate,
1337 "terminate": None
1338 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001339
delacruzramo32bab472019-09-13 12:24:22 +02001340 def __init__(self, db, fs, msg, auth):
1341 BaseTopic.__init__(self, db, fs, msg, auth)
1342 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01001343
1344 def _check_nsi_operation(self, session, nsir, operation, indata):
1345 """
1346 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001347 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001348 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1349 :param indata: descriptor with the parameters of the operation
1350 :return: None
1351 """
1352 nsds = {}
1353 nstd = nsir["network-slice-template"]
1354
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001355 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001356 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001357 for netslice_subnet in nstd["netslice-subnet"]:
1358 if nstId == netslice_subnet["id"]:
1359 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001360 if nsd_id not in nsds:
1361 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1362 return nsds[nsd_id]
1363 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001364 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1365 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001366 if operation == "instantiate":
1367 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001368 for in_nst in get_iterable(indata.get("netslice-subnet")):
1369 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001370
1371 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1372 now = time()
1373 _id = str(uuid4())
1374 nsilcmop = {
1375 "id": _id,
1376 "_id": _id,
1377 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1378 "statusEnteredTime": now,
1379 "netsliceInstanceId": netsliceInstanceId,
1380 "lcmOperationType": operation,
1381 "startTime": now,
1382 "isAutomaticInvocation": False,
1383 "operationParams": params,
1384 "isCancelPending": False,
1385 "links": {
1386 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001387 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001388 }
1389 }
1390 return nsilcmop
1391
Felipe Vicens09e65422019-01-22 15:06:46 +01001392 def add_shared_nsr_2vld(self, nsir, nsr_item):
1393 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1394 if nst_sb_item.get("is-shared-nss"):
1395 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1396 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1397 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1398 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1399 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1400 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1401 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1402 break
1403 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1404 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1405
tierno65ca36d2019-02-12 19:27:52 +01001406 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001407 """
1408 Performs a new operation over a ns
1409 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001410 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001411 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001412 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001413 operation: it can be: instantiate, terminate, action, TODO: update, heal
1414 :param kwargs: used to override the indata descriptor
1415 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001416 :return: id of the nslcmops
1417 """
1418 try:
1419 # Override descriptor with query string kwargs
1420 self._update_input_with_kwargs(indata, kwargs)
1421 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001422 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001423 validate_input(indata, self.operation_schema[operation])
1424
Felipe Vicens126af572019-06-05 19:13:04 +02001425 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001426 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001427 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001428 nsir = self.db.get_one("nsis", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001429 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001430
1431 # initial checking
1432 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1433 if operation == "terminate" and indata.get("autoremove"):
1434 # NSIR must be deleted
tierno586ae812019-10-17 13:56:53 +00001435 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 +01001436 if operation != "instantiate":
1437 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001438 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001439 else:
tierno65ca36d2019-02-12 19:27:52 +01001440 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001441 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001442 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001443
1444 # Creating all the NS_operation (nslcmop)
1445 # Get service list from db
1446 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1447 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001448 # nslcmops_item = None
1449 for index, nsr_item in enumerate(nsrs_list):
1450 nsi = None
1451 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001452 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tiernob4844ab2019-05-23 08:42:12 +00001453 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1454 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001455 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001456 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001457 if operation == "terminate":
1458 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1459 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1460
Felipe Vicens09e65422019-01-22 15:06:46 +01001461 # looks the first nsi fulfilling the conditions but not being the current NSIR
1462 if nsi:
1463 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1464 for nsi_nsr_item in nsi_admin_shared:
1465 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1466 self.add_shared_nsr_2vld(nsir, nsr_item)
1467 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1468 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1469 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1470 break
1471 # continue to not create nslcmop since nsrs is shared and nsrs was created
1472 continue
1473 else:
1474 self.add_shared_nsr_2vld(nsir, nsr_item)
1475
1476 try:
1477 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1478 indata_ns = {}
1479 indata_ns = service["instantiate_params"]
1480 indata_ns["lcmOperationType"] = operation
1481 indata_ns["nsInstanceId"] = service["_id"]
1482 # Including netslice_id in the ns instantiate Operation
Felipe Vicens126af572019-06-05 19:13:04 +02001483 indata_ns["netsliceInstanceId"] = netsliceInstanceId
tierno99d4b172019-07-02 09:28:40 +00001484 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001485 # message via kafka bus
tiernobdebce92019-07-01 15:36:49 +00001486 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
1487 slice_object=True)
Felipe Vicens09e65422019-01-22 15:06:46 +01001488 nslcmops.append(nslcmop)
1489 if operation == "terminate":
1490 nslcmop = None
1491 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1492 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1493 except (DbException, EngineException) as e:
1494 if e.http_code == HTTPStatus.NOT_FOUND:
1495 self.logger.info("HTTPStatus.NOT_FOUND")
1496 pass
1497 else:
1498 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001499
1500 # Creates nsilcmop
1501 indata["nslcmops_ids"] = nslcmops
1502 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001503
Felipe Vicens126af572019-06-05 19:13:04 +02001504 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001505 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001506 _id = self.db.create("nsilcmops", nsilcmop_desc)
1507 rollback.append({"topic": "nsilcmops", "_id": _id})
1508 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001509 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01001510 except ValidationError as e:
1511 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001512
tierno65ca36d2019-02-12 19:27:52 +01001513 def delete(self, session, _id, dry_run=False):
Felipe Vicens07f31722018-10-29 15:16:44 +01001514 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1515
tierno65ca36d2019-02-12 19:27:52 +01001516 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001517 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)