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