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