blob: ce9a3c6e8def9862358b586654782fdc65559227 [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
Felipe Vicens07f31722018-10-29 15:16:44 +010021from validation import validate_input, ValidationError, ns_instantiate, ns_action, ns_scale, nsi_instantiate
tiernob24258a2018-10-04 18:39:49 +020022from base_topic import BaseTopic, EngineException, get_iterable
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
delacruzramo36ffe552019-05-03 14:52:37 +020026from re import match # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020027
28__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
29
30
31class NsrTopic(BaseTopic):
32 topic = "nsrs"
33 topic_msg = "ns"
tiernod77ba6f2019-06-27 14:31:10 +000034 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020035
36 def __init__(self, db, fs, msg):
37 BaseTopic.__init__(self, db, fs, msg)
38
39 def _check_descriptor_dependencies(self, session, descriptor):
40 """
41 Check that the dependent descriptors exist on a new descriptor or edition
42 :param session: client session information
43 :param descriptor: descriptor to be inserted or edit
44 :return: None or raises exception
45 """
46 if not descriptor.get("nsdId"):
47 return
48 nsd_id = descriptor["nsdId"]
49 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
50 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
51 http_code=HTTPStatus.CONFLICT)
52
53 @staticmethod
54 def format_on_new(content, project_id=None, make_public=False):
55 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
56 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
57
tiernob4844ab2019-05-23 08:42:12 +000058 def check_conflict_on_del(self, session, _id, db_content):
59 """
60 Check that NSR is not instantiated
61 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
62 :param _id: nsr internal id
63 :param db_content: The database content of the nsr
64 :return: None or raises EngineException with the conflict
65 """
tierno65ca36d2019-02-12 19:27:52 +010066 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020067 return
tiernob4844ab2019-05-23 08:42:12 +000068 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020069 if nsr["_admin"].get("nsState") == "INSTANTIATED":
70 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
71 "Launch 'terminate' operation first; or force deletion".format(_id),
72 http_code=HTTPStatus.CONFLICT)
73
tiernob4844ab2019-05-23 08:42:12 +000074 def delete_extra(self, session, _id, db_content):
75 """
76 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
77 Set usageState of pdu, vnfd, nsd
78 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
79 :param _id: server internal id
80 :param db_content: The database content of the descriptor
81 :return: None if ok or raises EngineException with the problem
82 """
tiernobee085c2018-12-12 17:03:04 +000083 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +020084 self.db.del_list("nslcmops", {"nsInstanceId": _id})
85 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +000086
tiernob24258a2018-10-04 18:39:49 +020087 # set all used pdus as free
88 self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
tierno36ec8602018-11-02 17:27:11 +010089 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
tiernob24258a2018-10-04 18:39:49 +020090
tiernob4844ab2019-05-23 08:42:12 +000091 # Set NSD usageState
92 nsr = db_content
93 used_nsd_id = nsr.get("nsd-id")
94 if used_nsd_id:
95 # check if used by another NSR
96 nsrs_list = self.db.get_one("nsrs", {"nsd-id": used_nsd_id},
97 fail_on_empty=False, fail_on_more=False)
98 if not nsrs_list:
99 self.db.set_one("nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"})
100
101 # Set VNFD usageState
102 used_vnfd_id_list = nsr.get("vnfd-id")
103 if used_vnfd_id_list:
104 for used_vnfd_id in used_vnfd_id_list:
105 # check if used by another NSR
106 nsrs_list = self.db.get_one("nsrs", {"vnfd-id": used_vnfd_id},
107 fail_on_empty=False, fail_on_more=False)
108 if not nsrs_list:
109 self.db.set_one("vnfds", {"_id": used_vnfd_id}, {"_admin.usageState": "NOT_IN_USE"})
110
tiernobee085c2018-12-12 17:03:04 +0000111 @staticmethod
112 def _format_ns_request(ns_request):
113 formated_request = copy(ns_request)
114 formated_request.pop("additionalParamsForNs", None)
115 formated_request.pop("additionalParamsForVnf", None)
116 return formated_request
117
118 @staticmethod
119 def _format_addional_params(ns_request, member_vnf_index=None, descriptor=None):
120 """
121 Get and format user additional params for NS or VNF
122 :param ns_request: User instantiation additional parameters
123 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
124 :param descriptor: If not None it check that needed parameters of descriptor are supplied
125 :return: a formated copy of additional params or None if not supplied
126 """
127 additional_params = None
128 if not member_vnf_index:
129 additional_params = copy(ns_request.get("additionalParamsForNs"))
130 where_ = "additionalParamsForNs"
131 elif ns_request.get("additionalParamsForVnf"):
132 for additionalParamsForVnf in get_iterable(ns_request.get("additionalParamsForVnf")):
133 if additionalParamsForVnf["member-vnf-index"] == member_vnf_index:
134 additional_params = copy(additionalParamsForVnf.get("additionalParams"))
135 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
136 additionalParamsForVnf["member-vnf-index"])
137 break
138 if additional_params:
139 for k, v in additional_params.items():
delacruzramo36ffe552019-05-03 14:52:37 +0200140 # BEGIN Check that additional parameter names are valid Jinja2 identifiers
141 if not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k):
142 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
143 "and underscores, and cannot start with a digit"
144 .format(where_, k))
145 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000146 if not isinstance(k, str):
147 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
148 if "." in k or "$" in k:
149 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
150 if isinstance(v, (dict, tuple, list)):
151 additional_params[k] = "!!yaml " + safe_dump(v)
152
153 if descriptor:
154 # check that enough parameters are supplied for the initial-config-primitive
155 # TODO: check for cloud-init
156 if member_vnf_index:
157 if descriptor.get("vnf-configuration"):
158 for initial_primitive in get_iterable(
159 descriptor["vnf-configuration"].get("initial-config-primitive")):
160 for param in get_iterable(initial_primitive.get("parameter")):
161 if param["value"].startswith("<") and param["value"].endswith(">"):
162 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>"):
163 continue
164 if not additional_params or param["value"][1:-1] not in additional_params:
165 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
166 "initial-config-primitive[name={}] not supplied".
167 format(param["value"], descriptor["id"],
168 initial_primitive["name"]))
169
170 return additional_params
171
tierno65ca36d2019-02-12 19:27:52 +0100172 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200173 """
174 Creates a new nsr into database. It also creates needed vnfrs
175 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100176 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200177 :param indata: params to be used for the nsr
178 :param kwargs: used to override the indata descriptor
179 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200180 :return: the _id of nsr descriptor created at database
181 """
182
183 try:
tierno99d4b172019-07-02 09:28:40 +0000184 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200185 ns_request = self._remove_envelop(indata)
186 # Override descriptor with query string kwargs
187 self._update_input_with_kwargs(ns_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100188 self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200189
tiernob24258a2018-10-04 18:39:49 +0200190 # look for nsr
191 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
tiernob4844ab2019-05-23 08:42:12 +0000192 _filter = self._get_project_filter(session)
193 _filter["_id"] = ns_request["nsdId"]
tiernob24258a2018-10-04 18:39:49 +0200194 nsd = self.db.get_one("nsds", _filter)
tiernob4844ab2019-05-23 08:42:12 +0000195 del _filter["_id"]
tiernob24258a2018-10-04 18:39:49 +0200196
197 nsr_id = str(uuid4())
tiernobee085c2018-12-12 17:03:04 +0000198
tiernob24258a2018-10-04 18:39:49 +0200199 now = time()
200 step = "filling nsr from input data"
201 nsr_descriptor = {
202 "name": ns_request["nsName"],
203 "name-ref": ns_request["nsName"],
204 "short-name": ns_request["nsName"],
205 "admin-status": "ENABLED",
206 "nsd": nsd,
207 "datacenter": ns_request["vimAccountId"],
208 "resource-orchestrator": "osmopenmano",
209 "description": ns_request.get("nsDescription", ""),
210 "constituent-vnfr-ref": [],
211
212 "operational-status": "init", # typedef ns-operational-
213 "config-status": "init", # typedef config-states
214 "detailed-status": "scheduled",
215
216 "orchestration-progress": {},
217 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
218
tierno65ca36d2019-02-12 19:27:52 +0100219 "create-time": now,
tiernob24258a2018-10-04 18:39:49 +0200220 "nsd-name-ref": nsd["name"],
221 "operational-events": [], # "id", "timestamp", "description", "event",
222 "nsd-ref": nsd["id"],
tiernof0637052019-03-07 16:26:47 +0000223 "nsd-id": nsd["_id"],
tiernob4844ab2019-05-23 08:42:12 +0000224 "vnfd-id": [],
tiernobee085c2018-12-12 17:03:04 +0000225 "instantiate_params": self._format_ns_request(ns_request),
226 "additionalParamsForNs": self._format_addional_params(ns_request),
tiernob24258a2018-10-04 18:39:49 +0200227 "ns-instance-config-ref": nsr_id,
228 "id": nsr_id,
229 "_id": nsr_id,
230 # "input-parameter": xpath, value,
tierno99d4b172019-07-02 09:28:40 +0000231 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
tiernob24258a2018-10-04 18:39:49 +0200232 }
233 ns_request["nsr_id"] = nsr_id
tierno36ec8602018-11-02 17:27:11 +0100234 # Create vld
235 if nsd.get("vld"):
236 nsr_descriptor["vld"] = []
237 for nsd_vld in nsd.get("vld"):
238 nsr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100239 {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 +0200240
241 # Create VNFR
242 needed_vnfds = {}
gcalvino4f269dd2018-11-06 13:18:31 +0100243 for member_vnf in nsd.get("constituent-vnfd", ()):
tiernob24258a2018-10-04 18:39:49 +0200244 vnfd_id = member_vnf["vnfd-id-ref"]
245 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
246 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
247 if vnfd_id not in needed_vnfds:
248 # Obtain vnfd
tiernob4844ab2019-05-23 08:42:12 +0000249 _filter["id"] = vnfd_id
250 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
251 del _filter["id"]
tiernob24258a2018-10-04 18:39:49 +0200252 vnfd.pop("_admin")
253 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000254 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200255 else:
256 vnfd = needed_vnfds[vnfd_id]
257 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
258 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
259 vnfr_id = str(uuid4())
260 vnfr_descriptor = {
261 "id": vnfr_id,
262 "_id": vnfr_id,
263 "nsr-id-ref": nsr_id,
264 "member-vnf-index-ref": member_vnf["member-vnf-index"],
tiernobee085c2018-12-12 17:03:04 +0000265 "additionalParamsForVnf": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
266 vnfd),
tiernob24258a2018-10-04 18:39:49 +0200267 "created-time": now,
268 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
269 "vnfd-ref": vnfd_id,
270 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
271 "vim-account-id": None,
272 "vdur": [],
273 "connection-point": [],
274 "ip-address": None, # mgmt-interface filled by LCM
275 }
tierno36ec8602018-11-02 17:27:11 +0100276
277 # Create vld
278 if vnfd.get("internal-vld"):
279 vnfr_descriptor["vld"] = []
280 for vnfd_vld in vnfd.get("internal-vld"):
281 vnfr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100282 {key: vnfd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in
283 vnfd_vld})
tierno36ec8602018-11-02 17:27:11 +0100284
285 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
tiernob24258a2018-10-04 18:39:49 +0200286 for cp in vnfd.get("connection-point", ()):
287 vnf_cp = {
288 "name": cp["name"],
289 "connection-point-id": cp.get("id"),
290 "id": cp.get("id"),
291 # "ip-address", "mac-address" # filled by LCM
292 # vim-id # TODO it would be nice having a vim port id
293 }
294 vnfr_descriptor["connection-point"].append(vnf_cp)
gcalvinoe45aded2018-11-13 17:17:28 +0100295 for vdu in vnfd.get("vdu", ()):
tiernob24258a2018-10-04 18:39:49 +0200296 vdur = {
tiernob24258a2018-10-04 18:39:49 +0200297 "vdu-id-ref": vdu["id"],
298 # TODO "name": "" Name of the VDU in the VIM
299 "ip-address": None, # mgmt-interface filled by LCM
300 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
301 "internal-connection-point": [],
302 "interfaces": [],
303 }
tiernocc103432018-10-19 14:10:35 +0200304 if vdu.get("pdu-type"):
305 vdur["pdu-type"] = vdu["pdu-type"]
tiernob24258a2018-10-04 18:39:49 +0200306 # TODO volumes: name, volume-id
307 for icp in vdu.get("internal-connection-point", ()):
308 vdu_icp = {
309 "id": icp["id"],
310 "connection-point-id": icp["id"],
311 "name": icp.get("name"),
312 # "ip-address", "mac-address" # filled by LCM
313 # vim-id # TODO it would be nice having a vim port id
314 }
315 vdur["internal-connection-point"].append(vdu_icp)
316 for iface in vdu.get("interface", ()):
317 vdu_iface = {
318 "name": iface.get("name"),
319 # "ip-address", "mac-address" # filled by LCM
320 # vim-id # TODO it would be nice having a vim port id
321 }
tierno36ec8602018-11-02 17:27:11 +0100322 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
323 vdu_iface["mgmt-vnf"] = True
tiernocc103432018-10-19 14:10:35 +0200324 if iface.get("mgmt-interface"):
tierno36ec8602018-11-02 17:27:11 +0100325 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
326
327 # look for network where this interface is connected
328 if iface.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 iface["external-connection-point-ref"] and \
333 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
334 vdu_iface["ns-vld-id"] = nsd_vld["id"]
335 break
336 else:
337 continue
338 break
339 elif iface.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") == iface["internal-connection-point-ref"]:
343 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
344 break
345 else:
346 continue
347 break
tiernocc103432018-10-19 14:10:35 +0200348
tiernob24258a2018-10-04 18:39:49 +0200349 vdur["interfaces"].append(vdu_iface)
tiernocc103432018-10-19 14:10:35 +0200350 count = vdu.get("count", 1)
351 if count is None:
352 count = 1
353 count = int(count) # TODO remove when descriptor serialized with payngbind
354 for index in range(0, count):
355 if index:
356 vdur = deepcopy(vdur)
357 vdur["_id"] = str(uuid4())
358 vdur["count-index"] = index
359 vnfr_descriptor["vdur"].append(vdur)
tiernob24258a2018-10-04 18:39:49 +0200360
361 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
362 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
363
364 # add at database
tierno65ca36d2019-02-12 19:27:52 +0100365 BaseTopic.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200366 self.db.create("vnfrs", vnfr_descriptor)
367 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
368 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
369
370 step = "creating nsr at database"
tierno65ca36d2019-02-12 19:27:52 +0100371 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200372 self.db.create("nsrs", nsr_descriptor)
373 rollback.append({"topic": "nsrs", "_id": nsr_id})
tiernobee085c2018-12-12 17:03:04 +0000374
375 step = "creating nsr temporal folder"
376 self.fs.mkdir(nsr_id)
377
tiernob24258a2018-10-04 18:39:49 +0200378 return nsr_id
379 except Exception as e:
380 self.logger.exception("Exception {} at NsrTopic.new()".format(e), exc_info=True)
381 raise EngineException("Error {}: {}".format(step, e))
382 except ValidationError as e:
383 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
384
tierno65ca36d2019-02-12 19:27:52 +0100385 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200386 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
387
388
389class VnfrTopic(BaseTopic):
390 topic = "vnfrs"
391 topic_msg = None
392
393 def __init__(self, db, fs, msg):
394 BaseTopic.__init__(self, db, fs, msg)
395
tierno65ca36d2019-02-12 19:27:52 +0100396 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200397 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
398
tierno65ca36d2019-02-12 19:27:52 +0100399 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200400 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
401
tierno65ca36d2019-02-12 19:27:52 +0100402 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200403 # Not used because vnfrs are created and deleted by NsrTopic class directly
404 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
405
406
407class NsLcmOpTopic(BaseTopic):
408 topic = "nslcmops"
409 topic_msg = "ns"
410 operation_schema = { # mapping between operation and jsonschema to validate
411 "instantiate": ns_instantiate,
412 "action": ns_action,
413 "scale": ns_scale,
414 "terminate": None,
415 }
416
417 def __init__(self, db, fs, msg):
418 BaseTopic.__init__(self, db, fs, msg)
419
tiernob24258a2018-10-04 18:39:49 +0200420 def _check_ns_operation(self, session, nsr, operation, indata):
421 """
422 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100423 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200424 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
425 :param indata: descriptor with the parameters of the operation
426 :return: None
427 """
428 vnfds = {}
429 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000430 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200431 nsd = nsr["nsd"]
432
433 def check_valid_vnf_member_index(member_vnf_index):
434 # TODO change to vnfR
435 for vnf in nsd["constituent-vnfd"]:
436 if member_vnf_index == vnf["member-vnf-index"]:
437 vnfd_id = vnf["vnfd-id-ref"]
438 if vnfd_id not in vnfds:
439 vnfds[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
440 return vnfds[vnfd_id]
441 else:
442 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
443 "nsd:constituent-vnfd".format(member_vnf_index))
444
gcalvino5e72d152018-10-23 11:46:57 +0200445 def _check_vnf_instantiation_params(in_vnfd, vnfd):
446
tierno40fbcad2018-10-26 10:58:15 +0200447 for in_vdu in get_iterable(in_vnfd.get("vdu")):
448 for vdu in get_iterable(vnfd.get("vdu")):
449 if in_vdu["id"] == vdu["id"]:
450 for volume in get_iterable(in_vdu.get("volume")):
451 for volumed in get_iterable(vdu.get("volumes")):
452 if volumed["name"] == volume["name"]:
453 break
454 else:
455 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
456 "volume:name='{}' is not present at vnfd:vdu:volumes list".
457 format(in_vnf["member-vnf-index"], in_vdu["id"],
458 volume["name"]))
459 for in_iface in get_iterable(in_vdu["interface"]):
460 for iface in get_iterable(vdu.get("interface")):
461 if in_iface["name"] == iface["name"]:
462 break
463 else:
464 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
465 "interface[name='{}'] is not present at vnfd:vdu:interface"
466 .format(in_vnf["member-vnf-index"], in_vdu["id"],
467 in_iface["name"]))
468 break
gcalvino5e72d152018-10-23 11:46:57 +0200469 else:
tierno40fbcad2018-10-26 10:58:15 +0200470 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
471 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200472
473 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
474 for ivld in get_iterable(vnfd.get("internal-vld")):
475 if in_ivld["name"] == ivld["name"] or in_ivld["name"] == ivld["id"]:
476 for in_icp in get_iterable(in_ivld["internal-connection-point"]):
477 for icp in ivld["internal-connection-point"]:
478 if in_icp["id-ref"] == icp["id-ref"]:
479 break
480 else:
tierno40fbcad2018-10-26 10:58:15 +0200481 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
482 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
483 "vnfd:internal-vld:name/id:internal-connection-point"
484 .format(in_vnf["member-vnf-index"], in_ivld["name"],
485 in_icp["id-ref"], vnfd["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200486 break
487 else:
488 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
489 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
490 in_ivld["name"], vnfd["id"]))
491
tiernob24258a2018-10-04 18:39:49 +0200492 def check_valid_vim_account(vim_account):
493 if vim_account in vim_accounts:
494 return
495 try:
tierno65ca36d2019-02-12 19:27:52 +0100496 db_filter = self._get_project_filter(session)
tiernocc103432018-10-19 14:10:35 +0200497 db_filter["_id"] = vim_account
498 self.db.get_one("vim_accounts", db_filter)
tiernob24258a2018-10-04 18:39:49 +0200499 except Exception:
tiernocc103432018-10-19 14:10:35 +0200500 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
tiernob24258a2018-10-04 18:39:49 +0200501 vim_accounts.append(vim_account)
502
tierno4f9d4ae2019-03-20 17:24:11 +0000503 def check_valid_wim_account(wim_account):
504 if not isinstance(wim_account, str):
505 return
506 elif wim_account in wim_accounts:
507 return
508 try:
509 db_filter = self._get_project_filter(session, write=False, show_all=True)
510 db_filter["_id"] = wim_account
511 self.db.get_one("wim_accounts", db_filter)
512 except Exception:
513 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
514 wim_accounts.append(wim_account)
515
tiernob24258a2018-10-04 18:39:49 +0200516 if operation == "action":
517 # check vnf_member_index
518 if indata.get("vnf_member_index"):
519 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
tierno1ac7f462019-06-03 17:22:12 +0000520 if indata.get("member_vnf_index"):
521 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
522 descriptor_configuration = vnfd.get("vnf-configuration", {}).get("config-primitive")
523 else: # use a NSD
524 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
tiernob24258a2018-10-04 18:39:49 +0200525 # check primitive
tierno1ac7f462019-06-03 17:22:12 +0000526 for config_primitive in get_iterable(descriptor_configuration):
tiernob24258a2018-10-04 18:39:49 +0200527 if indata["primitive"] == config_primitive["name"]:
528 # check needed primitive_params are provided
529 if indata.get("primitive_params"):
530 in_primitive_params_copy = copy(indata["primitive_params"])
531 else:
532 in_primitive_params_copy = {}
533 for paramd in get_iterable(config_primitive.get("parameter")):
534 if paramd["name"] in in_primitive_params_copy:
535 del in_primitive_params_copy[paramd["name"]]
536 elif not paramd.get("default-value"):
537 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
538 paramd["name"], indata["primitive"]))
539 # check no extra primitive params are provided
540 if in_primitive_params_copy:
tierno1ac7f462019-06-03 17:22:12 +0000541 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
tiernob24258a2018-10-04 18:39:49 +0200542 list(in_primitive_params_copy.keys()), indata["primitive"]))
543 break
544 else:
tierno1ac7f462019-06-03 17:22:12 +0000545 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
tiernob24258a2018-10-04 18:39:49 +0200546 if operation == "scale":
547 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
548 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
549 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
550 break
551 else:
552 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
553 "present at vnfd:scaling-group-descriptor".format(
554 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
555 if operation == "instantiate":
556 # check vim_account
557 check_valid_vim_account(indata["vimAccountId"])
tierno4f9d4ae2019-03-20 17:24:11 +0000558 check_valid_wim_account(indata.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200559 for in_vnf in get_iterable(indata.get("vnf")):
560 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
gcalvino5e72d152018-10-23 11:46:57 +0200561 _check_vnf_instantiation_params(in_vnf, vnfd)
tiernob24258a2018-10-04 18:39:49 +0200562 if in_vnf.get("vimAccountId"):
563 check_valid_vim_account(in_vnf["vimAccountId"])
tiernob24258a2018-10-04 18:39:49 +0200564
tiernob24258a2018-10-04 18:39:49 +0200565 for in_vld in get_iterable(indata.get("vld")):
tierno4f9d4ae2019-03-20 17:24:11 +0000566 check_valid_wim_account(in_vld.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200567 for vldd in get_iterable(nsd.get("vld")):
568 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
569 break
570 else:
571 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
572 in_vld["name"]))
573
tierno36ec8602018-11-02 17:27:11 +0100574 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200575 """
tierno36ec8602018-11-02 17:27:11 +0100576 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
577 (ip_address, ...) information.
578 Modifies PDU _admin.usageState to 'IN_USE'
579
tierno65ca36d2019-02-12 19:27:52 +0100580 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100581 :param rollback: list with the database modifications to rollback if needed
582 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
583 :param vim_account: vim_account where this vnfr should be deployed
584 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
585 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
586 of the changed vnfr is needed
587
588 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
589 "vim-network-name": used at VIM
590 "name": interface name
591 "vnf-vld-id": internal VNFD vld where this interface is connected, or
592 "ns-vld-id": NSD vld where this interface is connected.
593 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 +0200594 """
tierno36ec8602018-11-02 17:27:11 +0100595
596 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +0200597 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
598 if not vdur.get("pdu-type"):
599 continue
600 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +0100601 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +0100602 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +0200603 pdu_filter["type"] = pdu_type
604 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +0100605 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +0200606 # TODO feature 1417: "shared": True,
607
608 available_pdus = self.db.get_list("pdus", pdu_filter)
609 for pdu in available_pdus:
610 # step 1 check if this pdu contains needed interfaces:
611 match_interfaces = True
612 for vdur_interface in vdur["interfaces"]:
613 for pdu_interface in pdu["interfaces"]:
614 if pdu_interface["name"] == vdur_interface["name"]:
615 # TODO feature 1417: match per mgmt type
616 break
617 else: # no interface found for name
618 match_interfaces = False
619 break
620 if match_interfaces:
621 break
622 else:
623 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +0100624 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
625 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +0200626
627 # step 2. Update pdu
628 rollback_pdu = {
629 "_admin.usageState": pdu["_admin"]["usageState"],
630 "_admin.usage.vnfr_id": None,
631 "_admin.usage.nsr_id": None,
632 "_admin.usage.vdur": None,
633 }
634 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +0100635 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +0000636 "_admin.usage": {"vnfr_id": vnfr["_id"],
637 "nsr_id": vnfr["nsr-id-ref"],
638 "vdur": vdur["vdu-id-ref"]}
639 })
tiernocc103432018-10-19 14:10:35 +0200640 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
641
642 # step 3. Fill vnfr info by filling vdur
643 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +0100644 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +0200645 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
646 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
647 for pdu_interface in pdu["interfaces"]:
648 if pdu_interface["name"] == vdur_interface["name"]:
649 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
650 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +0100651 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
652 vnfr_update[iface_text + ".{}".format(k)] = v
653 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
654 if pdu_interface.get("ip-address"):
655 if vdur_interface.get("mgmt-interface"):
656 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
657 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
658 if vdur_interface.get("mgmt-vnf"):
659 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
660 vnfr_update["ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +0100661 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +0100662 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +0100663 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
664 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
665 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +0100666 if pdu_interface.get("vim-network-id"):
667 ifaces_forcing_vim_network.append({
668 "vim-network-id": pdu_interface.get("vim-network-id")})
669 if pdu_interface.get("vim-network-name"):
670 ifaces_forcing_vim_network.append({
671 "vim-network-name": pdu_interface.get("vim-network-name")})
tiernocc103432018-10-19 14:10:35 +0200672 break
673
tierno36ec8602018-11-02 17:27:11 +0100674 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +0200675
676 def _update_vnfrs(self, session, rollback, nsr, indata):
677 vnfrs = None
678 # get vnfr
679 nsr_id = nsr["_id"]
680 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
681
682 for vnfr in vnfrs:
683 vnfr_update = {}
684 vnfr_update_rollback = {}
685 member_vnf_index = vnfr["member-vnf-index-ref"]
686 # update vim-account-id
687
688 vim_account = indata["vimAccountId"]
689 # check instantiate parameters
690 for vnf_inst_params in get_iterable(indata.get("vnf")):
691 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
692 continue
693 if vnf_inst_params.get("vimAccountId"):
694 vim_account = vnf_inst_params.get("vimAccountId")
695
696 vnfr_update["vim-account-id"] = vim_account
697 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
698
699 # get pdu
tierno36ec8602018-11-02 17:27:11 +0100700 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
701 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +0200702
tierno36ec8602018-11-02 17:27:11 +0100703 # updata database vnfr
704 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
705 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
706
707 # Update indada in case pdu forces to use a concrete vim-network-name
708 # TODO check if user has already insert a vim-network-name and raises an error
709 if not ifaces_forcing_vim_network:
710 continue
711 for iface_info in ifaces_forcing_vim_network:
712 if iface_info.get("ns-vld-id"):
713 if "vld" not in indata:
714 indata["vld"] = []
715 indata["vld"].append({key: iface_info[key] for key in
716 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
717
718 elif iface_info.get("vnf-vld-id"):
719 if "vnf" not in indata:
720 indata["vnf"] = []
721 indata["vnf"].append({
722 "member-vnf-index": member_vnf_index,
723 "internal-vld": [{key: iface_info[key] for key in
724 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
725 })
726
727 @staticmethod
728 def _create_nslcmop(nsr_id, operation, params):
729 """
730 Creates a ns-lcm-opp content to be stored at database.
731 :param nsr_id: internal id of the instance
732 :param operation: instantiate, terminate, scale, action, ...
733 :param params: user parameters for the operation
734 :return: dictionary following SOL005 format
735 """
tiernob24258a2018-10-04 18:39:49 +0200736 now = time()
737 _id = str(uuid4())
738 nslcmop = {
739 "id": _id,
740 "_id": _id,
741 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
742 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +0100743 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200744 "lcmOperationType": operation,
745 "startTime": now,
746 "isAutomaticInvocation": False,
747 "operationParams": params,
748 "isCancelPending": False,
749 "links": {
750 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +0100751 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200752 }
753 }
754 return nslcmop
755
tierno65ca36d2019-02-12 19:27:52 +0100756 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +0200757 """
758 Performs a new operation over a ns
759 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100760 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200761 :param indata: descriptor with the parameters of the operation. It must contains among others
762 nsInstanceId: _id of the nsr to perform the operation
763 operation: it can be: instantiate, terminate, action, TODO: update, heal
764 :param kwargs: used to override the indata descriptor
765 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200766 :return: id of the nslcmops
767 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +0200768 def check_if_nsr_is_not_slice_member(session, nsr_id):
769 nsis = None
770 db_filter = self._get_project_filter(session)
771 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
772 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
773 if nsis:
774 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
775 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
776
tiernob24258a2018-10-04 18:39:49 +0200777 try:
778 # Override descriptor with query string kwargs
779 self._update_input_with_kwargs(indata, kwargs)
780 operation = indata["lcmOperationType"]
781 nsInstanceId = indata["nsInstanceId"]
782
783 validate_input(indata, self.operation_schema[operation])
784 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +0100785 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +0200786 _filter["_id"] = nsInstanceId
787 nsr = self.db.get_one("nsrs", _filter)
788
789 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +0200790 if operation == "terminate" and slice_object is False:
791 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +0200792 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
793 if operation == "terminate" and indata.get("autoremove"):
794 # NSR must be deleted
tiernoe8631782018-12-21 13:31:52 +0000795 return None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +0200796 if operation != "instantiate":
797 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
798 nsInstanceId, operation), HTTPStatus.CONFLICT)
799 else:
tierno65ca36d2019-02-12 19:27:52 +0100800 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200801 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
802 nsInstanceId, operation), HTTPStatus.CONFLICT)
803 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +0100804
tiernocc103432018-10-19 14:10:35 +0200805 if operation == "instantiate":
806 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +0100807
808 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +0100809 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200810 _id = self.db.create("nslcmops", nslcmop_desc)
811 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +0100812 if not slice_object:
813 self.msg.write("ns", operation, nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +0200814 return _id
815 except ValidationError as e:
816 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
817 # except DbException as e:
818 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
819
tierno65ca36d2019-02-12 19:27:52 +0100820 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200821 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
822
tierno65ca36d2019-02-12 19:27:52 +0100823 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200824 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +0200825
826
827class NsiTopic(BaseTopic):
828 topic = "nsis"
829 topic_msg = "nsi"
830
831 def __init__(self, db, fs, msg):
832 BaseTopic.__init__(self, db, fs, msg)
tiernofd160572019-01-21 10:41:37 +0000833 self.nsrTopic = NsrTopic(db, fs, msg)
Felipe Vicensb57758d2018-10-16 16:00:20 +0200834
Felipe Vicensc37b3842019-01-12 12:24:42 +0100835 @staticmethod
836 def _format_ns_request(ns_request):
837 formated_request = copy(ns_request)
838 # TODO: Add request params
839 return formated_request
840
841 @staticmethod
tiernofd160572019-01-21 10:41:37 +0000842 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +0100843 """
844 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +0000845 :param slice_request: User instantiation additional parameters
846 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +0100847 """
tiernofd160572019-01-21 10:41:37 +0000848 additional_params = copy(slice_request.get("additionalParamsForNsi"))
849 if additional_params:
850 for k, v in additional_params.items():
851 if not isinstance(k, str):
852 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
853 format(k))
854 if "." in k or "$" in k:
855 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
856 format(k))
857 if isinstance(v, (dict, tuple, list)):
858 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +0100859 return additional_params
860
Felipe Vicensb57758d2018-10-16 16:00:20 +0200861 def _check_descriptor_dependencies(self, session, descriptor):
862 """
863 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +0100864 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +0200865 :param descriptor: descriptor to be inserted or edit
866 :return: None or raises exception
867 """
Felipe Vicens07f31722018-10-29 15:16:44 +0100868 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +0200869 return
Felipe Vicens07f31722018-10-29 15:16:44 +0100870 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +0200871 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +0100872 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +0200873 http_code=HTTPStatus.CONFLICT)
874
tiernob4844ab2019-05-23 08:42:12 +0000875 def check_conflict_on_del(self, session, _id, db_content):
876 """
877 Check that NSI is not instantiated
878 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
879 :param _id: nsi internal id
880 :param db_content: The database content of the _id
881 :return: None or raises EngineException with the conflict
882 """
tierno65ca36d2019-02-12 19:27:52 +0100883 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +0200884 return
tiernob4844ab2019-05-23 08:42:12 +0000885 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +0200886 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
887 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
888 "Launch 'terminate' operation first; or force deletion".format(_id),
889 http_code=HTTPStatus.CONFLICT)
890
tiernob4844ab2019-05-23 08:42:12 +0000891 def delete_extra(self, session, _id, db_content):
Felipe Vicensb57758d2018-10-16 16:00:20 +0200892 """
tiernob4844ab2019-05-23 08:42:12 +0000893 Deletes associated nsilcmops from database. Deletes associated filesystem.
894 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +0100895 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +0200896 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +0000897 :param db_content: The database content of the descriptor
898 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +0200899 """
Felipe Vicens07f31722018-10-29 15:16:44 +0100900
Felipe Vicens09e65422019-01-22 15:06:46 +0100901 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +0000902 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +0100903 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
904 nsr_id = nsrs_detailed_item["nsrId"]
905 if nsrs_detailed_item.get("shared"):
906 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
907 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
908 "_id.ne": nsir["_id"]}
909 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
910 if nsi: # last one using nsr
911 continue
912 try:
tierno65ca36d2019-02-12 19:27:52 +0100913 self.nsrTopic.delete(session, nsr_id, dry_run=False)
Felipe Vicens09e65422019-01-22 15:06:46 +0100914 except (DbException, EngineException) as e:
915 if e.http_code == HTTPStatus.NOT_FOUND:
916 pass
917 else:
918 raise
Felipe Vicens07f31722018-10-29 15:16:44 +0100919
tiernob4844ab2019-05-23 08:42:12 +0000920 # delete related nsilcmops database entries
921 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +0100922
tiernob4844ab2019-05-23 08:42:12 +0000923 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +0100924 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +0000925 if nsir_admin and nsir_admin.get("nst-id"):
926 # check if used by another NSI
927 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
928 fail_on_empty=False, fail_on_more=False)
929 if not nsis_list:
930 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
931
932 # def delete(self, session, _id, dry_run=False):
933 # """
934 # Delete item by its internal _id
935 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
936 # :param _id: server internal id
937 # :param dry_run: make checking but do not delete
938 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
939 # """
940 # # TODO add admin to filter, validate rights
941 # BaseTopic.delete(self, session, _id, dry_run=True)
942 # if dry_run:
943 # return
944 #
945 # # Deleting the nsrs belonging to nsir
946 # nsir = self.db.get_one("nsis", {"_id": _id})
947 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
948 # nsr_id = nsrs_detailed_item["nsrId"]
949 # if nsrs_detailed_item.get("shared"):
950 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
951 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
952 # "_id.ne": nsir["_id"]}
953 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
954 # if nsi: # last one using nsr
955 # continue
956 # try:
957 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
958 # except (DbException, EngineException) as e:
959 # if e.http_code == HTTPStatus.NOT_FOUND:
960 # pass
961 # else:
962 # raise
963 # # deletes NetSlice instance object
964 # v = self.db.del_one("nsis", {"_id": _id})
965 #
966 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
967 # _filter = {"netsliceInstanceId": _id}
968 # self.db.del_list("nsilcmops", _filter)
969 #
970 # # Search if nst is being used by other nsi
971 # nsir_admin = nsir.get("_admin")
972 # if nsir_admin:
973 # if nsir_admin.get("nst-id"):
974 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
975 # fail_on_empty=False, fail_on_more=False)
976 # if not nsis_list:
977 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
978 # return v
Felipe Vicensb57758d2018-10-16 16:00:20 +0200979
tierno65ca36d2019-02-12 19:27:52 +0100980 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +0200981 """
Felipe Vicens07f31722018-10-29 15:16:44 +0100982 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +0200983 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100984 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +0200985 :param indata: params to be used for the nsir
986 :param kwargs: used to override the indata descriptor
987 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +0200988 :return: the _id of nsi descriptor created at database
989 """
990
991 try:
tierno99d4b172019-07-02 09:28:40 +0000992 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +0200993 slice_request = self._remove_envelop(indata)
994 # Override descriptor with query string kwargs
995 self._update_input_with_kwargs(slice_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100996 self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +0200997
Felipe Vicensb57758d2018-10-16 16:00:20 +0200998 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +0000999 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001000 _filter = self._get_project_filter(session)
1001 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001002 nstd = self.db.get_one("nsts", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001003 del _filter["_id"]
1004
Felipe Vicens07f31722018-10-29 15:16:44 +01001005 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001006 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001007 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001008 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001009
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001010 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001011 nsi_descriptor = {
1012 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001013 "name": slice_request["nsiName"],
1014 "description": slice_request.get("nsiDescription", ""),
1015 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001016 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001017 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001018 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001019 "nsr-ref-list": [],
1020 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001021 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001022 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001023 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001024
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001025 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001026 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001027 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1028 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001029 nsi_descriptor["_admin"]["deployed"] = {}
1030 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1031 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1032
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001033 # Creating netslice-vld for the RO.
1034 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001035
1036 # Building the vlds list to be deployed
1037 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001038 nsi_vlds = []
1039
1040 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1041 # Getting template Instantiation parameters from NST
1042 nsi_vld = deepcopy(netslice_vlds)
1043 nsi_vld["shared-nsrs-list"] = []
1044 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1045 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001046
1047 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
Felipe Vicens07f31722018-10-29 15:16:44 +01001048 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001049 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001050 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001051
Felipe Vicens09e65422019-01-22 15:06:46 +01001052 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001053 for member_ns in nstd["netslice-subnet"]:
1054 nsd_id = member_ns["nsd-ref"]
1055 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1056 member_ns["nsd-ref"], member_ns["id"])
1057 if nsd_id not in needed_nsds:
1058 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001059 _filter["id"] = nsd_id
1060 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1061 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001062 nsd.pop("_admin")
1063 needed_nsds[nsd_id] = nsd
1064 else:
1065 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001066 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1067 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001068
Felipe Vicensb57758d2018-10-16 16:00:20 +02001069 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1070 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001071
Felipe Vicens07f31722018-10-29 15:16:44 +01001072 # creates Network Services records (NSRs)
1073 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001074 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001075 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001076 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001077 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001078 # Check if the netslice-subnet is shared and if it is share if the nss exists
1079 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001080 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001081 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001082 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1083 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001084 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
tierno032916c2019-03-22 13:27:12 +00001085
Felipe Vicens09e65422019-01-22 15:06:46 +01001086 if nsi and service.get("is-shared-nss"):
1087 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1088 for nsrs_detailed_item in nsrs_detailed_list:
1089 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
1090 _id_nsr = nsrs_detailed_item["nsrId"]
1091 break
1092 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1093 if netslice_subnet["nss-id"] == service["id"]:
1094 indata_ns = netslice_subnet
1095 break
1096 else:
1097 indata_ns = {}
1098 if service.get("instantiation-parameters"):
1099 indata_ns = deepcopy(service["instantiation-parameters"])
1100 # del service["instantiation-parameters"]
1101
1102 indata_ns["nsdId"] = service["_id"]
1103 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1104 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1105 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001106 if slice_request.get("ssh_keys"):
1107 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001108
Felipe Vicens09e65422019-01-22 15:06:46 +01001109 if ns_params:
1110 for ns_param in ns_params:
1111 if ns_param.get("id") == service["id"]:
1112 copy_ns_param = deepcopy(ns_param)
1113 del copy_ns_param["id"]
1114 indata_ns.update(copy_ns_param)
1115 break
1116
1117 # Creates Nsr objects
tierno65ca36d2019-02-12 19:27:52 +01001118 _id_nsr = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001119 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
1120 "nslcmop_instantiate": None}
1121 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001122 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001123 nsi_netslice_subnet.append(indata_ns)
1124 nsr_ref = {"nsr-ref": _id_nsr}
1125 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001126
1127 # Adding the nsrs list to the nsi
1128 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001129 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001130 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1131
Felipe Vicens07f31722018-10-29 15:16:44 +01001132 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001133 self.db.create("nsis", nsi_descriptor)
1134 rollback.append({"topic": "nsis", "_id": nsi_id})
1135 return nsi_id
1136 except Exception as e:
1137 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1138 raise EngineException("Error {}: {}".format(step, e))
1139 except ValidationError as e:
1140 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1141
tierno65ca36d2019-02-12 19:27:52 +01001142 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001143 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001144
1145
1146class NsiLcmOpTopic(BaseTopic):
1147 topic = "nsilcmops"
1148 topic_msg = "nsi"
1149 operation_schema = { # mapping between operation and jsonschema to validate
1150 "instantiate": nsi_instantiate,
1151 "terminate": None
1152 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001153
Felipe Vicens07f31722018-10-29 15:16:44 +01001154 def __init__(self, db, fs, msg):
1155 BaseTopic.__init__(self, db, fs, msg)
Felipe Vicens09e65422019-01-22 15:06:46 +01001156 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg)
Felipe Vicens07f31722018-10-29 15:16:44 +01001157
1158 def _check_nsi_operation(self, session, nsir, operation, indata):
1159 """
1160 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001161 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001162 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1163 :param indata: descriptor with the parameters of the operation
1164 :return: None
1165 """
1166 nsds = {}
1167 nstd = nsir["network-slice-template"]
1168
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001169 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001170 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001171 for netslice_subnet in nstd["netslice-subnet"]:
1172 if nstId == netslice_subnet["id"]:
1173 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001174 if nsd_id not in nsds:
1175 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1176 return nsds[nsd_id]
1177 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001178 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1179 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001180 if operation == "instantiate":
1181 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001182 for in_nst in get_iterable(indata.get("netslice-subnet")):
1183 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001184
1185 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1186 now = time()
1187 _id = str(uuid4())
1188 nsilcmop = {
1189 "id": _id,
1190 "_id": _id,
1191 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1192 "statusEnteredTime": now,
1193 "netsliceInstanceId": netsliceInstanceId,
1194 "lcmOperationType": operation,
1195 "startTime": now,
1196 "isAutomaticInvocation": False,
1197 "operationParams": params,
1198 "isCancelPending": False,
1199 "links": {
1200 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001201 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001202 }
1203 }
1204 return nsilcmop
1205
Felipe Vicens09e65422019-01-22 15:06:46 +01001206 def add_shared_nsr_2vld(self, nsir, nsr_item):
1207 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1208 if nst_sb_item.get("is-shared-nss"):
1209 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1210 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1211 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1212 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1213 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1214 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1215 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1216 break
1217 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1218 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1219
tierno65ca36d2019-02-12 19:27:52 +01001220 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001221 """
1222 Performs a new operation over a ns
1223 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001224 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001225 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001226 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001227 operation: it can be: instantiate, terminate, action, TODO: update, heal
1228 :param kwargs: used to override the indata descriptor
1229 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001230 :return: id of the nslcmops
1231 """
1232 try:
1233 # Override descriptor with query string kwargs
1234 self._update_input_with_kwargs(indata, kwargs)
1235 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001236 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001237 validate_input(indata, self.operation_schema[operation])
1238
Felipe Vicens126af572019-06-05 19:13:04 +02001239 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001240 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001241 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001242 nsir = self.db.get_one("nsis", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001243 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001244
1245 # initial checking
1246 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1247 if operation == "terminate" and indata.get("autoremove"):
1248 # NSIR must be deleted
tiernoe8631782018-12-21 13:31:52 +00001249 return None # a none in this case is used to indicate not instantiated. It can be removed
Felipe Vicens07f31722018-10-29 15:16:44 +01001250 if operation != "instantiate":
1251 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001252 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001253 else:
tierno65ca36d2019-02-12 19:27:52 +01001254 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001255 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001256 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001257
1258 # Creating all the NS_operation (nslcmop)
1259 # Get service list from db
1260 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1261 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001262 # nslcmops_item = None
1263 for index, nsr_item in enumerate(nsrs_list):
1264 nsi = None
1265 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001266 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tiernob4844ab2019-05-23 08:42:12 +00001267 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1268 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001269 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001270 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001271 if operation == "terminate":
1272 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1273 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1274
Felipe Vicens09e65422019-01-22 15:06:46 +01001275 # looks the first nsi fulfilling the conditions but not being the current NSIR
1276 if nsi:
1277 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1278 for nsi_nsr_item in nsi_admin_shared:
1279 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1280 self.add_shared_nsr_2vld(nsir, nsr_item)
1281 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1282 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1283 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1284 break
1285 # continue to not create nslcmop since nsrs is shared and nsrs was created
1286 continue
1287 else:
1288 self.add_shared_nsr_2vld(nsir, nsr_item)
1289
1290 try:
1291 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1292 indata_ns = {}
1293 indata_ns = service["instantiate_params"]
1294 indata_ns["lcmOperationType"] = operation
1295 indata_ns["nsInstanceId"] = service["_id"]
1296 # Including netslice_id in the ns instantiate Operation
Felipe Vicens126af572019-06-05 19:13:04 +02001297 indata_ns["netsliceInstanceId"] = netsliceInstanceId
tierno99d4b172019-07-02 09:28:40 +00001298 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001299 # message via kafka bus
tierno65ca36d2019-02-12 19:27:52 +01001300 nslcmop = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
Felipe Vicens09e65422019-01-22 15:06:46 +01001301 slice_object=True)
1302 nslcmops.append(nslcmop)
1303 if operation == "terminate":
1304 nslcmop = None
1305 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1306 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1307 except (DbException, EngineException) as e:
1308 if e.http_code == HTTPStatus.NOT_FOUND:
1309 self.logger.info("HTTPStatus.NOT_FOUND")
1310 pass
1311 else:
1312 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001313
1314 # Creates nsilcmop
1315 indata["nslcmops_ids"] = nslcmops
1316 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001317
Felipe Vicens126af572019-06-05 19:13:04 +02001318 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001319 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001320 _id = self.db.create("nsilcmops", nsilcmop_desc)
1321 rollback.append({"topic": "nsilcmops", "_id": _id})
1322 self.msg.write("nsi", operation, nsilcmop_desc)
1323 return _id
1324 except ValidationError as e:
1325 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001326
tierno65ca36d2019-02-12 19:27:52 +01001327 def delete(self, session, _id, dry_run=False):
Felipe Vicens07f31722018-10-29 15:16:44 +01001328 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1329
tierno65ca36d2019-02-12 19:27:52 +01001330 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001331 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)