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