139ced72da3d638b8b3f63c6b159e62fa0575321
[osm/NBI.git] / osm_nbi / instance_topics.py
1 # -*- coding: utf-8 -*-
2
3 # 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
16 # import logging
17 from uuid import uuid4
18 from http import HTTPStatus
19 from time import time
20 from copy import copy, deepcopy
21 from osm_nbi.validation import validate_input, ValidationError, ns_instantiate, ns_action, ns_scale, nsi_instantiate
22 from osm_nbi.base_topic import BaseTopic, EngineException, get_iterable, deep_get
23 # from descriptor_topics import DescriptorTopic
24 from yaml import safe_dump
25 from osm_common.dbbase import DbException
26 from osm_common.msgbase import MsgException
27 from osm_common.fsbase import FsException
28 from re import match # For checking that additional parameter names are valid Jinja2 identifiers
29
30 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
31
32
33 class NsrTopic(BaseTopic):
34 topic = "nsrs"
35 topic_msg = "ns"
36 schema_new = ns_instantiate
37
38 def __init__(self, db, fs, msg, auth):
39 BaseTopic.__init__(self, db, fs, msg, auth)
40
41 def _check_descriptor_dependencies(self, session, descriptor):
42 """
43 Check that the dependent descriptors exist on a new descriptor or edition
44 :param session: client session information
45 :param descriptor: descriptor to be inserted or edit
46 :return: None or raises exception
47 """
48 if not descriptor.get("nsdId"):
49 return
50 nsd_id = descriptor["nsdId"]
51 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
52 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
53 http_code=HTTPStatus.CONFLICT)
54
55 @staticmethod
56 def format_on_new(content, project_id=None, make_public=False):
57 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
58 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
59 return None
60
61 def check_conflict_on_del(self, session, _id, db_content):
62 """
63 Check that NSR is not instantiated
64 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
65 :param _id: nsr internal id
66 :param db_content: The database content of the nsr
67 :return: None or raises EngineException with the conflict
68 """
69 if session["force"]:
70 return
71 nsr = db_content
72 if nsr["_admin"].get("nsState") == "INSTANTIATED":
73 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
74 "Launch 'terminate' operation first; or force deletion".format(_id),
75 http_code=HTTPStatus.CONFLICT)
76
77 def delete_extra(self, session, _id, db_content, not_send_msg=None):
78 """
79 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
80 Set usageState of pdu, vnfd, nsd
81 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
82 :param _id: server internal id
83 :param db_content: The database content of the descriptor
84 :param not_send_msg: To not send message (False) or store content (list) instead
85 :return: None if ok or raises EngineException with the problem
86 """
87 self.fs.file_delete(_id, ignore_non_exist=True)
88 self.db.del_list("nslcmops", {"nsInstanceId": _id})
89 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
90
91 # set all used pdus as free
92 self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
93 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
94
95 # Set NSD usageState
96 nsr = db_content
97 used_nsd_id = nsr.get("nsd-id")
98 if used_nsd_id:
99 # check if used by another NSR
100 nsrs_list = self.db.get_one("nsrs", {"nsd-id": used_nsd_id},
101 fail_on_empty=False, fail_on_more=False)
102 if not nsrs_list:
103 self.db.set_one("nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"})
104
105 # Set VNFD usageState
106 used_vnfd_id_list = nsr.get("vnfd-id")
107 if used_vnfd_id_list:
108 for used_vnfd_id in used_vnfd_id_list:
109 # check if used by another NSR
110 nsrs_list = self.db.get_one("nsrs", {"vnfd-id": used_vnfd_id},
111 fail_on_empty=False, fail_on_more=False)
112 if not nsrs_list:
113 self.db.set_one("vnfds", {"_id": used_vnfd_id}, {"_admin.usageState": "NOT_IN_USE"})
114
115 @staticmethod
116 def _format_ns_request(ns_request):
117 formated_request = copy(ns_request)
118 formated_request.pop("additionalParamsForNs", None)
119 formated_request.pop("additionalParamsForVnf", None)
120 return formated_request
121
122 @staticmethod
123 def _format_addional_params(ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None):
124 """
125 Get and format user additional params for NS or VNF
126 :param ns_request: User instantiation additional parameters
127 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
128 :param descriptor: If not None it check that needed parameters of descriptor are supplied
129 :return: a formatted copy of additional params or None if not supplied
130 """
131 additional_params = None
132 if not member_vnf_index:
133 additional_params = copy(ns_request.get("additionalParamsForNs"))
134 where_ = "additionalParamsForNs"
135 elif ns_request.get("additionalParamsForVnf"):
136 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index)
137 item = next((x for x in ns_request["additionalParamsForVnf"] if x["member-vnf-index"] == member_vnf_index),
138 None)
139 if item:
140 additional_params = copy(item.get("additionalParams")) or {}
141 if vdu_id and item.get("additionalParamsForVdu"):
142 item_vdu = next((x for x in item["additionalParamsForVdu"] if x["vdu_id"] == vdu_id), None)
143 if item_vdu and item_vdu.get("additionalParams"):
144 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
145 additional_params = item_vdu["additionalParams"]
146 if kdu_name:
147 additional_params = {}
148 if item.get("additionalParamsForKdu"):
149 item_kdu = next((x for x in item["additionalParamsForKdu"] if x["kdu_name"] == kdu_name), None)
150 if item_kdu and item_kdu.get("additionalParams"):
151 where_ += ".additionalParamsForKdu[kdu_name={}]".format(kdu_name)
152 additional_params = item_kdu["additionalParams"]
153
154 if additional_params:
155 for k, v in additional_params.items():
156 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
157 if not kdu_name and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k):
158 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
159 "and underscores, and cannot start with a digit"
160 .format(where_, k))
161 # END Check that additional parameter names are valid Jinja2 identifiers
162 if not isinstance(k, str):
163 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
164 if "." in k or "$" in k:
165 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
166 if isinstance(v, (dict, tuple, list)):
167 additional_params[k] = "!!yaml " + safe_dump(v)
168
169 if descriptor:
170 # check that enough parameters are supplied for the initial-config-primitive
171 # TODO: check for cloud-init
172 if member_vnf_index:
173 if kdu_name:
174 initial_primitives = None
175 elif vdu_id:
176 vdud = next(x for x in descriptor["vdu"] if x["id"] == vdu_id)
177 initial_primitives = deep_get(vdud, ("vdu-configuration", "initial-config-primitive"))
178 else:
179 initial_primitives = deep_get(descriptor, ("vnf-configuration", "initial-config-primitive"))
180 else:
181 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
182
183 for initial_primitive in get_iterable(initial_primitives):
184 for param in get_iterable(initial_primitive.get("parameter")):
185 if param["value"].startswith("<") and param["value"].endswith(">"):
186 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
187 continue
188 if not additional_params or param["value"][1:-1] not in additional_params:
189 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
190 "initial-config-primitive[name={}] not supplied".
191 format(param["value"], descriptor["id"],
192 initial_primitive["name"]))
193
194 return additional_params or None
195
196 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
197 """
198 Creates a new nsr into database. It also creates needed vnfrs
199 :param rollback: list to append the created items at database in case a rollback must be done
200 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
201 :param indata: params to be used for the nsr
202 :param kwargs: used to override the indata descriptor
203 :param headers: http request headers
204 :return: the _id of nsr descriptor created at database. Or an exception of type
205 EngineException, ValidationError, DbException, FsException, MsgException.
206 Note: Exceptions are not captured on purpose. They should be captured at called
207 """
208
209 try:
210 step = "checking quotas"
211 self.check_quota(session)
212
213 step = "validating input parameters"
214 ns_request = self._remove_envelop(indata)
215 # Override descriptor with query string kwargs
216 self._update_input_with_kwargs(ns_request, kwargs)
217 self._validate_input_new(ns_request, session["force"])
218
219 # look for nsr
220 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
221 _filter = self._get_project_filter(session)
222 _filter["_id"] = ns_request["nsdId"]
223 nsd = self.db.get_one("nsds", _filter)
224 del _filter["_id"]
225
226 nsr_id = str(uuid4())
227
228 now = time()
229 step = "filling nsr from input data"
230 nsr_descriptor = {
231 "name": ns_request["nsName"],
232 "name-ref": ns_request["nsName"],
233 "short-name": ns_request["nsName"],
234 "admin-status": "ENABLED",
235 "nsd": nsd,
236 "datacenter": ns_request["vimAccountId"],
237 "resource-orchestrator": "osmopenmano",
238 "description": ns_request.get("nsDescription", ""),
239 "constituent-vnfr-ref": [],
240
241 "operational-status": "init", # typedef ns-operational-
242 "config-status": "init", # typedef config-states
243 "detailed-status": "scheduled",
244
245 "orchestration-progress": {},
246 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
247
248 "create-time": now,
249 "nsd-name-ref": nsd["name"],
250 "operational-events": [], # "id", "timestamp", "description", "event",
251 "nsd-ref": nsd["id"],
252 "nsd-id": nsd["_id"],
253 "vnfd-id": [],
254 "instantiate_params": self._format_ns_request(ns_request),
255 "additionalParamsForNs": self._format_addional_params(ns_request, descriptor=nsd),
256 "ns-instance-config-ref": nsr_id,
257 "id": nsr_id,
258 "_id": nsr_id,
259 # "input-parameter": xpath, value,
260 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
261 }
262 ns_request["nsr_id"] = nsr_id
263 # Create vld
264 if nsd.get("vld"):
265 nsr_descriptor["vld"] = []
266 for nsd_vld in nsd.get("vld"):
267 nsr_descriptor["vld"].append(
268 {key: nsd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in nsd_vld})
269
270 # Create VNFR
271 needed_vnfds = {}
272 for member_vnf in nsd.get("constituent-vnfd", ()):
273 vnfd_id = member_vnf["vnfd-id-ref"]
274 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
275 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
276 if vnfd_id not in needed_vnfds:
277 # Obtain vnfd
278 _filter["id"] = vnfd_id
279 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
280 del _filter["id"]
281 vnfd.pop("_admin")
282 needed_vnfds[vnfd_id] = vnfd
283 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
284 else:
285 vnfd = needed_vnfds[vnfd_id]
286 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
287 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
288 vnfr_id = str(uuid4())
289 vnfr_descriptor = {
290 "id": vnfr_id,
291 "_id": vnfr_id,
292 "nsr-id-ref": nsr_id,
293 "member-vnf-index-ref": member_vnf["member-vnf-index"],
294 "additionalParamsForVnf": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
295 descriptor=vnfd),
296 "created-time": now,
297 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
298 "vnfd-ref": vnfd_id,
299 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
300 "vim-account-id": None,
301 "vdur": [],
302 "connection-point": [],
303 "ip-address": None, # mgmt-interface filled by LCM
304 }
305
306 # Create vld
307 if vnfd.get("internal-vld"):
308 vnfr_descriptor["vld"] = []
309 for vnfd_vld in vnfd.get("internal-vld"):
310 vnfr_descriptor["vld"].append(
311 {key: vnfd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in
312 vnfd_vld})
313
314 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
315 for cp in vnfd.get("connection-point", ()):
316 vnf_cp = {
317 "name": cp["name"],
318 "connection-point-id": cp.get("id"),
319 "id": cp.get("id"),
320 # "ip-address", "mac-address" # filled by LCM
321 # vim-id # TODO it would be nice having a vim port id
322 }
323 vnfr_descriptor["connection-point"].append(vnf_cp)
324
325 # Create k8s-cluster information
326 if vnfd.get("k8s-cluster"):
327 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
328 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
329 if net.get("external-connection-point-ref"):
330 for nsd_vld in get_iterable(nsd.get("vld")):
331 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
332 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
333 net["external-connection-point-ref"] and \
334 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
335 net["ns-vld-id"] = nsd_vld["id"]
336 break
337 else:
338 continue
339 break
340 elif net.get("internal-connection-point-ref"):
341 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
342 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
343 if vnfd_ivld_icp.get("id-ref") == net["internal-connection-point-ref"]:
344 net["vnf-vld-id"] = vnfd_ivld["id"]
345 break
346 else:
347 continue
348 break
349 # update kdus
350 for kdu in get_iterable(vnfd.get("kdu")):
351 kdur = {x: kdu[x] for x in kdu if x in ("helm-chart", "juju-bundle")}
352 kdur["kdu-name"] = kdu["name"]
353 # TODO "name": "" Name of the VDU in the VIM
354 kdur["ip-address"] = None # mgmt-interface filled by LCM
355 kdur["k8s-cluster"] = {}
356 kdur["additionalParams"] = self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
357 kdu_name=kdu["name"], descriptor=vnfd)
358 if not vnfr_descriptor.get("kdur"):
359 vnfr_descriptor["kdur"] = []
360 vnfr_descriptor["kdur"].append(kdur)
361
362 for vdu in vnfd.get("vdu", ()):
363 vdur = {
364 "vdu-id-ref": vdu["id"],
365 # TODO "name": "" Name of the VDU in the VIM
366 "ip-address": None, # mgmt-interface filled by LCM
367 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
368 "internal-connection-point": [],
369 "interfaces": [],
370 "additionalParams": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
371 vdu_id=vdu["id"], descriptor=vnfd)
372 }
373 if vdu.get("pdu-type"):
374 vdur["pdu-type"] = vdu["pdu-type"]
375 # TODO volumes: name, volume-id
376 for icp in vdu.get("internal-connection-point", ()):
377 vdu_icp = {
378 "id": icp["id"],
379 "connection-point-id": icp["id"],
380 "name": icp.get("name"),
381 # "ip-address", "mac-address" # filled by LCM
382 # vim-id # TODO it would be nice having a vim port id
383 }
384 vdur["internal-connection-point"].append(vdu_icp)
385 for iface in vdu.get("interface", ()):
386 vdu_iface = {
387 "name": iface.get("name"),
388 # "ip-address", "mac-address" # filled by LCM
389 # vim-id # TODO it would be nice having a vim port id
390 }
391 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
392 vdu_iface["mgmt-vnf"] = True
393 if iface.get("mgmt-interface"):
394 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
395
396 # look for network where this interface is connected
397 if iface.get("external-connection-point-ref"):
398 for nsd_vld in get_iterable(nsd.get("vld")):
399 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
400 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
401 iface["external-connection-point-ref"] and \
402 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
403 vdu_iface["ns-vld-id"] = nsd_vld["id"]
404 break
405 else:
406 continue
407 break
408 elif iface.get("internal-connection-point-ref"):
409 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
410 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
411 if vnfd_ivld_icp.get("id-ref") == iface["internal-connection-point-ref"]:
412 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
413 break
414 else:
415 continue
416 break
417
418 vdur["interfaces"].append(vdu_iface)
419 count = vdu.get("count", 1)
420 if count is None:
421 count = 1
422 count = int(count) # TODO remove when descriptor serialized with payngbind
423 for index in range(0, count):
424 if index:
425 vdur = deepcopy(vdur)
426 vdur["_id"] = str(uuid4())
427 vdur["count-index"] = index
428 vnfr_descriptor["vdur"].append(vdur)
429
430 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
431 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
432
433 # add at database
434 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
435 self.db.create("vnfrs", vnfr_descriptor)
436 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
437 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
438
439 step = "creating nsr at database"
440 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
441 self.db.create("nsrs", nsr_descriptor)
442 rollback.append({"topic": "nsrs", "_id": nsr_id})
443
444 step = "creating nsr temporal folder"
445 self.fs.mkdir(nsr_id)
446
447 return nsr_id, None
448 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
449 raise type(e)("{} while '{}".format(e, step), http_code=e.http_code)
450
451 def edit(self, session, _id, indata=None, kwargs=None, content=None):
452 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
453
454
455 class VnfrTopic(BaseTopic):
456 topic = "vnfrs"
457 topic_msg = None
458
459 def __init__(self, db, fs, msg, auth):
460 BaseTopic.__init__(self, db, fs, msg, auth)
461
462 def delete(self, session, _id, dry_run=False, not_send_msg=None):
463 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
464
465 def edit(self, session, _id, indata=None, kwargs=None, content=None):
466 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
467
468 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
469 # Not used because vnfrs are created and deleted by NsrTopic class directly
470 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
471
472
473 class NsLcmOpTopic(BaseTopic):
474 topic = "nslcmops"
475 topic_msg = "ns"
476 operation_schema = { # mapping between operation and jsonschema to validate
477 "instantiate": ns_instantiate,
478 "action": ns_action,
479 "scale": ns_scale,
480 "terminate": None,
481 }
482
483 def __init__(self, db, fs, msg, auth):
484 BaseTopic.__init__(self, db, fs, msg, auth)
485
486 def _check_ns_operation(self, session, nsr, operation, indata):
487 """
488 Check that user has enter right parameters for the operation
489 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
490 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
491 :param indata: descriptor with the parameters of the operation
492 :return: None
493 """
494 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
495 vim_accounts = []
496 wim_accounts = []
497 nsd = nsr["nsd"]
498
499 def check_valid_vnf_member_index(member_vnf_index):
500 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
501 if vnf_member_index_to_vnfd.get(member_vnf_index):
502 return vnf_member_index_to_vnfd[member_vnf_index]
503 vnfr = self.db.get_one("vnfrs",
504 {"nsr-id-ref": nsr["_id"], "member-vnf-index-ref": member_vnf_index},
505 fail_on_empty=False)
506 if not vnfr:
507 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
508 "nsd:constituent-vnfd".format(member_vnf_index))
509 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
510 if not vnfd:
511 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
512 format(vnfr["vnfd-id"]))
513 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
514 return vnfd
515
516 def check_valid_vdu(vnfd, vdu_id):
517 for vdud in get_iterable(vnfd.get("vdu")):
518 if vdud["id"] == vdu_id:
519 return vdud
520 else:
521 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
522
523 def check_valid_kdu(vnfd, kdu_name):
524 for kdud in get_iterable(vnfd.get("kdu")):
525 if kdud["name"] == kdu_name:
526 return kdud
527 else:
528 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
529
530 def _check_vnf_instantiation_params(in_vnfd, vnfd):
531
532 for in_vdu in get_iterable(in_vnfd.get("vdu")):
533 for vdu in get_iterable(vnfd.get("vdu")):
534 if in_vdu["id"] == vdu["id"]:
535 for volume in get_iterable(in_vdu.get("volume")):
536 for volumed in get_iterable(vdu.get("volumes")):
537 if volumed["name"] == volume["name"]:
538 break
539 else:
540 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
541 "volume:name='{}' is not present at vnfd:vdu:volumes list".
542 format(in_vnf["member-vnf-index"], in_vdu["id"],
543 volume["name"]))
544 for in_iface in get_iterable(in_vdu["interface"]):
545 for iface in get_iterable(vdu.get("interface")):
546 if in_iface["name"] == iface["name"]:
547 break
548 else:
549 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
550 "interface[name='{}'] is not present at vnfd:vdu:interface"
551 .format(in_vnf["member-vnf-index"], in_vdu["id"],
552 in_iface["name"]))
553 break
554 else:
555 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
556 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
557
558 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
559 for ivld in get_iterable(vnfd.get("internal-vld")):
560 if in_ivld["name"] == ivld["name"] or in_ivld["name"] == ivld["id"]:
561 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
562 for icp in ivld["internal-connection-point"]:
563 if in_icp["id-ref"] == icp["id-ref"]:
564 break
565 else:
566 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
567 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
568 "vnfd:internal-vld:name/id:internal-connection-point"
569 .format(in_vnf["member-vnf-index"], in_ivld["name"],
570 in_icp["id-ref"], vnfd["id"]))
571 break
572 else:
573 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
574 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
575 in_ivld["name"], vnfd["id"]))
576
577 def check_valid_vim_account(vim_account):
578 if vim_account in vim_accounts:
579 return
580 try:
581 db_filter = self._get_project_filter(session)
582 db_filter["_id"] = vim_account
583 self.db.get_one("vim_accounts", db_filter)
584 except Exception:
585 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
586 vim_accounts.append(vim_account)
587
588 def check_valid_wim_account(wim_account):
589 if not isinstance(wim_account, str):
590 return
591 elif wim_account in wim_accounts:
592 return
593 try:
594 db_filter = self._get_project_filter(session, write=False, show_all=True)
595 db_filter["_id"] = wim_account
596 self.db.get_one("wim_accounts", db_filter)
597 except Exception:
598 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
599 wim_accounts.append(wim_account)
600
601 if operation == "action":
602 # check vnf_member_index
603 if indata.get("vnf_member_index"):
604 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
605 if indata.get("member_vnf_index"):
606 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
607 if indata.get("vdu_id"):
608 vdud = check_valid_vdu(vnfd, indata["vdu_id"])
609 descriptor_configuration = vdud.get("vdu-configuration", {}).get("config-primitive")
610 elif indata.get("kdu_name"):
611 kdud = check_valid_kdu(vnfd, indata["kdu_name"])
612 descriptor_configuration = kdud.get("kdu-configuration", {}).get("config-primitive")
613 else:
614 descriptor_configuration = vnfd.get("vnf-configuration", {}).get("config-primitive")
615 else: # use a NSD
616 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
617
618 # For k8s allows default primitives without validating the parameters
619 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
620 # TODO should be checked that rollback only can contains revsision_numbe????
621 if not indata.get("member_vnf_index"):
622 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
623 .format(indata["primitive"]))
624 return
625 # if not, check primitive
626 for config_primitive in get_iterable(descriptor_configuration):
627 if indata["primitive"] == config_primitive["name"]:
628 # check needed primitive_params are provided
629 if indata.get("primitive_params"):
630 in_primitive_params_copy = copy(indata["primitive_params"])
631 else:
632 in_primitive_params_copy = {}
633 for paramd in get_iterable(config_primitive.get("parameter")):
634 if paramd["name"] in in_primitive_params_copy:
635 del in_primitive_params_copy[paramd["name"]]
636 elif not paramd.get("default-value"):
637 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
638 paramd["name"], indata["primitive"]))
639 # check no extra primitive params are provided
640 if in_primitive_params_copy:
641 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
642 list(in_primitive_params_copy.keys()), indata["primitive"]))
643 break
644 else:
645 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
646 if operation == "scale":
647 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
648 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
649 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
650 break
651 else:
652 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
653 "present at vnfd:scaling-group-descriptor".format(
654 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
655 if operation == "instantiate":
656 # check vim_account
657 check_valid_vim_account(indata["vimAccountId"])
658 check_valid_wim_account(indata.get("wimAccountId"))
659 for in_vnf in get_iterable(indata.get("vnf")):
660 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
661 _check_vnf_instantiation_params(in_vnf, vnfd)
662 if in_vnf.get("vimAccountId"):
663 check_valid_vim_account(in_vnf["vimAccountId"])
664
665 for in_vld in get_iterable(indata.get("vld")):
666 check_valid_wim_account(in_vld.get("wimAccountId"))
667 for vldd in get_iterable(nsd.get("vld")):
668 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
669 break
670 else:
671 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
672 in_vld["name"]))
673
674 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
675 """
676 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
677 (ip_address, ...) information.
678 Modifies PDU _admin.usageState to 'IN_USE'
679 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
680 :param rollback: list with the database modifications to rollback if needed
681 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
682 :param vim_account: vim_account where this vnfr should be deployed
683 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
684 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
685 of the changed vnfr is needed
686
687 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
688 "vim-network-name": used at VIM
689 "name": interface name
690 "vnf-vld-id": internal VNFD vld where this interface is connected, or
691 "ns-vld-id": NSD vld where this interface is connected.
692 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
693 """
694
695 ifaces_forcing_vim_network = []
696 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
697 if not vdur.get("pdu-type"):
698 continue
699 pdu_type = vdur.get("pdu-type")
700 pdu_filter = self._get_project_filter(session)
701 pdu_filter["vim_accounts"] = vim_account
702 pdu_filter["type"] = pdu_type
703 pdu_filter["_admin.operationalState"] = "ENABLED"
704 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
705 # TODO feature 1417: "shared": True,
706
707 available_pdus = self.db.get_list("pdus", pdu_filter)
708 for pdu in available_pdus:
709 # step 1 check if this pdu contains needed interfaces:
710 match_interfaces = True
711 for vdur_interface in vdur["interfaces"]:
712 for pdu_interface in pdu["interfaces"]:
713 if pdu_interface["name"] == vdur_interface["name"]:
714 # TODO feature 1417: match per mgmt type
715 break
716 else: # no interface found for name
717 match_interfaces = False
718 break
719 if match_interfaces:
720 break
721 else:
722 raise EngineException(
723 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
724 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
725
726 # step 2. Update pdu
727 rollback_pdu = {
728 "_admin.usageState": pdu["_admin"]["usageState"],
729 "_admin.usage.vnfr_id": None,
730 "_admin.usage.nsr_id": None,
731 "_admin.usage.vdur": None,
732 }
733 self.db.set_one("pdus", {"_id": pdu["_id"]},
734 {"_admin.usageState": "IN_USE",
735 "_admin.usage": {"vnfr_id": vnfr["_id"],
736 "nsr_id": vnfr["nsr-id-ref"],
737 "vdur": vdur["vdu-id-ref"]}
738 })
739 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
740
741 # step 3. Fill vnfr info by filling vdur
742 vdu_text = "vdur.{}".format(vdur_index)
743 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
744 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
745 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
746 for pdu_interface in pdu["interfaces"]:
747 if pdu_interface["name"] == vdur_interface["name"]:
748 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
749 for k, v in pdu_interface.items():
750 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
751 vnfr_update[iface_text + ".{}".format(k)] = v
752 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
753 if pdu_interface.get("ip-address"):
754 if vdur_interface.get("mgmt-interface"):
755 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
756 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
757 if vdur_interface.get("mgmt-vnf"):
758 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
759 vnfr_update["ip-address"] = pdu_interface["ip-address"]
760 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
761 ifaces_forcing_vim_network.append({
762 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
763 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
764 "ns-vld-id": vdur_interface.get("ns-vld-id")})
765 if pdu_interface.get("vim-network-id"):
766 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
767 if pdu_interface.get("vim-network-name"):
768 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
769 break
770
771 return ifaces_forcing_vim_network
772
773 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
774 """
775 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
776 Fills vnfr.kdur with the selected k8scluster
777
778 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
779 :param rollback: list with the database modifications to rollback if needed
780 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
781 :param vim_account: vim_account where this vnfr should be deployed
782 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
783 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
784 of the changed vnfr is needed
785
786 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
787 "vim-network-name": used at VIM
788 "name": interface name
789 "vnf-vld-id": internal VNFD vld where this interface is connected, or
790 "ns-vld-id": NSD vld where this interface is connected.
791 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
792 """
793
794 ifaces_forcing_vim_network = []
795 if not vnfr.get("kdur"):
796 return ifaces_forcing_vim_network
797
798 kdu_filter = self._get_project_filter(session)
799 kdu_filter["vim_account"] = vim_account
800 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
801 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
802
803 k8s_requirements = {} # just for logging
804 for k8scluster in available_k8sclusters:
805 if not vnfr.get("k8s-cluster"):
806 break
807 # restrict by cni
808 if vnfr["k8s-cluster"].get("cni"):
809 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
810 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
811 continue
812 # restrict by version
813 if vnfr["k8s-cluster"].get("version"):
814 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
815 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
816 continue
817 # restrict by number of networks
818 if vnfr["k8s-cluster"].get("nets"):
819 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
820 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
821 continue
822 break
823 else:
824 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
825 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
826
827 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
828 # step 3. Fill vnfr info by filling kdur
829 kdu_text = "kdur.{}.".format(kdur_index)
830 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
831 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
832
833 # step 4. Check VIM networks that forces the selected k8s_cluster
834 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
835 k8scluster_net_list = list(k8scluster.get("nets").keys())
836 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
837 # get a network from k8s_cluster nets. If name matches use this, if not use other
838 if kdur_net["id"] in k8scluster_net_list: # name matches
839 vim_net = k8scluster["nets"][kdur_net["id"]]
840 k8scluster_net_list.remove(kdur_net["id"])
841 else:
842 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
843 k8scluster_net_list.pop(0)
844 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
845 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
846 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
847 ifaces_forcing_vim_network.append({
848 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
849 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
850 "ns-vld-id": kdur_net.get("ns-vld-id"),
851 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
852 })
853 # TODO check that this forcing is not incompatible with other forcing
854 return ifaces_forcing_vim_network
855
856 def _update_vnfrs(self, session, rollback, nsr, indata):
857 # get vnfr
858 nsr_id = nsr["_id"]
859 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
860
861 for vnfr in vnfrs:
862 vnfr_update = {}
863 vnfr_update_rollback = {}
864 member_vnf_index = vnfr["member-vnf-index-ref"]
865 # update vim-account-id
866
867 vim_account = indata["vimAccountId"]
868 # check instantiate parameters
869 for vnf_inst_params in get_iterable(indata.get("vnf")):
870 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
871 continue
872 if vnf_inst_params.get("vimAccountId"):
873 vim_account = vnf_inst_params.get("vimAccountId")
874
875 vnfr_update["vim-account-id"] = vim_account
876 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
877
878 # get pdu
879 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
880 vnfr_update_rollback)
881
882 # get kdus
883 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
884 vnfr_update_rollback)
885 # update database vnfr
886 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
887 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
888
889 # Update indada in case pdu forces to use a concrete vim-network-name
890 # TODO check if user has already insert a vim-network-name and raises an error
891 if not ifaces_forcing_vim_network:
892 continue
893 for iface_info in ifaces_forcing_vim_network:
894 if iface_info.get("ns-vld-id"):
895 if "vld" not in indata:
896 indata["vld"] = []
897 indata["vld"].append({key: iface_info[key] for key in
898 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
899
900 elif iface_info.get("vnf-vld-id"):
901 if "vnf" not in indata:
902 indata["vnf"] = []
903 indata["vnf"].append({
904 "member-vnf-index": member_vnf_index,
905 "internal-vld": [{key: iface_info[key] for key in
906 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
907 })
908
909 @staticmethod
910 def _create_nslcmop(nsr_id, operation, params):
911 """
912 Creates a ns-lcm-opp content to be stored at database.
913 :param nsr_id: internal id of the instance
914 :param operation: instantiate, terminate, scale, action, ...
915 :param params: user parameters for the operation
916 :return: dictionary following SOL005 format
917 """
918 now = time()
919 _id = str(uuid4())
920 nslcmop = {
921 "id": _id,
922 "_id": _id,
923 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
924 "statusEnteredTime": now,
925 "nsInstanceId": nsr_id,
926 "lcmOperationType": operation,
927 "startTime": now,
928 "isAutomaticInvocation": False,
929 "operationParams": params,
930 "isCancelPending": False,
931 "links": {
932 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
933 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
934 }
935 }
936 return nslcmop
937
938 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
939 """
940 Performs a new operation over a ns
941 :param rollback: list to append created items at database in case a rollback must to be done
942 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
943 :param indata: descriptor with the parameters of the operation. It must contains among others
944 nsInstanceId: _id of the nsr to perform the operation
945 operation: it can be: instantiate, terminate, action, TODO: update, heal
946 :param kwargs: used to override the indata descriptor
947 :param headers: http request headers
948 :return: id of the nslcmops
949 """
950 def check_if_nsr_is_not_slice_member(session, nsr_id):
951 nsis = None
952 db_filter = self._get_project_filter(session)
953 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
954 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
955 if nsis:
956 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
957 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
958
959 try:
960 # Override descriptor with query string kwargs
961 self._update_input_with_kwargs(indata, kwargs)
962 operation = indata["lcmOperationType"]
963 nsInstanceId = indata["nsInstanceId"]
964
965 validate_input(indata, self.operation_schema[operation])
966 # get ns from nsr_id
967 _filter = BaseTopic._get_project_filter(session)
968 _filter["_id"] = nsInstanceId
969 nsr = self.db.get_one("nsrs", _filter)
970
971 # initial checking
972 if operation == "terminate" and slice_object is False:
973 check_if_nsr_is_not_slice_member(session, nsr["_id"])
974 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
975 if operation == "terminate" and indata.get("autoremove"):
976 # NSR must be deleted
977 return None, None # a none in this case is used to indicate not instantiated. It can be removed
978 if operation != "instantiate":
979 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
980 nsInstanceId, operation), HTTPStatus.CONFLICT)
981 else:
982 if operation == "instantiate" and not session["force"]:
983 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
984 nsInstanceId, operation), HTTPStatus.CONFLICT)
985 self._check_ns_operation(session, nsr, operation, indata)
986
987 if operation == "instantiate":
988 self._update_vnfrs(session, rollback, nsr, indata)
989
990 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
991 _id = nslcmop_desc["_id"]
992 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
993 self.db.create("nslcmops", nslcmop_desc)
994 rollback.append({"topic": "nslcmops", "_id": _id})
995 if not slice_object:
996 self.msg.write("ns", operation, nslcmop_desc)
997 return _id, None
998 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
999 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1000 # except DbException as e:
1001 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1002
1003 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1004 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1005
1006 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1007 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1008
1009
1010 class NsiTopic(BaseTopic):
1011 topic = "nsis"
1012 topic_msg = "nsi"
1013
1014 def __init__(self, db, fs, msg, auth):
1015 BaseTopic.__init__(self, db, fs, msg, auth)
1016 self.nsrTopic = NsrTopic(db, fs, msg, auth)
1017
1018 @staticmethod
1019 def _format_ns_request(ns_request):
1020 formated_request = copy(ns_request)
1021 # TODO: Add request params
1022 return formated_request
1023
1024 @staticmethod
1025 def _format_addional_params(slice_request):
1026 """
1027 Get and format user additional params for NS or VNF
1028 :param slice_request: User instantiation additional parameters
1029 :return: a formatted copy of additional params or None if not supplied
1030 """
1031 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1032 if additional_params:
1033 for k, v in additional_params.items():
1034 if not isinstance(k, str):
1035 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1036 format(k))
1037 if "." in k or "$" in k:
1038 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1039 format(k))
1040 if isinstance(v, (dict, tuple, list)):
1041 additional_params[k] = "!!yaml " + safe_dump(v)
1042 return additional_params
1043
1044 def _check_descriptor_dependencies(self, session, descriptor):
1045 """
1046 Check that the dependent descriptors exist on a new descriptor or edition
1047 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1048 :param descriptor: descriptor to be inserted or edit
1049 :return: None or raises exception
1050 """
1051 if not descriptor.get("nst-ref"):
1052 return
1053 nstd_id = descriptor["nst-ref"]
1054 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
1055 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
1056 http_code=HTTPStatus.CONFLICT)
1057
1058 def check_conflict_on_del(self, session, _id, db_content):
1059 """
1060 Check that NSI is not instantiated
1061 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1062 :param _id: nsi internal id
1063 :param db_content: The database content of the _id
1064 :return: None or raises EngineException with the conflict
1065 """
1066 if session["force"]:
1067 return
1068 nsi = db_content
1069 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1070 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1071 "Launch 'terminate' operation first; or force deletion".format(_id),
1072 http_code=HTTPStatus.CONFLICT)
1073
1074 def delete_extra(self, session, _id, db_content, not_send_msg=None):
1075 """
1076 Deletes associated nsilcmops from database. Deletes associated filesystem.
1077 Set usageState of nst
1078 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1079 :param _id: server internal id
1080 :param db_content: The database content of the descriptor
1081 :param not_send_msg: To not send message (False) or store content (list) instead
1082 :return: None if ok or raises EngineException with the problem
1083 """
1084
1085 # Deleting the nsrs belonging to nsir
1086 nsir = db_content
1087 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1088 nsr_id = nsrs_detailed_item["nsrId"]
1089 if nsrs_detailed_item.get("shared"):
1090 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1091 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1092 "_id.ne": nsir["_id"]}
1093 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1094 if nsi: # last one using nsr
1095 continue
1096 try:
1097 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
1098 except (DbException, EngineException) as e:
1099 if e.http_code == HTTPStatus.NOT_FOUND:
1100 pass
1101 else:
1102 raise
1103
1104 # delete related nsilcmops database entries
1105 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
1106
1107 # Check and set used NST usage state
1108 nsir_admin = nsir.get("_admin")
1109 if nsir_admin and nsir_admin.get("nst-id"):
1110 # check if used by another NSI
1111 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1112 fail_on_empty=False, fail_on_more=False)
1113 if not nsis_list:
1114 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1115
1116 # def delete(self, session, _id, dry_run=False):
1117 # """
1118 # Delete item by its internal _id
1119 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1120 # :param _id: server internal id
1121 # :param dry_run: make checking but do not delete
1122 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1123 # """
1124 # # TODO add admin to filter, validate rights
1125 # BaseTopic.delete(self, session, _id, dry_run=True)
1126 # if dry_run:
1127 # return
1128 #
1129 # # Deleting the nsrs belonging to nsir
1130 # nsir = self.db.get_one("nsis", {"_id": _id})
1131 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1132 # nsr_id = nsrs_detailed_item["nsrId"]
1133 # if nsrs_detailed_item.get("shared"):
1134 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1135 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1136 # "_id.ne": nsir["_id"]}
1137 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1138 # if nsi: # last one using nsr
1139 # continue
1140 # try:
1141 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1142 # except (DbException, EngineException) as e:
1143 # if e.http_code == HTTPStatus.NOT_FOUND:
1144 # pass
1145 # else:
1146 # raise
1147 # # deletes NetSlice instance object
1148 # v = self.db.del_one("nsis", {"_id": _id})
1149 #
1150 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1151 # _filter = {"netsliceInstanceId": _id}
1152 # self.db.del_list("nsilcmops", _filter)
1153 #
1154 # # Search if nst is being used by other nsi
1155 # nsir_admin = nsir.get("_admin")
1156 # if nsir_admin:
1157 # if nsir_admin.get("nst-id"):
1158 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1159 # fail_on_empty=False, fail_on_more=False)
1160 # if not nsis_list:
1161 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1162 # return v
1163
1164 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1165 """
1166 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1167 :param rollback: list to append the created items at database in case a rollback must be done
1168 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1169 :param indata: params to be used for the nsir
1170 :param kwargs: used to override the indata descriptor
1171 :param headers: http request headers
1172 :return: the _id of nsi descriptor created at database
1173 """
1174
1175 try:
1176 step = "checking quotas"
1177 self.check_quota(session)
1178
1179 step = ""
1180 slice_request = self._remove_envelop(indata)
1181 # Override descriptor with query string kwargs
1182 self._update_input_with_kwargs(slice_request, kwargs)
1183 self._validate_input_new(slice_request, session["force"])
1184
1185 # look for nstd
1186 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
1187 _filter = self._get_project_filter(session)
1188 _filter["_id"] = slice_request["nstId"]
1189 nstd = self.db.get_one("nsts", _filter)
1190 del _filter["_id"]
1191
1192 nstd.pop("_admin", None)
1193 nstd_id = nstd.pop("_id", None)
1194 nsi_id = str(uuid4())
1195 step = "filling nsi_descriptor with input data"
1196
1197 # Creating the NSIR
1198 nsi_descriptor = {
1199 "id": nsi_id,
1200 "name": slice_request["nsiName"],
1201 "description": slice_request.get("nsiDescription", ""),
1202 "datacenter": slice_request["vimAccountId"],
1203 "nst-ref": nstd["id"],
1204 "instantiation_parameters": slice_request,
1205 "network-slice-template": nstd,
1206 "nsr-ref-list": [],
1207 "vlr-list": [],
1208 "_id": nsi_id,
1209 "additionalParamsForNsi": self._format_addional_params(slice_request)
1210 }
1211
1212 step = "creating nsi at database"
1213 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
1214 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1215 nsi_descriptor["_admin"]["netslice-subnet"] = None
1216 nsi_descriptor["_admin"]["deployed"] = {}
1217 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1218 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1219
1220 # Creating netslice-vld for the RO.
1221 step = "creating netslice-vld at database"
1222
1223 # Building the vlds list to be deployed
1224 # From netslice descriptors, creating the initial list
1225 nsi_vlds = []
1226
1227 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1228 # Getting template Instantiation parameters from NST
1229 nsi_vld = deepcopy(netslice_vlds)
1230 nsi_vld["shared-nsrs-list"] = []
1231 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1232 nsi_vlds.append(nsi_vld)
1233
1234 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
1235 # Creating netslice-subnet_record.
1236 needed_nsds = {}
1237 services = []
1238
1239 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1240 for member_ns in nstd["netslice-subnet"]:
1241 nsd_id = member_ns["nsd-ref"]
1242 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1243 member_ns["nsd-ref"], member_ns["id"])
1244 if nsd_id not in needed_nsds:
1245 # Obtain nsd
1246 _filter["id"] = nsd_id
1247 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1248 del _filter["id"]
1249 nsd.pop("_admin")
1250 needed_nsds[nsd_id] = nsd
1251 else:
1252 nsd = needed_nsds[nsd_id]
1253 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1254 services.append(member_ns)
1255
1256 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1257 member_ns["nsd-ref"], member_ns["id"])
1258
1259 # creates Network Services records (NSRs)
1260 step = "creating nsrs at database using NsrTopic.new()"
1261 ns_params = slice_request.get("netslice-subnet")
1262 nsrs_list = []
1263 nsi_netslice_subnet = []
1264 for service in services:
1265 # Check if the netslice-subnet is shared and if it is share if the nss exists
1266 _id_nsr = None
1267 indata_ns = {}
1268 # Is the nss shared and instantiated?
1269 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1270 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
1271 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
1272 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1273 if nsi and service.get("is-shared-nss"):
1274 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1275 for nsrs_detailed_item in nsrs_detailed_list:
1276 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
1277 if nsrs_detailed_item["nss-id"] == service["id"]:
1278 _id_nsr = nsrs_detailed_item["nsrId"]
1279 break
1280 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1281 if netslice_subnet["nss-id"] == service["id"]:
1282 indata_ns = netslice_subnet
1283 break
1284 else:
1285 indata_ns = {}
1286 if service.get("instantiation-parameters"):
1287 indata_ns = deepcopy(service["instantiation-parameters"])
1288 # del service["instantiation-parameters"]
1289
1290 indata_ns["nsdId"] = service["_id"]
1291 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1292 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1293 indata_ns["nsDescription"] = service["description"]
1294 if slice_request.get("ssh_keys"):
1295 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
1296
1297 if ns_params:
1298 for ns_param in ns_params:
1299 if ns_param.get("id") == service["id"]:
1300 copy_ns_param = deepcopy(ns_param)
1301 del copy_ns_param["id"]
1302 indata_ns.update(copy_ns_param)
1303 break
1304
1305 # Creates Nsr objects
1306 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
1307 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
1308 "nss-id": service["id"], "nslcmop_instantiate": None}
1309 indata_ns["nss-id"] = service["id"]
1310 nsrs_list.append(nsrs_item)
1311 nsi_netslice_subnet.append(indata_ns)
1312 nsr_ref = {"nsr-ref": _id_nsr}
1313 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
1314
1315 # Adding the nsrs list to the nsi
1316 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
1317 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1318 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1319
1320 # Creating the entry in the database
1321 self.db.create("nsis", nsi_descriptor)
1322 rollback.append({"topic": "nsis", "_id": nsi_id})
1323 return nsi_id, None
1324 except Exception as e: # TODO remove try Except, it is captured at nbi.py
1325 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1326 raise EngineException("Error {}: {}".format(step, e))
1327 except ValidationError as e:
1328 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1329
1330 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1331 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1332
1333
1334 class NsiLcmOpTopic(BaseTopic):
1335 topic = "nsilcmops"
1336 topic_msg = "nsi"
1337 operation_schema = { # mapping between operation and jsonschema to validate
1338 "instantiate": nsi_instantiate,
1339 "terminate": None
1340 }
1341
1342 def __init__(self, db, fs, msg, auth):
1343 BaseTopic.__init__(self, db, fs, msg, auth)
1344 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
1345
1346 def _check_nsi_operation(self, session, nsir, operation, indata):
1347 """
1348 Check that user has enter right parameters for the operation
1349 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1350 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1351 :param indata: descriptor with the parameters of the operation
1352 :return: None
1353 """
1354 nsds = {}
1355 nstd = nsir["network-slice-template"]
1356
1357 def check_valid_netslice_subnet_id(nstId):
1358 # TODO change to vnfR (??)
1359 for netslice_subnet in nstd["netslice-subnet"]:
1360 if nstId == netslice_subnet["id"]:
1361 nsd_id = netslice_subnet["nsd-ref"]
1362 if nsd_id not in nsds:
1363 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1364 return nsds[nsd_id]
1365 else:
1366 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1367 "nst:netslice-subnet".format(nstId))
1368 if operation == "instantiate":
1369 # check the existance of netslice-subnet items
1370 for in_nst in get_iterable(indata.get("netslice-subnet")):
1371 check_valid_netslice_subnet_id(in_nst["id"])
1372
1373 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1374 now = time()
1375 _id = str(uuid4())
1376 nsilcmop = {
1377 "id": _id,
1378 "_id": _id,
1379 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1380 "statusEnteredTime": now,
1381 "netsliceInstanceId": netsliceInstanceId,
1382 "lcmOperationType": operation,
1383 "startTime": now,
1384 "isAutomaticInvocation": False,
1385 "operationParams": params,
1386 "isCancelPending": False,
1387 "links": {
1388 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
1389 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
1390 }
1391 }
1392 return nsilcmop
1393
1394 def add_shared_nsr_2vld(self, nsir, nsr_item):
1395 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1396 if nst_sb_item.get("is-shared-nss"):
1397 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1398 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1399 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1400 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1401 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1402 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1403 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1404 break
1405 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1406 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1407
1408 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1409 """
1410 Performs a new operation over a ns
1411 :param rollback: list to append created items at database in case a rollback must to be done
1412 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1413 :param indata: descriptor with the parameters of the operation. It must contains among others
1414 netsliceInstanceId: _id of the nsir to perform the operation
1415 operation: it can be: instantiate, terminate, action, TODO: update, heal
1416 :param kwargs: used to override the indata descriptor
1417 :param headers: http request headers
1418 :return: id of the nslcmops
1419 """
1420 try:
1421 # Override descriptor with query string kwargs
1422 self._update_input_with_kwargs(indata, kwargs)
1423 operation = indata["lcmOperationType"]
1424 netsliceInstanceId = indata["netsliceInstanceId"]
1425 validate_input(indata, self.operation_schema[operation])
1426
1427 # get nsi from netsliceInstanceId
1428 _filter = self._get_project_filter(session)
1429 _filter["_id"] = netsliceInstanceId
1430 nsir = self.db.get_one("nsis", _filter)
1431 del _filter["_id"]
1432
1433 # initial checking
1434 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1435 if operation == "terminate" and indata.get("autoremove"):
1436 # NSIR must be deleted
1437 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1438 if operation != "instantiate":
1439 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1440 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
1441 else:
1442 if operation == "instantiate" and not session["force"]:
1443 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1444 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
1445
1446 # Creating all the NS_operation (nslcmop)
1447 # Get service list from db
1448 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1449 nslcmops = []
1450 # nslcmops_item = None
1451 for index, nsr_item in enumerate(nsrs_list):
1452 nsi = None
1453 if nsr_item.get("shared"):
1454 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1455 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1456 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1457 _filter["_id.ne"] = netsliceInstanceId
1458 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1459 if operation == "terminate":
1460 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1461 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1462
1463 # looks the first nsi fulfilling the conditions but not being the current NSIR
1464 if nsi:
1465 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1466 for nsi_nsr_item in nsi_admin_shared:
1467 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1468 self.add_shared_nsr_2vld(nsir, nsr_item)
1469 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1470 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1471 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1472 break
1473 # continue to not create nslcmop since nsrs is shared and nsrs was created
1474 continue
1475 else:
1476 self.add_shared_nsr_2vld(nsir, nsr_item)
1477
1478 try:
1479 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1480 indata_ns = {}
1481 indata_ns = service["instantiate_params"]
1482 indata_ns["lcmOperationType"] = operation
1483 indata_ns["nsInstanceId"] = service["_id"]
1484 # Including netslice_id in the ns instantiate Operation
1485 indata_ns["netsliceInstanceId"] = netsliceInstanceId
1486 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1487 # message via kafka bus
1488 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
1489 slice_object=True)
1490 nslcmops.append(nslcmop)
1491 if operation == "terminate":
1492 nslcmop = None
1493 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1494 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1495 except (DbException, EngineException) as e:
1496 if e.http_code == HTTPStatus.NOT_FOUND:
1497 self.logger.info("HTTPStatus.NOT_FOUND")
1498 pass
1499 else:
1500 raise
1501
1502 # Creates nsilcmop
1503 indata["nslcmops_ids"] = nslcmops
1504 self._check_nsi_operation(session, nsir, operation, indata)
1505
1506 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
1507 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
1508 _id = self.db.create("nsilcmops", nsilcmop_desc)
1509 rollback.append({"topic": "nsilcmops", "_id": _id})
1510 self.msg.write("nsi", operation, nsilcmop_desc)
1511 return _id, None
1512 except ValidationError as e:
1513 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1514
1515 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1516 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1517
1518 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1519 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)