Feature 10239: Distributed VCA
[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, increment_ip_mac
24 from yaml import safe_dump
25 from osm_common.dbbase import DbException
26 from osm_common.msgbase import MsgException
27 from osm_common.fsbase import FsException
28 from osm_nbi import utils
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 # delete extra ro_nsrs used for internal RO module
118 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
119
120 @staticmethod
121 def _format_ns_request(ns_request):
122 formated_request = copy(ns_request)
123 formated_request.pop("additionalParamsForNs", None)
124 formated_request.pop("additionalParamsForVnf", None)
125 return formated_request
126
127 @staticmethod
128 def _format_additional_params(ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None):
129 """
130 Get and format user additional params for NS or VNF
131 :param ns_request: User instantiation additional parameters
132 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
133 :param descriptor: If not None it check that needed parameters of descriptor are supplied
134 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
135 """
136 additional_params = None
137 other_params = None
138 if not member_vnf_index:
139 additional_params = copy(ns_request.get("additionalParamsForNs"))
140 where_ = "additionalParamsForNs"
141 elif ns_request.get("additionalParamsForVnf"):
142 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index)
143 item = next((x for x in ns_request["additionalParamsForVnf"] if x["member-vnf-index"] == member_vnf_index),
144 None)
145 if item:
146 if not vdu_id and not kdu_name:
147 other_params = item
148 additional_params = copy(item.get("additionalParams")) or {}
149 if vdu_id and item.get("additionalParamsForVdu"):
150 item_vdu = next((x for x in item["additionalParamsForVdu"] if x["vdu_id"] == vdu_id), None)
151 other_params = item_vdu
152 if item_vdu and item_vdu.get("additionalParams"):
153 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
154 additional_params = item_vdu["additionalParams"]
155 if kdu_name:
156 additional_params = {}
157 if item.get("additionalParamsForKdu"):
158 item_kdu = next((x for x in item["additionalParamsForKdu"] if x["kdu_name"] == kdu_name), None)
159 other_params = item_kdu
160 if item_kdu and item_kdu.get("additionalParams"):
161 where_ += ".additionalParamsForKdu[kdu_name={}]".format(kdu_name)
162 additional_params = item_kdu["additionalParams"]
163
164 if additional_params:
165 for k, v in additional_params.items():
166 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
167 if not kdu_name and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k):
168 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
169 "and underscores, and cannot start with a digit"
170 .format(where_, k))
171 # END Check that additional parameter names are valid Jinja2 identifiers
172 if not isinstance(k, str):
173 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
174 if "." in k or "$" in k:
175 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
176 if isinstance(v, (dict, tuple, list)):
177 additional_params[k] = "!!yaml " + safe_dump(v)
178
179 if descriptor:
180 for df in descriptor.get("df", []):
181 # check that enough parameters are supplied for the initial-config-primitive
182 # TODO: check for cloud-init
183 if member_vnf_index:
184 initial_primitives = []
185 if "lcm-operations-configuration" in df \
186 and "operate-vnf-op-config" in df["lcm-operations-configuration"]:
187 for config in df["lcm-operations-configuration"]["operate-vnf-op-config"].get("day1-2", []):
188 for primitive in get_iterable(config.get("initial-config-primitive")):
189 initial_primitives.append(primitive)
190 else:
191 initial_primitives = deep_get(descriptor, ("ns-configuration", "initial-config-primitive"))
192
193 for initial_primitive in get_iterable(initial_primitives):
194 for param in get_iterable(initial_primitive.get("parameter")):
195 if param["value"].startswith("<") and param["value"].endswith(">"):
196 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
197 continue
198 if not additional_params or param["value"][1:-1] not in additional_params:
199 raise EngineException("Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
200 "initial-config-primitive[name={}] not supplied".
201 format(param["value"], descriptor["id"],
202 initial_primitive["name"]))
203
204 return additional_params or None, other_params or None
205
206 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
207 """
208 Creates a new nsr into database. It also creates needed vnfrs
209 :param rollback: list to append the created items at database in case a rollback must be done
210 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
211 :param indata: params to be used for the nsr
212 :param kwargs: used to override the indata descriptor
213 :param headers: http request headers
214 :return: the _id of nsr descriptor created at database. Or an exception of type
215 EngineException, ValidationError, DbException, FsException, MsgException.
216 Note: Exceptions are not captured on purpose. They should be captured at called
217 """
218 try:
219 step = "checking quotas"
220 self.check_quota(session)
221
222 step = "validating input parameters"
223 ns_request = self._remove_envelop(indata)
224 self._update_input_with_kwargs(ns_request, kwargs)
225 ns_request = self._validate_input_new(ns_request, session["force"])
226
227 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
228 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
229 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
230
231 step = "checking nsdOperationalState"
232 self._check_nsd_operational_state(nsd, ns_request)
233
234 step = "filling nsr from input data"
235 nsr_id = str(uuid4())
236 nsr_descriptor = self._create_nsr_descriptor_from_nsd(nsd, ns_request, nsr_id, session)
237
238 # Create VNFRs
239 needed_vnfds = {}
240 # TODO: Change for multiple df support
241 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
242 for vnfp in vnf_profiles:
243 vnfd_id = vnfp.get("vnfd-id")
244 vnf_index = vnfp.get("id")
245 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(vnfd_id, vnf_index)
246 if vnfd_id not in needed_vnfds:
247 vnfd = self._get_vnfd_from_db(vnfd_id, session)
248 needed_vnfds[vnfd_id] = vnfd
249 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
250 else:
251 vnfd = needed_vnfds[vnfd_id]
252
253 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(vnfd_id, vnf_index)
254 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(nsd, vnfd, vnfd_id, vnf_index, nsr_descriptor,
255 ns_request, ns_k8s_namespace)
256
257 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(vnfd_id, vnf_index)
258 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
259 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
260
261 step = "creating nsr at database"
262 self._add_nsr_to_db(nsr_descriptor, rollback, session)
263
264 step = "creating nsr temporal folder"
265 self.fs.mkdir(nsr_id)
266
267 return nsr_id, None
268 except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
269 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
270
271 def _get_nsd_from_db(self, nsd_id, session):
272 _filter = self._get_project_filter(session)
273 _filter["_id"] = nsd_id
274 return self.db.get_one("nsds", _filter)
275
276 def _get_vnfd_from_db(self, vnfd_id, session):
277 _filter = self._get_project_filter(session)
278 _filter["id"] = vnfd_id
279 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
280 vnfd.pop("_admin")
281 return vnfd
282
283 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
284 self.format_on_new(nsr_descriptor, session["project_id"], make_public=session["public"])
285 self.db.create("nsrs", nsr_descriptor)
286 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
287
288 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
289 self.format_on_new(vnfr_descriptor, session["project_id"], make_public=session["public"])
290 self.db.create("vnfrs", vnfr_descriptor)
291 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
292
293 def _check_nsd_operational_state(self, nsd, ns_request):
294 if nsd["_admin"]["operationalState"] == "DISABLED":
295 raise EngineException("nsd with id '{}' is DISABLED, and thus cannot be used to create "
296 "a network service".format(ns_request["nsdId"]), http_code=HTTPStatus.CONFLICT)
297
298 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
299 additional_params, _ = self._format_additional_params(ns_request, descriptor=nsd)
300 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
301 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
302 if ns_request and ns_request.get("k8s-namespace"):
303 ns_k8s_namespace = ns_request["k8s-namespace"]
304 if additional_params and additional_params.get("k8s-namespace"):
305 ns_k8s_namespace = additional_params["k8s-namespace"]
306
307 return ns_k8s_namespace
308
309 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
310 now = time()
311 additional_params, _ = self._format_additional_params(ns_request, descriptor=nsd)
312
313 nsr_descriptor = {
314 "name": ns_request["nsName"],
315 "name-ref": ns_request["nsName"],
316 "short-name": ns_request["nsName"],
317 "admin-status": "ENABLED",
318 "nsState": "NOT_INSTANTIATED",
319 "currentOperation": "IDLE",
320 "currentOperationID": None,
321 "errorDescription": None,
322 "errorDetail": None,
323 "deploymentStatus": None,
324 "configurationStatus": None,
325 "vcaStatus": None,
326 "nsd": {k: v for k, v in nsd.items()},
327 "datacenter": ns_request["vimAccountId"],
328 "resource-orchestrator": "osmopenmano",
329 "description": ns_request.get("nsDescription", ""),
330 "constituent-vnfr-ref": [],
331 "operational-status": "init", # typedef ns-operational-
332 "config-status": "init", # typedef config-states
333 "detailed-status": "scheduled",
334 "orchestration-progress": {},
335 "create-time": now,
336 "nsd-name-ref": nsd["name"],
337 "operational-events": [], # "id", "timestamp", "description", "event",
338 "nsd-ref": nsd["id"],
339 "nsd-id": nsd["_id"],
340 "vnfd-id": [],
341 "instantiate_params": self._format_ns_request(ns_request),
342 "additionalParamsForNs": additional_params,
343 "ns-instance-config-ref": nsr_id,
344 "id": nsr_id,
345 "_id": nsr_id,
346 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
347 "flavor": [],
348 "image": [],
349 }
350 ns_request["nsr_id"] = nsr_id
351 if ns_request and ns_request.get("config-units"):
352 nsr_descriptor["config-units"] = ns_request["config-units"]
353
354 # Create vld
355 if nsd.get("virtual-link-desc"):
356 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
357 # Fill each vld with vnfd-connection-point-ref data
358 # TODO: Change for multiple df support
359 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
360 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
361 for vnf_profile in vnf_profiles:
362 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
363 for cpd in vlc.get("constituent-cpd-id", ()):
364 all_vld_connection_point_data[vlc.get("virtual-link-profile-id")].append({
365 "member-vnf-index-ref": cpd.get("constituent-base-element-id"),
366 "vnfd-connection-point-ref": cpd.get("constituent-cpd-id"),
367 "vnfd-id-ref": vnf_profile.get("vnfd-id")
368 })
369
370 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
371
372 for vdu in vnfd.get("vdu", ()):
373 flavor_data = {}
374 guest_epa = {}
375 # Find this vdu compute and storage descriptors
376 vdu_virtual_compute = {}
377 vdu_virtual_storage = {}
378 for vcd in vnfd.get("virtual-compute-desc", ()):
379 if vcd.get("id") == vdu.get("virtual-compute-desc"):
380 vdu_virtual_compute = vcd
381 for vsd in vnfd.get("virtual-storage-desc", ()):
382 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
383 vdu_virtual_storage = vsd
384 # Get this vdu vcpus, memory and storage info for flavor_data
385 if vdu_virtual_compute.get("virtual-cpu", {}).get("num-virtual-cpu"):
386 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"]["num-virtual-cpu"]
387 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
388 flavor_data["memory-mb"] = float(vdu_virtual_compute["virtual-memory"]["size"]) * 1024.0
389 if vdu_virtual_storage.get("size-of-storage"):
390 flavor_data["storage-gb"] = vdu_virtual_storage["size-of-storage"]
391 # Get this vdu EPA info for guest_epa
392 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
393 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"]["cpu-quota"]
394 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
395 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
396 if vcpu_pinning.get("thread-policy"):
397 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning["thread-policy"]
398 if vcpu_pinning.get("policy"):
399 cpu_policy = "SHARED" if vcpu_pinning["policy"] == "dynamic" else "DEDICATED"
400 guest_epa["cpu-pinning-policy"] = cpu_policy
401 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
402 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"]["mem-quota"]
403 if vdu_virtual_compute.get("virtual-memory", {}).get("mempage-size"):
404 guest_epa["mempage-size"] = vdu_virtual_compute["virtual-memory"]["mempage-size"]
405 if vdu_virtual_compute.get("virtual-memory", {}).get("numa-node-policy"):
406 guest_epa["numa-node-policy"] = vdu_virtual_compute["virtual-memory"]["numa-node-policy"]
407 if vdu_virtual_storage.get("disk-io-quota"):
408 guest_epa["disk-io-quota"] = vdu_virtual_storage["disk-io-quota"]
409
410 if guest_epa:
411 flavor_data["guest-epa"] = guest_epa
412
413 flavor_data["name"] = vdu["id"][:56] + "-flv"
414 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
415 nsr_descriptor["flavor"].append(flavor_data)
416
417 sw_image_id = vdu.get("sw-image-desc")
418 if sw_image_id:
419 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
420 self._add_image_to_nsr(nsr_descriptor, image_data)
421
422 # also add alternative images to the list of images
423 for alt_image in vdu.get("alternative-sw-image-desc", ()):
424 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
425 self._add_image_to_nsr(nsr_descriptor, image_data)
426
427 for vld in nsr_vld:
428 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(vld.get("id"), [])
429 vld["name"] = vld["id"]
430 nsr_descriptor["vld"] = nsr_vld
431
432 return nsr_descriptor
433
434 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
435 sw_image_desc = utils.find_in_list(vnfd.get("sw-image-desc", ()),
436 lambda sw: sw["id"] == sw_image_id)
437 image_data = {}
438 if sw_image_desc.get("image"):
439 image_data["image"] = sw_image_desc["image"]
440 if sw_image_desc.get("checksum"):
441 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
442 if sw_image_desc.get("vim-type"):
443 image_data["vim-type"] = sw_image_desc["vim-type"]
444 return image_data
445
446 def _add_image_to_nsr(self, nsr_descriptor, image_data):
447 """
448 Adds image to nsr checking first it is not already added
449 """
450 img = next((f for f in nsr_descriptor["image"] if
451 all(f.get(k) == image_data[k] for k in image_data)), None)
452 if not img:
453 image_data["id"] = str(len(nsr_descriptor["image"]))
454 nsr_descriptor["image"].append(image_data)
455
456 def _create_vnfr_descriptor_from_vnfd(self, nsd, vnfd, vnfd_id, vnf_index, nsr_descriptor,
457 ns_request, ns_k8s_namespace):
458 vnfr_id = str(uuid4())
459 nsr_id = nsr_descriptor["id"]
460 now = time()
461 additional_params, vnf_params = self._format_additional_params(ns_request, vnf_index, descriptor=vnfd)
462
463 vnfr_descriptor = {
464 "id": vnfr_id,
465 "_id": vnfr_id,
466 "nsr-id-ref": nsr_id,
467 "member-vnf-index-ref": vnf_index,
468 "additionalParamsForVnf": additional_params,
469 "created-time": now,
470 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
471 "vnfd-ref": vnfd_id,
472 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
473 "vim-account-id": None,
474 "vca-id": None,
475 "vdur": [],
476 "connection-point": [],
477 "ip-address": None, # mgmt-interface filled by LCM
478 }
479 vnf_k8s_namespace = ns_k8s_namespace
480 if vnf_params:
481 if vnf_params.get("k8s-namespace"):
482 vnf_k8s_namespace = vnf_params["k8s-namespace"]
483 if vnf_params.get("config-units"):
484 vnfr_descriptor["config-units"] = vnf_params["config-units"]
485
486 # Create vld
487 if vnfd.get("int-virtual-link-desc"):
488 vnfr_descriptor["vld"] = []
489 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
490 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
491
492 for cp in vnfd.get("ext-cpd", ()):
493 vnf_cp = {
494 "name": cp.get("id"),
495 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
496 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
497 "id": cp.get("id"),
498 # "ip-address", "mac-address" # filled by LCM
499 # vim-id # TODO it would be nice having a vim port id
500 }
501 vnfr_descriptor["connection-point"].append(vnf_cp)
502
503 # Create k8s-cluster information
504 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
505 if vnfd.get("k8s-cluster"):
506 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
507 all_k8s_cluster_nets_cpds = {}
508 for cpd in get_iterable(vnfd.get("ext-cpd")):
509 if cpd.get("k8s-cluster-net"):
510 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get("id")
511 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
512 if net.get("id") in all_k8s_cluster_nets_cpds:
513 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[net.get("id")]
514
515 # update kdus
516 for kdu in get_iterable(vnfd.get("kdu")):
517 additional_params, kdu_params = self._format_additional_params(ns_request,
518 vnf_index,
519 kdu_name=kdu["name"],
520 descriptor=vnfd)
521 kdu_k8s_namespace = vnf_k8s_namespace
522 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
523 if kdu_params and kdu_params.get("k8s-namespace"):
524 kdu_k8s_namespace = kdu_params["k8s-namespace"]
525
526 kdur = {
527 "additionalParams": additional_params,
528 "k8s-namespace": kdu_k8s_namespace,
529 "kdu-name": kdu["name"],
530 # TODO "name": "" Name of the VDU in the VIM
531 "ip-address": None, # mgmt-interface filled by LCM
532 "k8s-cluster": {},
533 }
534 if kdu_params and kdu_params.get("config-units"):
535 kdur["config-units"] = kdu_params["config-units"]
536 if kdu.get("helm-version"):
537 kdur["helm-version"] = kdu["helm-version"]
538 for k8s_type in ("helm-chart", "juju-bundle"):
539 if kdu.get(k8s_type):
540 kdur[k8s_type] = kdu_model or kdu[k8s_type]
541 if not vnfr_descriptor.get("kdur"):
542 vnfr_descriptor["kdur"] = []
543 vnfr_descriptor["kdur"].append(kdur)
544
545 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
546
547 for vdu in vnfd.get("vdu", ()):
548 vdu_mgmt_cp = []
549 try:
550 configs = vnfd.get("df")[0]["lcm-operations-configuration"]["operate-vnf-op-config"]["day1-2"]
551 vdu_config = utils.find_in_list(configs, lambda config: config["id"] == vdu["id"])
552 except Exception:
553 vdu_config = None
554
555 try:
556 vdu_instantiation_level = utils.find_in_list(
557 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
558 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"]
559 )
560 except Exception:
561 vdu_instantiation_level = None
562
563 if vdu_config:
564 external_connection_ee = utils.filter_in_list(
565 vdu_config.get("execution-environment-list", []),
566 lambda ee: "external-connection-point-ref" in ee
567 )
568 for ee in external_connection_ee:
569 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
570
571 additional_params, vdu_params = self._format_additional_params(
572 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd)
573 vdur = {
574 "vdu-id-ref": vdu["id"],
575 # TODO "name": "" Name of the VDU in the VIM
576 "ip-address": None, # mgmt-interface filled by LCM
577 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
578 "internal-connection-point": [],
579 "interfaces": [],
580 "additionalParams": additional_params,
581 "vdu-name": vdu["name"]
582 }
583 if vdu_params and vdu_params.get("config-units"):
584 vdur["config-units"] = vdu_params["config-units"]
585 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
586 vdur["boot-data-drive"] = vdu["supplemental-boot-data"]["boot-data-drive"]
587 if vdu.get("pdu-type"):
588 vdur["pdu-type"] = vdu["pdu-type"]
589 vdur["name"] = vdu["pdu-type"]
590 # TODO volumes: name, volume-id
591 for icp in vdu.get("int-cpd", ()):
592 vdu_icp = {
593 "id": icp["id"],
594 "connection-point-id": icp["id"],
595 "name": icp.get("id"),
596 }
597
598 vdur["internal-connection-point"].append(vdu_icp)
599
600 for iface in icp.get("virtual-network-interface-requirement", ()):
601 iface_fields = ("name", "mac-address")
602 vdu_iface = {x: iface[x] for x in iface_fields if iface.get(x) is not None}
603
604 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
605 if "port-security-enabled" in icp:
606 vdu_iface["port-security-enabled"] = icp["port-security-enabled"]
607
608 if "port-security-disable-strategy" in icp:
609 vdu_iface["port-security-disable-strategy"] = icp["port-security-disable-strategy"]
610
611 for ext_cp in vnfd.get("ext-cpd", ()):
612 if not ext_cp.get("int-cpd"):
613 continue
614 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
615 continue
616 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
617 vdu_iface["external-connection-point-ref"] = ext_cp.get("id")
618
619 if "port-security-enabled" in ext_cp:
620 vdu_iface["port-security-enabled"] = (
621 ext_cp["port-security-enabled"]
622 )
623
624 if "port-security-disable-strategy" in ext_cp:
625 vdu_iface["port-security-disable-strategy"] = (
626 ext_cp["port-security-disable-strategy"]
627 )
628
629 break
630
631 if vnfd_mgmt_cp and vdu_iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
632 vdu_iface["mgmt-vnf"] = True
633 vdu_iface["mgmt-interface"] = True
634
635 for ecp in vdu_mgmt_cp:
636 if vdu_iface.get("external-connection-point-ref") == ecp:
637 vdu_iface["mgmt-interface"] = True
638
639 if iface.get("virtual-interface"):
640 vdu_iface.update(deepcopy(iface["virtual-interface"]))
641
642 # look for network where this interface is connected
643 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
644 if iface_ext_cp:
645 # TODO: Change for multiple df support
646 for df in get_iterable(nsd.get("df")):
647 for vnf_profile in get_iterable(df.get("vnf-profile")):
648 for vlc_index, vlc in \
649 enumerate(get_iterable(vnf_profile.get("virtual-link-connectivity"))):
650 for cpd in get_iterable(vlc.get("constituent-cpd-id")):
651 if cpd.get("constituent-cpd-id") == iface_ext_cp:
652 vdu_iface["ns-vld-id"] = vlc.get("virtual-link-profile-id")
653 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
654 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
655 nsr_descriptor["vld"][vlc_index]["pci-interfaces"] = True
656 break
657 elif vdu_iface.get("internal-connection-point-ref"):
658 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
659 # TODO: store fixed IP address in the record (if it exists in the ICP)
660 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
661 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
662 ivld_index = utils.find_index_in_list(vnfd.get("int-virtual-link-desc", ()),
663 lambda ivld:
664 ivld["id"] == icp.get("int-virtual-link-desc")
665 )
666 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
667
668 vdur["interfaces"].append(vdu_iface)
669
670 if vdu.get("sw-image-desc"):
671 sw_image = utils.find_in_list(
672 vnfd.get("sw-image-desc", ()),
673 lambda image: image["id"] == vdu.get("sw-image-desc"))
674 nsr_sw_image_data = utils.find_in_list(
675 nsr_descriptor["image"],
676 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image"))
677 )
678 vdur["ns-image-id"] = nsr_sw_image_data["id"]
679
680 if vdu.get("alternative-sw-image-desc"):
681 alt_image_ids = []
682 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
683 sw_image = utils.find_in_list(
684 vnfd.get("sw-image-desc", ()),
685 lambda image: image["id"] == alt_image_id)
686 nsr_sw_image_data = utils.find_in_list(
687 nsr_descriptor["image"],
688 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image"))
689 )
690 alt_image_ids.append(nsr_sw_image_data["id"])
691 vdur["alt-image-ids"] = alt_image_ids
692
693 flavor_data_name = vdu["id"][:56] + "-flv"
694 nsr_flavor_desc = utils.find_in_list(
695 nsr_descriptor["flavor"],
696 lambda flavor: flavor["name"] == flavor_data_name)
697
698 if nsr_flavor_desc:
699 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
700
701 if vdu_instantiation_level:
702 count = vdu_instantiation_level.get("number-of-instances")
703 else:
704 count = 1
705
706 for index in range(0, count):
707 vdur = deepcopy(vdur)
708 for iface in vdur["interfaces"]:
709 if iface.get("ip-address"):
710 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
711 if iface.get("mac-address"):
712 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
713
714 vdur["_id"] = str(uuid4())
715 vdur["id"] = vdur["_id"]
716 vdur["count-index"] = index
717 vnfr_descriptor["vdur"].append(vdur)
718
719 return vnfr_descriptor
720
721 def edit(self, session, _id, indata=None, kwargs=None, content=None):
722 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
723
724
725 class VnfrTopic(BaseTopic):
726 topic = "vnfrs"
727 topic_msg = None
728
729 def __init__(self, db, fs, msg, auth):
730 BaseTopic.__init__(self, db, fs, msg, auth)
731
732 def delete(self, session, _id, dry_run=False, not_send_msg=None):
733 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
734
735 def edit(self, session, _id, indata=None, kwargs=None, content=None):
736 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
737
738 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
739 # Not used because vnfrs are created and deleted by NsrTopic class directly
740 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
741
742
743 class NsLcmOpTopic(BaseTopic):
744 topic = "nslcmops"
745 topic_msg = "ns"
746 operation_schema = { # mapping between operation and jsonschema to validate
747 "instantiate": ns_instantiate,
748 "action": ns_action,
749 "scale": ns_scale,
750 "terminate": ns_terminate,
751 }
752
753 def __init__(self, db, fs, msg, auth):
754 BaseTopic.__init__(self, db, fs, msg, auth)
755
756 def _check_ns_operation(self, session, nsr, operation, indata):
757 """
758 Check that user has enter right parameters for the operation
759 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
760 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
761 :param indata: descriptor with the parameters of the operation
762 :return: None
763 """
764 if operation == "action":
765 self._check_action_ns_operation(indata, nsr)
766 elif operation == "scale":
767 self._check_scale_ns_operation(indata, nsr)
768 elif operation == "instantiate":
769 self._check_instantiate_ns_operation(indata, nsr, session)
770
771 def _check_action_ns_operation(self, indata, nsr):
772 nsd = nsr["nsd"]
773 # check vnf_member_index
774 if indata.get("vnf_member_index"):
775 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
776 if indata.get("member_vnf_index"):
777 vnfd = self._get_vnfd_from_vnf_member_index(indata["member_vnf_index"], nsr["_id"])
778 try:
779 configs = vnfd.get("df")[0]["lcm-operations-configuration"]["operate-vnf-op-config"]["day1-2"]
780 except Exception:
781 configs = []
782
783 if indata.get("vdu_id"):
784 self._check_valid_vdu(vnfd, indata["vdu_id"])
785 descriptor_configuration = utils.find_in_list(
786 configs,
787 lambda config: config["id"] == indata["vdu_id"]
788 )
789 elif indata.get("kdu_name"):
790 self._check_valid_kdu(vnfd, indata["kdu_name"])
791 descriptor_configuration = utils.find_in_list(
792 configs,
793 lambda config: config["id"] == indata.get("kdu_name")
794 )
795 else:
796 descriptor_configuration = utils.find_in_list(
797 configs,
798 lambda config: config["id"] == vnfd["id"]
799 )
800 if descriptor_configuration is not None:
801 descriptor_configuration = descriptor_configuration.get("config-primitive")
802 else: # use a NSD
803 descriptor_configuration = nsd.get("ns-configuration", {}).get("config-primitive")
804
805 # For k8s allows default primitives without validating the parameters
806 if indata.get("kdu_name") and indata["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
807 # TODO should be checked that rollback only can contains revsision_numbe????
808 if not indata.get("member_vnf_index"):
809 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
810 .format(indata["primitive"]))
811 return
812 # if not, check primitive
813 for config_primitive in get_iterable(descriptor_configuration):
814 if indata["primitive"] == config_primitive["name"]:
815 # check needed primitive_params are provided
816 if indata.get("primitive_params"):
817 in_primitive_params_copy = copy(indata["primitive_params"])
818 else:
819 in_primitive_params_copy = {}
820 for paramd in get_iterable(config_primitive.get("parameter")):
821 if paramd["name"] in in_primitive_params_copy:
822 del in_primitive_params_copy[paramd["name"]]
823 elif not paramd.get("default-value"):
824 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
825 paramd["name"], indata["primitive"]))
826 # check no extra primitive params are provided
827 if in_primitive_params_copy:
828 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
829 list(in_primitive_params_copy.keys()), indata["primitive"]))
830 break
831 else:
832 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata["primitive"]))
833
834 def _check_scale_ns_operation(self, indata, nsr):
835 vnfd = self._get_vnfd_from_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"],
836 nsr["_id"])
837 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
838 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_aspect["id"]:
839 break
840 else:
841 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
842 "present at vnfd:scaling-aspect"
843 .format(indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
844
845 def _check_instantiate_ns_operation(self, indata, nsr, session):
846 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
847 vim_accounts = []
848 wim_accounts = []
849 nsd = nsr["nsd"]
850 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
851 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
852 for in_vnf in get_iterable(indata.get("vnf")):
853 member_vnf_index = in_vnf["member-vnf-index"]
854 if vnf_member_index_to_vnfd.get(member_vnf_index):
855 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
856 else:
857 vnfd = self._get_vnfd_from_vnf_member_index(member_vnf_index, nsr["_id"])
858 vnf_member_index_to_vnfd[member_vnf_index] = vnfd # add to cache, avoiding a later look for
859 self._check_vnf_instantiation_params(in_vnf, vnfd)
860 if in_vnf.get("vimAccountId"):
861 self._check_valid_vim_account(in_vnf["vimAccountId"], vim_accounts, session)
862
863 for in_vld in get_iterable(indata.get("vld")):
864 self._check_valid_wim_account(in_vld.get("wimAccountId"), wim_accounts, session)
865 for vldd in get_iterable(nsd.get("virtual-link-desc")):
866 if in_vld["name"] == vldd["id"]:
867 break
868 else:
869 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
870 in_vld["name"]))
871
872 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
873 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
874 vnfr = self.db.get_one("vnfrs",
875 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
876 fail_on_empty=False)
877 if not vnfr:
878 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
879 "nsd:constituent-vnfd".format(member_vnf_index))
880 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
881 if not vnfd:
882 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
883 format(vnfr["vnfd-id"]))
884 return vnfd
885
886 def _check_valid_vdu(self, vnfd, vdu_id):
887 for vdud in get_iterable(vnfd.get("vdu")):
888 if vdud["id"] == vdu_id:
889 return vdud
890 else:
891 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id))
892
893 def _check_valid_kdu(self, vnfd, kdu_name):
894 for kdud in get_iterable(vnfd.get("kdu")):
895 if kdud["name"] == kdu_name:
896 return kdud
897 else:
898 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name))
899
900 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
901 for in_vdu in get_iterable(in_vnf.get("vdu")):
902 for vdu in get_iterable(vnfd.get("vdu")):
903 if in_vdu["id"] == vdu["id"]:
904 for volume in get_iterable(in_vdu.get("volume")):
905 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
906 if volumed["id"] == volume["name"]:
907 break
908 else:
909 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
910 "volume:name='{}' is not present at "
911 "vnfd:vdu:virtual-storage-desc list".
912 format(in_vnf["member-vnf-index"], in_vdu["id"],
913 volume["id"]))
914
915 vdu_if_names = set()
916 for cpd in get_iterable(vdu.get("int-cpd")):
917 for iface in get_iterable(cpd.get("virtual-network-interface-requirement")):
918 vdu_if_names.add(iface.get("name"))
919
920 for in_iface in get_iterable(in_vdu["interface"]):
921 if in_iface["name"] in vdu_if_names:
922 break
923 else:
924 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
925 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd"
926 .format(in_vnf["member-vnf-index"], in_vdu["id"],
927 in_iface["name"]))
928 break
929
930 else:
931 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
932 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
933
934 vnfd_ivlds_cpds = {ivld.get("id"): set() for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))}
935 for vdu in get_iterable(vnfd.get("vdu")):
936 for cpd in get_iterable(vnfd.get("int-cpd")):
937 if cpd.get("int-virtual-link-desc"):
938 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
939
940 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
941 if in_ivld.get("name") in vnfd_ivlds_cpds:
942 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
943 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
944 break
945 else:
946 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
947 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
948 "vnfd:internal-vld:name/id:internal-connection-point"
949 .format(in_vnf["member-vnf-index"], in_ivld["name"],
950 in_icp["id-ref"]))
951 else:
952 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
953 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
954 in_ivld["name"], vnfd["id"]))
955
956 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
957 if vim_account in vim_accounts:
958 return
959 try:
960 db_filter = self._get_project_filter(session)
961 db_filter["_id"] = vim_account
962 self.db.get_one("vim_accounts", db_filter)
963 except Exception:
964 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
965 vim_accounts.append(vim_account)
966
967 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
968 if not isinstance(wim_account, str):
969 return
970 if wim_account in wim_accounts:
971 return
972 try:
973 db_filter = self._get_project_filter(session, write=False, show_all=True)
974 db_filter["_id"] = wim_account
975 self.db.get_one("wim_accounts", db_filter)
976 except Exception:
977 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account))
978 wim_accounts.append(wim_account)
979
980 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
981 """
982 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
983 (ip_address, ...) information.
984 Modifies PDU _admin.usageState to 'IN_USE'
985 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
986 :param rollback: list with the database modifications to rollback if needed
987 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
988 :param vim_account: vim_account where this vnfr should be deployed
989 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
990 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
991 of the changed vnfr is needed
992
993 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
994 "vim-network-name": used at VIM
995 "name": interface name
996 "vnf-vld-id": internal VNFD vld where this interface is connected, or
997 "ns-vld-id": NSD vld where this interface is connected.
998 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
999 """
1000
1001 ifaces_forcing_vim_network = []
1002 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1003 if not vdur.get("pdu-type"):
1004 continue
1005 pdu_type = vdur.get("pdu-type")
1006 pdu_filter = self._get_project_filter(session)
1007 pdu_filter["vim_accounts"] = vim_account
1008 pdu_filter["type"] = pdu_type
1009 pdu_filter["_admin.operationalState"] = "ENABLED"
1010 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
1011 # TODO feature 1417: "shared": True,
1012
1013 available_pdus = self.db.get_list("pdus", pdu_filter)
1014 for pdu in available_pdus:
1015 # step 1 check if this pdu contains needed interfaces:
1016 match_interfaces = True
1017 for vdur_interface in vdur["interfaces"]:
1018 for pdu_interface in pdu["interfaces"]:
1019 if pdu_interface["name"] == vdur_interface["name"]:
1020 # TODO feature 1417: match per mgmt type
1021 break
1022 else: # no interface found for name
1023 match_interfaces = False
1024 break
1025 if match_interfaces:
1026 break
1027 else:
1028 raise EngineException(
1029 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1030 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
1031
1032 # step 2. Update pdu
1033 rollback_pdu = {
1034 "_admin.usageState": pdu["_admin"]["usageState"],
1035 "_admin.usage.vnfr_id": None,
1036 "_admin.usage.nsr_id": None,
1037 "_admin.usage.vdur": None,
1038 }
1039 self.db.set_one("pdus", {"_id": pdu["_id"]},
1040 {"_admin.usageState": "IN_USE",
1041 "_admin.usage": {"vnfr_id": vnfr["_id"],
1042 "nsr_id": vnfr["nsr-id-ref"],
1043 "vdur": vdur["vdu-id-ref"]}
1044 })
1045 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
1046
1047 # step 3. Fill vnfr info by filling vdur
1048 vdu_text = "vdur.{}".format(vdur_index)
1049 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
1050 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1051 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1052 for pdu_interface in pdu["interfaces"]:
1053 if pdu_interface["name"] == vdur_interface["name"]:
1054 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1055 for k, v in pdu_interface.items():
1056 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
1057 vnfr_update[iface_text + ".{}".format(k)] = v
1058 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
1059 if pdu_interface.get("ip-address"):
1060 if vdur_interface.get("mgmt-interface") or vdur_interface.get("mgmt-vnf"):
1061 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
1062 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
1063 if vdur_interface.get("mgmt-vnf"):
1064 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
1065 vnfr_update["ip-address"] = pdu_interface["ip-address"]
1066 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
1067 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
1068 ifaces_forcing_vim_network.append({
1069 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
1070 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1071 "ns-vld-id": vdur_interface.get("ns-vld-id")})
1072 if pdu_interface.get("vim-network-id"):
1073 ifaces_forcing_vim_network[-1]["vim-network-id"] = pdu_interface["vim-network-id"]
1074 if pdu_interface.get("vim-network-name"):
1075 ifaces_forcing_vim_network[-1]["vim-network-name"] = pdu_interface["vim-network-name"]
1076 break
1077
1078 return ifaces_forcing_vim_network
1079
1080 def _look_for_k8scluster(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
1081 """
1082 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1083 Fills vnfr.kdur with the selected k8scluster
1084
1085 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1086 :param rollback: list with the database modifications to rollback if needed
1087 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1088 :param vim_account: vim_account where this vnfr should be deployed
1089 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1090 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1091 of the changed vnfr is needed
1092
1093 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1094 "vim-network-name": used at VIM
1095 "name": interface name
1096 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1097 "ns-vld-id": NSD vld where this interface is connected.
1098 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1099 """
1100
1101 ifaces_forcing_vim_network = []
1102 if not vnfr.get("kdur"):
1103 return ifaces_forcing_vim_network
1104
1105 kdu_filter = self._get_project_filter(session)
1106 kdu_filter["vim_account"] = vim_account
1107 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1108 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1109
1110 k8s_requirements = {} # just for logging
1111 for k8scluster in available_k8sclusters:
1112 if not vnfr.get("k8s-cluster"):
1113 break
1114 # restrict by cni
1115 if vnfr["k8s-cluster"].get("cni"):
1116 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
1117 if not set(vnfr["k8s-cluster"]["cni"]).intersection(k8scluster.get("cni", ())):
1118 continue
1119 # restrict by version
1120 if vnfr["k8s-cluster"].get("version"):
1121 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1122 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1123 continue
1124 # restrict by number of networks
1125 if vnfr["k8s-cluster"].get("nets"):
1126 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
1127 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(vnfr["k8s-cluster"]["nets"]):
1128 continue
1129 break
1130 else:
1131 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
1132 .format(k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]))
1133
1134 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
1135 # step 3. Fill vnfr info by filling kdur
1136 kdu_text = "kdur.{}.".format(kdur_index)
1137 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1138 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1139
1140 # step 4. Check VIM networks that forces the selected k8s_cluster
1141 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1142 k8scluster_net_list = list(k8scluster.get("nets").keys())
1143 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1144 # get a network from k8s_cluster nets. If name matches use this, if not use other
1145 if kdur_net["id"] in k8scluster_net_list: # name matches
1146 vim_net = k8scluster["nets"][kdur_net["id"]]
1147 k8scluster_net_list.remove(kdur_net["id"])
1148 else:
1149 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1150 k8scluster_net_list.pop(0)
1151 vnfr_update_rollback["k8s-cluster.nets.{}.vim_net".format(net_index)] = None
1152 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
1153 if vim_net and (kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")):
1154 ifaces_forcing_vim_network.append({
1155 "name": kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id"),
1156 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1157 "ns-vld-id": kdur_net.get("ns-vld-id"),
1158 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1159 })
1160 # TODO check that this forcing is not incompatible with other forcing
1161 return ifaces_forcing_vim_network
1162
1163 def _update_vnfrs(self, session, rollback, nsr, indata):
1164 # get vnfr
1165 nsr_id = nsr["_id"]
1166 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1167
1168 for vnfr in vnfrs:
1169 vnfr_update = {}
1170 vnfr_update_rollback = {}
1171 member_vnf_index = vnfr["member-vnf-index-ref"]
1172 # update vim-account-id
1173
1174 vim_account = indata["vimAccountId"]
1175 vca_id = indata.get("vcaId")
1176 # check instantiate parameters
1177 for vnf_inst_params in get_iterable(indata.get("vnf")):
1178 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1179 continue
1180 if vnf_inst_params.get("vimAccountId"):
1181 vim_account = vnf_inst_params.get("vimAccountId")
1182 if vnf_inst_params.get("vcaId"):
1183 vca_id = vnf_inst_params.get("vcaId")
1184
1185 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1186 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1187 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1188 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1189 continue
1190 for iface_inst_param in get_iterable(vdu_inst_param.get("interface")):
1191 iface_index, _ = next(i for i in enumerate(vdur["interfaces"])
1192 if i[1]["name"] == iface_inst_param["name"])
1193 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1194 if iface_inst_param.get("ip-address"):
1195 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1196 iface_inst_param.get("ip-address"), vdur.get("count-index", 0))
1197 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1198 if iface_inst_param.get("mac-address"):
1199 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1200 iface_inst_param.get("mac-address"), vdur.get("count-index", 0))
1201 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1202 if iface_inst_param.get("floating-ip-required"):
1203 vnfr_update[vnfr_update_text + ".floating-ip-required"] = True
1204 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1205 # TODO update vld with the ip-profile
1206 for ivld_inst_param in get_iterable(vnf_inst_params.get("internal-vld")):
1207 for icp_inst_param in get_iterable(ivld_inst_param.get("internal-connection-point")):
1208 # look for iface
1209 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1210 for iface_index, iface in enumerate(vdur["interfaces"]):
1211 if iface.get("internal-connection-point-ref") == icp_inst_param["id-ref"]:
1212 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1213 if icp_inst_param.get("ip-address"):
1214 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1215 icp_inst_param.get("ip-address"), vdur.get("count-index", 0))
1216 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1217 if icp_inst_param.get("mac-address"):
1218 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1219 icp_inst_param.get("mac-address"), vdur.get("count-index", 0))
1220 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1221 break
1222 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1223 for vld_inst_param in get_iterable(indata.get("vld")):
1224 for vnfcp_inst_param in get_iterable(vld_inst_param.get("vnfd-connection-point-ref")):
1225 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1226 continue
1227 # look for iface
1228 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1229 for iface_index, iface in enumerate(vdur["interfaces"]):
1230 if iface.get("external-connection-point-ref") == \
1231 vnfcp_inst_param["vnfd-connection-point-ref"]:
1232 vnfr_update_text = "vdur.{}.interfaces.{}".format(vdur_index, iface_index)
1233 if vnfcp_inst_param.get("ip-address"):
1234 vnfr_update[vnfr_update_text + ".ip-address"] = increment_ip_mac(
1235 vnfcp_inst_param.get("ip-address"), vdur.get("count-index", 0))
1236 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1237 if vnfcp_inst_param.get("mac-address"):
1238 vnfr_update[vnfr_update_text + ".mac-address"] = increment_ip_mac(
1239 vnfcp_inst_param.get("mac-address"), vdur.get("count-index", 0))
1240 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1241 break
1242
1243 vnfr_update["vim-account-id"] = vim_account
1244 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1245
1246 if vca_id:
1247 vnfr_update["vca-id"] = vca_id
1248 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1249
1250 # get pdu
1251 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
1252 vnfr_update_rollback)
1253
1254 # get kdus
1255 ifaces_forcing_vim_network += self._look_for_k8scluster(session, rollback, vnfr, vim_account, vnfr_update,
1256 vnfr_update_rollback)
1257 # update database vnfr
1258 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1259 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
1260
1261 # Update indada in case pdu forces to use a concrete vim-network-name
1262 # TODO check if user has already insert a vim-network-name and raises an error
1263 if not ifaces_forcing_vim_network:
1264 continue
1265 for iface_info in ifaces_forcing_vim_network:
1266 if iface_info.get("ns-vld-id"):
1267 if "vld" not in indata:
1268 indata["vld"] = []
1269 indata["vld"].append({key: iface_info[key] for key in
1270 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
1271
1272 elif iface_info.get("vnf-vld-id"):
1273 if "vnf" not in indata:
1274 indata["vnf"] = []
1275 indata["vnf"].append({
1276 "member-vnf-index": member_vnf_index,
1277 "internal-vld": [{key: iface_info[key] for key in
1278 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
1279 })
1280
1281 @staticmethod
1282 def _create_nslcmop(nsr_id, operation, params):
1283 """
1284 Creates a ns-lcm-opp content to be stored at database.
1285 :param nsr_id: internal id of the instance
1286 :param operation: instantiate, terminate, scale, action, ...
1287 :param params: user parameters for the operation
1288 :return: dictionary following SOL005 format
1289 """
1290 now = time()
1291 _id = str(uuid4())
1292 nslcmop = {
1293 "id": _id,
1294 "_id": _id,
1295 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1296 "queuePosition": None,
1297 "stage": None,
1298 "errorMessage": None,
1299 "detailedStatus": None,
1300 "statusEnteredTime": now,
1301 "nsInstanceId": nsr_id,
1302 "lcmOperationType": operation,
1303 "startTime": now,
1304 "isAutomaticInvocation": False,
1305 "operationParams": params,
1306 "isCancelPending": False,
1307 "links": {
1308 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
1309 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
1310 }
1311 }
1312 return nslcmop
1313
1314 def _get_enabled_vims(self, session):
1315 """
1316 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1317 :param session: current session with user information
1318 """
1319 db_filter = self._get_project_filter(session)
1320 db_filter["_admin.operationalState"] = "ENABLED"
1321 vims = self.db.get_list("vim_accounts", db_filter)
1322 vimAccounts = []
1323 for vim in vims:
1324 vimAccounts.append(vim['_id'])
1325 return vimAccounts
1326
1327 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
1328 """
1329 Performs a new operation over a ns
1330 :param rollback: list to append created items at database in case a rollback must to be done
1331 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1332 :param indata: descriptor with the parameters of the operation. It must contains among others
1333 nsInstanceId: _id of the nsr to perform the operation
1334 operation: it can be: instantiate, terminate, action, TODO: update, heal
1335 :param kwargs: used to override the indata descriptor
1336 :param headers: http request headers
1337 :return: id of the nslcmops
1338 """
1339 def check_if_nsr_is_not_slice_member(session, nsr_id):
1340 nsis = None
1341 db_filter = self._get_project_filter(session)
1342 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1343 nsis = self.db.get_one("nsis", db_filter, fail_on_empty=False, fail_on_more=False)
1344 if nsis:
1345 raise EngineException("The NS instance {} cannot be terminated because is used by the slice {}".format(
1346 nsr_id, nsis["_id"]), http_code=HTTPStatus.CONFLICT)
1347
1348 try:
1349 # Override descriptor with query string kwargs
1350 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
1351 operation = indata["lcmOperationType"]
1352 nsInstanceId = indata["nsInstanceId"]
1353
1354 validate_input(indata, self.operation_schema[operation])
1355 # get ns from nsr_id
1356 _filter = BaseTopic._get_project_filter(session)
1357 _filter["_id"] = nsInstanceId
1358 nsr = self.db.get_one("nsrs", _filter)
1359
1360 # initial checking
1361 if operation == "terminate" and slice_object is False:
1362 check_if_nsr_is_not_slice_member(session, nsr["_id"])
1363 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1364 if operation == "terminate" and indata.get("autoremove"):
1365 # NSR must be deleted
1366 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1367 if operation != "instantiate":
1368 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1369 nsInstanceId, operation), HTTPStatus.CONFLICT)
1370 else:
1371 if operation == "instantiate" and not session["force"]:
1372 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1373 nsInstanceId, operation), HTTPStatus.CONFLICT)
1374 self._check_ns_operation(session, nsr, operation, indata)
1375
1376 if operation == "instantiate":
1377 self._update_vnfrs(session, rollback, nsr, indata)
1378
1379 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
1380 _id = nslcmop_desc["_id"]
1381 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1382 if indata.get("placement-engine"):
1383 # Save valid vim accounts in lcm operation descriptor
1384 nslcmop_desc['operationParams']['validVimAccounts'] = self._get_enabled_vims(session)
1385 self.db.create("nslcmops", nslcmop_desc)
1386 rollback.append({"topic": "nslcmops", "_id": _id})
1387 if not slice_object:
1388 self.msg.write("ns", operation, nslcmop_desc)
1389 return _id, None
1390 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
1391 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1392 # except DbException as e:
1393 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1394
1395 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1396 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1397
1398 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1399 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1400
1401
1402 class NsiTopic(BaseTopic):
1403 topic = "nsis"
1404 topic_msg = "nsi"
1405 quota_name = "slice_instances"
1406
1407 def __init__(self, db, fs, msg, auth):
1408 BaseTopic.__init__(self, db, fs, msg, auth)
1409 self.nsrTopic = NsrTopic(db, fs, msg, auth)
1410
1411 @staticmethod
1412 def _format_ns_request(ns_request):
1413 formated_request = copy(ns_request)
1414 # TODO: Add request params
1415 return formated_request
1416
1417 @staticmethod
1418 def _format_addional_params(slice_request):
1419 """
1420 Get and format user additional params for NS or VNF
1421 :param slice_request: User instantiation additional parameters
1422 :return: a formatted copy of additional params or None if not supplied
1423 """
1424 additional_params = copy(slice_request.get("additionalParamsForNsi"))
1425 if additional_params:
1426 for k, v in additional_params.items():
1427 if not isinstance(k, str):
1428 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1429 format(k))
1430 if "." in k or "$" in k:
1431 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1432 format(k))
1433 if isinstance(v, (dict, tuple, list)):
1434 additional_params[k] = "!!yaml " + safe_dump(v)
1435 return additional_params
1436
1437 def _check_descriptor_dependencies(self, session, descriptor):
1438 """
1439 Check that the dependent descriptors exist on a new descriptor or edition
1440 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1441 :param descriptor: descriptor to be inserted or edit
1442 :return: None or raises exception
1443 """
1444 if not descriptor.get("nst-ref"):
1445 return
1446 nstd_id = descriptor["nst-ref"]
1447 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
1448 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
1449 http_code=HTTPStatus.CONFLICT)
1450
1451 def check_conflict_on_del(self, session, _id, db_content):
1452 """
1453 Check that NSI is not instantiated
1454 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1455 :param _id: nsi internal id
1456 :param db_content: The database content of the _id
1457 :return: None or raises EngineException with the conflict
1458 """
1459 if session["force"]:
1460 return
1461 nsi = db_content
1462 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
1463 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1464 "Launch 'terminate' operation first; or force deletion".format(_id),
1465 http_code=HTTPStatus.CONFLICT)
1466
1467 def delete_extra(self, session, _id, db_content, not_send_msg=None):
1468 """
1469 Deletes associated nsilcmops from database. Deletes associated filesystem.
1470 Set usageState of nst
1471 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1472 :param _id: server internal id
1473 :param db_content: The database content of the descriptor
1474 :param not_send_msg: To not send message (False) or store content (list) instead
1475 :return: None if ok or raises EngineException with the problem
1476 """
1477
1478 # Deleting the nsrs belonging to nsir
1479 nsir = db_content
1480 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1481 nsr_id = nsrs_detailed_item["nsrId"]
1482 if nsrs_detailed_item.get("shared"):
1483 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1484 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1485 "_id.ne": nsir["_id"]}
1486 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1487 if nsi: # last one using nsr
1488 continue
1489 try:
1490 self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
1491 except (DbException, EngineException) as e:
1492 if e.http_code == HTTPStatus.NOT_FOUND:
1493 pass
1494 else:
1495 raise
1496
1497 # delete related nsilcmops database entries
1498 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
1499
1500 # Check and set used NST usage state
1501 nsir_admin = nsir.get("_admin")
1502 if nsir_admin and nsir_admin.get("nst-id"):
1503 # check if used by another NSI
1504 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1505 fail_on_empty=False, fail_on_more=False)
1506 if not nsis_list:
1507 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1508
1509 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1510 """
1511 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1512 :param rollback: list to append the created items at database in case a rollback must be done
1513 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1514 :param indata: params to be used for the nsir
1515 :param kwargs: used to override the indata descriptor
1516 :param headers: http request headers
1517 :return: the _id of nsi descriptor created at database
1518 """
1519
1520 try:
1521 step = "checking quotas"
1522 self.check_quota(session)
1523
1524 step = ""
1525 slice_request = self._remove_envelop(indata)
1526 # Override descriptor with query string kwargs
1527 self._update_input_with_kwargs(slice_request, kwargs)
1528 slice_request = self._validate_input_new(slice_request, session["force"])
1529
1530 # look for nstd
1531 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
1532 _filter = self._get_project_filter(session)
1533 _filter["_id"] = slice_request["nstId"]
1534 nstd = self.db.get_one("nsts", _filter)
1535 # check NST is not disabled
1536 step = "checking NST operationalState"
1537 if nstd["_admin"]["operationalState"] == "DISABLED":
1538 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
1539 "instance".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
1540 del _filter["_id"]
1541
1542 # check NSD is not disabled
1543 step = "checking operationalState"
1544 if nstd["_admin"]["operationalState"] == "DISABLED":
1545 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create "
1546 "a network slice".format(slice_request["nstId"]), http_code=HTTPStatus.CONFLICT)
1547
1548 nstd.pop("_admin", None)
1549 nstd_id = nstd.pop("_id", None)
1550 nsi_id = str(uuid4())
1551 step = "filling nsi_descriptor with input data"
1552
1553 # Creating the NSIR
1554 nsi_descriptor = {
1555 "id": nsi_id,
1556 "name": slice_request["nsiName"],
1557 "description": slice_request.get("nsiDescription", ""),
1558 "datacenter": slice_request["vimAccountId"],
1559 "nst-ref": nstd["id"],
1560 "instantiation_parameters": slice_request,
1561 "network-slice-template": nstd,
1562 "nsr-ref-list": [],
1563 "vlr-list": [],
1564 "_id": nsi_id,
1565 "additionalParamsForNsi": self._format_addional_params(slice_request)
1566 }
1567
1568 step = "creating nsi at database"
1569 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
1570 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1571 nsi_descriptor["_admin"]["netslice-subnet"] = None
1572 nsi_descriptor["_admin"]["deployed"] = {}
1573 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1574 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1575
1576 # Creating netslice-vld for the RO.
1577 step = "creating netslice-vld at database"
1578
1579 # Building the vlds list to be deployed
1580 # From netslice descriptors, creating the initial list
1581 nsi_vlds = []
1582
1583 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1584 # Getting template Instantiation parameters from NST
1585 nsi_vld = deepcopy(netslice_vlds)
1586 nsi_vld["shared-nsrs-list"] = []
1587 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1588 nsi_vlds.append(nsi_vld)
1589
1590 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
1591 # Creating netslice-subnet_record.
1592 needed_nsds = {}
1593 services = []
1594
1595 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1596 for member_ns in nstd["netslice-subnet"]:
1597 nsd_id = member_ns["nsd-ref"]
1598 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1599 member_ns["nsd-ref"], member_ns["id"])
1600 if nsd_id not in needed_nsds:
1601 # Obtain nsd
1602 _filter["id"] = nsd_id
1603 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1604 del _filter["id"]
1605 nsd.pop("_admin")
1606 needed_nsds[nsd_id] = nsd
1607 else:
1608 nsd = needed_nsds[nsd_id]
1609 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1610 services.append(member_ns)
1611
1612 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1613 member_ns["nsd-ref"], member_ns["id"])
1614
1615 # creates Network Services records (NSRs)
1616 step = "creating nsrs at database using NsrTopic.new()"
1617 ns_params = slice_request.get("netslice-subnet")
1618 nsrs_list = []
1619 nsi_netslice_subnet = []
1620 for service in services:
1621 # Check if the netslice-subnet is shared and if it is share if the nss exists
1622 _id_nsr = None
1623 indata_ns = {}
1624 # Is the nss shared and instantiated?
1625 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1626 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
1627 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
1628 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1629 if nsi and service.get("is-shared-nss"):
1630 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1631 for nsrs_detailed_item in nsrs_detailed_list:
1632 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
1633 if nsrs_detailed_item["nss-id"] == service["id"]:
1634 _id_nsr = nsrs_detailed_item["nsrId"]
1635 break
1636 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1637 if netslice_subnet["nss-id"] == service["id"]:
1638 indata_ns = netslice_subnet
1639 break
1640 else:
1641 indata_ns = {}
1642 if service.get("instantiation-parameters"):
1643 indata_ns = deepcopy(service["instantiation-parameters"])
1644 # del service["instantiation-parameters"]
1645
1646 indata_ns["nsdId"] = service["_id"]
1647 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1648 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1649 indata_ns["nsDescription"] = service["description"]
1650 if slice_request.get("ssh_keys"):
1651 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
1652
1653 if ns_params:
1654 for ns_param in ns_params:
1655 if ns_param.get("id") == service["id"]:
1656 copy_ns_param = deepcopy(ns_param)
1657 del copy_ns_param["id"]
1658 indata_ns.update(copy_ns_param)
1659 break
1660
1661 # Creates Nsr objects
1662 _id_nsr, _ = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
1663 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
1664 "nss-id": service["id"], "nslcmop_instantiate": None}
1665 indata_ns["nss-id"] = service["id"]
1666 nsrs_list.append(nsrs_item)
1667 nsi_netslice_subnet.append(indata_ns)
1668 nsr_ref = {"nsr-ref": _id_nsr}
1669 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
1670
1671 # Adding the nsrs list to the nsi
1672 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
1673 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1674 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1675
1676 # Creating the entry in the database
1677 self.db.create("nsis", nsi_descriptor)
1678 rollback.append({"topic": "nsis", "_id": nsi_id})
1679 return nsi_id, None
1680 except Exception as e: # TODO remove try Except, it is captured at nbi.py
1681 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1682 raise EngineException("Error {}: {}".format(step, e))
1683 except ValidationError as e:
1684 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1685
1686 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1687 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1688
1689
1690 class NsiLcmOpTopic(BaseTopic):
1691 topic = "nsilcmops"
1692 topic_msg = "nsi"
1693 operation_schema = { # mapping between operation and jsonschema to validate
1694 "instantiate": nsi_instantiate,
1695 "terminate": None
1696 }
1697
1698 def __init__(self, db, fs, msg, auth):
1699 BaseTopic.__init__(self, db, fs, msg, auth)
1700 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
1701
1702 def _check_nsi_operation(self, session, nsir, operation, indata):
1703 """
1704 Check that user has enter right parameters for the operation
1705 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1706 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1707 :param indata: descriptor with the parameters of the operation
1708 :return: None
1709 """
1710 nsds = {}
1711 nstd = nsir["network-slice-template"]
1712
1713 def check_valid_netslice_subnet_id(nstId):
1714 # TODO change to vnfR (??)
1715 for netslice_subnet in nstd["netslice-subnet"]:
1716 if nstId == netslice_subnet["id"]:
1717 nsd_id = netslice_subnet["nsd-ref"]
1718 if nsd_id not in nsds:
1719 _filter = self._get_project_filter(session)
1720 _filter["id"] = nsd_id
1721 nsds[nsd_id] = self.db.get_one("nsds", _filter)
1722 return nsds[nsd_id]
1723 else:
1724 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1725 "nst:netslice-subnet".format(nstId))
1726 if operation == "instantiate":
1727 # check the existance of netslice-subnet items
1728 for in_nst in get_iterable(indata.get("netslice-subnet")):
1729 check_valid_netslice_subnet_id(in_nst["id"])
1730
1731 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1732 now = time()
1733 _id = str(uuid4())
1734 nsilcmop = {
1735 "id": _id,
1736 "_id": _id,
1737 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1738 "statusEnteredTime": now,
1739 "netsliceInstanceId": netsliceInstanceId,
1740 "lcmOperationType": operation,
1741 "startTime": now,
1742 "isAutomaticInvocation": False,
1743 "operationParams": params,
1744 "isCancelPending": False,
1745 "links": {
1746 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
1747 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
1748 }
1749 }
1750 return nsilcmop
1751
1752 def add_shared_nsr_2vld(self, nsir, nsr_item):
1753 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1754 if nst_sb_item.get("is-shared-nss"):
1755 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1756 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1757 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1758 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1759 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1760 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1761 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1762 break
1763 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1764 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1765
1766 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1767 """
1768 Performs a new operation over a ns
1769 :param rollback: list to append created items at database in case a rollback must to be done
1770 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1771 :param indata: descriptor with the parameters of the operation. It must contains among others
1772 netsliceInstanceId: _id of the nsir to perform the operation
1773 operation: it can be: instantiate, terminate, action, TODO: update, heal
1774 :param kwargs: used to override the indata descriptor
1775 :param headers: http request headers
1776 :return: id of the nslcmops
1777 """
1778 try:
1779 # Override descriptor with query string kwargs
1780 self._update_input_with_kwargs(indata, kwargs)
1781 operation = indata["lcmOperationType"]
1782 netsliceInstanceId = indata["netsliceInstanceId"]
1783 validate_input(indata, self.operation_schema[operation])
1784
1785 # get nsi from netsliceInstanceId
1786 _filter = self._get_project_filter(session)
1787 _filter["_id"] = netsliceInstanceId
1788 nsir = self.db.get_one("nsis", _filter)
1789 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
1790 del _filter["_id"]
1791
1792 # initial checking
1793 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1794 if operation == "terminate" and indata.get("autoremove"):
1795 # NSIR must be deleted
1796 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1797 if operation != "instantiate":
1798 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1799 netsliceInstanceId, operation), HTTPStatus.CONFLICT)
1800 else:
1801 if operation == "instantiate" and not session["force"]:
1802 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1803 format(netsliceInstanceId, operation), HTTPStatus.CONFLICT)
1804
1805 # Creating all the NS_operation (nslcmop)
1806 # Get service list from db
1807 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1808 nslcmops = []
1809 # nslcmops_item = None
1810 for index, nsr_item in enumerate(nsrs_list):
1811 nsr_id = nsr_item["nsrId"]
1812 if nsr_item.get("shared"):
1813 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1814 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1815 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1816 _filter["_id.ne"] = netsliceInstanceId
1817 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1818 if operation == "terminate":
1819 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1820 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1821 if nsi: # other nsi is using this nsr and it needs this nsr instantiated
1822 continue # do not create nsilcmop
1823 else: # instantiate
1824 # looks the first nsi fulfilling the conditions but not being the current NSIR
1825 if nsi:
1826 nsi_nsr_item = next(n for n in nsi["_admin"]["nsrs-detailed-list"] if
1827 n["nsrId"] == nsr_id and n["shared"] and
1828 n["nslcmop_instantiate"])
1829 self.add_shared_nsr_2vld(nsir, nsr_item)
1830 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1831 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1832 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1833 # continue to not create nslcmop since nsrs is shared and nsrs was created
1834 continue
1835 else:
1836 self.add_shared_nsr_2vld(nsir, nsr_item)
1837
1838 # create operation
1839 try:
1840 indata_ns = {
1841 "lcmOperationType": operation,
1842 "nsInstanceId": nsr_id,
1843 # Including netslice_id in the ns instantiate Operation
1844 "netsliceInstanceId": netsliceInstanceId,
1845 }
1846 if operation == "instantiate":
1847 service = self.db.get_one("nsrs", {"_id": nsr_id})
1848 indata_ns.update(service["instantiate_params"])
1849
1850 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1851 # message via kafka bus
1852 nslcmop, _ = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, None, headers,
1853 slice_object=True)
1854 nslcmops.append(nslcmop)
1855 if operation == "instantiate":
1856 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1857 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1858 except (DbException, EngineException) as e:
1859 if e.http_code == HTTPStatus.NOT_FOUND:
1860 self.logger.info(logging_prefix + "skipping NS={} because not found".format(nsr_id))
1861 pass
1862 else:
1863 raise
1864
1865 # Creates nsilcmop
1866 indata["nslcmops_ids"] = nslcmops
1867 self._check_nsi_operation(session, nsir, operation, indata)
1868
1869 nsilcmop_desc = self._create_nsilcmop(session, netsliceInstanceId, operation, indata)
1870 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
1871 _id = self.db.create("nsilcmops", nsilcmop_desc)
1872 rollback.append({"topic": "nsilcmops", "_id": _id})
1873 self.msg.write("nsi", operation, nsilcmop_desc)
1874 return _id, None
1875 except ValidationError as e:
1876 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1877
1878 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1879 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1880
1881 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1882 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)