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