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