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