blob: 12deff7617470b17b8ee5911e05fd427b6293d8e [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernob24258a2018-10-04 18:39:49 +020016# import logging
17from uuid import uuid4
18from http import HTTPStatus
19from time import time
tiernocc103432018-10-19 14:10:35 +020020from copy import copy, deepcopy
tierno1c38f2f2020-03-24 11:51:39 +000021from osm_nbi.validation import validate_input, ValidationError, ns_instantiate, ns_terminate, ns_action, ns_scale,\
22 nsi_instantiate
tierno714954e2019-11-29 13:43:26 +000023from osm_nbi.base_topic import BaseTopic, EngineException, get_iterable, deep_get
tiernob4844ab2019-05-23 08:42:12 +000024# from descriptor_topics import DescriptorTopic
tiernobee085c2018-12-12 17:03:04 +000025from yaml import safe_dump
Felipe Vicens09e65422019-01-22 15:06:46 +010026from osm_common.dbbase import DbException
tierno1bfe4e22019-09-02 16:03:25 +000027from osm_common.msgbase import MsgException
28from osm_common.fsbase import FsException
delacruzramo36ffe552019-05-03 14:52:37 +020029from re import match # For checking that additional parameter names are valid Jinja2 identifiers
tiernob24258a2018-10-04 18:39:49 +020030
31__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
32
33
34class NsrTopic(BaseTopic):
35 topic = "nsrs"
36 topic_msg = "ns"
tierno6b02b052020-06-02 10:07:41 +000037 quota_name = "ns_instances"
tiernod77ba6f2019-06-27 14:31:10 +000038 schema_new = ns_instantiate
tiernob24258a2018-10-04 18:39:49 +020039
delacruzramo32bab472019-09-13 12:24:22 +020040 def __init__(self, db, fs, msg, auth):
41 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020042
43 def _check_descriptor_dependencies(self, session, descriptor):
44 """
45 Check that the dependent descriptors exist on a new descriptor or edition
46 :param session: client session information
47 :param descriptor: descriptor to be inserted or edit
48 :return: None or raises exception
49 """
50 if not descriptor.get("nsdId"):
51 return
52 nsd_id = descriptor["nsdId"]
53 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
54 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
55 http_code=HTTPStatus.CONFLICT)
56
57 @staticmethod
58 def format_on_new(content, project_id=None, make_public=False):
59 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
60 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
tiernobdebce92019-07-01 15:36:49 +000061 return None
tiernob24258a2018-10-04 18:39:49 +020062
tiernob4844ab2019-05-23 08:42:12 +000063 def check_conflict_on_del(self, session, _id, db_content):
64 """
65 Check that NSR is not instantiated
66 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
67 :param _id: nsr internal id
68 :param db_content: The database content of the nsr
69 :return: None or raises EngineException with the conflict
70 """
tierno65ca36d2019-02-12 19:27:52 +010071 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +020072 return
tiernob4844ab2019-05-23 08:42:12 +000073 nsr = db_content
tiernob24258a2018-10-04 18:39:49 +020074 if nsr["_admin"].get("nsState") == "INSTANTIATED":
75 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
76 "Launch 'terminate' operation first; or force deletion".format(_id),
77 http_code=HTTPStatus.CONFLICT)
78
tiernobee3bad2019-12-05 12:26:01 +000079 def delete_extra(self, session, _id, db_content, not_send_msg=None):
tiernob4844ab2019-05-23 08:42:12 +000080 """
81 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
82 Set usageState of pdu, vnfd, nsd
83 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
84 :param _id: server internal id
85 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +000086 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +000087 :return: None if ok or raises EngineException with the problem
88 """
tiernobee085c2018-12-12 17:03:04 +000089 self.fs.file_delete(_id, ignore_non_exist=True)
tiernob24258a2018-10-04 18:39:49 +020090 self.db.del_list("nslcmops", {"nsInstanceId": _id})
91 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
tiernob4844ab2019-05-23 08:42:12 +000092
tiernob24258a2018-10-04 18:39:49 +020093 # set all used pdus as free
94 self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
tierno36ec8602018-11-02 17:27:11 +010095 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
tiernob24258a2018-10-04 18:39:49 +020096
tiernob4844ab2019-05-23 08:42:12 +000097 # Set NSD usageState
98 nsr = db_content
99 used_nsd_id = nsr.get("nsd-id")
100 if used_nsd_id:
101 # check if used by another NSR
102 nsrs_list = self.db.get_one("nsrs", {"nsd-id": used_nsd_id},
103 fail_on_empty=False, fail_on_more=False)
104 if not nsrs_list:
105 self.db.set_one("nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"})
106
107 # Set VNFD usageState
108 used_vnfd_id_list = nsr.get("vnfd-id")
109 if used_vnfd_id_list:
110 for used_vnfd_id in used_vnfd_id_list:
111 # check if used by another NSR
112 nsrs_list = self.db.get_one("nsrs", {"vnfd-id": used_vnfd_id},
113 fail_on_empty=False, fail_on_more=False)
114 if not nsrs_list:
115 self.db.set_one("vnfds", {"_id": used_vnfd_id}, {"_admin.usageState": "NOT_IN_USE"})
116
tiernobee085c2018-12-12 17:03:04 +0000117 @staticmethod
118 def _format_ns_request(ns_request):
119 formated_request = copy(ns_request)
120 formated_request.pop("additionalParamsForNs", None)
121 formated_request.pop("additionalParamsForVnf", None)
122 return formated_request
123
124 @staticmethod
tiernoe19707b2020-04-21 13:08:04 +0000125 def _format_additional_params(ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None):
tiernobee085c2018-12-12 17:03:04 +0000126 """
127 Get and format user additional params for NS or VNF
128 :param ns_request: User instantiation additional parameters
129 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
130 :param descriptor: If not None it check that needed parameters of descriptor are supplied
tierno54db2e42020-04-06 15:29:42 +0000131 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
tiernobee085c2018-12-12 17:03:04 +0000132 """
133 additional_params = None
tierno54db2e42020-04-06 15:29:42 +0000134 other_params = None
tiernobee085c2018-12-12 17:03:04 +0000135 if not member_vnf_index:
136 additional_params = copy(ns_request.get("additionalParamsForNs"))
137 where_ = "additionalParamsForNs"
138 elif ns_request.get("additionalParamsForVnf"):
tierno714954e2019-11-29 13:43:26 +0000139 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index)
140 item = next((x for x in ns_request["additionalParamsForVnf"] if x["member-vnf-index"] == member_vnf_index),
141 None)
142 if item:
tierno54db2e42020-04-06 15:29:42 +0000143 if not vdu_id and not kdu_name:
144 other_params = item
tierno714954e2019-11-29 13:43:26 +0000145 additional_params = copy(item.get("additionalParams")) or {}
146 if vdu_id and item.get("additionalParamsForVdu"):
147 item_vdu = next((x for x in item["additionalParamsForVdu"] if x["vdu_id"] == vdu_id), None)
tiernobce98f02020-04-17 11:27:47 +0000148 other_params = item_vdu
tierno714954e2019-11-29 13:43:26 +0000149 if item_vdu and item_vdu.get("additionalParams"):
150 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
tiernob091dc12019-12-02 15:53:25 +0000151 additional_params = item_vdu["additionalParams"]
152 if kdu_name:
153 additional_params = {}
154 if item.get("additionalParamsForKdu"):
155 item_kdu = next((x for x in item["additionalParamsForKdu"] if x["kdu_name"] == kdu_name), None)
tiernobce98f02020-04-17 11:27:47 +0000156 other_params = item_kdu
tiernob091dc12019-12-02 15:53:25 +0000157 if item_kdu and item_kdu.get("additionalParams"):
158 where_ += ".additionalParamsForKdu[kdu_name={}]".format(kdu_name)
159 additional_params = item_kdu["additionalParams"]
tierno714954e2019-11-29 13:43:26 +0000160
tiernobee085c2018-12-12 17:03:04 +0000161 if additional_params:
162 for k, v in additional_params.items():
tierno714954e2019-11-29 13:43:26 +0000163 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
164 if not kdu_name and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k):
delacruzramo36ffe552019-05-03 14:52:37 +0200165 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
166 "and underscores, and cannot start with a digit"
167 .format(where_, k))
168 # END Check that additional parameter names are valid Jinja2 identifiers
tiernobee085c2018-12-12 17:03:04 +0000169 if not isinstance(k, str):
170 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
171 if "." in k or "$" in k:
172 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
173 if isinstance(v, (dict, tuple, list)):
174 additional_params[k] = "!!yaml " + safe_dump(v)
175
176 if descriptor:
177 # check that enough parameters are supplied for the initial-config-primitive
178 # TODO: check for cloud-init
179 if member_vnf_index:
tierno714954e2019-11-29 13:43:26 +0000180 if kdu_name:
181 initial_primitives = None
182 elif vdu_id:
183 vdud = next(x for x in descriptor["vdu"] if x["id"] == vdu_id)
184 initial_primitives = deep_get(vdud, ("vdu-configuration", "initial-config-primitive"))
185 else:
186 initial_primitives = deep_get(descriptor, ("vnf-configuration", "initial-config-primitive"))
187 else:
188 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
tiernobee085c2018-12-12 17:03:04 +0000189
tierno714954e2019-11-29 13:43:26 +0000190 for initial_primitive in get_iterable(initial_primitives):
191 for param in get_iterable(initial_primitive.get("parameter")):
192 if param["value"].startswith("<") and param["value"].endswith(">"):
193 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
194 continue
195 if not additional_params or param["value"][1:-1] not in additional_params:
196 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
197 "initial-config-primitive[name={}] not supplied".
198 format(param["value"], descriptor["id"],
199 initial_primitive["name"]))
200
tierno54db2e42020-04-06 15:29:42 +0000201 return additional_params or None, other_params or None
tiernobee085c2018-12-12 17:03:04 +0000202
tierno65ca36d2019-02-12 19:27:52 +0100203 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200204 """
205 Creates a new nsr into database. It also creates needed vnfrs
206 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +0100207 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200208 :param indata: params to be used for the nsr
209 :param kwargs: used to override the indata descriptor
210 :param headers: http request headers
tierno1bfe4e22019-09-02 16:03:25 +0000211 :return: the _id of nsr descriptor created at database. Or an exception of type
212 EngineException, ValidationError, DbException, FsException, MsgException.
213 Note: Exceptions are not captured on purpose. They should be captured at called
tiernob24258a2018-10-04 18:39:49 +0200214 """
215
216 try:
delacruzramo32bab472019-09-13 12:24:22 +0200217 step = "checking quotas"
218 self.check_quota(session)
219
tierno99d4b172019-07-02 09:28:40 +0000220 step = "validating input parameters"
tiernob24258a2018-10-04 18:39:49 +0200221 ns_request = self._remove_envelop(indata)
222 # Override descriptor with query string kwargs
223 self._update_input_with_kwargs(ns_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100224 self._validate_input_new(ns_request, session["force"])
tiernob24258a2018-10-04 18:39:49 +0200225
tierno54db2e42020-04-06 15:29:42 +0000226 # look for nsd
tiernob24258a2018-10-04 18:39:49 +0200227 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
tiernob4844ab2019-05-23 08:42:12 +0000228 _filter = self._get_project_filter(session)
229 _filter["_id"] = ns_request["nsdId"]
tiernob24258a2018-10-04 18:39:49 +0200230 nsd = self.db.get_one("nsds", _filter)
tiernob4844ab2019-05-23 08:42:12 +0000231 del _filter["_id"]
tiernob24258a2018-10-04 18:39:49 +0200232
233 nsr_id = str(uuid4())
tiernobee085c2018-12-12 17:03:04 +0000234
tiernob24258a2018-10-04 18:39:49 +0200235 now = time()
236 step = "filling nsr from input data"
tiernoe19707b2020-04-21 13:08:04 +0000237 additional_params, _ = self._format_additional_params(ns_request, descriptor=nsd)
tierno54db2e42020-04-06 15:29:42 +0000238
239 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
240 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
241 if ns_request and ns_request.get("k8s-namespace"):
242 ns_k8s_namespace = ns_request["k8s-namespace"]
243 if additional_params and additional_params.get("k8s-namespace"):
244 ns_k8s_namespace = additional_params["k8s-namespace"]
245
tiernob24258a2018-10-04 18:39:49 +0200246 nsr_descriptor = {
247 "name": ns_request["nsName"],
248 "name-ref": ns_request["nsName"],
249 "short-name": ns_request["nsName"],
250 "admin-status": "ENABLED",
tiernoecf94bd2020-01-09 12:40:45 +0000251 "nsState": "NOT_INSTANTIATED",
252 "currentOperation": "IDLE",
253 "currentOperationID": None,
254 "errorDescription": None,
255 "errorDetail": None,
256 "deploymentStatus": None,
257 "configurationStatus": None,
258 "vcaStatus": None,
preethika.pee12aa02020-07-10 13:14:22 +0000259 "nsd": {k: v for k, v in nsd.items() if k in ("vld", "_id", "id", "constituent-vnfd", "name",
260 "ns-configuration")},
tiernob24258a2018-10-04 18:39:49 +0200261 "datacenter": ns_request["vimAccountId"],
262 "resource-orchestrator": "osmopenmano",
263 "description": ns_request.get("nsDescription", ""),
264 "constituent-vnfr-ref": [],
265
266 "operational-status": "init", # typedef ns-operational-
267 "config-status": "init", # typedef config-states
268 "detailed-status": "scheduled",
269
270 "orchestration-progress": {},
271 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
272
tierno65ca36d2019-02-12 19:27:52 +0100273 "create-time": now,
tiernob24258a2018-10-04 18:39:49 +0200274 "nsd-name-ref": nsd["name"],
275 "operational-events": [], # "id", "timestamp", "description", "event",
276 "nsd-ref": nsd["id"],
tiernof0637052019-03-07 16:26:47 +0000277 "nsd-id": nsd["_id"],
tiernob4844ab2019-05-23 08:42:12 +0000278 "vnfd-id": [],
tiernobee085c2018-12-12 17:03:04 +0000279 "instantiate_params": self._format_ns_request(ns_request),
tierno54db2e42020-04-06 15:29:42 +0000280 "additionalParamsForNs": additional_params,
tiernob24258a2018-10-04 18:39:49 +0200281 "ns-instance-config-ref": nsr_id,
282 "id": nsr_id,
283 "_id": nsr_id,
284 # "input-parameter": xpath, value,
tierno99d4b172019-07-02 09:28:40 +0000285 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
tiernob24258a2018-10-04 18:39:49 +0200286 }
287 ns_request["nsr_id"] = nsr_id
tierno59338b12020-06-25 13:26:28 +0000288 if ns_request and ns_request.get("config-units"):
289 nsr_descriptor["config-units"] = ns_request["config-units"]
290
tierno36ec8602018-11-02 17:27:11 +0100291 # Create vld
292 if nsd.get("vld"):
tierno340df482020-04-03 10:09:06 +0000293 nsr_descriptor["vld"] = nsd["vld"]
tiernob24258a2018-10-04 18:39:49 +0200294
295 # Create VNFR
296 needed_vnfds = {}
gcalvino4f269dd2018-11-06 13:18:31 +0100297 for member_vnf in nsd.get("constituent-vnfd", ()):
tiernob24258a2018-10-04 18:39:49 +0200298 vnfd_id = member_vnf["vnfd-id-ref"]
299 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
300 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
301 if vnfd_id not in needed_vnfds:
302 # Obtain vnfd
tiernob4844ab2019-05-23 08:42:12 +0000303 _filter["id"] = vnfd_id
304 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
305 del _filter["id"]
tiernob24258a2018-10-04 18:39:49 +0200306 vnfd.pop("_admin")
307 needed_vnfds[vnfd_id] = vnfd
tiernob4844ab2019-05-23 08:42:12 +0000308 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
tiernob24258a2018-10-04 18:39:49 +0200309 else:
310 vnfd = needed_vnfds[vnfd_id]
311 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
312 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
313 vnfr_id = str(uuid4())
tiernoe19707b2020-04-21 13:08:04 +0000314 additional_params, vnf_params = self._format_additional_params(ns_request,
315 member_vnf["member-vnf-index"],
316 descriptor=vnfd)
tiernob24258a2018-10-04 18:39:49 +0200317 vnfr_descriptor = {
318 "id": vnfr_id,
319 "_id": vnfr_id,
320 "nsr-id-ref": nsr_id,
321 "member-vnf-index-ref": member_vnf["member-vnf-index"],
tierno54db2e42020-04-06 15:29:42 +0000322 "additionalParamsForVnf": additional_params,
tiernob24258a2018-10-04 18:39:49 +0200323 "created-time": now,
324 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
325 "vnfd-ref": vnfd_id,
326 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
327 "vim-account-id": None,
328 "vdur": [],
329 "connection-point": [],
330 "ip-address": None, # mgmt-interface filled by LCM
331 }
tierno59338b12020-06-25 13:26:28 +0000332 vnf_k8s_namespace = ns_k8s_namespace
333 if vnf_params:
334 if vnf_params.get("k8s-namespace"):
335 vnf_k8s_namespace = vnf_params["k8s-namespace"]
336 if vnf_params.get("config-units"):
337 vnfr_descriptor["config-units"] = vnf_params["config-units"]
tierno36ec8602018-11-02 17:27:11 +0100338
339 # Create vld
340 if vnfd.get("internal-vld"):
341 vnfr_descriptor["vld"] = []
342 for vnfd_vld in vnfd.get("internal-vld"):
343 vnfr_descriptor["vld"].append(
gcalvino17d5b732018-12-17 16:26:21 +0100344 {key: vnfd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in
345 vnfd_vld})
tierno36ec8602018-11-02 17:27:11 +0100346
347 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
tiernob24258a2018-10-04 18:39:49 +0200348 for cp in vnfd.get("connection-point", ()):
349 vnf_cp = {
350 "name": cp["name"],
351 "connection-point-id": cp.get("id"),
352 "id": cp.get("id"),
353 # "ip-address", "mac-address" # filled by LCM
354 # vim-id # TODO it would be nice having a vim port id
355 }
356 vnfr_descriptor["connection-point"].append(vnf_cp)
tierno9cb7d672019-10-30 12:13:48 +0000357
tiernoc67b0e92019-11-05 12:45:29 +0000358 # Create k8s-cluster information
359 if vnfd.get("k8s-cluster"):
360 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
361 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
362 if net.get("external-connection-point-ref"):
363 for nsd_vld in get_iterable(nsd.get("vld")):
364 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
365 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
366 net["external-connection-point-ref"] and \
367 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
368 net["ns-vld-id"] = nsd_vld["id"]
369 break
370 else:
371 continue
372 break
373 elif net.get("internal-connection-point-ref"):
374 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
375 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
376 if vnfd_ivld_icp.get("id-ref") == net["internal-connection-point-ref"]:
377 net["vnf-vld-id"] = vnfd_ivld["id"]
378 break
379 else:
380 continue
381 break
tierno9cb7d672019-10-30 12:13:48 +0000382 # update kdus
383 for kdu in get_iterable(vnfd.get("kdu")):
tiernoe19707b2020-04-21 13:08:04 +0000384 additional_params, kdu_params = self._format_additional_params(ns_request,
385 member_vnf["member-vnf-index"],
386 kdu_name=kdu["name"],
387 descriptor=vnfd)
tierno54db2e42020-04-06 15:29:42 +0000388 kdu_k8s_namespace = vnf_k8s_namespace
tiernobce98f02020-04-17 11:27:47 +0000389 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
tierno54db2e42020-04-06 15:29:42 +0000390 if kdu_params and kdu_params.get("k8s-namespace"):
391 kdu_k8s_namespace = kdu_params["k8s-namespace"]
392
393 kdur = {
394 "additionalParams": additional_params,
395 "k8s-namespace": kdu_k8s_namespace,
396 "kdu-name": kdu["name"],
397 # TODO "name": "" Name of the VDU in the VIM
398 "ip-address": None, # mgmt-interface filled by LCM
399 "k8s-cluster": {},
400 }
tierno59338b12020-06-25 13:26:28 +0000401 if kdu_params and kdu_params.get("config-units"):
402 kdur["config-units"] = kdu_params["config-units"]
tierno54db2e42020-04-06 15:29:42 +0000403 for k8s_type in ("helm-chart", "juju-bundle"):
404 if kdu.get(k8s_type):
405 kdur[k8s_type] = kdu_model or kdu[k8s_type]
tierno9cb7d672019-10-30 12:13:48 +0000406 if not vnfr_descriptor.get("kdur"):
407 vnfr_descriptor["kdur"] = []
408 vnfr_descriptor["kdur"].append(kdur)
409
gcalvinoe45aded2018-11-13 17:17:28 +0100410 for vdu in vnfd.get("vdu", ()):
tierno59338b12020-06-25 13:26:28 +0000411 additional_params, vdu_params = self._format_additional_params(
412 ns_request, member_vnf["member-vnf-index"], vdu_id=vdu["id"], descriptor=vnfd)
tiernob24258a2018-10-04 18:39:49 +0200413 vdur = {
tiernob24258a2018-10-04 18:39:49 +0200414 "vdu-id-ref": vdu["id"],
415 # TODO "name": "" Name of the VDU in the VIM
416 "ip-address": None, # mgmt-interface filled by LCM
417 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
418 "internal-connection-point": [],
419 "interfaces": [],
tierno54db2e42020-04-06 15:29:42 +0000420 "additionalParams": additional_params
tiernob24258a2018-10-04 18:39:49 +0200421 }
tierno59338b12020-06-25 13:26:28 +0000422 if vdu_params and vdu_params.get("config-units"):
423 vdur["config-units"] = vdu_params["config-units"]
424 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
425 vdur["boot-data-drive"] = vdu["supplemental-boot-data"]["boot-data-drive"]
tiernocc103432018-10-19 14:10:35 +0200426 if vdu.get("pdu-type"):
427 vdur["pdu-type"] = vdu["pdu-type"]
tiernob24258a2018-10-04 18:39:49 +0200428 # TODO volumes: name, volume-id
429 for icp in vdu.get("internal-connection-point", ()):
430 vdu_icp = {
431 "id": icp["id"],
432 "connection-point-id": icp["id"],
433 "name": icp.get("name"),
434 # "ip-address", "mac-address" # filled by LCM
435 # vim-id # TODO it would be nice having a vim port id
436 }
437 vdur["internal-connection-point"].append(vdu_icp)
438 for iface in vdu.get("interface", ()):
439 vdu_iface = {
440 "name": iface.get("name"),
441 # "ip-address", "mac-address" # filled by LCM
442 # vim-id # TODO it would be nice having a vim port id
443 }
tierno36ec8602018-11-02 17:27:11 +0100444 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
445 vdu_iface["mgmt-vnf"] = True
tiernocc103432018-10-19 14:10:35 +0200446 if iface.get("mgmt-interface"):
tierno36ec8602018-11-02 17:27:11 +0100447 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
448
449 # look for network where this interface is connected
450 if iface.get("external-connection-point-ref"):
451 for nsd_vld in get_iterable(nsd.get("vld")):
452 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
453 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
454 iface["external-connection-point-ref"] and \
455 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
456 vdu_iface["ns-vld-id"] = nsd_vld["id"]
457 break
458 else:
459 continue
460 break
461 elif iface.get("internal-connection-point-ref"):
462 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
463 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
464 if vnfd_ivld_icp.get("id-ref") == iface["internal-connection-point-ref"]:
465 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
466 break
467 else:
468 continue
469 break
tiernocc103432018-10-19 14:10:35 +0200470
tiernob24258a2018-10-04 18:39:49 +0200471 vdur["interfaces"].append(vdu_iface)
tiernocc103432018-10-19 14:10:35 +0200472 count = vdu.get("count", 1)
473 if count is None:
474 count = 1
475 count = int(count) # TODO remove when descriptor serialized with payngbind
476 for index in range(0, count):
477 if index:
478 vdur = deepcopy(vdur)
479 vdur["_id"] = str(uuid4())
480 vdur["count-index"] = index
481 vnfr_descriptor["vdur"].append(vdur)
tiernob24258a2018-10-04 18:39:49 +0200482
483 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
484 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
485
486 # add at database
tiernobdebce92019-07-01 15:36:49 +0000487 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200488 self.db.create("vnfrs", vnfr_descriptor)
489 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
490 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
491
492 step = "creating nsr at database"
tierno65ca36d2019-02-12 19:27:52 +0100493 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
tiernob24258a2018-10-04 18:39:49 +0200494 self.db.create("nsrs", nsr_descriptor)
495 rollback.append({"topic": "nsrs", "_id": nsr_id})
tiernobee085c2018-12-12 17:03:04 +0000496
497 step = "creating nsr temporal folder"
498 self.fs.mkdir(nsr_id)
499
tiernobdebce92019-07-01 15:36:49 +0000500 return nsr_id, None
tierno1bfe4e22019-09-02 16:03:25 +0000501 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
502 raise type(e)("{} while '{}".format(e, step), http_code=e.http_code)
tiernob24258a2018-10-04 18:39:49 +0200503
tierno65ca36d2019-02-12 19:27:52 +0100504 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200505 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
506
507
508class VnfrTopic(BaseTopic):
509 topic = "vnfrs"
510 topic_msg = None
511
delacruzramo32bab472019-09-13 12:24:22 +0200512 def __init__(self, db, fs, msg, auth):
513 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200514
tiernobee3bad2019-12-05 12:26:01 +0000515 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200516 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
517
tierno65ca36d2019-02-12 19:27:52 +0100518 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200519 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
520
tierno65ca36d2019-02-12 19:27:52 +0100521 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200522 # Not used because vnfrs are created and deleted by NsrTopic class directly
523 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
524
525
526class NsLcmOpTopic(BaseTopic):
527 topic = "nslcmops"
528 topic_msg = "ns"
529 operation_schema = { # mapping between operation and jsonschema to validate
530 "instantiate": ns_instantiate,
531 "action": ns_action,
532 "scale": ns_scale,
tierno1c38f2f2020-03-24 11:51:39 +0000533 "terminate": ns_terminate,
tiernob24258a2018-10-04 18:39:49 +0200534 }
535
delacruzramo32bab472019-09-13 12:24:22 +0200536 def __init__(self, db, fs, msg, auth):
537 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200538
tiernob24258a2018-10-04 18:39:49 +0200539 def _check_ns_operation(self, session, nsr, operation, indata):
540 """
541 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +0100542 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200543 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
544 :param indata: descriptor with the parameters of the operation
545 :return: None
546 """
tierno982da4e2019-09-03 11:51:55 +0000547 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
tiernob24258a2018-10-04 18:39:49 +0200548 vim_accounts = []
tierno4f9d4ae2019-03-20 17:24:11 +0000549 wim_accounts = []
tiernob24258a2018-10-04 18:39:49 +0200550 nsd = nsr["nsd"]
551
552 def check_valid_vnf_member_index(member_vnf_index):
tierno982da4e2019-09-03 11:51:55 +0000553 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
554 if vnf_member_index_to_vnfd.get(member_vnf_index):
555 return vnf_member_index_to_vnfd[member_vnf_index]
556 vnfr = self.db.get_one("vnfrs",
557 {"nsr-id-ref": nsr["_id"], "member-vnf-index-ref": member_vnf_index},
558 fail_on_empty=False)
559 if not vnfr:
tiernob24258a2018-10-04 18:39:49 +0200560 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
561 "nsd:constituent-vnfd".format(member_vnf_index))
tierno982da4e2019-09-03 11:51:55 +0000562 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
563 if not vnfd:
564 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
565 format(vnfr["vnfd-id"]))
566 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
567 return vnfd
tiernob24258a2018-10-04 18:39:49 +0200568
tierno260dd6f2019-09-02 10:48:56 +0000569 def check_valid_vdu(vnfd, vdu_id):
570 for vdud in get_iterable(vnfd.get("vdu")):
571 if vdud["id"] == vdu_id:
572 return vdud
573 else:
574 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
575
tierno9cb7d672019-10-30 12:13:48 +0000576 def check_valid_kdu(vnfd, kdu_name):
577 for kdud in get_iterable(vnfd.get("kdu")):
578 if kdud["name"] == kdu_name:
579 return kdud
580 else:
581 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
582
gcalvino5e72d152018-10-23 11:46:57 +0200583 def _check_vnf_instantiation_params(in_vnfd, vnfd):
584
tierno40fbcad2018-10-26 10:58:15 +0200585 for in_vdu in get_iterable(in_vnfd.get("vdu")):
586 for vdu in get_iterable(vnfd.get("vdu")):
587 if in_vdu["id"] == vdu["id"]:
588 for volume in get_iterable(in_vdu.get("volume")):
589 for volumed in get_iterable(vdu.get("volumes")):
590 if volumed["name"] == volume["name"]:
591 break
592 else:
593 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
594 "volume:name='{}' is not present at vnfd:vdu:volumes list".
595 format(in_vnf["member-vnf-index"], in_vdu["id"],
596 volume["name"]))
597 for in_iface in get_iterable(in_vdu["interface"]):
598 for iface in get_iterable(vdu.get("interface")):
599 if in_iface["name"] == iface["name"]:
600 break
601 else:
602 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
603 "interface[name='{}'] is not present at vnfd:vdu:interface"
604 .format(in_vnf["member-vnf-index"], in_vdu["id"],
605 in_iface["name"]))
606 break
gcalvino5e72d152018-10-23 11:46:57 +0200607 else:
tierno40fbcad2018-10-26 10:58:15 +0200608 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
609 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
gcalvino5e72d152018-10-23 11:46:57 +0200610
611 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
612 for ivld in get_iterable(vnfd.get("internal-vld")):
tierno75d5a4e2020-05-21 15:09:22 +0000613 if in_ivld["name"] in (ivld["id"], ivld.get("name")):
tierno1bfe4e22019-09-02 16:03:25 +0000614 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
gcalvino5e72d152018-10-23 11:46:57 +0200615 for icp in ivld["internal-connection-point"]:
616 if in_icp["id-ref"] == icp["id-ref"]:
617 break
618 else:
tierno40fbcad2018-10-26 10:58:15 +0200619 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
620 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
621 "vnfd:internal-vld:name/id:internal-connection-point"
622 .format(in_vnf["member-vnf-index"], in_ivld["name"],
tierno670b0c62020-05-12 13:01:19 +0000623 in_icp["id-ref"]))
gcalvino5e72d152018-10-23 11:46:57 +0200624 break
625 else:
626 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
627 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
628 in_ivld["name"], vnfd["id"]))
629
tiernob24258a2018-10-04 18:39:49 +0200630 def check_valid_vim_account(vim_account):
631 if vim_account in vim_accounts:
632 return
633 try:
tierno65ca36d2019-02-12 19:27:52 +0100634 db_filter = self._get_project_filter(session)
tiernocc103432018-10-19 14:10:35 +0200635 db_filter["_id"] = vim_account
636 self.db.get_one("vim_accounts", db_filter)
tiernob24258a2018-10-04 18:39:49 +0200637 except Exception:
tiernocc103432018-10-19 14:10:35 +0200638 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
tiernob24258a2018-10-04 18:39:49 +0200639 vim_accounts.append(vim_account)
640
tierno4f9d4ae2019-03-20 17:24:11 +0000641 def check_valid_wim_account(wim_account):
642 if not isinstance(wim_account, str):
643 return
644 elif wim_account in wim_accounts:
645 return
646 try:
647 db_filter = self._get_project_filter(session, write=False, show_all=True)
648 db_filter["_id"] = wim_account
649 self.db.get_one("wim_accounts", db_filter)
650 except Exception:
651 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
652 wim_accounts.append(wim_account)
653
tiernob24258a2018-10-04 18:39:49 +0200654 if operation == "action":
655 # check vnf_member_index
656 if indata.get("vnf_member_index"):
657 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
tierno1ac7f462019-06-03 17:22:12 +0000658 if indata.get("member_vnf_index"):
659 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
tierno260dd6f2019-09-02 10:48:56 +0000660 if indata.get("vdu_id"):
661 vdud = check_valid_vdu(vnfd, indata["vdu_id"])
662 descriptor_configuration = vdud.get("vdu-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000663 elif indata.get("kdu_name"):
tiernoc67b0e92019-11-05 12:45:29 +0000664 kdud = check_valid_kdu(vnfd, indata["kdu_name"])
tierno9cb7d672019-10-30 12:13:48 +0000665 descriptor_configuration = kdud.get("kdu-configuration", {}).get("config-primitive")
tierno260dd6f2019-09-02 10:48:56 +0000666 else:
667 descriptor_configuration = vnfd.get("vnf-configuration", {}).get("config-primitive")
tierno1ac7f462019-06-03 17:22:12 +0000668 else: # use a NSD
669 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
tierno9cb7d672019-10-30 12:13:48 +0000670
671 # For k8s allows default primitives without validating the parameters
delacruzramo6ddff2e2019-11-28 11:24:09 +0100672 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
tierno9cb7d672019-10-30 12:13:48 +0000673 # TODO should be checked that rollback only can contains revsision_numbe????
delacruzramo6ddff2e2019-11-28 11:24:09 +0100674 if not indata.get("member_vnf_index"):
675 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
676 .format(indata["primitive"]))
tierno9cb7d672019-10-30 12:13:48 +0000677 return
678 # if not, check primitive
tierno1ac7f462019-06-03 17:22:12 +0000679 for config_primitive in get_iterable(descriptor_configuration):
tiernob24258a2018-10-04 18:39:49 +0200680 if indata["primitive"] == config_primitive["name"]:
681 # check needed primitive_params are provided
682 if indata.get("primitive_params"):
683 in_primitive_params_copy = copy(indata["primitive_params"])
684 else:
685 in_primitive_params_copy = {}
686 for paramd in get_iterable(config_primitive.get("parameter")):
687 if paramd["name"] in in_primitive_params_copy:
688 del in_primitive_params_copy[paramd["name"]]
689 elif not paramd.get("default-value"):
690 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
691 paramd["name"], indata["primitive"]))
692 # check no extra primitive params are provided
693 if in_primitive_params_copy:
tierno1ac7f462019-06-03 17:22:12 +0000694 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
tiernob24258a2018-10-04 18:39:49 +0200695 list(in_primitive_params_copy.keys()), indata["primitive"]))
696 break
697 else:
tierno1ac7f462019-06-03 17:22:12 +0000698 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
tiernob24258a2018-10-04 18:39:49 +0200699 if operation == "scale":
700 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
701 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
702 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
703 break
704 else:
705 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
706 "present at vnfd:scaling-group-descriptor".format(
707 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
708 if operation == "instantiate":
709 # check vim_account
710 check_valid_vim_account(indata["vimAccountId"])
tierno4f9d4ae2019-03-20 17:24:11 +0000711 check_valid_wim_account(indata.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200712 for in_vnf in get_iterable(indata.get("vnf")):
713 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
gcalvino5e72d152018-10-23 11:46:57 +0200714 _check_vnf_instantiation_params(in_vnf, vnfd)
tiernob24258a2018-10-04 18:39:49 +0200715 if in_vnf.get("vimAccountId"):
716 check_valid_vim_account(in_vnf["vimAccountId"])
tiernob24258a2018-10-04 18:39:49 +0200717
tiernob24258a2018-10-04 18:39:49 +0200718 for in_vld in get_iterable(indata.get("vld")):
tierno4f9d4ae2019-03-20 17:24:11 +0000719 check_valid_wim_account(in_vld.get("wimAccountId"))
tiernob24258a2018-10-04 18:39:49 +0200720 for vldd in get_iterable(nsd.get("vld")):
721 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
722 break
723 else:
724 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
725 in_vld["name"]))
726
tierno36ec8602018-11-02 17:27:11 +0100727 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
tiernocc103432018-10-19 14:10:35 +0200728 """
tierno36ec8602018-11-02 17:27:11 +0100729 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
730 (ip_address, ...) information.
731 Modifies PDU _admin.usageState to 'IN_USE'
tierno65ca36d2019-02-12 19:27:52 +0100732 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno36ec8602018-11-02 17:27:11 +0100733 :param rollback: list with the database modifications to rollback if needed
734 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
735 :param vim_account: vim_account where this vnfr should be deployed
736 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
737 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
738 of the changed vnfr is needed
739
740 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
741 "vim-network-name": used at VIM
742 "name": interface name
743 "vnf-vld-id": internal VNFD vld where this interface is connected, or
744 "ns-vld-id": NSD vld where this interface is connected.
745 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 +0200746 """
tierno36ec8602018-11-02 17:27:11 +0100747
748 ifaces_forcing_vim_network = []
tiernocc103432018-10-19 14:10:35 +0200749 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
750 if not vdur.get("pdu-type"):
751 continue
752 pdu_type = vdur.get("pdu-type")
tierno65ca36d2019-02-12 19:27:52 +0100753 pdu_filter = self._get_project_filter(session)
tierno36ec8602018-11-02 17:27:11 +0100754 pdu_filter["vim_accounts"] = vim_account
tiernocc103432018-10-19 14:10:35 +0200755 pdu_filter["type"] = pdu_type
756 pdu_filter["_admin.operationalState"] = "ENABLED"
tierno36ec8602018-11-02 17:27:11 +0100757 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
tiernocc103432018-10-19 14:10:35 +0200758 # TODO feature 1417: "shared": True,
759
760 available_pdus = self.db.get_list("pdus", pdu_filter)
761 for pdu in available_pdus:
762 # step 1 check if this pdu contains needed interfaces:
763 match_interfaces = True
764 for vdur_interface in vdur["interfaces"]:
765 for pdu_interface in pdu["interfaces"]:
766 if pdu_interface["name"] == vdur_interface["name"]:
767 # TODO feature 1417: match per mgmt type
768 break
769 else: # no interface found for name
770 match_interfaces = False
771 break
772 if match_interfaces:
773 break
774 else:
775 raise EngineException(
tierno36ec8602018-11-02 17:27:11 +0100776 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
777 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
tiernocc103432018-10-19 14:10:35 +0200778
779 # step 2. Update pdu
780 rollback_pdu = {
781 "_admin.usageState": pdu["_admin"]["usageState"],
782 "_admin.usage.vnfr_id": None,
783 "_admin.usage.nsr_id": None,
784 "_admin.usage.vdur": None,
785 }
786 self.db.set_one("pdus", {"_id": pdu["_id"]},
tierno36ec8602018-11-02 17:27:11 +0100787 {"_admin.usageState": "IN_USE",
tiernoe8631782018-12-21 13:31:52 +0000788 "_admin.usage": {"vnfr_id": vnfr["_id"],
789 "nsr_id": vnfr["nsr-id-ref"],
790 "vdur": vdur["vdu-id-ref"]}
791 })
tiernocc103432018-10-19 14:10:35 +0200792 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
793
794 # step 3. Fill vnfr info by filling vdur
795 vdu_text = "vdur.{}".format(vdur_index)
tierno36ec8602018-11-02 17:27:11 +0100796 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
tiernocc103432018-10-19 14:10:35 +0200797 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
798 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
799 for pdu_interface in pdu["interfaces"]:
800 if pdu_interface["name"] == vdur_interface["name"]:
801 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
802 for k, v in pdu_interface.items():
tierno36ec8602018-11-02 17:27:11 +0100803 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
804 vnfr_update[iface_text + ".{}".format(k)] = v
805 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
806 if pdu_interface.get("ip-address"):
tiernoc88003e2020-03-12 17:31:42 +0000807 if vdur_interface.get("mgmt-interface") or vdur_interface.get("mgmt-vnf"):
tierno36ec8602018-11-02 17:27:11 +0100808 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
809 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
810 if vdur_interface.get("mgmt-vnf"):
811 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
812 vnfr_update["ip-address"] = pdu_interface["ip-address"]
tierno72b16e12020-03-18 09:49:43 +0000813 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
gcalvino17d5b732018-12-17 16:26:21 +0100814 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
tierno36ec8602018-11-02 17:27:11 +0100815 ifaces_forcing_vim_network.append({
tierno36ec8602018-11-02 17:27:11 +0100816 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
817 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
818 "ns-vld-id": vdur_interface.get("ns-vld-id")})
gcalvino17d5b732018-12-17 16:26:21 +0100819 if pdu_interface.get("vim-network-id"):
tiernoc67b0e92019-11-05 12:45:29 +0000820 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
gcalvino17d5b732018-12-17 16:26:21 +0100821 if pdu_interface.get("vim-network-name"):
tiernoc67b0e92019-11-05 12:45:29 +0000822 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
tiernocc103432018-10-19 14:10:35 +0200823 break
824
tierno36ec8602018-11-02 17:27:11 +0100825 return ifaces_forcing_vim_network
tiernocc103432018-10-19 14:10:35 +0200826
tierno9cb7d672019-10-30 12:13:48 +0000827 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
828 """
829 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
830 Fills vnfr.kdur with the selected k8scluster
831
832 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
833 :param rollback: list with the database modifications to rollback if needed
834 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
835 :param vim_account: vim_account where this vnfr should be deployed
836 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
837 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
838 of the changed vnfr is needed
839
840 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
841 "vim-network-name": used at VIM
842 "name": interface name
843 "vnf-vld-id": internal VNFD vld where this interface is connected, or
844 "ns-vld-id": NSD vld where this interface is connected.
845 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
846 """
847
848 ifaces_forcing_vim_network = []
tiernoc67b0e92019-11-05 12:45:29 +0000849 if not vnfr.get("kdur"):
850 return ifaces_forcing_vim_network
tierno9cb7d672019-10-30 12:13:48 +0000851
tiernoc67b0e92019-11-05 12:45:29 +0000852 kdu_filter = self._get_project_filter(session)
853 kdu_filter["vim_account"] = vim_account
854 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
855 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
856
857 k8s_requirements = {} # just for logging
858 for k8scluster in available_k8sclusters:
859 if not vnfr.get("k8s-cluster"):
tierno9cb7d672019-10-30 12:13:48 +0000860 break
tiernoc67b0e92019-11-05 12:45:29 +0000861 # restrict by cni
862 if vnfr["k8s-cluster"].get("cni"):
863 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
864 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
865 continue
866 # restrict by version
867 if vnfr["k8s-cluster"].get("version"):
868 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
869 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
870 continue
871 # restrict by number of networks
872 if vnfr["k8s-cluster"].get("nets"):
873 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
874 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
875 continue
876 break
877 else:
878 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
879 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
tierno9cb7d672019-10-30 12:13:48 +0000880
tiernoc67b0e92019-11-05 12:45:29 +0000881 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
tierno9cb7d672019-10-30 12:13:48 +0000882 # step 3. Fill vnfr info by filling kdur
883 kdu_text = "kdur.{}.".format(kdur_index)
884 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
885 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
886
tiernoc67b0e92019-11-05 12:45:29 +0000887 # step 4. Check VIM networks that forces the selected k8s_cluster
888 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
889 k8scluster_net_list = list(k8scluster.get("nets").keys())
890 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
891 # get a network from k8s_cluster nets. If name matches use this, if not use other
892 if kdur_net["id"] in k8scluster_net_list: # name matches
893 vim_net = k8scluster["nets"][kdur_net["id"]]
894 k8scluster_net_list.remove(kdur_net["id"])
895 else:
896 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
897 k8scluster_net_list.pop(0)
898 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
899 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
900 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
901 ifaces_forcing_vim_network.append({
902 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
903 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
904 "ns-vld-id": kdur_net.get("ns-vld-id"),
905 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
906 })
907 # TODO check that this forcing is not incompatible with other forcing
tierno9cb7d672019-10-30 12:13:48 +0000908 return ifaces_forcing_vim_network
909
tiernocc103432018-10-19 14:10:35 +0200910 def _update_vnfrs(self, session, rollback, nsr, indata):
tiernocc103432018-10-19 14:10:35 +0200911 # get vnfr
912 nsr_id = nsr["_id"]
913 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
914
915 for vnfr in vnfrs:
916 vnfr_update = {}
917 vnfr_update_rollback = {}
918 member_vnf_index = vnfr["member-vnf-index-ref"]
919 # update vim-account-id
920
921 vim_account = indata["vimAccountId"]
922 # check instantiate parameters
923 for vnf_inst_params in get_iterable(indata.get("vnf")):
924 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
925 continue
926 if vnf_inst_params.get("vimAccountId"):
927 vim_account = vnf_inst_params.get("vimAccountId")
928
929 vnfr_update["vim-account-id"] = vim_account
930 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
931
932 # get pdu
tierno36ec8602018-11-02 17:27:11 +0100933 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
934 vnfr_update_rollback)
tiernocc103432018-10-19 14:10:35 +0200935
tierno9cb7d672019-10-30 12:13:48 +0000936 # get kdus
937 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
938 vnfr_update_rollback)
939 # update database vnfr
tierno36ec8602018-11-02 17:27:11 +0100940 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
941 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
942
943 # Update indada in case pdu forces to use a concrete vim-network-name
944 # TODO check if user has already insert a vim-network-name and raises an error
945 if not ifaces_forcing_vim_network:
946 continue
947 for iface_info in ifaces_forcing_vim_network:
948 if iface_info.get("ns-vld-id"):
949 if "vld" not in indata:
950 indata["vld"] = []
951 indata["vld"].append({key: iface_info[key] for key in
952 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
953
954 elif iface_info.get("vnf-vld-id"):
955 if "vnf" not in indata:
956 indata["vnf"] = []
957 indata["vnf"].append({
958 "member-vnf-index": member_vnf_index,
959 "internal-vld": [{key: iface_info[key] for key in
960 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
961 })
962
963 @staticmethod
964 def _create_nslcmop(nsr_id, operation, params):
965 """
966 Creates a ns-lcm-opp content to be stored at database.
967 :param nsr_id: internal id of the instance
968 :param operation: instantiate, terminate, scale, action, ...
969 :param params: user parameters for the operation
970 :return: dictionary following SOL005 format
971 """
tiernob24258a2018-10-04 18:39:49 +0200972 now = time()
973 _id = str(uuid4())
974 nslcmop = {
975 "id": _id,
976 "_id": _id,
977 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
tiernoecf94bd2020-01-09 12:40:45 +0000978 "queuePosition": None,
979 "stage": None,
980 "errorMessage": None,
981 "detailedStatus": None,
tiernob24258a2018-10-04 18:39:49 +0200982 "statusEnteredTime": now,
tierno36ec8602018-11-02 17:27:11 +0100983 "nsInstanceId": nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200984 "lcmOperationType": operation,
985 "startTime": now,
986 "isAutomaticInvocation": False,
987 "operationParams": params,
988 "isCancelPending": False,
989 "links": {
990 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
tierno36ec8602018-11-02 17:27:11 +0100991 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
tiernob24258a2018-10-04 18:39:49 +0200992 }
993 }
994 return nslcmop
995
magnussonlf318b302020-01-20 18:38:18 +0100996 def _get_enabled_vims(self, session):
997 """
998 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
999 :param session: current session with user information
1000 """
1001 db_filter = self._get_project_filter(session)
1002 db_filter["_admin.operationalState"] = "ENABLED"
1003 vims = self.db.get_list("vim_accounts", db_filter)
1004 vimAccounts = []
1005 for vim in vims:
1006 vimAccounts.append(vim['_id'])
1007 return vimAccounts
1008
tierno65ca36d2019-02-12 19:27:52 +01001009 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
tiernob24258a2018-10-04 18:39:49 +02001010 """
1011 Performs a new operation over a ns
1012 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001013 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +02001014 :param indata: descriptor with the parameters of the operation. It must contains among others
1015 nsInstanceId: _id of the nsr to perform the operation
1016 operation: it can be: instantiate, terminate, action, TODO: update, heal
1017 :param kwargs: used to override the indata descriptor
1018 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +02001019 :return: id of the nslcmops
1020 """
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001021 def check_if_nsr_is_not_slice_member(session, nsr_id):
1022 nsis = None
1023 db_filter = self._get_project_filter(session)
1024 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1025 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
1026 if nsis:
1027 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
1028 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
1029
tiernob24258a2018-10-04 18:39:49 +02001030 try:
1031 # Override descriptor with query string kwargs
tierno1c38f2f2020-03-24 11:51:39 +00001032 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
tiernob24258a2018-10-04 18:39:49 +02001033 operation = indata["lcmOperationType"]
1034 nsInstanceId = indata["nsInstanceId"]
1035
1036 validate_input(indata, self.operation_schema[operation])
1037 # get ns from nsr_id
tierno65ca36d2019-02-12 19:27:52 +01001038 _filter = BaseTopic._get_project_filter(session)
tiernob24258a2018-10-04 18:39:49 +02001039 _filter["_id"] = nsInstanceId
1040 nsr = self.db.get_one("nsrs", _filter)
1041
1042 # initial checking
Felipe Vicens90fbc9c2019-06-06 01:03:00 +02001043 if operation == "terminate" and slice_object is False:
1044 check_if_nsr_is_not_slice_member(session, nsr["_id"])
tiernob24258a2018-10-04 18:39:49 +02001045 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1046 if operation == "terminate" and indata.get("autoremove"):
1047 # NSR must be deleted
tierno586ae812019-10-17 13:56:53 +00001048 return None, None # a none in this case is used to indicate not instantiated. It can be removed
tiernob24258a2018-10-04 18:39:49 +02001049 if operation != "instantiate":
1050 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1051 nsInstanceId, operation), HTTPStatus.CONFLICT)
1052 else:
tierno65ca36d2019-02-12 19:27:52 +01001053 if operation == "instantiate" and not session["force"]:
tiernob24258a2018-10-04 18:39:49 +02001054 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1055 nsInstanceId, operation), HTTPStatus.CONFLICT)
1056 self._check_ns_operation(session, nsr, operation, indata)
tierno36ec8602018-11-02 17:27:11 +01001057
tiernocc103432018-10-19 14:10:35 +02001058 if operation == "instantiate":
1059 self._update_vnfrs(session, rollback, nsr, indata)
tierno36ec8602018-11-02 17:27:11 +01001060
1061 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
tierno1bfe4e22019-09-02 16:03:25 +00001062 _id = nslcmop_desc["_id"]
tierno65ca36d2019-02-12 19:27:52 +01001063 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
magnussonlf318b302020-01-20 18:38:18 +01001064 if indata.get("placement-engine"):
1065 # Save valid vim accounts in lcm operation descriptor
1066 nslcmop_desc['operationParams']['validVimAccounts'] = self._get_enabled_vims(session)
tierno1bfe4e22019-09-02 16:03:25 +00001067 self.db.create("nslcmops", nslcmop_desc)
tiernob24258a2018-10-04 18:39:49 +02001068 rollback.append({"topic": "nslcmops", "_id": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001069 if not slice_object:
1070 self.msg.write("ns", operation, nslcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001071 return _id, None
1072 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
tiernob24258a2018-10-04 18:39:49 +02001073 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1074 # except DbException as e:
1075 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1076
tiernobee3bad2019-12-05 12:26:01 +00001077 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +02001078 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1079
tierno65ca36d2019-02-12 19:27:52 +01001080 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +02001081 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001082
1083
1084class NsiTopic(BaseTopic):
1085 topic = "nsis"
1086 topic_msg = "nsi"
tierno6b02b052020-06-02 10:07:41 +00001087 quota_name = "slice_instances"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001088
delacruzramo32bab472019-09-13 12:24:22 +02001089 def __init__(self, db, fs, msg, auth):
1090 BaseTopic.__init__(self, db, fs, msg, auth)
1091 self.nsrTopic = NsrTopic(db, fs, msg, auth)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001092
Felipe Vicensc37b3842019-01-12 12:24:42 +01001093 @staticmethod
1094 def _format_ns_request(ns_request):
1095 formated_request = copy(ns_request)
1096 # TODO: Add request params
1097 return formated_request
1098
1099 @staticmethod
tiernofd160572019-01-21 10:41:37 +00001100 def _format_addional_params(slice_request):
Felipe Vicensc37b3842019-01-12 12:24:42 +01001101 """
1102 Get and format user additional params for NS or VNF
tiernofd160572019-01-21 10:41:37 +00001103 :param slice_request: User instantiation additional parameters
1104 :return: a formatted copy of additional params or None if not supplied
Felipe Vicensc37b3842019-01-12 12:24:42 +01001105 """
tiernofd160572019-01-21 10:41:37 +00001106 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1107 if additional_params:
1108 for k, v in additional_params.items():
1109 if not isinstance(k, str):
1110 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1111 format(k))
1112 if "." in k or "$" in k:
1113 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1114 format(k))
1115 if isinstance(v, (dict, tuple, list)):
1116 additional_params[k] = "!!yaml " + safe_dump(v)
Felipe Vicensc37b3842019-01-12 12:24:42 +01001117 return additional_params
1118
Felipe Vicensb57758d2018-10-16 16:00:20 +02001119 def _check_descriptor_dependencies(self, session, descriptor):
1120 """
1121 Check that the dependent descriptors exist on a new descriptor or edition
tierno65ca36d2019-02-12 19:27:52 +01001122 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001123 :param descriptor: descriptor to be inserted or edit
1124 :return: None or raises exception
1125 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001126 if not descriptor.get("nst-ref"):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001127 return
Felipe Vicens07f31722018-10-29 15:16:44 +01001128 nstd_id = descriptor["nst-ref"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001129 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
Felipe Vicens07f31722018-10-29 15:16:44 +01001130 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
Felipe Vicensb57758d2018-10-16 16:00:20 +02001131 http_code=HTTPStatus.CONFLICT)
1132
tiernob4844ab2019-05-23 08:42:12 +00001133 def check_conflict_on_del(self, session, _id, db_content):
1134 """
1135 Check that NSI is not instantiated
1136 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1137 :param _id: nsi internal id
1138 :param db_content: The database content of the _id
1139 :return: None or raises EngineException with the conflict
1140 """
tierno65ca36d2019-02-12 19:27:52 +01001141 if session["force"]:
Felipe Vicensb57758d2018-10-16 16:00:20 +02001142 return
tiernob4844ab2019-05-23 08:42:12 +00001143 nsi = db_content
Felipe Vicensb57758d2018-10-16 16:00:20 +02001144 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1145 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1146 "Launch 'terminate' operation first; or force deletion".format(_id),
1147 http_code=HTTPStatus.CONFLICT)
1148
tiernobee3bad2019-12-05 12:26:01 +00001149 def delete_extra(self, session, _id, db_content, not_send_msg=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001150 """
tiernob4844ab2019-05-23 08:42:12 +00001151 Deletes associated nsilcmops from database. Deletes associated filesystem.
1152 Set usageState of nst
tierno65ca36d2019-02-12 19:27:52 +01001153 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001154 :param _id: server internal id
tiernob4844ab2019-05-23 08:42:12 +00001155 :param db_content: The database content of the descriptor
tiernobee3bad2019-12-05 12:26:01 +00001156 :param not_send_msg: To not send message (False) or store content (list) instead
tiernob4844ab2019-05-23 08:42:12 +00001157 :return: None if ok or raises EngineException with the problem
Felipe Vicensb57758d2018-10-16 16:00:20 +02001158 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001159
Felipe Vicens09e65422019-01-22 15:06:46 +01001160 # Deleting the nsrs belonging to nsir
tiernob4844ab2019-05-23 08:42:12 +00001161 nsir = db_content
Felipe Vicens09e65422019-01-22 15:06:46 +01001162 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1163 nsr_id = nsrs_detailed_item["nsrId"]
1164 if nsrs_detailed_item.get("shared"):
1165 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1166 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1167 "_id.ne": nsir["_id"]}
1168 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1169 if nsi: # last one using nsr
1170 continue
1171 try:
tiernobee3bad2019-12-05 12:26:01 +00001172 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
Felipe Vicens09e65422019-01-22 15:06:46 +01001173 except (DbException, EngineException) as e:
1174 if e.http_code == HTTPStatus.NOT_FOUND:
1175 pass
1176 else:
1177 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001178
tiernob4844ab2019-05-23 08:42:12 +00001179 # delete related nsilcmops database entries
1180 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
Felipe Vicens07f31722018-10-29 15:16:44 +01001181
tiernob4844ab2019-05-23 08:42:12 +00001182 # Check and set used NST usage state
Felipe Vicens09e65422019-01-22 15:06:46 +01001183 nsir_admin = nsir.get("_admin")
tiernob4844ab2019-05-23 08:42:12 +00001184 if nsir_admin and nsir_admin.get("nst-id"):
1185 # check if used by another NSI
1186 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1187 fail_on_empty=False, fail_on_more=False)
1188 if not nsis_list:
1189 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1190
1191 # def delete(self, session, _id, dry_run=False):
1192 # """
1193 # Delete item by its internal _id
1194 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1195 # :param _id: server internal id
1196 # :param dry_run: make checking but do not delete
1197 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1198 # """
1199 # # TODO add admin to filter, validate rights
1200 # BaseTopic.delete(self, session, _id, dry_run=True)
1201 # if dry_run:
1202 # return
1203 #
1204 # # Deleting the nsrs belonging to nsir
1205 # nsir = self.db.get_one("nsis", {"_id": _id})
1206 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1207 # nsr_id = nsrs_detailed_item["nsrId"]
1208 # if nsrs_detailed_item.get("shared"):
1209 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1210 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1211 # "_id.ne": nsir["_id"]}
1212 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1213 # if nsi: # last one using nsr
1214 # continue
1215 # try:
1216 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1217 # except (DbException, EngineException) as e:
1218 # if e.http_code == HTTPStatus.NOT_FOUND:
1219 # pass
1220 # else:
1221 # raise
1222 # # deletes NetSlice instance object
1223 # v = self.db.del_one("nsis", {"_id": _id})
1224 #
1225 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1226 # _filter = {"netsliceInstanceId": _id}
1227 # self.db.del_list("nsilcmops", _filter)
1228 #
1229 # # Search if nst is being used by other nsi
1230 # nsir_admin = nsir.get("_admin")
1231 # if nsir_admin:
1232 # if nsir_admin.get("nst-id"):
1233 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1234 # fail_on_empty=False, fail_on_more=False)
1235 # if not nsis_list:
1236 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1237 # return v
Felipe Vicensb57758d2018-10-16 16:00:20 +02001238
tierno65ca36d2019-02-12 19:27:52 +01001239 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001240 """
Felipe Vicens07f31722018-10-29 15:16:44 +01001241 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
Felipe Vicensb57758d2018-10-16 16:00:20 +02001242 :param rollback: list to append the created items at database in case a rollback must be done
tierno65ca36d2019-02-12 19:27:52 +01001243 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicensb57758d2018-10-16 16:00:20 +02001244 :param indata: params to be used for the nsir
1245 :param kwargs: used to override the indata descriptor
1246 :param headers: http request headers
Felipe Vicensb57758d2018-10-16 16:00:20 +02001247 :return: the _id of nsi descriptor created at database
1248 """
1249
1250 try:
delacruzramo32bab472019-09-13 12:24:22 +02001251 step = "checking quotas"
1252 self.check_quota(session)
1253
tierno99d4b172019-07-02 09:28:40 +00001254 step = ""
Felipe Vicensb57758d2018-10-16 16:00:20 +02001255 slice_request = self._remove_envelop(indata)
1256 # Override descriptor with query string kwargs
1257 self._update_input_with_kwargs(slice_request, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001258 self._validate_input_new(slice_request, session["force"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001259
Felipe Vicensb57758d2018-10-16 16:00:20 +02001260 # look for nstd
tierno9e5eea32018-11-29 09:42:09 +00001261 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
tiernob4844ab2019-05-23 08:42:12 +00001262 _filter = self._get_project_filter(session)
1263 _filter["_id"] = slice_request["nstId"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001264 nstd = self.db.get_one("nsts", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001265 del _filter["_id"]
1266
Felipe Vicens07f31722018-10-29 15:16:44 +01001267 nstd.pop("_admin", None)
Felipe Vicens09e65422019-01-22 15:06:46 +01001268 nstd_id = nstd.pop("_id", None)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001269 nsi_id = str(uuid4())
Felipe Vicensb57758d2018-10-16 16:00:20 +02001270 step = "filling nsi_descriptor with input data"
Felipe Vicens07f31722018-10-29 15:16:44 +01001271
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001272 # Creating the NSIR
Felipe Vicensb57758d2018-10-16 16:00:20 +02001273 nsi_descriptor = {
1274 "id": nsi_id,
garciadeblasc54d4202018-11-29 23:41:37 +01001275 "name": slice_request["nsiName"],
1276 "description": slice_request.get("nsiDescription", ""),
1277 "datacenter": slice_request["vimAccountId"],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001278 "nst-ref": nstd["id"],
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001279 "instantiation_parameters": slice_request,
Felipe Vicensb57758d2018-10-16 16:00:20 +02001280 "network-slice-template": nstd,
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001281 "nsr-ref-list": [],
1282 "vlr-list": [],
Felipe Vicensb57758d2018-10-16 16:00:20 +02001283 "_id": nsi_id,
tiernofd160572019-01-21 10:41:37 +00001284 "additionalParamsForNsi": self._format_addional_params(slice_request)
Felipe Vicensb57758d2018-10-16 16:00:20 +02001285 }
Felipe Vicensb57758d2018-10-16 16:00:20 +02001286
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001287 step = "creating nsi at database"
tierno65ca36d2019-02-12 19:27:52 +01001288 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001289 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1290 nsi_descriptor["_admin"]["netslice-subnet"] = None
Felipe Vicens09e65422019-01-22 15:06:46 +01001291 nsi_descriptor["_admin"]["deployed"] = {}
1292 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1293 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1294
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001295 # Creating netslice-vld for the RO.
1296 step = "creating netslice-vld at database"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001297
1298 # Building the vlds list to be deployed
1299 # From netslice descriptors, creating the initial list
Felipe Vicens09e65422019-01-22 15:06:46 +01001300 nsi_vlds = []
1301
1302 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1303 # Getting template Instantiation parameters from NST
1304 nsi_vld = deepcopy(netslice_vlds)
1305 nsi_vld["shared-nsrs-list"] = []
1306 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1307 nsi_vlds.append(nsi_vld)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001308
1309 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
tierno3ffc7a42019-12-03 09:39:40 +00001310 # Creating netslice-subnet_record.
Felipe Vicensb57758d2018-10-16 16:00:20 +02001311 needed_nsds = {}
Felipe Vicens07f31722018-10-29 15:16:44 +01001312 services = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001313
Felipe Vicens09e65422019-01-22 15:06:46 +01001314 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
Felipe Vicensb57758d2018-10-16 16:00:20 +02001315 for member_ns in nstd["netslice-subnet"]:
1316 nsd_id = member_ns["nsd-ref"]
1317 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1318 member_ns["nsd-ref"], member_ns["id"])
1319 if nsd_id not in needed_nsds:
1320 # Obtain nsd
tiernob4844ab2019-05-23 08:42:12 +00001321 _filter["id"] = nsd_id
1322 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1323 del _filter["id"]
Felipe Vicensb57758d2018-10-16 16:00:20 +02001324 nsd.pop("_admin")
1325 needed_nsds[nsd_id] = nsd
1326 else:
1327 nsd = needed_nsds[nsd_id]
Felipe Vicens09e65422019-01-22 15:06:46 +01001328 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1329 services.append(member_ns)
Felipe Vicens07f31722018-10-29 15:16:44 +01001330
Felipe Vicensb57758d2018-10-16 16:00:20 +02001331 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1332 member_ns["nsd-ref"], member_ns["id"])
Felipe Vicensb57758d2018-10-16 16:00:20 +02001333
Felipe Vicens07f31722018-10-29 15:16:44 +01001334 # creates Network Services records (NSRs)
1335 step = "creating nsrs at database using NsrTopic.new()"
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001336 ns_params = slice_request.get("netslice-subnet")
Felipe Vicens07f31722018-10-29 15:16:44 +01001337 nsrs_list = []
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001338 nsi_netslice_subnet = []
Felipe Vicens07f31722018-10-29 15:16:44 +01001339 for service in services:
Felipe Vicens09e65422019-01-22 15:06:46 +01001340 # Check if the netslice-subnet is shared and if it is share if the nss exists
1341 _id_nsr = None
Felipe Vicens07f31722018-10-29 15:16:44 +01001342 indata_ns = {}
Felipe Vicens09e65422019-01-22 15:06:46 +01001343 # Is the nss shared and instantiated?
tiernob4844ab2019-05-23 08:42:12 +00001344 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1345 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
Felipe Vicens08ddb142019-08-09 15:52:40 +02001346 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
Felipe Vicens09e65422019-01-22 15:06:46 +01001347 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens09e65422019-01-22 15:06:46 +01001348 if nsi and service.get("is-shared-nss"):
1349 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1350 for nsrs_detailed_item in nsrs_detailed_list:
1351 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
Felipe Vicens08ddb142019-08-09 15:52:40 +02001352 if nsrs_detailed_item["nss-id"] == service["id"]:
1353 _id_nsr = nsrs_detailed_item["nsrId"]
1354 break
Felipe Vicens09e65422019-01-22 15:06:46 +01001355 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1356 if netslice_subnet["nss-id"] == service["id"]:
1357 indata_ns = netslice_subnet
1358 break
1359 else:
1360 indata_ns = {}
1361 if service.get("instantiation-parameters"):
1362 indata_ns = deepcopy(service["instantiation-parameters"])
1363 # del service["instantiation-parameters"]
1364
1365 indata_ns["nsdId"] = service["_id"]
1366 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1367 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1368 indata_ns["nsDescription"] = service["description"]
tierno99d4b172019-07-02 09:28:40 +00001369 if slice_request.get("ssh_keys"):
1370 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
Felipe Vicensc37b3842019-01-12 12:24:42 +01001371
Felipe Vicens09e65422019-01-22 15:06:46 +01001372 if ns_params:
1373 for ns_param in ns_params:
1374 if ns_param.get("id") == service["id"]:
1375 copy_ns_param = deepcopy(ns_param)
1376 del copy_ns_param["id"]
1377 indata_ns.update(copy_ns_param)
1378 break
1379
1380 # Creates Nsr objects
tiernobdebce92019-07-01 15:36:49 +00001381 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
Felipe Vicens09e65422019-01-22 15:06:46 +01001382 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
Felipe Vicens08ddb142019-08-09 15:52:40 +02001383 "nss-id": service["id"], "nslcmop_instantiate": None}
Felipe Vicens09e65422019-01-22 15:06:46 +01001384 indata_ns["nss-id"] = service["id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001385 nsrs_list.append(nsrs_item)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001386 nsi_netslice_subnet.append(indata_ns)
1387 nsr_ref = {"nsr-ref": _id_nsr}
1388 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
Felipe Vicens07f31722018-10-29 15:16:44 +01001389
1390 # Adding the nsrs list to the nsi
1391 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001392 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
Felipe Vicens09e65422019-01-22 15:06:46 +01001393 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1394
Felipe Vicens07f31722018-10-29 15:16:44 +01001395 # Creating the entry in the database
Felipe Vicensb57758d2018-10-16 16:00:20 +02001396 self.db.create("nsis", nsi_descriptor)
1397 rollback.append({"topic": "nsis", "_id": nsi_id})
tiernobdebce92019-07-01 15:36:49 +00001398 return nsi_id, None
1399 except Exception as e: # TODO remove try Except, it is captured at nbi.py
Felipe Vicensb57758d2018-10-16 16:00:20 +02001400 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1401 raise EngineException("Error {}: {}".format(step, e))
1402 except ValidationError as e:
1403 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1404
tierno65ca36d2019-02-12 19:27:52 +01001405 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicensb57758d2018-10-16 16:00:20 +02001406 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
Felipe Vicens07f31722018-10-29 15:16:44 +01001407
1408
1409class NsiLcmOpTopic(BaseTopic):
1410 topic = "nsilcmops"
1411 topic_msg = "nsi"
1412 operation_schema = { # mapping between operation and jsonschema to validate
1413 "instantiate": nsi_instantiate,
1414 "terminate": None
1415 }
Felipe Vicens09e65422019-01-22 15:06:46 +01001416
delacruzramo32bab472019-09-13 12:24:22 +02001417 def __init__(self, db, fs, msg, auth):
1418 BaseTopic.__init__(self, db, fs, msg, auth)
1419 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
Felipe Vicens07f31722018-10-29 15:16:44 +01001420
1421 def _check_nsi_operation(self, session, nsir, operation, indata):
1422 """
1423 Check that user has enter right parameters for the operation
tierno65ca36d2019-02-12 19:27:52 +01001424 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001425 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1426 :param indata: descriptor with the parameters of the operation
1427 :return: None
1428 """
1429 nsds = {}
1430 nstd = nsir["network-slice-template"]
1431
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001432 def check_valid_netslice_subnet_id(nstId):
Felipe Vicens07f31722018-10-29 15:16:44 +01001433 # TODO change to vnfR (??)
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001434 for netslice_subnet in nstd["netslice-subnet"]:
1435 if nstId == netslice_subnet["id"]:
1436 nsd_id = netslice_subnet["nsd-ref"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001437 if nsd_id not in nsds:
Felipe Vicens5403f542020-05-22 16:37:39 +02001438 _filter = self._get_project_filter(session)
1439 _filter["id"] = nsd_id
1440 nsds[nsd_id] = self.db.get_one("nsds", _filter)
Felipe Vicens07f31722018-10-29 15:16:44 +01001441 return nsds[nsd_id]
1442 else:
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001443 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1444 "nst:netslice-subnet".format(nstId))
Felipe Vicens07f31722018-10-29 15:16:44 +01001445 if operation == "instantiate":
1446 # check the existance of netslice-subnet items
Felipe Vicensc8bbaaa2018-12-01 04:42:40 +01001447 for in_nst in get_iterable(indata.get("netslice-subnet")):
1448 check_valid_netslice_subnet_id(in_nst["id"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001449
1450 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1451 now = time()
1452 _id = str(uuid4())
1453 nsilcmop = {
1454 "id": _id,
1455 "_id": _id,
1456 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1457 "statusEnteredTime": now,
1458 "netsliceInstanceId": netsliceInstanceId,
1459 "lcmOperationType": operation,
1460 "startTime": now,
1461 "isAutomaticInvocation": False,
1462 "operationParams": params,
1463 "isCancelPending": False,
1464 "links": {
1465 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
Felipe Vicens126af572019-06-05 19:13:04 +02001466 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
Felipe Vicens07f31722018-10-29 15:16:44 +01001467 }
1468 }
1469 return nsilcmop
1470
Felipe Vicens09e65422019-01-22 15:06:46 +01001471 def add_shared_nsr_2vld(self, nsir, nsr_item):
1472 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1473 if nst_sb_item.get("is-shared-nss"):
1474 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1475 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1476 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1477 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1478 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1479 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1480 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1481 break
1482 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1483 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1484
tierno65ca36d2019-02-12 19:27:52 +01001485 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001486 """
1487 Performs a new operation over a ns
1488 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +01001489 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Felipe Vicens07f31722018-10-29 15:16:44 +01001490 :param indata: descriptor with the parameters of the operation. It must contains among others
Felipe Vicens126af572019-06-05 19:13:04 +02001491 netsliceInstanceId: _id of the nsir to perform the operation
Felipe Vicens07f31722018-10-29 15:16:44 +01001492 operation: it can be: instantiate, terminate, action, TODO: update, heal
1493 :param kwargs: used to override the indata descriptor
1494 :param headers: http request headers
Felipe Vicens07f31722018-10-29 15:16:44 +01001495 :return: id of the nslcmops
1496 """
1497 try:
1498 # Override descriptor with query string kwargs
1499 self._update_input_with_kwargs(indata, kwargs)
1500 operation = indata["lcmOperationType"]
Felipe Vicens126af572019-06-05 19:13:04 +02001501 netsliceInstanceId = indata["netsliceInstanceId"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001502 validate_input(indata, self.operation_schema[operation])
1503
Felipe Vicens126af572019-06-05 19:13:04 +02001504 # get nsi from netsliceInstanceId
tiernob4844ab2019-05-23 08:42:12 +00001505 _filter = self._get_project_filter(session)
Felipe Vicens126af572019-06-05 19:13:04 +02001506 _filter["_id"] = netsliceInstanceId
Felipe Vicens07f31722018-10-29 15:16:44 +01001507 nsir = self.db.get_one("nsis", _filter)
tiernob4844ab2019-05-23 08:42:12 +00001508 del _filter["_id"]
Felipe Vicens07f31722018-10-29 15:16:44 +01001509
1510 # initial checking
1511 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1512 if operation == "terminate" and indata.get("autoremove"):
1513 # NSIR must be deleted
tierno586ae812019-10-17 13:56:53 +00001514 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 +01001515 if operation != "instantiate":
1516 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
Felipe Vicens126af572019-06-05 19:13:04 +02001517 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001518 else:
tierno65ca36d2019-02-12 19:27:52 +01001519 if operation == "instantiate" and not session["force"]:
Felipe Vicens07f31722018-10-29 15:16:44 +01001520 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
Felipe Vicens126af572019-06-05 19:13:04 +02001521 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
Felipe Vicens07f31722018-10-29 15:16:44 +01001522
1523 # Creating all the NS_operation (nslcmop)
1524 # Get service list from db
1525 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1526 nslcmops = []
Felipe Vicens09e65422019-01-22 15:06:46 +01001527 # nslcmops_item = None
1528 for index, nsr_item in enumerate(nsrs_list):
1529 nsi = None
1530 if nsr_item.get("shared"):
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001531 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
tiernob4844ab2019-05-23 08:42:12 +00001532 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1533 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
Felipe Vicens126af572019-06-05 19:13:04 +02001534 _filter["_id.ne"] = netsliceInstanceId
Felipe Vicens09e65422019-01-22 15:06:46 +01001535 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
Felipe Vicens58e2d2f2019-05-30 13:01:20 +02001536 if operation == "terminate":
1537 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1538 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1539
Felipe Vicens09e65422019-01-22 15:06:46 +01001540 # looks the first nsi fulfilling the conditions but not being the current NSIR
1541 if nsi:
1542 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1543 for nsi_nsr_item in nsi_admin_shared:
1544 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1545 self.add_shared_nsr_2vld(nsir, nsr_item)
1546 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1547 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1548 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1549 break
1550 # continue to not create nslcmop since nsrs is shared and nsrs was created
1551 continue
1552 else:
1553 self.add_shared_nsr_2vld(nsir, nsr_item)
1554
1555 try:
1556 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
tierno0b8752f2020-05-12 09:42:02 +00001557 indata_ns = {
1558 "lcmOperationType": operation,
1559 "nsInstanceId": service["_id"],
1560 # Including netslice_id in the ns instantiate Operation
1561 "netsliceInstanceId": netsliceInstanceId,
1562 }
1563 if operation == "instantiate":
1564 indata_ns.update(service["instantiate_params"])
1565
tierno99d4b172019-07-02 09:28:40 +00001566 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
Felipe Vicens09e65422019-01-22 15:06:46 +01001567 # message via kafka bus
tiernobdebce92019-07-01 15:36:49 +00001568 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
1569 slice_object=True)
Felipe Vicens09e65422019-01-22 15:06:46 +01001570 nslcmops.append(nslcmop)
1571 if operation == "terminate":
1572 nslcmop = None
1573 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1574 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1575 except (DbException, EngineException) as e:
1576 if e.http_code == HTTPStatus.NOT_FOUND:
1577 self.logger.info("HTTPStatus.NOT_FOUND")
1578 pass
1579 else:
1580 raise
Felipe Vicens07f31722018-10-29 15:16:44 +01001581
1582 # Creates nsilcmop
1583 indata["nslcmops_ids"] = nslcmops
1584 self._check_nsi_operation(session, nsir, operation, indata)
Felipe Vicens09e65422019-01-22 15:06:46 +01001585
Felipe Vicens126af572019-06-05 19:13:04 +02001586 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
tierno65ca36d2019-02-12 19:27:52 +01001587 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
Felipe Vicens07f31722018-10-29 15:16:44 +01001588 _id = self.db.create("nsilcmops", nsilcmop_desc)
1589 rollback.append({"topic": "nsilcmops", "_id": _id})
1590 self.msg.write("nsi", operation, nsilcmop_desc)
tiernobdebce92019-07-01 15:36:49 +00001591 return _id, None
Felipe Vicens07f31722018-10-29 15:16:44 +01001592 except ValidationError as e:
1593 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
Felipe Vicens07f31722018-10-29 15:16:44 +01001594
tiernobee3bad2019-12-05 12:26:01 +00001595 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001596 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1597
tierno65ca36d2019-02-12 19:27:52 +01001598 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Felipe Vicens07f31722018-10-29 15:16:44 +01001599 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)