6121ff2c860668cc22fe3dfd8dbcffce51882ca1
[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") or vdur_interface.get("mgmt-vnf"):
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 _get_enabled_vims(self, session):
951 """
952 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
953 :param session: current session with user information
954 """
955 db_filter = self._get_project_filter(session)
956 db_filter["_admin.operationalState"] = "ENABLED"
957 vims = self.db.get_list("vim_accounts", db_filter)
958 vimAccounts = []
959 for vim in vims:
960 vimAccounts.append(vim['_id'])
961 return vimAccounts
962
963 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
964 """
965 Performs a new operation over a ns
966 :param rollback: list to append created items at database in case a rollback must to be done
967 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
968 :param indata: descriptor with the parameters of the operation. It must contains among others
969 nsInstanceId: _id of the nsr to perform the operation
970 operation: it can be: instantiate, terminate, action, TODO: update, heal
971 :param kwargs: used to override the indata descriptor
972 :param headers: http request headers
973 :return: id of the nslcmops
974 """
975 def check_if_nsr_is_not_slice_member(session, nsr_id):
976 nsis = None
977 db_filter = self._get_project_filter(session)
978 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
979 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
980 if nsis:
981 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
982 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
983
984 try:
985 # Override descriptor with query string kwargs
986 self._update_input_with_kwargs(indata, kwargs)
987 operation = indata["lcmOperationType"]
988 nsInstanceId = indata["nsInstanceId"]
989
990 validate_input(indata, self.operation_schema[operation])
991 # get ns from nsr_id
992 _filter = BaseTopic._get_project_filter(session)
993 _filter["_id"] = nsInstanceId
994 nsr = self.db.get_one("nsrs", _filter)
995
996 # initial checking
997 if operation == "terminate" and slice_object is False:
998 check_if_nsr_is_not_slice_member(session, nsr["_id"])
999 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1000 if operation == "terminate" and indata.get("autoremove"):
1001 # NSR must be deleted
1002 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1003 if operation != "instantiate":
1004 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1005 nsInstanceId, operation), HTTPStatus.CONFLICT)
1006 else:
1007 if operation == "instantiate" and not session["force"]:
1008 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1009 nsInstanceId, operation), HTTPStatus.CONFLICT)
1010 self._check_ns_operation(session, nsr, operation, indata)
1011
1012 if operation == "instantiate":
1013 self._update_vnfrs(session, rollback, nsr, indata)
1014
1015 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
1016 _id = nslcmop_desc["_id"]
1017 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1018 if indata.get("placement-engine"):
1019 # Save valid vim accounts in lcm operation descriptor
1020 nslcmop_desc['operationParams']['validVimAccounts'] = self._get_enabled_vims(session)
1021 self.db.create("nslcmops", nslcmop_desc)
1022 rollback.append({"topic": "nslcmops", "_id": _id})
1023 if not slice_object:
1024 self.msg.write("ns", operation, nslcmop_desc)
1025 return _id, None
1026 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
1027 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1028 # except DbException as e:
1029 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1030
1031 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1032 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1033
1034 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1035 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1036
1037
1038 class NsiTopic(BaseTopic):
1039 topic = "nsis"
1040 topic_msg = "nsi"
1041
1042 def __init__(self, db, fs, msg, auth):
1043 BaseTopic.__init__(self, db, fs, msg, auth)
1044 self.nsrTopic = NsrTopic(db, fs, msg, auth)
1045
1046 @staticmethod
1047 def _format_ns_request(ns_request):
1048 formated_request = copy(ns_request)
1049 # TODO: Add request params
1050 return formated_request
1051
1052 @staticmethod
1053 def _format_addional_params(slice_request):
1054 """
1055 Get and format user additional params for NS or VNF
1056 :param slice_request: User instantiation additional parameters
1057 :return: a formatted copy of additional params or None if not supplied
1058 """
1059 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1060 if additional_params:
1061 for k, v in additional_params.items():
1062 if not isinstance(k, str):
1063 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1064 format(k))
1065 if "." in k or "$" in k:
1066 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1067 format(k))
1068 if isinstance(v, (dict, tuple, list)):
1069 additional_params[k] = "!!yaml " + safe_dump(v)
1070 return additional_params
1071
1072 def _check_descriptor_dependencies(self, session, descriptor):
1073 """
1074 Check that the dependent descriptors exist on a new descriptor or edition
1075 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1076 :param descriptor: descriptor to be inserted or edit
1077 :return: None or raises exception
1078 """
1079 if not descriptor.get("nst-ref"):
1080 return
1081 nstd_id = descriptor["nst-ref"]
1082 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
1083 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
1084 http_code=HTTPStatus.CONFLICT)
1085
1086 def check_conflict_on_del(self, session, _id, db_content):
1087 """
1088 Check that NSI is not instantiated
1089 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1090 :param _id: nsi internal id
1091 :param db_content: The database content of the _id
1092 :return: None or raises EngineException with the conflict
1093 """
1094 if session["force"]:
1095 return
1096 nsi = db_content
1097 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1098 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1099 "Launch 'terminate' operation first; or force deletion".format(_id),
1100 http_code=HTTPStatus.CONFLICT)
1101
1102 def delete_extra(self, session, _id, db_content, not_send_msg=None):
1103 """
1104 Deletes associated nsilcmops from database. Deletes associated filesystem.
1105 Set usageState of nst
1106 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1107 :param _id: server internal id
1108 :param db_content: The database content of the descriptor
1109 :param not_send_msg: To not send message (False) or store content (list) instead
1110 :return: None if ok or raises EngineException with the problem
1111 """
1112
1113 # Deleting the nsrs belonging to nsir
1114 nsir = db_content
1115 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1116 nsr_id = nsrs_detailed_item["nsrId"]
1117 if nsrs_detailed_item.get("shared"):
1118 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1119 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1120 "_id.ne": nsir["_id"]}
1121 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1122 if nsi: # last one using nsr
1123 continue
1124 try:
1125 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
1126 except (DbException, EngineException) as e:
1127 if e.http_code == HTTPStatus.NOT_FOUND:
1128 pass
1129 else:
1130 raise
1131
1132 # delete related nsilcmops database entries
1133 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
1134
1135 # Check and set used NST usage state
1136 nsir_admin = nsir.get("_admin")
1137 if nsir_admin and nsir_admin.get("nst-id"):
1138 # check if used by another NSI
1139 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1140 fail_on_empty=False, fail_on_more=False)
1141 if not nsis_list:
1142 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1143
1144 # def delete(self, session, _id, dry_run=False):
1145 # """
1146 # Delete item by its internal _id
1147 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1148 # :param _id: server internal id
1149 # :param dry_run: make checking but do not delete
1150 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1151 # """
1152 # # TODO add admin to filter, validate rights
1153 # BaseTopic.delete(self, session, _id, dry_run=True)
1154 # if dry_run:
1155 # return
1156 #
1157 # # Deleting the nsrs belonging to nsir
1158 # nsir = self.db.get_one("nsis", {"_id": _id})
1159 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1160 # nsr_id = nsrs_detailed_item["nsrId"]
1161 # if nsrs_detailed_item.get("shared"):
1162 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1163 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1164 # "_id.ne": nsir["_id"]}
1165 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1166 # if nsi: # last one using nsr
1167 # continue
1168 # try:
1169 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1170 # except (DbException, EngineException) as e:
1171 # if e.http_code == HTTPStatus.NOT_FOUND:
1172 # pass
1173 # else:
1174 # raise
1175 # # deletes NetSlice instance object
1176 # v = self.db.del_one("nsis", {"_id": _id})
1177 #
1178 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1179 # _filter = {"netsliceInstanceId": _id}
1180 # self.db.del_list("nsilcmops", _filter)
1181 #
1182 # # Search if nst is being used by other nsi
1183 # nsir_admin = nsir.get("_admin")
1184 # if nsir_admin:
1185 # if nsir_admin.get("nst-id"):
1186 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1187 # fail_on_empty=False, fail_on_more=False)
1188 # if not nsis_list:
1189 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1190 # return v
1191
1192 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1193 """
1194 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1195 :param rollback: list to append the created items at database in case a rollback must be done
1196 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1197 :param indata: params to be used for the nsir
1198 :param kwargs: used to override the indata descriptor
1199 :param headers: http request headers
1200 :return: the _id of nsi descriptor created at database
1201 """
1202
1203 try:
1204 step = "checking quotas"
1205 self.check_quota(session)
1206
1207 step = ""
1208 slice_request = self._remove_envelop(indata)
1209 # Override descriptor with query string kwargs
1210 self._update_input_with_kwargs(slice_request, kwargs)
1211 self._validate_input_new(slice_request, session["force"])
1212
1213 # look for nstd
1214 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
1215 _filter = self._get_project_filter(session)
1216 _filter["_id"] = slice_request["nstId"]
1217 nstd = self.db.get_one("nsts", _filter)
1218 del _filter["_id"]
1219
1220 nstd.pop("_admin", None)
1221 nstd_id = nstd.pop("_id", None)
1222 nsi_id = str(uuid4())
1223 step = "filling nsi_descriptor with input data"
1224
1225 # Creating the NSIR
1226 nsi_descriptor = {
1227 "id": nsi_id,
1228 "name": slice_request["nsiName"],
1229 "description": slice_request.get("nsiDescription", ""),
1230 "datacenter": slice_request["vimAccountId"],
1231 "nst-ref": nstd["id"],
1232 "instantiation_parameters": slice_request,
1233 "network-slice-template": nstd,
1234 "nsr-ref-list": [],
1235 "vlr-list": [],
1236 "_id": nsi_id,
1237 "additionalParamsForNsi": self._format_addional_params(slice_request)
1238 }
1239
1240 step = "creating nsi at database"
1241 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
1242 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1243 nsi_descriptor["_admin"]["netslice-subnet"] = None
1244 nsi_descriptor["_admin"]["deployed"] = {}
1245 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1246 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1247
1248 # Creating netslice-vld for the RO.
1249 step = "creating netslice-vld at database"
1250
1251 # Building the vlds list to be deployed
1252 # From netslice descriptors, creating the initial list
1253 nsi_vlds = []
1254
1255 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1256 # Getting template Instantiation parameters from NST
1257 nsi_vld = deepcopy(netslice_vlds)
1258 nsi_vld["shared-nsrs-list"] = []
1259 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1260 nsi_vlds.append(nsi_vld)
1261
1262 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
1263 # Creating netslice-subnet_record.
1264 needed_nsds = {}
1265 services = []
1266
1267 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1268 for member_ns in nstd["netslice-subnet"]:
1269 nsd_id = member_ns["nsd-ref"]
1270 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1271 member_ns["nsd-ref"], member_ns["id"])
1272 if nsd_id not in needed_nsds:
1273 # Obtain nsd
1274 _filter["id"] = nsd_id
1275 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1276 del _filter["id"]
1277 nsd.pop("_admin")
1278 needed_nsds[nsd_id] = nsd
1279 else:
1280 nsd = needed_nsds[nsd_id]
1281 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1282 services.append(member_ns)
1283
1284 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1285 member_ns["nsd-ref"], member_ns["id"])
1286
1287 # creates Network Services records (NSRs)
1288 step = "creating nsrs at database using NsrTopic.new()"
1289 ns_params = slice_request.get("netslice-subnet")
1290 nsrs_list = []
1291 nsi_netslice_subnet = []
1292 for service in services:
1293 # Check if the netslice-subnet is shared and if it is share if the nss exists
1294 _id_nsr = None
1295 indata_ns = {}
1296 # Is the nss shared and instantiated?
1297 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1298 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
1299 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
1300 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1301 if nsi and service.get("is-shared-nss"):
1302 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1303 for nsrs_detailed_item in nsrs_detailed_list:
1304 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
1305 if nsrs_detailed_item["nss-id"] == service["id"]:
1306 _id_nsr = nsrs_detailed_item["nsrId"]
1307 break
1308 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1309 if netslice_subnet["nss-id"] == service["id"]:
1310 indata_ns = netslice_subnet
1311 break
1312 else:
1313 indata_ns = {}
1314 if service.get("instantiation-parameters"):
1315 indata_ns = deepcopy(service["instantiation-parameters"])
1316 # del service["instantiation-parameters"]
1317
1318 indata_ns["nsdId"] = service["_id"]
1319 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1320 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1321 indata_ns["nsDescription"] = service["description"]
1322 if slice_request.get("ssh_keys"):
1323 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
1324
1325 if ns_params:
1326 for ns_param in ns_params:
1327 if ns_param.get("id") == service["id"]:
1328 copy_ns_param = deepcopy(ns_param)
1329 del copy_ns_param["id"]
1330 indata_ns.update(copy_ns_param)
1331 break
1332
1333 # Creates Nsr objects
1334 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
1335 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
1336 "nss-id": service["id"], "nslcmop_instantiate": None}
1337 indata_ns["nss-id"] = service["id"]
1338 nsrs_list.append(nsrs_item)
1339 nsi_netslice_subnet.append(indata_ns)
1340 nsr_ref = {"nsr-ref": _id_nsr}
1341 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
1342
1343 # Adding the nsrs list to the nsi
1344 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
1345 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1346 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1347
1348 # Creating the entry in the database
1349 self.db.create("nsis", nsi_descriptor)
1350 rollback.append({"topic": "nsis", "_id": nsi_id})
1351 return nsi_id, None
1352 except Exception as e: # TODO remove try Except, it is captured at nbi.py
1353 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1354 raise EngineException("Error {}: {}".format(step, e))
1355 except ValidationError as e:
1356 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1357
1358 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1359 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1360
1361
1362 class NsiLcmOpTopic(BaseTopic):
1363 topic = "nsilcmops"
1364 topic_msg = "nsi"
1365 operation_schema = { # mapping between operation and jsonschema to validate
1366 "instantiate": nsi_instantiate,
1367 "terminate": None
1368 }
1369
1370 def __init__(self, db, fs, msg, auth):
1371 BaseTopic.__init__(self, db, fs, msg, auth)
1372 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
1373
1374 def _check_nsi_operation(self, session, nsir, operation, indata):
1375 """
1376 Check that user has enter right parameters for the operation
1377 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1378 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1379 :param indata: descriptor with the parameters of the operation
1380 :return: None
1381 """
1382 nsds = {}
1383 nstd = nsir["network-slice-template"]
1384
1385 def check_valid_netslice_subnet_id(nstId):
1386 # TODO change to vnfR (??)
1387 for netslice_subnet in nstd["netslice-subnet"]:
1388 if nstId == netslice_subnet["id"]:
1389 nsd_id = netslice_subnet["nsd-ref"]
1390 if nsd_id not in nsds:
1391 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1392 return nsds[nsd_id]
1393 else:
1394 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1395 "nst:netslice-subnet".format(nstId))
1396 if operation == "instantiate":
1397 # check the existance of netslice-subnet items
1398 for in_nst in get_iterable(indata.get("netslice-subnet")):
1399 check_valid_netslice_subnet_id(in_nst["id"])
1400
1401 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1402 now = time()
1403 _id = str(uuid4())
1404 nsilcmop = {
1405 "id": _id,
1406 "_id": _id,
1407 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1408 "statusEnteredTime": now,
1409 "netsliceInstanceId": netsliceInstanceId,
1410 "lcmOperationType": operation,
1411 "startTime": now,
1412 "isAutomaticInvocation": False,
1413 "operationParams": params,
1414 "isCancelPending": False,
1415 "links": {
1416 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
1417 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
1418 }
1419 }
1420 return nsilcmop
1421
1422 def add_shared_nsr_2vld(self, nsir, nsr_item):
1423 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1424 if nst_sb_item.get("is-shared-nss"):
1425 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1426 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1427 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1428 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1429 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1430 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1431 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1432 break
1433 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1434 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1435
1436 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1437 """
1438 Performs a new operation over a ns
1439 :param rollback: list to append created items at database in case a rollback must to be done
1440 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1441 :param indata: descriptor with the parameters of the operation. It must contains among others
1442 netsliceInstanceId: _id of the nsir to perform the operation
1443 operation: it can be: instantiate, terminate, action, TODO: update, heal
1444 :param kwargs: used to override the indata descriptor
1445 :param headers: http request headers
1446 :return: id of the nslcmops
1447 """
1448 try:
1449 # Override descriptor with query string kwargs
1450 self._update_input_with_kwargs(indata, kwargs)
1451 operation = indata["lcmOperationType"]
1452 netsliceInstanceId = indata["netsliceInstanceId"]
1453 validate_input(indata, self.operation_schema[operation])
1454
1455 # get nsi from netsliceInstanceId
1456 _filter = self._get_project_filter(session)
1457 _filter["_id"] = netsliceInstanceId
1458 nsir = self.db.get_one("nsis", _filter)
1459 del _filter["_id"]
1460
1461 # initial checking
1462 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1463 if operation == "terminate" and indata.get("autoremove"):
1464 # NSIR must be deleted
1465 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1466 if operation != "instantiate":
1467 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1468 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
1469 else:
1470 if operation == "instantiate" and not session["force"]:
1471 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1472 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
1473
1474 # Creating all the NS_operation (nslcmop)
1475 # Get service list from db
1476 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1477 nslcmops = []
1478 # nslcmops_item = None
1479 for index, nsr_item in enumerate(nsrs_list):
1480 nsi = None
1481 if nsr_item.get("shared"):
1482 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1483 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1484 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1485 _filter["_id.ne"] = netsliceInstanceId
1486 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1487 if operation == "terminate":
1488 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1489 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1490
1491 # looks the first nsi fulfilling the conditions but not being the current NSIR
1492 if nsi:
1493 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1494 for nsi_nsr_item in nsi_admin_shared:
1495 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1496 self.add_shared_nsr_2vld(nsir, nsr_item)
1497 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1498 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1499 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1500 break
1501 # continue to not create nslcmop since nsrs is shared and nsrs was created
1502 continue
1503 else:
1504 self.add_shared_nsr_2vld(nsir, nsr_item)
1505
1506 try:
1507 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1508 indata_ns = {}
1509 indata_ns = service["instantiate_params"]
1510 indata_ns["lcmOperationType"] = operation
1511 indata_ns["nsInstanceId"] = service["_id"]
1512 # Including netslice_id in the ns instantiate Operation
1513 indata_ns["netsliceInstanceId"] = netsliceInstanceId
1514 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1515 # message via kafka bus
1516 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
1517 slice_object=True)
1518 nslcmops.append(nslcmop)
1519 if operation == "terminate":
1520 nslcmop = None
1521 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1522 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1523 except (DbException, EngineException) as e:
1524 if e.http_code == HTTPStatus.NOT_FOUND:
1525 self.logger.info("HTTPStatus.NOT_FOUND")
1526 pass
1527 else:
1528 raise
1529
1530 # Creates nsilcmop
1531 indata["nslcmops_ids"] = nslcmops
1532 self._check_nsi_operation(session, nsir, operation, indata)
1533
1534 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
1535 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
1536 _id = self.db.create("nsilcmops", nsilcmop_desc)
1537 rollback.append({"topic": "nsilcmops", "_id": _id})
1538 self.msg.write("nsi", operation, nsilcmop_desc)
1539 return _id, None
1540 except ValidationError as e:
1541 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1542
1543 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1544 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1545
1546 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1547 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)