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