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