blob: d04d99b722acb2c8f911f66862bcba9979ff058a [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)
144 additional_params.update(item_vdu["additionalParams"])
145 if kdu_name and item.get("additionalParamsForKdu"):
146 item_kdu = next((x for x in item["additionalParamsForKdu"] if x["kdu_name"] == kdu_name), None)
147 if item_kdu and item_kdu.get("additionalParams"):
148 where_ += ".additionalParamsForKdu[kdu_name={}]".format(kdu_name)
149 additional_params.update(item_kdu["additionalParams"])
150
tiernobee085c2018-12-12 17:03:04 +0000151 if additional_params:
152 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000153 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
154 if not kdu_name and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k):
delacruzramo36ffe552019-05-03 14:52:37 +0200155 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
156 "and underscores, and cannot start with a digit"
157 .format(where_, k))
158 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000159 if not isinstance(k, str):
160 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
161 if "." in k or "$" in k:
162 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
163 if isinstance(v, (dict, tuple, list)):
164 additional_params[k] = "!!yaml " + safe_dump(v)
165
166 if descriptor:
167 # check that enough parameters are supplied for the initial-config-primitive
168 # TODO: check for cloud-init
169 if member_vnf_index:
tierno714954e2019-11-29 13:43:26 +0000170 if kdu_name:
171 initial_primitives = None
172 elif vdu_id:
173 vdud = next(x for x in descriptor["vdu"] if x["id"] == vdu_id)
174 initial_primitives = deep_get(vdud, ("vdu-configuration", "initial-config-primitive"))
175 else:
176 initial_primitives = deep_get(descriptor, ("vnf-configuration", "initial-config-primitive"))
177 else:
178 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
tiernobee085c2018-12-12 17:03:04 +0000179
tierno714954e2019-11-29 13:43:26 +0000180 for initial_primitive in get_iterable(initial_primitives):
181 for param in get_iterable(initial_primitive.get("parameter")):
182 if param["value"].startswith("<") and param["value"].endswith(">"):
183 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
184 continue
185 if not additional_params or param["value"][1:-1] not in additional_params:
186 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
187 "initial-config-primitive[name={}] not supplied".
188 format(param["value"], descriptor["id"],
189 initial_primitive["name"]))
190
191 return additional_params or None
tiernobee085c2018-12-12 17:03:04 +0000192
tierno65ca36d2019-02-12 19:27:52 +0100193 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200194 """
195 Creates a new nsr into database. It also creates needed vnfrs
196 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100197 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200198 :param indata: params to be used for the nsr
199 :param kwargs: used to override the indata descriptor
200 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000201 :return: the _id of nsr descriptor created at database. Or an exception of type
202 EngineException, ValidationError, DbException, FsException, MsgException.
203 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200204 """
205
206 try:
delacruzramo32bab472019-09-13 12:24:22 +0200207 step = "checking quotas"
208 self.check_quota(session)
209
tierno99d4b172019-07-02 09:28:40 +0000210 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200211 ns_request = self._remove_envelop(indata)
212 # Override descriptor with query string kwargs
213 self._update_input_with_kwargs(ns_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100214 self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200215
tiernob24258a2018-10-04 18:39:49 +0200216 # look for nsr
217 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
tiernob4844ab2019-05-23 08:42:12 +0000218 _filter = self._get_project_filter(session)
219 _filter["_id"] = ns_request["nsdId"]
tiernob24258a2018-10-04 18:39:49 +0200220 nsd = self.db.get_one("nsds", _filter)
tiernob4844ab2019-05-23 08:42:12 +0000221 del _filter["_id"]
tiernob24258a2018-10-04 18:39:49 +0200222
223 nsr_id = str(uuid4())
tiernobee085c2018-12-12 17:03:04 +0000224
tiernob24258a2018-10-04 18:39:49 +0200225 now = time()
226 step = "filling nsr from input data"
227 nsr_descriptor = {
228 "name": ns_request["nsName"],
229 "name-ref": ns_request["nsName"],
230 "short-name": ns_request["nsName"],
231 "admin-status": "ENABLED",
232 "nsd": nsd,
233 "datacenter": ns_request["vimAccountId"],
234 "resource-orchestrator": "osmopenmano",
235 "description": ns_request.get("nsDescription", ""),
236 "constituent-vnfr-ref": [],
237
238 "operational-status": "init", # typedef ns-operational-
239 "config-status": "init", # typedef config-states
240 "detailed-status": "scheduled",
241
242 "orchestration-progress": {},
243 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
244
tierno65ca36d2019-02-12 19:27:52 +0100245 "create-time": now,
tiernob24258a2018-10-04 18:39:49 +0200246 "nsd-name-ref": nsd["name"],
247 "operational-events": [], # "id", "timestamp", "description", "event",
248 "nsd-ref": nsd["id"],
tiernof0637052019-03-07 16:26:47 +0000249 "nsd-id": nsd["_id"],
tiernob4844ab2019-05-23 08:42:12 +0000250 "vnfd-id": [],
tiernobee085c2018-12-12 17:03:04 +0000251 "instantiate_params": self._format_ns_request(ns_request),
tierno714954e2019-11-29 13:43:26 +0000252 "additionalParamsForNs": self._format_addional_params(ns_request, descriptor=nsd),
tiernob24258a2018-10-04 18:39:49 +0200253 "ns-instance-config-ref": nsr_id,
254 "id": nsr_id,
255 "_id": nsr_id,
256 # "input-parameter": xpath, value,
tierno99d4b172019-07-02 09:28:40 +0000257 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
tiernob24258a2018-10-04 18:39:49 +0200258 }
259 ns_request["nsr_id"] = nsr_id
tierno36ec8602018-11-02 17:27:11 +0100260 # Create vld
261 if nsd.get("vld"):
262 nsr_descriptor["vld"] = []
263 for nsd_vld in nsd.get("vld"):
264 nsr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100265 {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 +0200266
267 # Create VNFR
268 needed_vnfds = {}
gcalvino4f269dd2018-11-06 13:18:31 +0100269 for member_vnf in nsd.get("constituent-vnfd", ()):
tiernob24258a2018-10-04 18:39:49 +0200270 vnfd_id = member_vnf["vnfd-id-ref"]
271 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
272 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
273 if vnfd_id not in needed_vnfds:
274 # Obtain vnfd
tiernob4844ab2019-05-23 08:42:12 +0000275 _filter["id"] = vnfd_id
276 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
277 del _filter["id"]
tiernob24258a2018-10-04 18:39:49 +0200278 vnfd.pop("_admin")
279 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000280 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200281 else:
282 vnfd = needed_vnfds[vnfd_id]
283 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
284 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
285 vnfr_id = str(uuid4())
286 vnfr_descriptor = {
287 "id": vnfr_id,
288 "_id": vnfr_id,
289 "nsr-id-ref": nsr_id,
290 "member-vnf-index-ref": member_vnf["member-vnf-index"],
tiernobee085c2018-12-12 17:03:04 +0000291 "additionalParamsForVnf": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
tierno714954e2019-11-29 13:43:26 +0000292 descriptor=vnfd),
tiernob24258a2018-10-04 18:39:49 +0200293 "created-time": now,
294 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
295 "vnfd-ref": vnfd_id,
296 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
297 "vim-account-id": None,
298 "vdur": [],
299 "connection-point": [],
300 "ip-address": None, # mgmt-interface filled by LCM
301 }
tierno36ec8602018-11-02 17:27:11 +0100302
303 # Create vld
304 if vnfd.get("internal-vld"):
305 vnfr_descriptor["vld"] = []
306 for vnfd_vld in vnfd.get("internal-vld"):
307 vnfr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100308 {key: vnfd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in
309 vnfd_vld})
tierno36ec8602018-11-02 17:27:11 +0100310
311 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
tiernob24258a2018-10-04 18:39:49 +0200312 for cp in vnfd.get("connection-point", ()):
313 vnf_cp = {
314 "name": cp["name"],
315 "connection-point-id": cp.get("id"),
316 "id": cp.get("id"),
317 # "ip-address", "mac-address" # filled by LCM
318 # vim-id # TODO it would be nice having a vim port id
319 }
320 vnfr_descriptor["connection-point"].append(vnf_cp)
tierno9cb7d672019-10-30 12:13:48 +0000321
tiernoc67b0e92019-11-05 12:45:29 +0000322 # Create k8s-cluster information
323 if vnfd.get("k8s-cluster"):
324 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
325 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
326 if net.get("external-connection-point-ref"):
327 for nsd_vld in get_iterable(nsd.get("vld")):
328 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
329 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
330 net["external-connection-point-ref"] and \
331 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
332 net["ns-vld-id"] = nsd_vld["id"]
333 break
334 else:
335 continue
336 break
337 elif net.get("internal-connection-point-ref"):
338 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
339 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
340 if vnfd_ivld_icp.get("id-ref") == net["internal-connection-point-ref"]:
341 net["vnf-vld-id"] = vnfd_ivld["id"]
342 break
343 else:
344 continue
345 break
tierno9cb7d672019-10-30 12:13:48 +0000346 # update kdus
347 for kdu in get_iterable(vnfd.get("kdu")):
tierno714954e2019-11-29 13:43:26 +0000348 kdur = {x: kdu[x] for x in kdu if x in ("helm-chart", "juju-bundle")}
349 kdur["kdu-name"] = kdu["name"]
350 # TODO "name": "" Name of the VDU in the VIM
351 kdur["ip-address"] = None, # mgmt-interface filled by LCM
352 kdur["k8s-cluster"] = {},
353 kdur["additionalParams"] = self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
354 kdu_name=kdu["name"], descriptor=vnfd),
tierno9cb7d672019-10-30 12:13:48 +0000355 if not vnfr_descriptor.get("kdur"):
356 vnfr_descriptor["kdur"] = []
357 vnfr_descriptor["kdur"].append(kdur)
358
gcalvinoe45aded2018-11-13 17:17:28 +0100359 for vdu in vnfd.get("vdu", ()):
tiernob24258a2018-10-04 18:39:49 +0200360 vdur = {
tiernob24258a2018-10-04 18:39:49 +0200361 "vdu-id-ref": vdu["id"],
362 # TODO "name": "" Name of the VDU in the VIM
363 "ip-address": None, # mgmt-interface filled by LCM
364 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
365 "internal-connection-point": [],
366 "interfaces": [],
tierno714954e2019-11-29 13:43:26 +0000367 "additionalParams": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
368 vdu_id=vdu["id"], descriptor=vnfd),
tiernob24258a2018-10-04 18:39:49 +0200369 }
tiernocc103432018-10-19 14:10:35 +0200370 if vdu.get("pdu-type"):
371 vdur["pdu-type"] = vdu["pdu-type"]
tiernob24258a2018-10-04 18:39:49 +0200372 # TODO volumes: name, volume-id
373 for icp in vdu.get("internal-connection-point", ()):
374 vdu_icp = {
375 "id": icp["id"],
376 "connection-point-id": icp["id"],
377 "name": icp.get("name"),
378 # "ip-address", "mac-address" # filled by LCM
379 # vim-id # TODO it would be nice having a vim port id
380 }
381 vdur["internal-connection-point"].append(vdu_icp)
382 for iface in vdu.get("interface", ()):
383 vdu_iface = {
384 "name": iface.get("name"),
385 # "ip-address", "mac-address" # filled by LCM
386 # vim-id # TODO it would be nice having a vim port id
387 }
tierno36ec8602018-11-02 17:27:11 +0100388 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
389 vdu_iface["mgmt-vnf"] = True
tiernocc103432018-10-19 14:10:35 +0200390 if iface.get("mgmt-interface"):
tierno36ec8602018-11-02 17:27:11 +0100391 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
392
393 # look for network where this interface is connected
394 if iface.get("external-connection-point-ref"):
395 for nsd_vld in get_iterable(nsd.get("vld")):
396 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
397 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
398 iface["external-connection-point-ref"] and \
399 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
400 vdu_iface["ns-vld-id"] = nsd_vld["id"]
401 break
402 else:
403 continue
404 break
405 elif iface.get("internal-connection-point-ref"):
406 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
407 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
408 if vnfd_ivld_icp.get("id-ref") == iface["internal-connection-point-ref"]:
409 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
410 break
411 else:
412 continue
413 break
tiernocc103432018-10-19 14:10:35 +0200414
tiernob24258a2018-10-04 18:39:49 +0200415 vdur["interfaces"].append(vdu_iface)
tiernocc103432018-10-19 14:10:35 +0200416 count = vdu.get("count", 1)
417 if count is None:
418 count = 1
419 count = int(count) # TODO remove when descriptor serialized with payngbind
420 for index in range(0, count):
421 if index:
422 vdur = deepcopy(vdur)
423 vdur["_id"] = str(uuid4())
424 vdur["count-index"] = index
425 vnfr_descriptor["vdur"].append(vdur)
tiernob24258a2018-10-04 18:39:49 +0200426
427 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
428 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
429
430 # add at database
tiernobdebce92019-07-01 15:36:49 +0000431 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200432 self.db.create("vnfrs", vnfr_descriptor)
433 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
434 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
435
436 step = "creating nsr at database"
tierno65ca36d2019-02-12 19:27:52 +0100437 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200438 self.db.create("nsrs", nsr_descriptor)
439 rollback.append({"topic": "nsrs", "_id": nsr_id})
tiernobee085c2018-12-12 17:03:04 +0000440
441 step = "creating nsr temporal folder"
442 self.fs.mkdir(nsr_id)
443
tiernobdebce92019-07-01 15:36:49 +0000444 return nsr_id, None
tierno1bfe4e22019-09-02 16:03:25 +0000445 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
446 raise type(e)("{} while '{}".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200447
tierno65ca36d2019-02-12 19:27:52 +0100448 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200449 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
450
451
452class VnfrTopic(BaseTopic):
453 topic = "vnfrs"
454 topic_msg = None
455
delacruzramo32bab472019-09-13 12:24:22 +0200456 def __init__(self, db, fs, msg, auth):
457 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200458
tierno65ca36d2019-02-12 19:27:52 +0100459 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200460 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
461
tierno65ca36d2019-02-12 19:27:52 +0100462 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200463 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
464
tierno65ca36d2019-02-12 19:27:52 +0100465 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200466 # Not used because vnfrs are created and deleted by NsrTopic class directly
467 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
468
469
470class NsLcmOpTopic(BaseTopic):
471 topic = "nslcmops"
472 topic_msg = "ns"
473 operation_schema = { # mapping between operation and jsonschema to validate
474 "instantiate": ns_instantiate,
475 "action": ns_action,
476 "scale": ns_scale,
477 "terminate": None,
478 }
479
delacruzramo32bab472019-09-13 12:24:22 +0200480 def __init__(self, db, fs, msg, auth):
481 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200482
tiernob24258a2018-10-04 18:39:49 +0200483 def _check_ns_operation(self, session, nsr, operation, indata):
484 """
485 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100486 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200487 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
488 :param indata: descriptor with the parameters of the operation
489 :return: None
490 """
tierno982da4e2019-09-03 11:51:55 +0000491 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +0200492 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000493 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200494 nsd = nsr["nsd"]
495
496 def check_valid_vnf_member_index(member_vnf_index):
tierno982da4e2019-09-03 11:51:55 +0000497 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
498 if vnf_member_index_to_vnfd.get(member_vnf_index):
499 return vnf_member_index_to_vnfd[member_vnf_index]
500 vnfr = self.db.get_one("vnfrs",
501 {"nsr-id-ref": nsr["_id"], "member-vnf-index-ref": member_vnf_index},
502 fail_on_empty=False)
503 if not vnfr:
tiernob24258a2018-10-04 18:39:49 +0200504 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
505 "nsd:constituent-vnfd".format(member_vnf_index))
tierno982da4e2019-09-03 11:51:55 +0000506 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
507 if not vnfd:
508 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
509 format(vnfr["vnfd-id"]))
510 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
511 return vnfd
tiernob24258a2018-10-04 18:39:49 +0200512
tierno260dd6f2019-09-02 10:48:56 +0000513 def check_valid_vdu(vnfd, vdu_id):
514 for vdud in get_iterable(vnfd.get("vdu")):
515 if vdud["id"] == vdu_id:
516 return vdud
517 else:
518 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
519
tierno9cb7d672019-10-30 12:13:48 +0000520 def check_valid_kdu(vnfd, kdu_name):
521 for kdud in get_iterable(vnfd.get("kdu")):
522 if kdud["name"] == kdu_name:
523 return kdud
524 else:
525 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
526
gcalvino5e72d152018-10-23 11:46:57 +0200527 def _check_vnf_instantiation_params(in_vnfd, vnfd):
528
tierno40fbcad2018-10-26 10:58:15 +0200529 for in_vdu in get_iterable(in_vnfd.get("vdu")):
530 for vdu in get_iterable(vnfd.get("vdu")):
531 if in_vdu["id"] == vdu["id"]:
532 for volume in get_iterable(in_vdu.get("volume")):
533 for volumed in get_iterable(vdu.get("volumes")):
534 if volumed["name"] == volume["name"]:
535 break
536 else:
537 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
538 "volume:name='{}' is not present at vnfd:vdu:volumes list".
539 format(in_vnf["member-vnf-index"], in_vdu["id"],
540 volume["name"]))
541 for in_iface in get_iterable(in_vdu["interface"]):
542 for iface in get_iterable(vdu.get("interface")):
543 if in_iface["name"] == iface["name"]:
544 break
545 else:
546 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
547 "interface[name='{}'] is not present at vnfd:vdu:interface"
548 .format(in_vnf["member-vnf-index"], in_vdu["id"],
549 in_iface["name"]))
550 break
gcalvino5e72d152018-10-23 11:46:57 +0200551 else:
tierno40fbcad2018-10-26 10:58:15 +0200552 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
553 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200554
555 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
556 for ivld in get_iterable(vnfd.get("internal-vld")):
557 if in_ivld["name"] == ivld["name"] or in_ivld["name"] == ivld["id"]:
tierno1bfe4e22019-09-02 16:03:25 +0000558 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
gcalvino5e72d152018-10-23 11:46:57 +0200559 for icp in ivld["internal-connection-point"]:
560 if in_icp["id-ref"] == icp["id-ref"]:
561 break
562 else:
tierno40fbcad2018-10-26 10:58:15 +0200563 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
564 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
565 "vnfd:internal-vld:name/id:internal-connection-point"
566 .format(in_vnf["member-vnf-index"], in_ivld["name"],
567 in_icp["id-ref"], vnfd["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200568 break
569 else:
570 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
571 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
572 in_ivld["name"], vnfd["id"]))
573
tiernob24258a2018-10-04 18:39:49 +0200574 def check_valid_vim_account(vim_account):
575 if vim_account in vim_accounts:
576 return
577 try:
tierno65ca36d2019-02-12 19:27:52 +0100578 db_filter = self._get_project_filter(session)
tiernocc103432018-10-19 14:10:35 +0200579 db_filter["_id"] = vim_account
580 self.db.get_one("vim_accounts", db_filter)
tiernob24258a2018-10-04 18:39:49 +0200581 except Exception:
tiernocc103432018-10-19 14:10:35 +0200582 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
tiernob24258a2018-10-04 18:39:49 +0200583 vim_accounts.append(vim_account)
584
tierno4f9d4ae2019-03-20 17:24:11 +0000585 def check_valid_wim_account(wim_account):
586 if not isinstance(wim_account, str):
587 return
588 elif wim_account in wim_accounts:
589 return
590 try:
591 db_filter = self._get_project_filter(session, write=False, show_all=True)
592 db_filter["_id"] = wim_account
593 self.db.get_one("wim_accounts", db_filter)
594 except Exception:
595 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
596 wim_accounts.append(wim_account)
597
tiernob24258a2018-10-04 18:39:49 +0200598 if operation == "action":
599 # check vnf_member_index
600 if indata.get("vnf_member_index"):
601 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
tierno1ac7f462019-06-03 17:22:12 +0000602 if indata.get("member_vnf_index"):
603 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
tierno260dd6f2019-09-02 10:48:56 +0000604 if indata.get("vdu_id"):
605 vdud = check_valid_vdu(vnfd, indata["vdu_id"])
606 descriptor_configuration = vdud.get("vdu-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000607 elif indata.get("kdu_name"):
tiernoc67b0e92019-11-05 12:45:29 +0000608 kdud = check_valid_kdu(vnfd, indata["kdu_name"])
tierno9cb7d672019-10-30 12:13:48 +0000609 descriptor_configuration = kdud.get("kdu-configuration", {}).get("config-primitive")
tierno260dd6f2019-09-02 10:48:56 +0000610 else:
611 descriptor_configuration = vnfd.get("vnf-configuration", {}).get("config-primitive")
tierno1ac7f462019-06-03 17:22:12 +0000612 else: # use a NSD
613 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000614
615 # For k8s allows default primitives without validating the parameters
delacruzramo6ddff2e2019-11-28 11:24:09 +0100616 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
tierno9cb7d672019-10-30 12:13:48 +0000617 # TODO should be checked that rollback only can contains revsision_numbe????
delacruzramo6ddff2e2019-11-28 11:24:09 +0100618 if not indata.get("member_vnf_index"):
619 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
620 .format(indata["primitive"]))
tierno9cb7d672019-10-30 12:13:48 +0000621 return
622 # if not, check primitive
tierno1ac7f462019-06-03 17:22:12 +0000623 for config_primitive in get_iterable(descriptor_configuration):
tiernob24258a2018-10-04 18:39:49 +0200624 if indata["primitive"] == config_primitive["name"]:
625 # check needed primitive_params are provided
626 if indata.get("primitive_params"):
627 in_primitive_params_copy = copy(indata["primitive_params"])
628 else:
629 in_primitive_params_copy = {}
630 for paramd in get_iterable(config_primitive.get("parameter")):
631 if paramd["name"] in in_primitive_params_copy:
632 del in_primitive_params_copy[paramd["name"]]
633 elif not paramd.get("default-value"):
634 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
635 paramd["name"], indata["primitive"]))
636 # check no extra primitive params are provided
637 if in_primitive_params_copy:
tierno1ac7f462019-06-03 17:22:12 +0000638 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
tiernob24258a2018-10-04 18:39:49 +0200639 list(in_primitive_params_copy.keys()), indata["primitive"]))
640 break
641 else:
tierno1ac7f462019-06-03 17:22:12 +0000642 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
tiernob24258a2018-10-04 18:39:49 +0200643 if operation == "scale":
644 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
645 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
646 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
647 break
648 else:
649 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
650 "present at vnfd:scaling-group-descriptor".format(
651 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
652 if operation == "instantiate":
653 # check vim_account
654 check_valid_vim_account(indata["vimAccountId"])
tierno4f9d4ae2019-03-20 17:24:11 +0000655 check_valid_wim_account(indata.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200656 for in_vnf in get_iterable(indata.get("vnf")):
657 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
gcalvino5e72d152018-10-23 11:46:57 +0200658 _check_vnf_instantiation_params(in_vnf, vnfd)
tiernob24258a2018-10-04 18:39:49 +0200659 if in_vnf.get("vimAccountId"):
660 check_valid_vim_account(in_vnf["vimAccountId"])
tiernob24258a2018-10-04 18:39:49 +0200661
tiernob24258a2018-10-04 18:39:49 +0200662 for in_vld in get_iterable(indata.get("vld")):
tierno4f9d4ae2019-03-20 17:24:11 +0000663 check_valid_wim_account(in_vld.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200664 for vldd in get_iterable(nsd.get("vld")):
665 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
666 break
667 else:
668 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
669 in_vld["name"]))
670
tierno36ec8602018-11-02 17:27:11 +0100671 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200672 """
tierno36ec8602018-11-02 17:27:11 +0100673 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
674 (ip_address, ...) information.
675 Modifies PDU _admin.usageState to 'IN_USE'
676
tierno65ca36d2019-02-12 19:27:52 +0100677 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100678 :param rollback: list with the database modifications to rollback if needed
679 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
680 :param vim_account: vim_account where this vnfr should be deployed
681 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
682 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
683 of the changed vnfr is needed
684
685 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
686 "vim-network-name": used at VIM
687 "name": interface name
688 "vnf-vld-id": internal VNFD vld where this interface is connected, or
689 "ns-vld-id": NSD vld where this interface is connected.
690 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 +0200691 """
tierno36ec8602018-11-02 17:27:11 +0100692
693 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +0200694 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
695 if not vdur.get("pdu-type"):
696 continue
697 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +0100698 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +0100699 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +0200700 pdu_filter["type"] = pdu_type
701 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +0100702 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +0200703 # TODO feature 1417: "shared": True,
704
705 available_pdus = self.db.get_list("pdus", pdu_filter)
706 for pdu in available_pdus:
707 # step 1 check if this pdu contains needed interfaces:
708 match_interfaces = True
709 for vdur_interface in vdur["interfaces"]:
710 for pdu_interface in pdu["interfaces"]:
711 if pdu_interface["name"] == vdur_interface["name"]:
712 # TODO feature 1417: match per mgmt type
713 break
714 else: # no interface found for name
715 match_interfaces = False
716 break
717 if match_interfaces:
718 break
719 else:
720 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +0100721 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
722 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +0200723
724 # step 2. Update pdu
725 rollback_pdu = {
726 "_admin.usageState": pdu["_admin"]["usageState"],
727 "_admin.usage.vnfr_id": None,
728 "_admin.usage.nsr_id": None,
729 "_admin.usage.vdur": None,
730 }
731 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +0100732 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +0000733 "_admin.usage": {"vnfr_id": vnfr["_id"],
734 "nsr_id": vnfr["nsr-id-ref"],
735 "vdur": vdur["vdu-id-ref"]}
736 })
tiernocc103432018-10-19 14:10:35 +0200737 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
738
739 # step 3. Fill vnfr info by filling vdur
740 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +0100741 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +0200742 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
743 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
744 for pdu_interface in pdu["interfaces"]:
745 if pdu_interface["name"] == vdur_interface["name"]:
746 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
747 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +0100748 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
749 vnfr_update[iface_text + ".{}".format(k)] = v
750 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
751 if pdu_interface.get("ip-address"):
752 if vdur_interface.get("mgmt-interface"):
753 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
754 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
755 if vdur_interface.get("mgmt-vnf"):
756 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
757 vnfr_update["ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +0100758 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +0100759 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +0100760 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
761 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
762 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +0100763 if pdu_interface.get("vim-network-id"):
tiernoc67b0e92019-11-05 12:45:29 +0000764 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +0100765 if pdu_interface.get("vim-network-name"):
tiernoc67b0e92019-11-05 12:45:29 +0000766 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +0200767 break
768
tierno36ec8602018-11-02 17:27:11 +0100769 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +0200770
tierno9cb7d672019-10-30 12:13:48 +0000771 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
772 """
773 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
774 Fills vnfr.kdur with the selected k8scluster
775
776 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
777 :param rollback: list with the database modifications to rollback if needed
778 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
779 :param vim_account: vim_account where this vnfr should be deployed
780 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
781 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
782 of the changed vnfr is needed
783
784 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
785 "vim-network-name": used at VIM
786 "name": interface name
787 "vnf-vld-id": internal VNFD vld where this interface is connected, or
788 "ns-vld-id": NSD vld where this interface is connected.
789 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
790 """
791
792 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +0000793 if not vnfr.get("kdur"):
794 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +0000795
tiernoc67b0e92019-11-05 12:45:29 +0000796 kdu_filter = self._get_project_filter(session)
797 kdu_filter["vim_account"] = vim_account
798 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
799 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
800
801 k8s_requirements = {} # just for logging
802 for k8scluster in available_k8sclusters:
803 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +0000804 break
tiernoc67b0e92019-11-05 12:45:29 +0000805 # restrict by cni
806 if vnfr["k8s-cluster"].get("cni"):
807 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
808 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
809 continue
810 # restrict by version
811 if vnfr["k8s-cluster"].get("version"):
812 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
813 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
814 continue
815 # restrict by number of networks
816 if vnfr["k8s-cluster"].get("nets"):
817 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
818 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
819 continue
820 break
821 else:
822 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
823 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
tierno9cb7d672019-10-30 12:13:48 +0000824
tiernoc67b0e92019-11-05 12:45:29 +0000825 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +0000826 # step 3. Fill vnfr info by filling kdur
827 kdu_text = "kdur.{}.".format(kdur_index)
828 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
829 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
830
tiernoc67b0e92019-11-05 12:45:29 +0000831 # step 4. Check VIM networks that forces the selected k8s_cluster
832 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
833 k8scluster_net_list = list(k8scluster.get("nets").keys())
834 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
835 # get a network from k8s_cluster nets. If name matches use this, if not use other
836 if kdur_net["id"] in k8scluster_net_list: # name matches
837 vim_net = k8scluster["nets"][kdur_net["id"]]
838 k8scluster_net_list.remove(kdur_net["id"])
839 else:
840 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
841 k8scluster_net_list.pop(0)
842 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
843 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
844 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
845 ifaces_forcing_vim_network.append({
846 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
847 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
848 "ns-vld-id": kdur_net.get("ns-vld-id"),
849 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
850 })
851 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +0000852 return ifaces_forcing_vim_network
853
tiernocc103432018-10-19 14:10:35 +0200854 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +0200855 # get vnfr
856 nsr_id = nsr["_id"]
857 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
858
859 for vnfr in vnfrs:
860 vnfr_update = {}
861 vnfr_update_rollback = {}
862 member_vnf_index = vnfr["member-vnf-index-ref"]
863 # update vim-account-id
864
865 vim_account = indata["vimAccountId"]
866 # check instantiate parameters
867 for vnf_inst_params in get_iterable(indata.get("vnf")):
868 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
869 continue
870 if vnf_inst_params.get("vimAccountId"):
871 vim_account = vnf_inst_params.get("vimAccountId")
872
873 vnfr_update["vim-account-id"] = vim_account
874 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
875
876 # get pdu
tierno36ec8602018-11-02 17:27:11 +0100877 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
878 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +0200879
tierno9cb7d672019-10-30 12:13:48 +0000880 # get kdus
881 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
882 vnfr_update_rollback)
883 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +0100884 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
885 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
886
887 # Update indada in case pdu forces to use a concrete vim-network-name
888 # TODO check if user has already insert a vim-network-name and raises an error
889 if not ifaces_forcing_vim_network:
890 continue
891 for iface_info in ifaces_forcing_vim_network:
892 if iface_info.get("ns-vld-id"):
893 if "vld" not in indata:
894 indata["vld"] = []
895 indata["vld"].append({key: iface_info[key] for key in
896 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
897
898 elif iface_info.get("vnf-vld-id"):
899 if "vnf" not in indata:
900 indata["vnf"] = []
901 indata["vnf"].append({
902 "member-vnf-index": member_vnf_index,
903 "internal-vld": [{key: iface_info[key] for key in
904 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
905 })
906
907 @staticmethod
908 def _create_nslcmop(nsr_id, operation, params):
909 """
910 Creates a ns-lcm-opp content to be stored at database.
911 :param nsr_id: internal id of the instance
912 :param operation: instantiate, terminate, scale, action, ...
913 :param params: user parameters for the operation
914 :return: dictionary following SOL005 format
915 """
tiernob24258a2018-10-04 18:39:49 +0200916 now = time()
917 _id = str(uuid4())
918 nslcmop = {
919 "id": _id,
920 "_id": _id,
921 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
922 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +0100923 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200924 "lcmOperationType": operation,
925 "startTime": now,
926 "isAutomaticInvocation": False,
927 "operationParams": params,
928 "isCancelPending": False,
929 "links": {
930 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +0100931 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200932 }
933 }
934 return nslcmop
935
tierno65ca36d2019-02-12 19:27:52 +0100936 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +0200937 """
938 Performs a new operation over a ns
939 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100940 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200941 :param indata: descriptor with the parameters of the operation. It must contains among others
942 nsInstanceId: _id of the nsr to perform the operation
943 operation: it can be: instantiate, terminate, action, TODO: update, heal
944 :param kwargs: used to override the indata descriptor
945 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200946 :return: id of the nslcmops
947 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +0200948 def check_if_nsr_is_not_slice_member(session, nsr_id):
949 nsis = None
950 db_filter = self._get_project_filter(session)
951 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
952 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
953 if nsis:
954 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
955 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
956
tiernob24258a2018-10-04 18:39:49 +0200957 try:
958 # Override descriptor with query string kwargs
959 self._update_input_with_kwargs(indata, kwargs)
960 operation = indata["lcmOperationType"]
961 nsInstanceId = indata["nsInstanceId"]
962
963 validate_input(indata, self.operation_schema[operation])
964 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +0100965 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +0200966 _filter["_id"] = nsInstanceId
967 nsr = self.db.get_one("nsrs", _filter)
968
969 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +0200970 if operation == "terminate" and slice_object is False:
971 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +0200972 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
973 if operation == "terminate" and indata.get("autoremove"):
974 # NSR must be deleted
tierno586ae812019-10-17 13:56:53 +0000975 return None, None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +0200976 if operation != "instantiate":
977 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
978 nsInstanceId, operation), HTTPStatus.CONFLICT)
979 else:
tierno65ca36d2019-02-12 19:27:52 +0100980 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200981 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
982 nsInstanceId, operation), HTTPStatus.CONFLICT)
983 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +0100984
tiernocc103432018-10-19 14:10:35 +0200985 if operation == "instantiate":
986 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +0100987
988 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +0000989 _id = nslcmop_desc["_id"]
tierno65ca36d2019-02-12 19:27:52 +0100990 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
tierno1bfe4e22019-09-02 16:03:25 +0000991 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +0200992 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +0100993 if not slice_object:
994 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +0000995 return _id, None
996 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +0200997 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
998 # except DbException as e:
999 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1000
tierno65ca36d2019-02-12 19:27:52 +01001001 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +02001002 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1003
tierno65ca36d2019-02-12 19:27:52 +01001004 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +02001005 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001006
1007
1008class NsiTopic(BaseTopic):
1009 topic = "nsis"
1010 topic_msg = "nsi"
1011
delacruzramo32bab472019-09-13 12:24:22 +02001012 def __init__(self, db, fs, msg, auth):
1013 BaseTopic.__init__(self, db, fs, msg, auth)
1014 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001015
Felipe Vicensc37b3842019-01-12 12:24:42 +01001016 @staticmethod
1017 def _format_ns_request(ns_request):
1018 formated_request = copy(ns_request)
1019 # TODO: Add request params
1020 return formated_request
1021
1022 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001023 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001024 """
1025 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001026 :param slice_request: User instantiation additional parameters
1027 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001028 """
tiernofd160572019-01-21 10:41:37 +00001029 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1030 if additional_params:
1031 for k, v in additional_params.items():
1032 if not isinstance(k, str):
1033 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1034 format(k))
1035 if "." in k or "$" in k:
1036 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1037 format(k))
1038 if isinstance(v, (dict, tuple, list)):
1039 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001040 return additional_params
1041
Felipe Vicensb57758d2018-10-16 16:00:20 +02001042 def _check_descriptor_dependencies(self, session, descriptor):
1043 """
1044 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001045 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001046 :param descriptor: descriptor to be inserted or edit
1047 :return: None or raises exception
1048 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001049 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001050 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001051 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001052 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +01001053 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +02001054 http_code=HTTPStatus.CONFLICT)
1055
tiernob4844ab2019-05-23 08:42:12 +00001056 def check_conflict_on_del(self, session, _id, db_content):
1057 """
1058 Check that NSI is not instantiated
1059 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1060 :param _id: nsi internal id
1061 :param db_content: The database content of the _id
1062 :return: None or raises EngineException with the conflict
1063 """
tierno65ca36d2019-02-12 19:27:52 +01001064 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02001065 return
tiernob4844ab2019-05-23 08:42:12 +00001066 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02001067 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1068 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1069 "Launch 'terminate' operation first; or force deletion".format(_id),
1070 http_code=HTTPStatus.CONFLICT)
1071
tiernob4844ab2019-05-23 08:42:12 +00001072 def delete_extra(self, session, _id, db_content):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001073 """
tiernob4844ab2019-05-23 08:42:12 +00001074 Deletes associated nsilcmops from database. Deletes associated filesystem.
1075 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01001076 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001077 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00001078 :param db_content: The database content of the descriptor
1079 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02001080 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001081
Felipe Vicens09e65422019-01-22 15:06:46 +01001082 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00001083 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01001084 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1085 nsr_id = nsrs_detailed_item["nsrId"]
1086 if nsrs_detailed_item.get("shared"):
1087 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1088 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1089 "_id.ne": nsir["_id"]}
1090 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1091 if nsi: # last one using nsr
1092 continue
1093 try:
tierno65ca36d2019-02-12 19:27:52 +01001094 self.nsrTopic.delete(session, nsr_id, dry_run=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001095 except (DbException, EngineException) as e:
1096 if e.http_code == HTTPStatus.NOT_FOUND:
1097 pass
1098 else:
1099 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001100
tiernob4844ab2019-05-23 08:42:12 +00001101 # delete related nsilcmops database entries
1102 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001103
tiernob4844ab2019-05-23 08:42:12 +00001104 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01001105 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00001106 if nsir_admin and nsir_admin.get("nst-id"):
1107 # check if used by another NSI
1108 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1109 fail_on_empty=False, fail_on_more=False)
1110 if not nsis_list:
1111 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1112
1113 # def delete(self, session, _id, dry_run=False):
1114 # """
1115 # Delete item by its internal _id
1116 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1117 # :param _id: server internal id
1118 # :param dry_run: make checking but do not delete
1119 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1120 # """
1121 # # TODO add admin to filter, validate rights
1122 # BaseTopic.delete(self, session, _id, dry_run=True)
1123 # if dry_run:
1124 # return
1125 #
1126 # # Deleting the nsrs belonging to nsir
1127 # nsir = self.db.get_one("nsis", {"_id": _id})
1128 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1129 # nsr_id = nsrs_detailed_item["nsrId"]
1130 # if nsrs_detailed_item.get("shared"):
1131 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1132 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1133 # "_id.ne": nsir["_id"]}
1134 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1135 # if nsi: # last one using nsr
1136 # continue
1137 # try:
1138 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1139 # except (DbException, EngineException) as e:
1140 # if e.http_code == HTTPStatus.NOT_FOUND:
1141 # pass
1142 # else:
1143 # raise
1144 # # deletes NetSlice instance object
1145 # v = self.db.del_one("nsis", {"_id": _id})
1146 #
1147 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1148 # _filter = {"netsliceInstanceId": _id}
1149 # self.db.del_list("nsilcmops", _filter)
1150 #
1151 # # Search if nst is being used by other nsi
1152 # nsir_admin = nsir.get("_admin")
1153 # if nsir_admin:
1154 # if nsir_admin.get("nst-id"):
1155 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1156 # fail_on_empty=False, fail_on_more=False)
1157 # if not nsis_list:
1158 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1159 # return v
Felipe Vicensb57758d2018-10-16 16:00:20 +02001160
tierno65ca36d2019-02-12 19:27:52 +01001161 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001162 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001163 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02001164 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01001165 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001166 :param indata: params to be used for the nsir
1167 :param kwargs: used to override the indata descriptor
1168 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02001169 :return: the _id of nsi descriptor created at database
1170 """
1171
1172 try:
delacruzramo32bab472019-09-13 12:24:22 +02001173 step = "checking quotas"
1174 self.check_quota(session)
1175
tierno99d4b172019-07-02 09:28:40 +00001176 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02001177 slice_request = self._remove_envelop(indata)
1178 # Override descriptor with query string kwargs
1179 self._update_input_with_kwargs(slice_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001180 self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001181
Felipe Vicensb57758d2018-10-16 16:00:20 +02001182 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +00001183 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001184 _filter = self._get_project_filter(session)
1185 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001186 nstd = self.db.get_one("nsts", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001187 del _filter["_id"]
1188
Felipe Vicens07f31722018-10-29 15:16:44 +01001189 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001190 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001191 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001192 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001193
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001194 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001195 nsi_descriptor = {
1196 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001197 "name": slice_request["nsiName"],
1198 "description": slice_request.get("nsiDescription", ""),
1199 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001200 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001201 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001202 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001203 "nsr-ref-list": [],
1204 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001205 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001206 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001207 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001208
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001209 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001210 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001211 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1212 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001213 nsi_descriptor["_admin"]["deployed"] = {}
1214 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1215 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1216
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001217 # Creating netslice-vld for the RO.
1218 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001219
1220 # Building the vlds list to be deployed
1221 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001222 nsi_vlds = []
1223
1224 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1225 # Getting template Instantiation parameters from NST
1226 nsi_vld = deepcopy(netslice_vlds)
1227 nsi_vld["shared-nsrs-list"] = []
1228 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1229 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001230
1231 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
Felipe Vicens07f31722018-10-29 15:16:44 +01001232 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001233 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001234 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001235
Felipe Vicens09e65422019-01-22 15:06:46 +01001236 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001237 for member_ns in nstd["netslice-subnet"]:
1238 nsd_id = member_ns["nsd-ref"]
1239 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1240 member_ns["nsd-ref"], member_ns["id"])
1241 if nsd_id not in needed_nsds:
1242 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001243 _filter["id"] = nsd_id
1244 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1245 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001246 nsd.pop("_admin")
1247 needed_nsds[nsd_id] = nsd
1248 else:
1249 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001250 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1251 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001252
Felipe Vicensb57758d2018-10-16 16:00:20 +02001253 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1254 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001255
Felipe Vicens07f31722018-10-29 15:16:44 +01001256 # creates Network Services records (NSRs)
1257 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001258 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001259 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001260 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001261 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001262 # Check if the netslice-subnet is shared and if it is share if the nss exists
1263 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001264 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001265 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001266 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1267 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens08ddb142019-08-09 15:52:40 +02001268 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001269 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001270 if nsi and service.get("is-shared-nss"):
1271 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1272 for nsrs_detailed_item in nsrs_detailed_list:
1273 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02001274 if nsrs_detailed_item["nss-id"] == service["id"]:
1275 _id_nsr = nsrs_detailed_item["nsrId"]
1276 break
Felipe Vicens09e65422019-01-22 15:06:46 +01001277 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1278 if netslice_subnet["nss-id"] == service["id"]:
1279 indata_ns = netslice_subnet
1280 break
1281 else:
1282 indata_ns = {}
1283 if service.get("instantiation-parameters"):
1284 indata_ns = deepcopy(service["instantiation-parameters"])
1285 # del service["instantiation-parameters"]
1286
1287 indata_ns["nsdId"] = service["_id"]
1288 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1289 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1290 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001291 if slice_request.get("ssh_keys"):
1292 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001293
Felipe Vicens09e65422019-01-22 15:06:46 +01001294 if ns_params:
1295 for ns_param in ns_params:
1296 if ns_param.get("id") == service["id"]:
1297 copy_ns_param = deepcopy(ns_param)
1298 del copy_ns_param["id"]
1299 indata_ns.update(copy_ns_param)
1300 break
1301
1302 # Creates Nsr objects
tiernobdebce92019-07-01 15:36:49 +00001303 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001304 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
Felipe Vicens08ddb142019-08-09 15:52:40 +02001305 "nss-id": service["id"], "nslcmop_instantiate": None}
Felipe Vicens09e65422019-01-22 15:06:46 +01001306 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001307 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001308 nsi_netslice_subnet.append(indata_ns)
1309 nsr_ref = {"nsr-ref": _id_nsr}
1310 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001311
1312 # Adding the nsrs list to the nsi
1313 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001314 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001315 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1316
Felipe Vicens07f31722018-10-29 15:16:44 +01001317 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001318 self.db.create("nsis", nsi_descriptor)
1319 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00001320 return nsi_id, None
1321 except Exception as e: # TODO remove try Except, it is captured at nbi.py
Felipe Vicensb57758d2018-10-16 16:00:20 +02001322 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1323 raise EngineException("Error {}: {}".format(step, e))
1324 except ValidationError as e:
1325 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1326
tierno65ca36d2019-02-12 19:27:52 +01001327 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001328 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001329
1330
1331class NsiLcmOpTopic(BaseTopic):
1332 topic = "nsilcmops"
1333 topic_msg = "nsi"
1334 operation_schema = { # mapping between operation and jsonschema to validate
1335 "instantiate": nsi_instantiate,
1336 "terminate": None
1337 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001338
delacruzramo32bab472019-09-13 12:24:22 +02001339 def __init__(self, db, fs, msg, auth):
1340 BaseTopic.__init__(self, db, fs, msg, auth)
1341 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01001342
1343 def _check_nsi_operation(self, session, nsir, operation, indata):
1344 """
1345 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001346 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001347 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1348 :param indata: descriptor with the parameters of the operation
1349 :return: None
1350 """
1351 nsds = {}
1352 nstd = nsir["network-slice-template"]
1353
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001354 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001355 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001356 for netslice_subnet in nstd["netslice-subnet"]:
1357 if nstId == netslice_subnet["id"]:
1358 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001359 if nsd_id not in nsds:
1360 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1361 return nsds[nsd_id]
1362 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001363 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1364 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001365 if operation == "instantiate":
1366 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001367 for in_nst in get_iterable(indata.get("netslice-subnet")):
1368 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001369
1370 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1371 now = time()
1372 _id = str(uuid4())
1373 nsilcmop = {
1374 "id": _id,
1375 "_id": _id,
1376 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1377 "statusEnteredTime": now,
1378 "netsliceInstanceId": netsliceInstanceId,
1379 "lcmOperationType": operation,
1380 "startTime": now,
1381 "isAutomaticInvocation": False,
1382 "operationParams": params,
1383 "isCancelPending": False,
1384 "links": {
1385 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001386 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001387 }
1388 }
1389 return nsilcmop
1390
Felipe Vicens09e65422019-01-22 15:06:46 +01001391 def add_shared_nsr_2vld(self, nsir, nsr_item):
1392 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1393 if nst_sb_item.get("is-shared-nss"):
1394 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1395 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1396 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1397 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1398 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1399 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1400 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1401 break
1402 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1403 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1404
tierno65ca36d2019-02-12 19:27:52 +01001405 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001406 """
1407 Performs a new operation over a ns
1408 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001409 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001410 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001411 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001412 operation: it can be: instantiate, terminate, action, TODO: update, heal
1413 :param kwargs: used to override the indata descriptor
1414 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001415 :return: id of the nslcmops
1416 """
1417 try:
1418 # Override descriptor with query string kwargs
1419 self._update_input_with_kwargs(indata, kwargs)
1420 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001421 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001422 validate_input(indata, self.operation_schema[operation])
1423
Felipe Vicens126af572019-06-05 19:13:04 +02001424 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001425 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001426 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001427 nsir = self.db.get_one("nsis", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001428 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001429
1430 # initial checking
1431 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1432 if operation == "terminate" and indata.get("autoremove"):
1433 # NSIR must be deleted
tierno586ae812019-10-17 13:56:53 +00001434 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 +01001435 if operation != "instantiate":
1436 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001437 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001438 else:
tierno65ca36d2019-02-12 19:27:52 +01001439 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001440 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001441 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001442
1443 # Creating all the NS_operation (nslcmop)
1444 # Get service list from db
1445 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1446 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001447 # nslcmops_item = None
1448 for index, nsr_item in enumerate(nsrs_list):
1449 nsi = None
1450 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001451 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tiernob4844ab2019-05-23 08:42:12 +00001452 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1453 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001454 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001455 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001456 if operation == "terminate":
1457 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1458 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1459
Felipe Vicens09e65422019-01-22 15:06:46 +01001460 # looks the first nsi fulfilling the conditions but not being the current NSIR
1461 if nsi:
1462 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1463 for nsi_nsr_item in nsi_admin_shared:
1464 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1465 self.add_shared_nsr_2vld(nsir, nsr_item)
1466 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1467 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1468 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1469 break
1470 # continue to not create nslcmop since nsrs is shared and nsrs was created
1471 continue
1472 else:
1473 self.add_shared_nsr_2vld(nsir, nsr_item)
1474
1475 try:
1476 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1477 indata_ns = {}
1478 indata_ns = service["instantiate_params"]
1479 indata_ns["lcmOperationType"] = operation
1480 indata_ns["nsInstanceId"] = service["_id"]
1481 # Including netslice_id in the ns instantiate Operation
Felipe Vicens126af572019-06-05 19:13:04 +02001482 indata_ns["netsliceInstanceId"] = netsliceInstanceId
tierno99d4b172019-07-02 09:28:40 +00001483 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001484 # message via kafka bus
tiernobdebce92019-07-01 15:36:49 +00001485 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
1486 slice_object=True)
Felipe Vicens09e65422019-01-22 15:06:46 +01001487 nslcmops.append(nslcmop)
1488 if operation == "terminate":
1489 nslcmop = None
1490 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1491 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1492 except (DbException, EngineException) as e:
1493 if e.http_code == HTTPStatus.NOT_FOUND:
1494 self.logger.info("HTTPStatus.NOT_FOUND")
1495 pass
1496 else:
1497 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001498
1499 # Creates nsilcmop
1500 indata["nslcmops_ids"] = nslcmops
1501 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001502
Felipe Vicens126af572019-06-05 19:13:04 +02001503 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001504 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001505 _id = self.db.create("nsilcmops", nsilcmop_desc)
1506 rollback.append({"topic": "nsilcmops", "_id": _id})
1507 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001508 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01001509 except ValidationError as e:
1510 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001511
tierno65ca36d2019-02-12 19:27:52 +01001512 def delete(self, session, _id, dry_run=False):
Felipe Vicens07f31722018-10-29 15:16:44 +01001513 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1514
tierno65ca36d2019-02-12 19:27:52 +01001515 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001516 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)