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