Bug 2024
[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 import json
18 from uuid import uuid4
19 from http import HTTPStatus
20 from time import time
21 from copy import copy, deepcopy
22 from osm_nbi.validation import (
23 validate_input,
24 ValidationError,
25 ns_instantiate,
26 ns_terminate,
27 ns_action,
28 ns_scale,
29 ns_update,
30 nsi_instantiate,
31 ns_migrate,
32 )
33 from osm_nbi.base_topic import (
34 BaseTopic,
35 EngineException,
36 get_iterable,
37 deep_get,
38 increment_ip_mac,
39 )
40 from yaml import safe_dump
41 from osm_common.dbbase import DbException
42 from osm_common.msgbase import MsgException
43 from osm_common.fsbase import FsException
44 from osm_nbi import utils
45 from re import (
46 match,
47 ) # For checking that additional parameter names are valid Jinja2 identifiers
48
49 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
50
51
52 class NsrTopic(BaseTopic):
53 topic = "nsrs"
54 topic_msg = "ns"
55 quota_name = "ns_instances"
56 schema_new = ns_instantiate
57
58 def __init__(self, db, fs, msg, auth):
59 BaseTopic.__init__(self, db, fs, msg, auth)
60
61 def _check_descriptor_dependencies(self, session, descriptor):
62 """
63 Check that the dependent descriptors exist on a new descriptor or edition
64 :param session: client session information
65 :param descriptor: descriptor to be inserted or edit
66 :return: None or raises exception
67 """
68 if not descriptor.get("nsdId"):
69 return
70 nsd_id = descriptor["nsdId"]
71 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
72 raise EngineException(
73 "Descriptor error at nsdId='{}' references a non exist nsd".format(
74 nsd_id
75 ),
76 http_code=HTTPStatus.CONFLICT,
77 )
78
79 @staticmethod
80 def format_on_new(content, project_id=None, make_public=False):
81 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
82 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
83 return None
84
85 def check_conflict_on_del(self, session, _id, db_content):
86 """
87 Check that NSR is not instantiated
88 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
89 :param _id: nsr internal id
90 :param db_content: The database content of the nsr
91 :return: None or raises EngineException with the conflict
92 """
93 if session["force"]:
94 return
95 nsr = db_content
96 if nsr["_admin"].get("nsState") == "INSTANTIATED":
97 raise EngineException(
98 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
99 "Launch 'terminate' operation first; or force deletion".format(_id),
100 http_code=HTTPStatus.CONFLICT,
101 )
102
103 def delete_extra(self, session, _id, db_content, not_send_msg=None):
104 """
105 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
106 Set usageState of pdu, vnfd, nsd
107 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
108 :param _id: server internal id
109 :param db_content: The database content of the descriptor
110 :param not_send_msg: To not send message (False) or store content (list) instead
111 :return: None if ok or raises EngineException with the problem
112 """
113 self.fs.file_delete(_id, ignore_non_exist=True)
114 self.db.del_list("nslcmops", {"nsInstanceId": _id})
115 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
116
117 # set all used pdus as free
118 self.db.set_list(
119 "pdus",
120 {"_admin.usage.nsr_id": _id},
121 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
122 )
123
124 # Set NSD usageState
125 nsr = db_content
126 used_nsd_id = nsr.get("nsd-id")
127 if used_nsd_id:
128 # check if used by another NSR
129 nsrs_list = self.db.get_one(
130 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
131 )
132 if not nsrs_list:
133 self.db.set_one(
134 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
135 )
136
137 # Set VNFD usageState
138 used_vnfd_id_list = nsr.get("vnfd-id")
139 if used_vnfd_id_list:
140 for used_vnfd_id in used_vnfd_id_list:
141 # check if used by another NSR
142 nsrs_list = self.db.get_one(
143 "nsrs",
144 {"vnfd-id": used_vnfd_id},
145 fail_on_empty=False,
146 fail_on_more=False,
147 )
148 if not nsrs_list:
149 self.db.set_one(
150 "vnfds",
151 {"_id": used_vnfd_id},
152 {"_admin.usageState": "NOT_IN_USE"},
153 )
154
155 # delete extra ro_nsrs used for internal RO module
156 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
157
158 @staticmethod
159 def _format_ns_request(ns_request):
160 formated_request = copy(ns_request)
161 formated_request.pop("additionalParamsForNs", None)
162 formated_request.pop("additionalParamsForVnf", None)
163 return formated_request
164
165 @staticmethod
166 def _format_additional_params(
167 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
168 ):
169 """
170 Get and format user additional params for NS or VNF
171 :param ns_request: User instantiation additional parameters
172 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
173 :param descriptor: If not None it check that needed parameters of descriptor are supplied
174 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
175 """
176 additional_params = None
177 other_params = None
178 if not member_vnf_index:
179 additional_params = copy(ns_request.get("additionalParamsForNs"))
180 where_ = "additionalParamsForNs"
181 elif ns_request.get("additionalParamsForVnf"):
182 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
183 member_vnf_index
184 )
185 item = next(
186 (
187 x
188 for x in ns_request["additionalParamsForVnf"]
189 if x["member-vnf-index"] == member_vnf_index
190 ),
191 None,
192 )
193 if item:
194 if not vdu_id and not kdu_name:
195 other_params = item
196 additional_params = copy(item.get("additionalParams")) or {}
197 if vdu_id and item.get("additionalParamsForVdu"):
198 item_vdu = next(
199 (
200 x
201 for x in item["additionalParamsForVdu"]
202 if x["vdu_id"] == vdu_id
203 ),
204 None,
205 )
206 other_params = item_vdu
207 if item_vdu and item_vdu.get("additionalParams"):
208 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
209 additional_params = item_vdu["additionalParams"]
210 if kdu_name:
211 additional_params = {}
212 if item.get("additionalParamsForKdu"):
213 item_kdu = next(
214 (
215 x
216 for x in item["additionalParamsForKdu"]
217 if x["kdu_name"] == kdu_name
218 ),
219 None,
220 )
221 other_params = item_kdu
222 if item_kdu and item_kdu.get("additionalParams"):
223 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
224 kdu_name
225 )
226 additional_params = item_kdu["additionalParams"]
227
228 if additional_params:
229 for k, v in additional_params.items():
230 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
231 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
232 raise EngineException(
233 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
234 "and underscores, and cannot start with a digit".format(
235 where_, k
236 )
237 )
238 # END Check that additional parameter names are valid Jinja2 identifiers
239 if not isinstance(k, str):
240 raise EngineException(
241 "Invalid param at {}:{}. Only string keys are allowed".format(
242 where_, k
243 )
244 )
245 if "$" in k:
246 raise EngineException(
247 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
248 where_, k
249 )
250 )
251 if isinstance(v, (dict, tuple, list)):
252 additional_params[k] = "!!yaml " + safe_dump(v)
253 if kdu_name:
254 additional_params = json.dumps(additional_params)
255
256 if descriptor:
257 for df in descriptor.get("df", []):
258 # check that enough parameters are supplied for the initial-config-primitive
259 # TODO: check for cloud-init
260 if member_vnf_index:
261 initial_primitives = []
262 if (
263 "lcm-operations-configuration" in df
264 and "operate-vnf-op-config"
265 in df["lcm-operations-configuration"]
266 ):
267 for config in df["lcm-operations-configuration"][
268 "operate-vnf-op-config"
269 ].get("day1-2", []):
270 for primitive in get_iterable(
271 config.get("initial-config-primitive")
272 ):
273 initial_primitives.append(primitive)
274 else:
275 initial_primitives = deep_get(
276 descriptor, ("ns-configuration", "initial-config-primitive")
277 )
278
279 for initial_primitive in get_iterable(initial_primitives):
280 for param in get_iterable(initial_primitive.get("parameter")):
281 if param["value"].startswith("<") and param["value"].endswith(
282 ">"
283 ):
284 if param["value"] in (
285 "<rw_mgmt_ip>",
286 "<VDU_SCALE_INFO>",
287 "<ns_config_info>",
288 ):
289 continue
290 if (
291 not additional_params
292 or param["value"][1:-1] not in additional_params
293 ):
294 raise EngineException(
295 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
296 "initial-config-primitive[name={}] not supplied".format(
297 param["value"],
298 descriptor["id"],
299 initial_primitive["name"],
300 )
301 )
302
303 return additional_params or None, other_params or None
304
305 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
306 """
307 Creates a new nsr into database. It also creates needed vnfrs
308 :param rollback: list to append the created items at database in case a rollback must be done
309 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
310 :param indata: params to be used for the nsr
311 :param kwargs: used to override the indata descriptor
312 :param headers: http request headers
313 :return: the _id of nsr descriptor created at database. Or an exception of type
314 EngineException, ValidationError, DbException, FsException, MsgException.
315 Note: Exceptions are not captured on purpose. They should be captured at called
316 """
317 try:
318 step = "checking quotas"
319 self.check_quota(session)
320
321 step = "validating input parameters"
322 ns_request = self._remove_envelop(indata)
323 self._update_input_with_kwargs(ns_request, kwargs)
324 ns_request = self._validate_input_new(ns_request, session["force"])
325
326 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
327 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
328 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
329
330 step = "checking nsdOperationalState"
331 self._check_nsd_operational_state(nsd, ns_request)
332
333 step = "filling nsr from input data"
334 nsr_id = str(uuid4())
335 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
336 nsd, ns_request, nsr_id, session
337 )
338
339 # Create VNFRs
340 needed_vnfds = {}
341 # TODO: Change for multiple df support
342 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
343 for vnfp in vnf_profiles:
344 vnfd_id = vnfp.get("vnfd-id")
345 vnf_index = vnfp.get("id")
346 step = (
347 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
348 vnfd_id, vnf_index
349 )
350 )
351 if vnfd_id not in needed_vnfds:
352 vnfd = self._get_vnfd_from_db(vnfd_id, session)
353 if "revision" in vnfd["_admin"]:
354 vnfd["revision"] = vnfd["_admin"]["revision"]
355 vnfd.pop("_admin")
356 needed_vnfds[vnfd_id] = vnfd
357 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
358 else:
359 vnfd = needed_vnfds[vnfd_id]
360
361 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
362 vnfd_id, vnf_index
363 )
364 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
365 nsd,
366 vnfd,
367 vnfd_id,
368 vnf_index,
369 nsr_descriptor,
370 ns_request,
371 ns_k8s_namespace,
372 )
373
374 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
375 vnfd_id, vnf_index
376 )
377 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
378 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
379
380 step = "creating nsr at database"
381 self._add_nsr_to_db(nsr_descriptor, rollback, session)
382
383 step = "creating nsr temporal folder"
384 self.fs.mkdir(nsr_id)
385
386 return nsr_id, None
387 except (
388 ValidationError,
389 EngineException,
390 DbException,
391 MsgException,
392 FsException,
393 ) as e:
394 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
395
396 def _get_nsd_from_db(self, nsd_id, session):
397 _filter = self._get_project_filter(session)
398 _filter["_id"] = nsd_id
399 return self.db.get_one("nsds", _filter)
400
401 def _get_vnfd_from_db(self, vnfd_id, session):
402 _filter = self._get_project_filter(session)
403 _filter["id"] = vnfd_id
404 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
405 return vnfd
406
407 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
408 self.format_on_new(
409 nsr_descriptor, session["project_id"], make_public=session["public"]
410 )
411 self.db.create("nsrs", nsr_descriptor)
412 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
413
414 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
415 self.format_on_new(
416 vnfr_descriptor, session["project_id"], make_public=session["public"]
417 )
418 self.db.create("vnfrs", vnfr_descriptor)
419 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
420
421 def _check_nsd_operational_state(self, nsd, ns_request):
422 if nsd["_admin"]["operationalState"] == "DISABLED":
423 raise EngineException(
424 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
425 "a network service".format(ns_request["nsdId"]),
426 http_code=HTTPStatus.CONFLICT,
427 )
428
429 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
430 additional_params, _ = self._format_additional_params(
431 ns_request, descriptor=nsd
432 )
433 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
434 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
435 if ns_request and ns_request.get("k8s-namespace"):
436 ns_k8s_namespace = ns_request["k8s-namespace"]
437 if additional_params and additional_params.get("k8s-namespace"):
438 ns_k8s_namespace = additional_params["k8s-namespace"]
439
440 return ns_k8s_namespace
441
442 def _add_flavor_to_nsr(self, vdu, vnfd, nsr_descriptor):
443 flavor_data = {}
444 guest_epa = {}
445 # Find this vdu compute and storage descriptors
446 vdu_virtual_compute = {}
447 vdu_virtual_storage = {}
448 for vcd in vnfd.get("virtual-compute-desc", ()):
449 if vcd.get("id") == vdu.get("virtual-compute-desc"):
450 vdu_virtual_compute = vcd
451 for vsd in vnfd.get("virtual-storage-desc", ()):
452 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
453 vdu_virtual_storage = vsd
454 # Get this vdu vcpus, memory and storage info for flavor_data
455 if vdu_virtual_compute.get("virtual-cpu", {}).get(
456 "num-virtual-cpu"
457 ):
458 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
459 "num-virtual-cpu"
460 ]
461 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
462 flavor_data["memory-mb"] = (
463 float(vdu_virtual_compute["virtual-memory"]["size"])
464 * 1024.0
465 )
466 if vdu_virtual_storage.get("size-of-storage"):
467 flavor_data["storage-gb"] = vdu_virtual_storage[
468 "size-of-storage"
469 ]
470 # Get this vdu EPA info for guest_epa
471 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
472 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
473 "cpu-quota"
474 ]
475 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
476 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
477 if vcpu_pinning.get("thread-policy"):
478 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
479 "thread-policy"
480 ]
481 if vcpu_pinning.get("policy"):
482 cpu_policy = (
483 "SHARED"
484 if vcpu_pinning["policy"] == "dynamic"
485 else "DEDICATED"
486 )
487 guest_epa["cpu-pinning-policy"] = cpu_policy
488 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
489 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
490 "mem-quota"
491 ]
492 if vdu_virtual_compute.get("virtual-memory", {}).get(
493 "mempage-size"
494 ):
495 guest_epa["mempage-size"] = vdu_virtual_compute[
496 "virtual-memory"
497 ]["mempage-size"]
498 if vdu_virtual_compute.get("virtual-memory", {}).get(
499 "numa-node-policy"
500 ):
501 guest_epa["numa-node-policy"] = vdu_virtual_compute[
502 "virtual-memory"
503 ]["numa-node-policy"]
504 if vdu_virtual_storage.get("disk-io-quota"):
505 guest_epa["disk-io-quota"] = vdu_virtual_storage[
506 "disk-io-quota"
507 ]
508
509 if guest_epa:
510 flavor_data["guest-epa"] = guest_epa
511
512 flavor_data["name"] = vdu["id"][:56] + "-flv"
513 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
514 nsr_descriptor["flavor"].append(flavor_data)
515
516 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
517 now = time()
518 additional_params, _ = self._format_additional_params(
519 ns_request, descriptor=nsd
520 )
521
522 nsr_descriptor = {
523 "name": ns_request["nsName"],
524 "name-ref": ns_request["nsName"],
525 "short-name": ns_request["nsName"],
526 "admin-status": "ENABLED",
527 "nsState": "NOT_INSTANTIATED",
528 "currentOperation": "IDLE",
529 "currentOperationID": None,
530 "errorDescription": None,
531 "errorDetail": None,
532 "deploymentStatus": None,
533 "configurationStatus": None,
534 "vcaStatus": None,
535 "nsd": {k: v for k, v in nsd.items()},
536 "datacenter": ns_request["vimAccountId"],
537 "resource-orchestrator": "osmopenmano",
538 "description": ns_request.get("nsDescription", ""),
539 "constituent-vnfr-ref": [],
540 "operational-status": "init", # typedef ns-operational-
541 "config-status": "init", # typedef config-states
542 "detailed-status": "scheduled",
543 "orchestration-progress": {},
544 "create-time": now,
545 "nsd-name-ref": nsd["name"],
546 "operational-events": [], # "id", "timestamp", "description", "event",
547 "nsd-ref": nsd["id"],
548 "nsd-id": nsd["_id"],
549 "vnfd-id": [],
550 "instantiate_params": self._format_ns_request(ns_request),
551 "additionalParamsForNs": additional_params,
552 "ns-instance-config-ref": nsr_id,
553 "id": nsr_id,
554 "_id": nsr_id,
555 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
556 "flavor": [],
557 "image": [],
558 "affinity-or-anti-affinity-group": [],
559 }
560 if "revision" in nsd["_admin"]:
561 nsr_descriptor["revision"] = nsd["_admin"]["revision"]
562
563 ns_request["nsr_id"] = nsr_id
564 if ns_request and ns_request.get("config-units"):
565 nsr_descriptor["config-units"] = ns_request["config-units"]
566 # Create vld
567 if nsd.get("virtual-link-desc"):
568 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
569 # Fill each vld with vnfd-connection-point-ref data
570 # TODO: Change for multiple df support
571 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
572 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
573 for vnf_profile in vnf_profiles:
574 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
575 for cpd in vlc.get("constituent-cpd-id", ()):
576 all_vld_connection_point_data[
577 vlc.get("virtual-link-profile-id")
578 ].append(
579 {
580 "member-vnf-index-ref": cpd.get(
581 "constituent-base-element-id"
582 ),
583 "vnfd-connection-point-ref": cpd.get(
584 "constituent-cpd-id"
585 ),
586 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
587 }
588 )
589
590 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
591 vnfd.pop("_admin")
592
593 for vdu in vnfd.get("vdu", ()):
594 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor)
595 sw_image_id = vdu.get("sw-image-desc")
596 if sw_image_id:
597 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
598 self._add_image_to_nsr(nsr_descriptor, image_data)
599
600 # also add alternative images to the list of images
601 for alt_image in vdu.get("alternative-sw-image-desc", ()):
602 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
603 self._add_image_to_nsr(nsr_descriptor, image_data)
604
605 # Add Affinity or Anti-affinity group information to NSR
606 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
607 affinity_group_prefix_name = "{}-{}".format(
608 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
609 )
610
611 for vdu_profile in vdu_profiles:
612 affinity_group_data = {}
613 for affinity_group in vdu_profile.get(
614 "affinity-or-anti-affinity-group", ()
615 ):
616 affinity_group_data = (
617 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
618 vnfd, affinity_group["id"]
619 )
620 )
621 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
622 self._add_affinity_or_anti_affinity_group_to_nsr(
623 nsr_descriptor,
624 affinity_group_data,
625 affinity_group_prefix_name,
626 )
627
628 for vld in nsr_vld:
629 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
630 vld.get("id"), []
631 )
632 vld["name"] = vld["id"]
633 nsr_descriptor["vld"] = nsr_vld
634
635 return nsr_descriptor
636
637 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
638 self, vnfd, affinity_group_id
639 ):
640 """
641 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
642 """
643 affinity_group = utils.find_in_list(
644 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
645 lambda ag: ag["id"] == affinity_group_id,
646 )
647 affinity_group_data = {}
648 if affinity_group:
649 if affinity_group.get("id"):
650 affinity_group_data["ag-id"] = affinity_group["id"]
651 if affinity_group.get("type"):
652 affinity_group_data["type"] = affinity_group["type"]
653 if affinity_group.get("scope"):
654 affinity_group_data["scope"] = affinity_group["scope"]
655 return affinity_group_data
656
657 def _add_affinity_or_anti_affinity_group_to_nsr(
658 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
659 ):
660 """
661 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
662 """
663 affinity_group = next(
664 (
665 f
666 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
667 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
668 ),
669 None,
670 )
671 if not affinity_group:
672 affinity_group_data["id"] = str(
673 len(nsr_descriptor["affinity-or-anti-affinity-group"])
674 )
675 affinity_group_data["name"] = "{}-{}".format(
676 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
677 )
678 nsr_descriptor["affinity-or-anti-affinity-group"].append(
679 affinity_group_data
680 )
681
682 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
683 sw_image_desc = utils.find_in_list(
684 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
685 )
686 image_data = {}
687 if sw_image_desc.get("image"):
688 image_data["image"] = sw_image_desc["image"]
689 if sw_image_desc.get("checksum"):
690 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
691 if sw_image_desc.get("vim-type"):
692 image_data["vim-type"] = sw_image_desc["vim-type"]
693 return image_data
694
695 def _add_image_to_nsr(self, nsr_descriptor, image_data):
696 """
697 Adds image to nsr checking first it is not already added
698 """
699 img = next(
700 (
701 f
702 for f in nsr_descriptor["image"]
703 if all(f.get(k) == image_data[k] for k in image_data)
704 ),
705 None,
706 )
707 if not img:
708 image_data["id"] = str(len(nsr_descriptor["image"]))
709 nsr_descriptor["image"].append(image_data)
710
711 def _create_vnfr_descriptor_from_vnfd(
712 self,
713 nsd,
714 vnfd,
715 vnfd_id,
716 vnf_index,
717 nsr_descriptor,
718 ns_request,
719 ns_k8s_namespace,
720 ):
721 vnfr_id = str(uuid4())
722 nsr_id = nsr_descriptor["id"]
723 now = time()
724 additional_params, vnf_params = self._format_additional_params(
725 ns_request, vnf_index, descriptor=vnfd
726 )
727
728 vnfr_descriptor = {
729 "id": vnfr_id,
730 "_id": vnfr_id,
731 "nsr-id-ref": nsr_id,
732 "member-vnf-index-ref": vnf_index,
733 "additionalParamsForVnf": additional_params,
734 "created-time": now,
735 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
736 "vnfd-ref": vnfd_id,
737 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
738 "vim-account-id": None,
739 "vca-id": None,
740 "vdur": [],
741 "connection-point": [],
742 "ip-address": None, # mgmt-interface filled by LCM
743 }
744
745 # Revision backwards compatility. Only specify the revision in the record if
746 # the original VNFD has a revision.
747 if "revision" in vnfd:
748 vnfr_descriptor["revision"] = vnfd["revision"]
749
750
751 vnf_k8s_namespace = ns_k8s_namespace
752 if vnf_params:
753 if vnf_params.get("k8s-namespace"):
754 vnf_k8s_namespace = vnf_params["k8s-namespace"]
755 if vnf_params.get("config-units"):
756 vnfr_descriptor["config-units"] = vnf_params["config-units"]
757
758 # Create vld
759 if vnfd.get("int-virtual-link-desc"):
760 vnfr_descriptor["vld"] = []
761 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
762 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
763
764 for cp in vnfd.get("ext-cpd", ()):
765 vnf_cp = {
766 "name": cp.get("id"),
767 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
768 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
769 "id": cp.get("id"),
770 # "ip-address", "mac-address" # filled by LCM
771 # vim-id # TODO it would be nice having a vim port id
772 }
773 vnfr_descriptor["connection-point"].append(vnf_cp)
774
775 # Create k8s-cluster information
776 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
777 if vnfd.get("k8s-cluster"):
778 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
779 all_k8s_cluster_nets_cpds = {}
780 for cpd in get_iterable(vnfd.get("ext-cpd")):
781 if cpd.get("k8s-cluster-net"):
782 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
783 "id"
784 )
785 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
786 if net.get("id") in all_k8s_cluster_nets_cpds:
787 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
788 net.get("id")
789 ]
790
791 # update kdus
792 for kdu in get_iterable(vnfd.get("kdu")):
793 additional_params, kdu_params = self._format_additional_params(
794 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
795 )
796 kdu_k8s_namespace = vnf_k8s_namespace
797 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
798 if kdu_params and kdu_params.get("k8s-namespace"):
799 kdu_k8s_namespace = kdu_params["k8s-namespace"]
800
801 kdu_deployment_name = ""
802 if kdu_params and kdu_params.get("kdu-deployment-name"):
803 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
804
805 kdur = {
806 "additionalParams": additional_params,
807 "k8s-namespace": kdu_k8s_namespace,
808 "kdu-deployment-name": kdu_deployment_name,
809 "kdu-name": kdu["name"],
810 # TODO "name": "" Name of the VDU in the VIM
811 "ip-address": None, # mgmt-interface filled by LCM
812 "k8s-cluster": {},
813 }
814 if kdu_params and kdu_params.get("config-units"):
815 kdur["config-units"] = kdu_params["config-units"]
816 if kdu.get("helm-version"):
817 kdur["helm-version"] = kdu["helm-version"]
818 for k8s_type in ("helm-chart", "juju-bundle"):
819 if kdu.get(k8s_type):
820 kdur[k8s_type] = kdu_model or kdu[k8s_type]
821 if not vnfr_descriptor.get("kdur"):
822 vnfr_descriptor["kdur"] = []
823 vnfr_descriptor["kdur"].append(kdur)
824
825 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
826
827 for vdu in vnfd.get("vdu", ()):
828 vdu_mgmt_cp = []
829 try:
830 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
831 "operate-vnf-op-config"
832 ]["day1-2"]
833 vdu_config = utils.find_in_list(
834 configs, lambda config: config["id"] == vdu["id"]
835 )
836 except Exception:
837 vdu_config = None
838
839 try:
840 vdu_instantiation_level = utils.find_in_list(
841 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
842 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
843 )
844 except Exception:
845 vdu_instantiation_level = None
846
847 if vdu_config:
848 external_connection_ee = utils.filter_in_list(
849 vdu_config.get("execution-environment-list", []),
850 lambda ee: "external-connection-point-ref" in ee,
851 )
852 for ee in external_connection_ee:
853 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
854
855 additional_params, vdu_params = self._format_additional_params(
856 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
857 )
858
859 try:
860 vdu_virtual_storage_descriptors = utils.filter_in_list(
861 vnfd.get("virtual-storage-desc", []),
862 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
863 )
864 except Exception:
865 vdu_virtual_storage_descriptors = []
866 vdur = {
867 "vdu-id-ref": vdu["id"],
868 # TODO "name": "" Name of the VDU in the VIM
869 "ip-address": None, # mgmt-interface filled by LCM
870 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
871 "internal-connection-point": [],
872 "interfaces": [],
873 "additionalParams": additional_params,
874 "vdu-name": vdu["name"],
875 "virtual-storages": vdu_virtual_storage_descriptors
876 }
877 if vdu_params and vdu_params.get("config-units"):
878 vdur["config-units"] = vdu_params["config-units"]
879 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
880 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
881 "boot-data-drive"
882 ]
883 if vdu.get("pdu-type"):
884 vdur["pdu-type"] = vdu["pdu-type"]
885 vdur["name"] = vdu["pdu-type"]
886 # TODO volumes: name, volume-id
887 for icp in vdu.get("int-cpd", ()):
888 vdu_icp = {
889 "id": icp["id"],
890 "connection-point-id": icp["id"],
891 "name": icp.get("id"),
892 }
893
894 vdur["internal-connection-point"].append(vdu_icp)
895
896 for iface in icp.get("virtual-network-interface-requirement", ()):
897 iface_fields = ("name", "mac-address")
898 vdu_iface = {
899 x: iface[x] for x in iface_fields if iface.get(x) is not None
900 }
901
902 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
903 if "port-security-enabled" in icp:
904 vdu_iface["port-security-enabled"] = icp[
905 "port-security-enabled"
906 ]
907
908 if "port-security-disable-strategy" in icp:
909 vdu_iface["port-security-disable-strategy"] = icp[
910 "port-security-disable-strategy"
911 ]
912
913 for ext_cp in vnfd.get("ext-cpd", ()):
914 if not ext_cp.get("int-cpd"):
915 continue
916 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
917 continue
918 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
919 vdu_iface["external-connection-point-ref"] = ext_cp.get(
920 "id"
921 )
922
923 if "port-security-enabled" in ext_cp:
924 vdu_iface["port-security-enabled"] = ext_cp[
925 "port-security-enabled"
926 ]
927
928 if "port-security-disable-strategy" in ext_cp:
929 vdu_iface["port-security-disable-strategy"] = ext_cp[
930 "port-security-disable-strategy"
931 ]
932
933 break
934
935 if (
936 vnfd_mgmt_cp
937 and vdu_iface.get("external-connection-point-ref")
938 == vnfd_mgmt_cp
939 ):
940 vdu_iface["mgmt-vnf"] = True
941 vdu_iface["mgmt-interface"] = True
942
943 for ecp in vdu_mgmt_cp:
944 if vdu_iface.get("external-connection-point-ref") == ecp:
945 vdu_iface["mgmt-interface"] = True
946
947 if iface.get("virtual-interface"):
948 vdu_iface.update(deepcopy(iface["virtual-interface"]))
949
950 # look for network where this interface is connected
951 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
952 if iface_ext_cp:
953 # TODO: Change for multiple df support
954 for df in get_iterable(nsd.get("df")):
955 for vnf_profile in get_iterable(df.get("vnf-profile")):
956 for vlc_index, vlc in enumerate(
957 get_iterable(
958 vnf_profile.get("virtual-link-connectivity")
959 )
960 ):
961 for cpd in get_iterable(
962 vlc.get("constituent-cpd-id")
963 ):
964 if (
965 cpd.get("constituent-cpd-id")
966 == iface_ext_cp
967 ):
968 vdu_iface["ns-vld-id"] = vlc.get(
969 "virtual-link-profile-id"
970 )
971 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
972 if vdu_iface.get("type") in (
973 "SR-IOV",
974 "PCI-PASSTHROUGH",
975 ):
976 nsr_descriptor["vld"][vlc_index][
977 "pci-interfaces"
978 ] = True
979 break
980 elif vdu_iface.get("internal-connection-point-ref"):
981 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
982 # TODO: store fixed IP address in the record (if it exists in the ICP)
983 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
984 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
985 ivld_index = utils.find_index_in_list(
986 vnfd.get("int-virtual-link-desc", ()),
987 lambda ivld: ivld["id"]
988 == icp.get("int-virtual-link-desc"),
989 )
990 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
991
992 vdur["interfaces"].append(vdu_iface)
993
994 if vdu.get("sw-image-desc"):
995 sw_image = utils.find_in_list(
996 vnfd.get("sw-image-desc", ()),
997 lambda image: image["id"] == vdu.get("sw-image-desc"),
998 )
999 nsr_sw_image_data = utils.find_in_list(
1000 nsr_descriptor["image"],
1001 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
1002 )
1003 vdur["ns-image-id"] = nsr_sw_image_data["id"]
1004
1005 if vdu.get("alternative-sw-image-desc"):
1006 alt_image_ids = []
1007 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1008 sw_image = utils.find_in_list(
1009 vnfd.get("sw-image-desc", ()),
1010 lambda image: image["id"] == alt_image_id,
1011 )
1012 nsr_sw_image_data = utils.find_in_list(
1013 nsr_descriptor["image"],
1014 lambda nsr_image: (
1015 nsr_image.get("image") == sw_image.get("image")
1016 ),
1017 )
1018 alt_image_ids.append(nsr_sw_image_data["id"])
1019 vdur["alt-image-ids"] = alt_image_ids
1020
1021 flavor_data_name = vdu["id"][:56] + "-flv"
1022 nsr_flavor_desc = utils.find_in_list(
1023 nsr_descriptor["flavor"],
1024 lambda flavor: flavor["name"] == flavor_data_name,
1025 )
1026
1027 if nsr_flavor_desc:
1028 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1029
1030 # Adding Affinity groups information to vdur
1031 try:
1032 vdu_profile_affinity_group = utils.find_in_list(
1033 vnfd.get("df")[0]["vdu-profile"],
1034 lambda a_vdu: a_vdu["id"] == vdu["id"],
1035 )
1036 except Exception:
1037 vdu_profile_affinity_group = None
1038
1039 if vdu_profile_affinity_group:
1040 affinity_group_ids = []
1041 for affinity_group in vdu_profile_affinity_group.get(
1042 "affinity-or-anti-affinity-group", ()
1043 ):
1044 vdu_affinity_group = utils.find_in_list(
1045 vdu_profile_affinity_group.get(
1046 "affinity-or-anti-affinity-group", ()
1047 ),
1048 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
1049 )
1050 nsr_affinity_group = utils.find_in_list(
1051 nsr_descriptor["affinity-or-anti-affinity-group"],
1052 lambda nsr_ag: (
1053 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1054 and nsr_ag.get("member-vnf-index")
1055 == vnfr_descriptor.get("member-vnf-index-ref")
1056 ),
1057 )
1058 # Update Affinity Group VIM name if VDU instantiation parameter is present
1059 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1060 vnf_params_affinity_group = utils.find_in_list(
1061 vnf_params["affinity-or-anti-affinity-group"],
1062 lambda vnfp_ag: (
1063 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1064 ),
1065 )
1066 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1067 nsr_affinity_group[
1068 "vim-affinity-group-id"
1069 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1070 affinity_group_ids.append(nsr_affinity_group["id"])
1071 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1072
1073 if vdu_instantiation_level:
1074 count = vdu_instantiation_level.get("number-of-instances")
1075 else:
1076 count = 1
1077
1078 for index in range(0, count):
1079 vdur = deepcopy(vdur)
1080 for iface in vdur["interfaces"]:
1081 if iface.get("ip-address") and index != 0:
1082 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
1083 if iface.get("mac-address") and index != 0:
1084 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1085
1086 vdur["_id"] = str(uuid4())
1087 vdur["id"] = vdur["_id"]
1088 vdur["count-index"] = index
1089 vnfr_descriptor["vdur"].append(vdur)
1090
1091 return vnfr_descriptor
1092
1093 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1094 """
1095 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1096 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1097 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1098 :param ns_instance_content: ns instance content
1099 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1100 :return: None
1101 """
1102 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
1103 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
1104 threshold_reached = time_delta > 120
1105 if force_refresh or threshold_reached:
1106 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1107 ns_instance_content["_admin"]["modified"] = time_now
1108 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1109 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
1110 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1111 nslcmop_desc["_admin"].pop("nsState")
1112 self.msg.write("ns", operation, nslcmop_desc)
1113 return
1114
1115 def show(self, session, _id, filter_q=None, api_req=False):
1116 """
1117 Get complete information on an ns instance.
1118 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1119 :param _id: string, ns instance id
1120 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1121 :param api_req: True if this call is serving an external API request. False if serving internal request.
1122 :return: dictionary, raise exception if not found.
1123 """
1124 ns_instance_content = super().show(session, _id, api_req)
1125 self.vca_status_refresh(session, ns_instance_content, filter_q)
1126 return ns_instance_content
1127
1128 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1129 raise EngineException(
1130 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1131 )
1132
1133
1134 class VnfrTopic(BaseTopic):
1135 topic = "vnfrs"
1136 topic_msg = None
1137
1138 def __init__(self, db, fs, msg, auth):
1139 BaseTopic.__init__(self, db, fs, msg, auth)
1140
1141 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1142 raise EngineException(
1143 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1144 )
1145
1146 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1147 raise EngineException(
1148 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1149 )
1150
1151 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1152 # Not used because vnfrs are created and deleted by NsrTopic class directly
1153 raise EngineException(
1154 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1155 )
1156
1157
1158 class NsLcmOpTopic(BaseTopic):
1159 topic = "nslcmops"
1160 topic_msg = "ns"
1161 operation_schema = { # mapping between operation and jsonschema to validate
1162 "instantiate": ns_instantiate,
1163 "action": ns_action,
1164 "update": ns_update,
1165 "scale": ns_scale,
1166 "terminate": ns_terminate,
1167 "migrate": ns_migrate,
1168 }
1169
1170 def __init__(self, db, fs, msg, auth):
1171 BaseTopic.__init__(self, db, fs, msg, auth)
1172 self.nsrtopic = NsrTopic(db, fs, msg, auth)
1173
1174 def _check_ns_operation(self, session, nsr, operation, indata):
1175 """
1176 Check that user has enter right parameters for the operation
1177 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1178 :param operation: it can be: instantiate, terminate, action, update. TODO: heal
1179 :param indata: descriptor with the parameters of the operation
1180 :return: None
1181 """
1182 if operation == "action":
1183 self._check_action_ns_operation(indata, nsr)
1184 elif operation == "scale":
1185 self._check_scale_ns_operation(indata, nsr)
1186 elif operation == "update":
1187 self._check_update_ns_operation(indata, nsr)
1188 elif operation == "instantiate":
1189 self._check_instantiate_ns_operation(indata, nsr, session)
1190
1191 def _check_action_ns_operation(self, indata, nsr):
1192 nsd = nsr["nsd"]
1193 # check vnf_member_index
1194 if indata.get("vnf_member_index"):
1195 indata["member_vnf_index"] = indata.pop(
1196 "vnf_member_index"
1197 ) # for backward compatibility
1198 if indata.get("member_vnf_index"):
1199 vnfd = self._get_vnfd_from_vnf_member_index(
1200 indata["member_vnf_index"], nsr["_id"]
1201 )
1202 try:
1203 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1204 "operate-vnf-op-config"
1205 ]["day1-2"]
1206 except Exception:
1207 configs = []
1208
1209 if indata.get("vdu_id"):
1210 self._check_valid_vdu(vnfd, indata["vdu_id"])
1211 descriptor_configuration = utils.find_in_list(
1212 configs, lambda config: config["id"] == indata["vdu_id"]
1213 )
1214 elif indata.get("kdu_name"):
1215 self._check_valid_kdu(vnfd, indata["kdu_name"])
1216 descriptor_configuration = utils.find_in_list(
1217 configs, lambda config: config["id"] == indata.get("kdu_name")
1218 )
1219 else:
1220 descriptor_configuration = utils.find_in_list(
1221 configs, lambda config: config["id"] == vnfd["id"]
1222 )
1223 if descriptor_configuration is not None:
1224 descriptor_configuration = descriptor_configuration.get(
1225 "config-primitive"
1226 )
1227 else: # use a NSD
1228 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1229 "config-primitive"
1230 )
1231
1232 # For k8s allows default primitives without validating the parameters
1233 if indata.get("kdu_name") and indata["primitive"] in (
1234 "upgrade",
1235 "rollback",
1236 "status",
1237 "inspect",
1238 "readme",
1239 ):
1240 # TODO should be checked that rollback only can contains revsision_numbe????
1241 if not indata.get("member_vnf_index"):
1242 raise EngineException(
1243 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1244 indata["primitive"]
1245 )
1246 )
1247 return
1248 # if not, check primitive
1249 for config_primitive in get_iterable(descriptor_configuration):
1250 if indata["primitive"] == config_primitive["name"]:
1251 # check needed primitive_params are provided
1252 if indata.get("primitive_params"):
1253 in_primitive_params_copy = copy(indata["primitive_params"])
1254 else:
1255 in_primitive_params_copy = {}
1256 for paramd in get_iterable(config_primitive.get("parameter")):
1257 if paramd["name"] in in_primitive_params_copy:
1258 del in_primitive_params_copy[paramd["name"]]
1259 elif not paramd.get("default-value"):
1260 raise EngineException(
1261 "Needed parameter {} not provided for primitive '{}'".format(
1262 paramd["name"], indata["primitive"]
1263 )
1264 )
1265 # check no extra primitive params are provided
1266 if in_primitive_params_copy:
1267 raise EngineException(
1268 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1269 list(in_primitive_params_copy.keys()), indata["primitive"]
1270 )
1271 )
1272 break
1273 else:
1274 raise EngineException(
1275 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1276 indata["primitive"]
1277 )
1278 )
1279
1280 def _check_update_ns_operation(self, indata, nsr) -> None:
1281 """Validates the ns-update request according to updateType
1282
1283 If updateType is CHANGE_VNFPKG:
1284 - it checks the vnfInstanceId, whether it's available under ns instance
1285 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1286 Otherwise exception will be raised.
1287 If updateType is REMOVE_VNF:
1288 - it checks if the vnfInstanceId is available in the ns instance
1289 - Otherwise exception will be raised.
1290
1291 Args:
1292 indata: includes updateType such as CHANGE_VNFPKG,
1293 nsr: network service record
1294
1295 Raises:
1296 EngineException:
1297 a meaningful error if given update parameters are not proper such as
1298 "Error in validating ns-update request: <ID> does not match
1299 with the vnfd-id of vnfinstance
1300 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1301
1302 """
1303 try:
1304 if indata["updateType"] == "CHANGE_VNFPKG":
1305 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1306 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1307 ns_instance_id = indata["nsInstanceId"]
1308 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1309
1310 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1311
1312 raise EngineException(
1313 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1314 f"belong to NS {ns_instance_id}",
1315 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1316 )
1317
1318 # Getting vnfrs through the ns_instance_id
1319 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1320 constituent_vnfd_id = next(
1321 (
1322 vnfr["vnfd-id"]
1323 for vnfr in vnfrs
1324 if vnfr["id"] == vnf_instance_id
1325 ),
1326 None,
1327 )
1328
1329 # Check the given vnfd-id belongs to given vnf instance
1330 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
1331
1332 raise EngineException(
1333 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1334 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1335 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1336 )
1337
1338 # Validating the ns update timeout
1339 if (
1340 indata.get("timeout_ns_update")
1341 and indata["timeout_ns_update"] < 300
1342 ):
1343 raise EngineException(
1344 "Error in validating ns-update request: {} second is not enough "
1345 "to upgrade the VNF instance: {}".format(
1346 indata["timeout_ns_update"], vnf_instance_id
1347 ),
1348 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1349 )
1350 elif indata["updateType"] == "REMOVE_VNF":
1351 vnf_instance_id = indata["removeVnfInstanceId"]
1352 ns_instance_id = indata["nsInstanceId"]
1353 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1354 raise EngineException(
1355 "Invalid VNF Instance Id. '{}' is not "
1356 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1357 )
1358
1359 except (
1360 DbException,
1361 AttributeError,
1362 IndexError,
1363 KeyError,
1364 ValueError,
1365 ) as e:
1366 raise type(e)(
1367 "Ns update request could not be processed with error: {}.".format(e)
1368 )
1369
1370 def _check_scale_ns_operation(self, indata, nsr):
1371 vnfd = self._get_vnfd_from_vnf_member_index(
1372 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1373 )
1374 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
1375 if (
1376 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1377 == scaling_aspect["id"]
1378 ):
1379 break
1380 else:
1381 raise EngineException(
1382 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1383 "present at vnfd:scaling-aspect".format(
1384 indata["scaleVnfData"]["scaleByStepData"][
1385 "scaling-group-descriptor"
1386 ]
1387 )
1388 )
1389
1390 def _check_instantiate_ns_operation(self, indata, nsr, session):
1391 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
1392 vim_accounts = []
1393 wim_accounts = []
1394 nsd = nsr["nsd"]
1395 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1396 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1397 for in_vnf in get_iterable(indata.get("vnf")):
1398 member_vnf_index = in_vnf["member-vnf-index"]
1399 if vnf_member_index_to_vnfd.get(member_vnf_index):
1400 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
1401 else:
1402 vnfd = self._get_vnfd_from_vnf_member_index(
1403 member_vnf_index, nsr["_id"]
1404 )
1405 vnf_member_index_to_vnfd[
1406 member_vnf_index
1407 ] = vnfd # add to cache, avoiding a later look for
1408 self._check_vnf_instantiation_params(in_vnf, vnfd)
1409 if in_vnf.get("vimAccountId"):
1410 self._check_valid_vim_account(
1411 in_vnf["vimAccountId"], vim_accounts, session
1412 )
1413
1414 for in_vld in get_iterable(indata.get("vld")):
1415 self._check_valid_wim_account(
1416 in_vld.get("wimAccountId"), wim_accounts, session
1417 )
1418 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1419 if in_vld["name"] == vldd["id"]:
1420 break
1421 else:
1422 raise EngineException(
1423 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1424 in_vld["name"]
1425 )
1426 )
1427
1428 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1429 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1430 vnfr = self.db.get_one(
1431 "vnfrs",
1432 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1433 fail_on_empty=False,
1434 )
1435 if not vnfr:
1436 raise EngineException(
1437 "Invalid parameter member_vnf_index='{}' is not one of the "
1438 "nsd:constituent-vnfd".format(member_vnf_index)
1439 )
1440
1441 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1442 if "revision" in vnfr:
1443 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
1444 vnfd = self.db.get_one("vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False)
1445 else:
1446 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1447
1448 if not vnfd:
1449 raise EngineException(
1450 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1451 vnfr["vnfd-id"]
1452 )
1453 )
1454 return vnfd
1455
1456 def _check_valid_vdu(self, vnfd, vdu_id):
1457 for vdud in get_iterable(vnfd.get("vdu")):
1458 if vdud["id"] == vdu_id:
1459 return vdud
1460 else:
1461 raise EngineException(
1462 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1463 vdu_id
1464 )
1465 )
1466
1467 def _check_valid_kdu(self, vnfd, kdu_name):
1468 for kdud in get_iterable(vnfd.get("kdu")):
1469 if kdud["name"] == kdu_name:
1470 return kdud
1471 else:
1472 raise EngineException(
1473 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1474 kdu_name
1475 )
1476 )
1477
1478 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1479 for in_vdu in get_iterable(in_vnf.get("vdu")):
1480 for vdu in get_iterable(vnfd.get("vdu")):
1481 if in_vdu["id"] == vdu["id"]:
1482 for volume in get_iterable(in_vdu.get("volume")):
1483 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1484 if volumed["id"] == volume["name"]:
1485 break
1486 else:
1487 raise EngineException(
1488 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1489 "volume:name='{}' is not present at "
1490 "vnfd:vdu:virtual-storage-desc list".format(
1491 in_vnf["member-vnf-index"],
1492 in_vdu["id"],
1493 volume["id"],
1494 )
1495 )
1496
1497 vdu_if_names = set()
1498 for cpd in get_iterable(vdu.get("int-cpd")):
1499 for iface in get_iterable(
1500 cpd.get("virtual-network-interface-requirement")
1501 ):
1502 vdu_if_names.add(iface.get("name"))
1503
1504 for in_iface in get_iterable(in_vdu["interface"]):
1505 if in_iface["name"] in vdu_if_names:
1506 break
1507 else:
1508 raise EngineException(
1509 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1510 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1511 in_vnf["member-vnf-index"],
1512 in_vdu["id"],
1513 in_iface["name"],
1514 )
1515 )
1516 break
1517
1518 else:
1519 raise EngineException(
1520 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1521 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1522 )
1523
1524 vnfd_ivlds_cpds = {
1525 ivld.get("id"): set()
1526 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1527 }
1528 for vdu in get_iterable(vnfd.get("vdu")):
1529 for cpd in get_iterable(vnfd.get("int-cpd")):
1530 if cpd.get("int-virtual-link-desc"):
1531 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1532
1533 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1534 if in_ivld.get("name") in vnfd_ivlds_cpds:
1535 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1536 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
1537 break
1538 else:
1539 raise EngineException(
1540 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1541 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1542 "vnfd:internal-vld:name/id:internal-connection-point".format(
1543 in_vnf["member-vnf-index"],
1544 in_ivld["name"],
1545 in_icp["id-ref"],
1546 )
1547 )
1548 else:
1549 raise EngineException(
1550 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1551 " is not present at vnfd '{}'".format(
1552 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1553 )
1554 )
1555
1556 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1557 if vim_account in vim_accounts:
1558 return
1559 try:
1560 db_filter = self._get_project_filter(session)
1561 db_filter["_id"] = vim_account
1562 self.db.get_one("vim_accounts", db_filter)
1563 except Exception:
1564 raise EngineException(
1565 "Invalid vimAccountId='{}' not present for the project".format(
1566 vim_account
1567 )
1568 )
1569 vim_accounts.append(vim_account)
1570
1571 def _get_vim_account(self, vim_id: str, session):
1572 try:
1573 db_filter = self._get_project_filter(session)
1574 db_filter["_id"] = vim_id
1575 return self.db.get_one("vim_accounts", db_filter)
1576 except Exception:
1577 raise EngineException(
1578 "Invalid vimAccountId='{}' not present for the project".format(
1579 vim_id
1580 )
1581 )
1582
1583 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1584 if not isinstance(wim_account, str):
1585 return
1586 if wim_account in wim_accounts:
1587 return
1588 try:
1589 db_filter = self._get_project_filter(session, write=False, show_all=True)
1590 db_filter["_id"] = wim_account
1591 self.db.get_one("wim_accounts", db_filter)
1592 except Exception:
1593 raise EngineException(
1594 "Invalid wimAccountId='{}' not present for the project".format(
1595 wim_account
1596 )
1597 )
1598 wim_accounts.append(wim_account)
1599
1600 def _look_for_pdu(
1601 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1602 ):
1603 """
1604 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1605 (ip_address, ...) information.
1606 Modifies PDU _admin.usageState to 'IN_USE'
1607 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1608 :param rollback: list with the database modifications to rollback if needed
1609 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1610 :param vim_account: vim_account where this vnfr should be deployed
1611 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1612 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1613 of the changed vnfr is needed
1614
1615 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1616 "vim-network-name": used at VIM
1617 "name": interface name
1618 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1619 "ns-vld-id": NSD vld where this interface is connected.
1620 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1621 """
1622
1623 ifaces_forcing_vim_network = []
1624 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1625 if not vdur.get("pdu-type"):
1626 continue
1627 pdu_type = vdur.get("pdu-type")
1628 pdu_filter = self._get_project_filter(session)
1629 pdu_filter["vim_accounts"] = vim_account
1630 pdu_filter["type"] = pdu_type
1631 pdu_filter["_admin.operationalState"] = "ENABLED"
1632 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
1633 # TODO feature 1417: "shared": True,
1634
1635 available_pdus = self.db.get_list("pdus", pdu_filter)
1636 for pdu in available_pdus:
1637 # step 1 check if this pdu contains needed interfaces:
1638 match_interfaces = True
1639 for vdur_interface in vdur["interfaces"]:
1640 for pdu_interface in pdu["interfaces"]:
1641 if pdu_interface["name"] == vdur_interface["name"]:
1642 # TODO feature 1417: match per mgmt type
1643 break
1644 else: # no interface found for name
1645 match_interfaces = False
1646 break
1647 if match_interfaces:
1648 break
1649 else:
1650 raise EngineException(
1651 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1652 "names".format(
1653 pdu_type,
1654 vim_account,
1655 vnfr["member-vnf-index-ref"],
1656 vdur["vdu-id-ref"],
1657 )
1658 )
1659
1660 # step 2. Update pdu
1661 rollback_pdu = {
1662 "_admin.usageState": pdu["_admin"]["usageState"],
1663 "_admin.usage.vnfr_id": None,
1664 "_admin.usage.nsr_id": None,
1665 "_admin.usage.vdur": None,
1666 }
1667 self.db.set_one(
1668 "pdus",
1669 {"_id": pdu["_id"]},
1670 {
1671 "_admin.usageState": "IN_USE",
1672 "_admin.usage": {
1673 "vnfr_id": vnfr["_id"],
1674 "nsr_id": vnfr["nsr-id-ref"],
1675 "vdur": vdur["vdu-id-ref"],
1676 },
1677 },
1678 )
1679 rollback.append(
1680 {
1681 "topic": "pdus",
1682 "_id": pdu["_id"],
1683 "operation": "set",
1684 "content": rollback_pdu,
1685 }
1686 )
1687
1688 # step 3. Fill vnfr info by filling vdur
1689 vdu_text = "vdur.{}".format(vdur_index)
1690 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
1691 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1692 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1693 for pdu_interface in pdu["interfaces"]:
1694 if pdu_interface["name"] == vdur_interface["name"]:
1695 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1696 for k, v in pdu_interface.items():
1697 if k in (
1698 "ip-address",
1699 "mac-address",
1700 ): # TODO: switch-xxxxx must be inserted
1701 vnfr_update[iface_text + ".{}".format(k)] = v
1702 vnfr_update_rollback[
1703 iface_text + ".{}".format(k)
1704 ] = vdur_interface.get(v)
1705 if pdu_interface.get("ip-address"):
1706 if vdur_interface.get(
1707 "mgmt-interface"
1708 ) or vdur_interface.get("mgmt-vnf"):
1709 vnfr_update_rollback[
1710 vdu_text + ".ip-address"
1711 ] = vdur.get("ip-address")
1712 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1713 "ip-address"
1714 ]
1715 if vdur_interface.get("mgmt-vnf"):
1716 vnfr_update_rollback["ip-address"] = vnfr.get(
1717 "ip-address"
1718 )
1719 vnfr_update["ip-address"] = pdu_interface["ip-address"]
1720 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1721 "ip-address"
1722 ]
1723 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1724 "vim-network-id"
1725 ):
1726 ifaces_forcing_vim_network.append(
1727 {
1728 "name": vdur_interface.get("vnf-vld-id")
1729 or vdur_interface.get("ns-vld-id"),
1730 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1731 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1732 }
1733 )
1734 if pdu_interface.get("vim-network-id"):
1735 ifaces_forcing_vim_network[-1][
1736 "vim-network-id"
1737 ] = pdu_interface["vim-network-id"]
1738 if pdu_interface.get("vim-network-name"):
1739 ifaces_forcing_vim_network[-1][
1740 "vim-network-name"
1741 ] = pdu_interface["vim-network-name"]
1742 break
1743
1744 return ifaces_forcing_vim_network
1745
1746 def _look_for_k8scluster(
1747 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1748 ):
1749 """
1750 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1751 Fills vnfr.kdur with the selected k8scluster
1752
1753 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1754 :param rollback: list with the database modifications to rollback if needed
1755 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1756 :param vim_account: vim_account where this vnfr should be deployed
1757 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1758 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1759 of the changed vnfr is needed
1760
1761 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1762 "vim-network-name": used at VIM
1763 "name": interface name
1764 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1765 "ns-vld-id": NSD vld where this interface is connected.
1766 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1767 """
1768
1769 ifaces_forcing_vim_network = []
1770 if not vnfr.get("kdur"):
1771 return ifaces_forcing_vim_network
1772
1773 kdu_filter = self._get_project_filter(session)
1774 kdu_filter["vim_account"] = vim_account
1775 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1776 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1777
1778 k8s_requirements = {} # just for logging
1779 for k8scluster in available_k8sclusters:
1780 if not vnfr.get("k8s-cluster"):
1781 break
1782 # restrict by cni
1783 if vnfr["k8s-cluster"].get("cni"):
1784 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
1785 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1786 k8scluster.get("cni", ())
1787 ):
1788 continue
1789 # restrict by version
1790 if vnfr["k8s-cluster"].get("version"):
1791 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1792 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1793 continue
1794 # restrict by number of networks
1795 if vnfr["k8s-cluster"].get("nets"):
1796 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
1797 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1798 vnfr["k8s-cluster"]["nets"]
1799 ):
1800 continue
1801 break
1802 else:
1803 raise EngineException(
1804 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1805 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1806 )
1807 )
1808
1809 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
1810 # step 3. Fill vnfr info by filling kdur
1811 kdu_text = "kdur.{}.".format(kdur_index)
1812 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1813 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1814
1815 # step 4. Check VIM networks that forces the selected k8s_cluster
1816 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1817 k8scluster_net_list = list(k8scluster.get("nets").keys())
1818 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1819 # get a network from k8s_cluster nets. If name matches use this, if not use other
1820 if kdur_net["id"] in k8scluster_net_list: # name matches
1821 vim_net = k8scluster["nets"][kdur_net["id"]]
1822 k8scluster_net_list.remove(kdur_net["id"])
1823 else:
1824 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1825 k8scluster_net_list.pop(0)
1826 vnfr_update_rollback[
1827 "k8s-cluster.nets.{}.vim_net".format(net_index)
1828 ] = None
1829 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
1830 if vim_net and (
1831 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1832 ):
1833 ifaces_forcing_vim_network.append(
1834 {
1835 "name": kdur_net.get("vnf-vld-id")
1836 or kdur_net.get("ns-vld-id"),
1837 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1838 "ns-vld-id": kdur_net.get("ns-vld-id"),
1839 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1840 }
1841 )
1842 # TODO check that this forcing is not incompatible with other forcing
1843 return ifaces_forcing_vim_network
1844
1845 def _update_vnfrs_from_nsd(self, nsr):
1846 try:
1847 nsr_id = nsr["_id"]
1848 nsd = nsr["nsd"]
1849
1850 step = "Getting vnf_profiles from nsd"
1851 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1852 vld_fixed_ip_connection_point_data = {}
1853
1854 step = "Getting ip-address info from vnf_profile if it exists"
1855 for vnfp in vnf_profiles:
1856 # Checking ip-address info from nsd.vnf_profile and storing
1857 for vlc in vnfp.get("virtual-link-connectivity", ()):
1858 for cpd in vlc.get("constituent-cpd-id", ()):
1859 if cpd.get("ip-address"):
1860 step = "Storing ip-address info"
1861 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1862 "vnfd-connection-point-ref": cpd.get(
1863 "constituent-cpd-id"),
1864 "ip-address": cpd.get(
1865 "ip-address")}})
1866
1867 # Inserting ip address to vnfr
1868 if len(vld_fixed_ip_connection_point_data) > 0:
1869 step = "Getting vnfrs"
1870 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1871 for item in vld_fixed_ip_connection_point_data.keys():
1872 step = "Filtering vnfrs"
1873 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1874 if vnfr:
1875 vnfr_update = {}
1876 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1877 for iface_index, iface in enumerate(vdur["interfaces"]):
1878 step = "Looking for matched interface"
1879 if (
1880 iface.get("external-connection-point-ref")
1881 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1882 iface.get("ns-vld-id") == item.split('.')[0]
1883
1884 ):
1885 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1886 vdur_index, iface_index
1887 )
1888 step = "Storing info in order to update vnfr"
1889 vnfr_update[
1890 vnfr_update_text + ".ip-address"
1891 ] = increment_ip_mac(
1892 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1893 vdur.get("count-index", 0), )
1894 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1895
1896 step = "updating vnfr at database"
1897 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1898 except (
1899 ValidationError,
1900 EngineException,
1901 DbException,
1902 MsgException,
1903 FsException,
1904 ) as e:
1905 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1906
1907 def _update_vnfrs(self, session, rollback, nsr, indata):
1908 # get vnfr
1909 nsr_id = nsr["_id"]
1910 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1911
1912 for vnfr in vnfrs:
1913 vnfr_update = {}
1914 vnfr_update_rollback = {}
1915 member_vnf_index = vnfr["member-vnf-index-ref"]
1916 # update vim-account-id
1917
1918 vim_account = indata["vimAccountId"]
1919 vca_id = self._get_vim_account(vim_account, session).get("vca")
1920 # check instantiate parameters
1921 for vnf_inst_params in get_iterable(indata.get("vnf")):
1922 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1923 continue
1924 if vnf_inst_params.get("vimAccountId"):
1925 vim_account = vnf_inst_params.get("vimAccountId")
1926 vca_id = self._get_vim_account(vim_account, session).get("vca")
1927
1928 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1929 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1930 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1931 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1932 continue
1933 for iface_inst_param in get_iterable(
1934 vdu_inst_param.get("interface")
1935 ):
1936 iface_index, _ = next(
1937 i
1938 for i in enumerate(vdur["interfaces"])
1939 if i[1]["name"] == iface_inst_param["name"]
1940 )
1941 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1942 vdur_index, iface_index
1943 )
1944 if iface_inst_param.get("ip-address"):
1945 vnfr_update[
1946 vnfr_update_text + ".ip-address"
1947 ] = increment_ip_mac(
1948 iface_inst_param.get("ip-address"),
1949 vdur.get("count-index", 0),
1950 )
1951 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1952 if iface_inst_param.get("mac-address"):
1953 vnfr_update[
1954 vnfr_update_text + ".mac-address"
1955 ] = increment_ip_mac(
1956 iface_inst_param.get("mac-address"),
1957 vdur.get("count-index", 0),
1958 )
1959 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1960 if iface_inst_param.get("floating-ip-required"):
1961 vnfr_update[
1962 vnfr_update_text + ".floating-ip-required"
1963 ] = True
1964 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1965 # TODO update vld with the ip-profile
1966 for ivld_inst_param in get_iterable(
1967 vnf_inst_params.get("internal-vld")
1968 ):
1969 for icp_inst_param in get_iterable(
1970 ivld_inst_param.get("internal-connection-point")
1971 ):
1972 # look for iface
1973 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1974 for iface_index, iface in enumerate(vdur["interfaces"]):
1975 if (
1976 iface.get("internal-connection-point-ref")
1977 == icp_inst_param["id-ref"]
1978 ):
1979 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1980 vdur_index, iface_index
1981 )
1982 if icp_inst_param.get("ip-address"):
1983 vnfr_update[
1984 vnfr_update_text + ".ip-address"
1985 ] = increment_ip_mac(
1986 icp_inst_param.get("ip-address"),
1987 vdur.get("count-index", 0),
1988 )
1989 vnfr_update[
1990 vnfr_update_text + ".fixed-ip"
1991 ] = True
1992 if icp_inst_param.get("mac-address"):
1993 vnfr_update[
1994 vnfr_update_text + ".mac-address"
1995 ] = increment_ip_mac(
1996 icp_inst_param.get("mac-address"),
1997 vdur.get("count-index", 0),
1998 )
1999 vnfr_update[
2000 vnfr_update_text + ".fixed-mac"
2001 ] = True
2002 break
2003 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2004 for vld_inst_param in get_iterable(indata.get("vld")):
2005 for vnfcp_inst_param in get_iterable(
2006 vld_inst_param.get("vnfd-connection-point-ref")
2007 ):
2008 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2009 continue
2010 # look for iface
2011 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2012 for iface_index, iface in enumerate(vdur["interfaces"]):
2013 if (
2014 iface.get("external-connection-point-ref")
2015 == vnfcp_inst_param["vnfd-connection-point-ref"]
2016 ):
2017 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2018 vdur_index, iface_index
2019 )
2020 if vnfcp_inst_param.get("ip-address"):
2021 vnfr_update[
2022 vnfr_update_text + ".ip-address"
2023 ] = increment_ip_mac(
2024 vnfcp_inst_param.get("ip-address"),
2025 vdur.get("count-index", 0),
2026 )
2027 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
2028 if vnfcp_inst_param.get("mac-address"):
2029 vnfr_update[
2030 vnfr_update_text + ".mac-address"
2031 ] = increment_ip_mac(
2032 vnfcp_inst_param.get("mac-address"),
2033 vdur.get("count-index", 0),
2034 )
2035 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
2036 break
2037
2038 vnfr_update["vim-account-id"] = vim_account
2039 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2040
2041 if vca_id:
2042 vnfr_update["vca-id"] = vca_id
2043 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2044
2045 # get pdu
2046 ifaces_forcing_vim_network = self._look_for_pdu(
2047 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2048 )
2049
2050 # get kdus
2051 ifaces_forcing_vim_network += self._look_for_k8scluster(
2052 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2053 )
2054 # update database vnfr
2055 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
2056 rollback.append(
2057 {
2058 "topic": "vnfrs",
2059 "_id": vnfr["_id"],
2060 "operation": "set",
2061 "content": vnfr_update_rollback,
2062 }
2063 )
2064
2065 # Update indada in case pdu forces to use a concrete vim-network-name
2066 # TODO check if user has already insert a vim-network-name and raises an error
2067 if not ifaces_forcing_vim_network:
2068 continue
2069 for iface_info in ifaces_forcing_vim_network:
2070 if iface_info.get("ns-vld-id"):
2071 if "vld" not in indata:
2072 indata["vld"] = []
2073 indata["vld"].append(
2074 {
2075 key: iface_info[key]
2076 for key in ("name", "vim-network-name", "vim-network-id")
2077 if iface_info.get(key)
2078 }
2079 )
2080
2081 elif iface_info.get("vnf-vld-id"):
2082 if "vnf" not in indata:
2083 indata["vnf"] = []
2084 indata["vnf"].append(
2085 {
2086 "member-vnf-index": member_vnf_index,
2087 "internal-vld": [
2088 {
2089 key: iface_info[key]
2090 for key in (
2091 "name",
2092 "vim-network-name",
2093 "vim-network-id",
2094 )
2095 if iface_info.get(key)
2096 }
2097 ],
2098 }
2099 )
2100
2101 @staticmethod
2102 def _create_nslcmop(nsr_id, operation, params):
2103 """
2104 Creates a ns-lcm-opp content to be stored at database.
2105 :param nsr_id: internal id of the instance
2106 :param operation: instantiate, terminate, scale, action, update ...
2107 :param params: user parameters for the operation
2108 :return: dictionary following SOL005 format
2109 """
2110 now = time()
2111 _id = str(uuid4())
2112 nslcmop = {
2113 "id": _id,
2114 "_id": _id,
2115 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2116 "queuePosition": None,
2117 "stage": None,
2118 "errorMessage": None,
2119 "detailedStatus": None,
2120 "statusEnteredTime": now,
2121 "nsInstanceId": nsr_id,
2122 "lcmOperationType": operation,
2123 "startTime": now,
2124 "isAutomaticInvocation": False,
2125 "operationParams": params,
2126 "isCancelPending": False,
2127 "links": {
2128 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
2129 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
2130 },
2131 }
2132 return nslcmop
2133
2134 def _get_enabled_vims(self, session):
2135 """
2136 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2137 :param session: current session with user information
2138 """
2139 db_filter = self._get_project_filter(session)
2140 db_filter["_admin.operationalState"] = "ENABLED"
2141 vims = self.db.get_list("vim_accounts", db_filter)
2142 vimAccounts = []
2143 for vim in vims:
2144 vimAccounts.append(vim["_id"])
2145 return vimAccounts
2146
2147 def new(
2148 self,
2149 rollback,
2150 session,
2151 indata=None,
2152 kwargs=None,
2153 headers=None,
2154 slice_object=False,
2155 ):
2156 """
2157 Performs a new operation over a ns
2158 :param rollback: list to append created items at database in case a rollback must to be done
2159 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2160 :param indata: descriptor with the parameters of the operation. It must contains among others
2161 nsInstanceId: _id of the nsr to perform the operation
2162 operation: it can be: instantiate, terminate, action, update TODO: heal
2163 :param kwargs: used to override the indata descriptor
2164 :param headers: http request headers
2165 :return: id of the nslcmops
2166 """
2167
2168 def check_if_nsr_is_not_slice_member(session, nsr_id):
2169 nsis = None
2170 db_filter = self._get_project_filter(session)
2171 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2172 nsis = self.db.get_one(
2173 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2174 )
2175 if nsis:
2176 raise EngineException(
2177 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2178 nsr_id, nsis["_id"]
2179 ),
2180 http_code=HTTPStatus.CONFLICT,
2181 )
2182
2183 try:
2184 # Override descriptor with query string kwargs
2185 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
2186 operation = indata["lcmOperationType"]
2187 nsInstanceId = indata["nsInstanceId"]
2188
2189 validate_input(indata, self.operation_schema[operation])
2190 # get ns from nsr_id
2191 _filter = BaseTopic._get_project_filter(session)
2192 _filter["_id"] = nsInstanceId
2193 nsr = self.db.get_one("nsrs", _filter)
2194
2195 # initial checking
2196 if operation == "terminate" and slice_object is False:
2197 check_if_nsr_is_not_slice_member(session, nsr["_id"])
2198 if (
2199 not nsr["_admin"].get("nsState")
2200 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2201 ):
2202 if operation == "terminate" and indata.get("autoremove"):
2203 # NSR must be deleted
2204 return (
2205 None,
2206 None,
2207 ) # a none in this case is used to indicate not instantiated. It can be removed
2208 if operation != "instantiate":
2209 raise EngineException(
2210 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2211 nsInstanceId, operation
2212 ),
2213 HTTPStatus.CONFLICT,
2214 )
2215 else:
2216 if operation == "instantiate" and not session["force"]:
2217 raise EngineException(
2218 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2219 nsInstanceId, operation
2220 ),
2221 HTTPStatus.CONFLICT,
2222 )
2223 self._check_ns_operation(session, nsr, operation, indata)
2224 if (indata.get("primitive_params")):
2225 indata["primitive_params"] = json.dumps(indata["primitive_params"])
2226 elif (indata.get("additionalParamsForVnf")):
2227 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
2228
2229 if operation == "instantiate":
2230 self._update_vnfrs_from_nsd(nsr)
2231 self._update_vnfrs(session, rollback, nsr, indata)
2232 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2233 nsr_update = {}
2234 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2235 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2236 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2237 ns_request = nsr["instantiate_params"]
2238 vnfr = self.db.get_one("vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]})
2239 latest_vnfd_revision = vnfd["_admin"].get("revision", 1)
2240 vnfr_vnfd_revision = vnfr.get("revision", 1)
2241 if latest_vnfd_revision != vnfr_vnfd_revision:
2242 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
2243 old_db_vnfd = self.db.get_one("vnfds_revisions", {"_id": old_vnfd_id})
2244 old_sw_version = old_db_vnfd.get("software-version", "1.0")
2245 new_sw_version = vnfd.get("software-version", "1.0")
2246 if new_sw_version != old_sw_version:
2247 vnf_index = vnfr["member-vnf-index-ref"]
2248 self.logger.info("nsr {}".format(nsr))
2249 for vdu in vnfd["vdu"]:
2250 self.nsrtopic._add_flavor_to_nsr(vdu, vnfd, nsr)
2251 sw_image_id = vdu.get("sw-image-desc")
2252 if sw_image_id:
2253 image_data = self.nsrtopic._get_image_data_from_vnfd(vnfd, sw_image_id)
2254 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2255 for alt_image in vdu.get("alternative-sw-image-desc", ()):
2256 image_data = self.nsrtopic._get_image_data_from_vnfd(vnfd, alt_image)
2257 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2258 nsr_update["image"] = nsr["image"]
2259 nsr_update["flavor"] = nsr["flavor"]
2260 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
2261 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(nsd, ns_request, session)
2262 vnfr_descriptor = self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2263 nsd,
2264 vnfd,
2265 vnfd_id,
2266 vnf_index,
2267 nsr,
2268 ns_request,
2269 ns_k8s_namespace,
2270 )
2271 indata["newVdur"] = vnfr_descriptor["vdur"]
2272 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
2273 _id = nslcmop_desc["_id"]
2274 self.format_on_new(
2275 nslcmop_desc, session["project_id"], make_public=session["public"]
2276 )
2277 if indata.get("placement-engine"):
2278 # Save valid vim accounts in lcm operation descriptor
2279 nslcmop_desc["operationParams"][
2280 "validVimAccounts"
2281 ] = self._get_enabled_vims(session)
2282 self.db.create("nslcmops", nslcmop_desc)
2283 rollback.append({"topic": "nslcmops", "_id": _id})
2284 if not slice_object:
2285 self.msg.write("ns", operation, nslcmop_desc)
2286 return _id, None
2287 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
2288 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2289 # except DbException as e:
2290 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2291
2292 def delete(self, session, _id, dry_run=False, not_send_msg=None):
2293 raise EngineException(
2294 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2295 )
2296
2297 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2298 raise EngineException(
2299 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2300 )
2301
2302
2303 class NsiTopic(BaseTopic):
2304 topic = "nsis"
2305 topic_msg = "nsi"
2306 quota_name = "slice_instances"
2307
2308 def __init__(self, db, fs, msg, auth):
2309 BaseTopic.__init__(self, db, fs, msg, auth)
2310 self.nsrTopic = NsrTopic(db, fs, msg, auth)
2311
2312 @staticmethod
2313 def _format_ns_request(ns_request):
2314 formated_request = copy(ns_request)
2315 # TODO: Add request params
2316 return formated_request
2317
2318 @staticmethod
2319 def _format_addional_params(slice_request):
2320 """
2321 Get and format user additional params for NS or VNF
2322 :param slice_request: User instantiation additional parameters
2323 :return: a formatted copy of additional params or None if not supplied
2324 """
2325 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2326 if additional_params:
2327 for k, v in additional_params.items():
2328 if not isinstance(k, str):
2329 raise EngineException(
2330 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2331 k
2332 )
2333 )
2334 if "." in k or "$" in k:
2335 raise EngineException(
2336 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2337 k
2338 )
2339 )
2340 if isinstance(v, (dict, tuple, list)):
2341 additional_params[k] = "!!yaml " + safe_dump(v)
2342 return additional_params
2343
2344 def _check_descriptor_dependencies(self, session, descriptor):
2345 """
2346 Check that the dependent descriptors exist on a new descriptor or edition
2347 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2348 :param descriptor: descriptor to be inserted or edit
2349 :return: None or raises exception
2350 """
2351 if not descriptor.get("nst-ref"):
2352 return
2353 nstd_id = descriptor["nst-ref"]
2354 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
2355 raise EngineException(
2356 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2357 nstd_id
2358 ),
2359 http_code=HTTPStatus.CONFLICT,
2360 )
2361
2362 def check_conflict_on_del(self, session, _id, db_content):
2363 """
2364 Check that NSI is not instantiated
2365 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2366 :param _id: nsi internal id
2367 :param db_content: The database content of the _id
2368 :return: None or raises EngineException with the conflict
2369 """
2370 if session["force"]:
2371 return
2372 nsi = db_content
2373 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
2374 raise EngineException(
2375 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2376 "Launch 'terminate' operation first; or force deletion".format(_id),
2377 http_code=HTTPStatus.CONFLICT,
2378 )
2379
2380 def delete_extra(self, session, _id, db_content, not_send_msg=None):
2381 """
2382 Deletes associated nsilcmops from database. Deletes associated filesystem.
2383 Set usageState of nst
2384 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2385 :param _id: server internal id
2386 :param db_content: The database content of the descriptor
2387 :param not_send_msg: To not send message (False) or store content (list) instead
2388 :return: None if ok or raises EngineException with the problem
2389 """
2390
2391 # Deleting the nsrs belonging to nsir
2392 nsir = db_content
2393 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2394 nsr_id = nsrs_detailed_item["nsrId"]
2395 if nsrs_detailed_item.get("shared"):
2396 _filter = {
2397 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2398 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2399 "_id.ne": nsir["_id"],
2400 }
2401 nsi = self.db.get_one(
2402 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2403 )
2404 if nsi: # last one using nsr
2405 continue
2406 try:
2407 self.nsrTopic.delete(
2408 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2409 )
2410 except (DbException, EngineException) as e:
2411 if e.http_code == HTTPStatus.NOT_FOUND:
2412 pass
2413 else:
2414 raise
2415
2416 # delete related nsilcmops database entries
2417 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
2418
2419 # Check and set used NST usage state
2420 nsir_admin = nsir.get("_admin")
2421 if nsir_admin and nsir_admin.get("nst-id"):
2422 # check if used by another NSI
2423 nsis_list = self.db.get_one(
2424 "nsis",
2425 {"nst-id": nsir_admin["nst-id"]},
2426 fail_on_empty=False,
2427 fail_on_more=False,
2428 )
2429 if not nsis_list:
2430 self.db.set_one(
2431 "nsts",
2432 {"_id": nsir_admin["nst-id"]},
2433 {"_admin.usageState": "NOT_IN_USE"},
2434 )
2435
2436 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
2437 """
2438 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2439 :param rollback: list to append the created items at database in case a rollback must be done
2440 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2441 :param indata: params to be used for the nsir
2442 :param kwargs: used to override the indata descriptor
2443 :param headers: http request headers
2444 :return: the _id of nsi descriptor created at database
2445 """
2446
2447 try:
2448 step = "checking quotas"
2449 self.check_quota(session)
2450
2451 step = ""
2452 slice_request = self._remove_envelop(indata)
2453 # Override descriptor with query string kwargs
2454 self._update_input_with_kwargs(slice_request, kwargs)
2455 slice_request = self._validate_input_new(slice_request, session["force"])
2456
2457 # look for nstd
2458 step = "getting nstd id='{}' from database".format(
2459 slice_request.get("nstId")
2460 )
2461 _filter = self._get_project_filter(session)
2462 _filter["_id"] = slice_request["nstId"]
2463 nstd = self.db.get_one("nsts", _filter)
2464 # check NST is not disabled
2465 step = "checking NST operationalState"
2466 if nstd["_admin"]["operationalState"] == "DISABLED":
2467 raise EngineException(
2468 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2469 "instance".format(slice_request["nstId"]),
2470 http_code=HTTPStatus.CONFLICT,
2471 )
2472 del _filter["_id"]
2473
2474 # check NSD is not disabled
2475 step = "checking operationalState"
2476 if nstd["_admin"]["operationalState"] == "DISABLED":
2477 raise EngineException(
2478 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2479 "a network slice".format(slice_request["nstId"]),
2480 http_code=HTTPStatus.CONFLICT,
2481 )
2482
2483 nstd.pop("_admin", None)
2484 nstd_id = nstd.pop("_id", None)
2485 nsi_id = str(uuid4())
2486 step = "filling nsi_descriptor with input data"
2487
2488 # Creating the NSIR
2489 nsi_descriptor = {
2490 "id": nsi_id,
2491 "name": slice_request["nsiName"],
2492 "description": slice_request.get("nsiDescription", ""),
2493 "datacenter": slice_request["vimAccountId"],
2494 "nst-ref": nstd["id"],
2495 "instantiation_parameters": slice_request,
2496 "network-slice-template": nstd,
2497 "nsr-ref-list": [],
2498 "vlr-list": [],
2499 "_id": nsi_id,
2500 "additionalParamsForNsi": self._format_addional_params(slice_request),
2501 }
2502
2503 step = "creating nsi at database"
2504 self.format_on_new(
2505 nsi_descriptor, session["project_id"], make_public=session["public"]
2506 )
2507 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2508 nsi_descriptor["_admin"]["netslice-subnet"] = None
2509 nsi_descriptor["_admin"]["deployed"] = {}
2510 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2511 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2512
2513 # Creating netslice-vld for the RO.
2514 step = "creating netslice-vld at database"
2515
2516 # Building the vlds list to be deployed
2517 # From netslice descriptors, creating the initial list
2518 nsi_vlds = []
2519
2520 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2521 # Getting template Instantiation parameters from NST
2522 nsi_vld = deepcopy(netslice_vlds)
2523 nsi_vld["shared-nsrs-list"] = []
2524 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2525 nsi_vlds.append(nsi_vld)
2526
2527 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
2528 # Creating netslice-subnet_record.
2529 needed_nsds = {}
2530 services = []
2531
2532 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2533 for member_ns in nstd["netslice-subnet"]:
2534 nsd_id = member_ns["nsd-ref"]
2535 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
2536 member_ns["nsd-ref"], member_ns["id"]
2537 )
2538 if nsd_id not in needed_nsds:
2539 # Obtain nsd
2540 _filter["id"] = nsd_id
2541 nsd = self.db.get_one(
2542 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2543 )
2544 del _filter["id"]
2545 nsd.pop("_admin")
2546 needed_nsds[nsd_id] = nsd
2547 else:
2548 nsd = needed_nsds[nsd_id]
2549 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2550 services.append(member_ns)
2551
2552 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2553 member_ns["nsd-ref"], member_ns["id"]
2554 )
2555
2556 # creates Network Services records (NSRs)
2557 step = "creating nsrs at database using NsrTopic.new()"
2558 ns_params = slice_request.get("netslice-subnet")
2559 nsrs_list = []
2560 nsi_netslice_subnet = []
2561 for service in services:
2562 # Check if the netslice-subnet is shared and if it is share if the nss exists
2563 _id_nsr = None
2564 indata_ns = {}
2565 # Is the nss shared and instantiated?
2566 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2567 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2568 "nsd-ref"
2569 ]
2570 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
2571 nsi = self.db.get_one(
2572 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2573 )
2574 if nsi and service.get("is-shared-nss"):
2575 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2576 for nsrs_detailed_item in nsrs_detailed_list:
2577 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
2578 if nsrs_detailed_item["nss-id"] == service["id"]:
2579 _id_nsr = nsrs_detailed_item["nsrId"]
2580 break
2581 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2582 if netslice_subnet["nss-id"] == service["id"]:
2583 indata_ns = netslice_subnet
2584 break
2585 else:
2586 indata_ns = {}
2587 if service.get("instantiation-parameters"):
2588 indata_ns = deepcopy(service["instantiation-parameters"])
2589 # del service["instantiation-parameters"]
2590
2591 indata_ns["nsdId"] = service["_id"]
2592 indata_ns["nsName"] = (
2593 slice_request.get("nsiName") + "." + service["id"]
2594 )
2595 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2596 indata_ns["nsDescription"] = service["description"]
2597 if slice_request.get("ssh_keys"):
2598 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
2599
2600 if ns_params:
2601 for ns_param in ns_params:
2602 if ns_param.get("id") == service["id"]:
2603 copy_ns_param = deepcopy(ns_param)
2604 del copy_ns_param["id"]
2605 indata_ns.update(copy_ns_param)
2606 break
2607
2608 # Creates Nsr objects
2609 _id_nsr, _ = self.nsrTopic.new(
2610 rollback, session, indata_ns, kwargs, headers
2611 )
2612 nsrs_item = {
2613 "nsrId": _id_nsr,
2614 "shared": service.get("is-shared-nss"),
2615 "nsd-id": service["nsd-ref"],
2616 "nss-id": service["id"],
2617 "nslcmop_instantiate": None,
2618 }
2619 indata_ns["nss-id"] = service["id"]
2620 nsrs_list.append(nsrs_item)
2621 nsi_netslice_subnet.append(indata_ns)
2622 nsr_ref = {"nsr-ref": _id_nsr}
2623 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
2624
2625 # Adding the nsrs list to the nsi
2626 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
2627 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2628 self.db.set_one(
2629 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2630 )
2631
2632 # Creating the entry in the database
2633 self.db.create("nsis", nsi_descriptor)
2634 rollback.append({"topic": "nsis", "_id": nsi_id})
2635 return nsi_id, None
2636 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2637 self.logger.exception(
2638 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2639 )
2640 raise EngineException("Error {}: {}".format(step, e))
2641 except ValidationError as e:
2642 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2643
2644 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2645 raise EngineException(
2646 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2647 )
2648
2649
2650 class NsiLcmOpTopic(BaseTopic):
2651 topic = "nsilcmops"
2652 topic_msg = "nsi"
2653 operation_schema = { # mapping between operation and jsonschema to validate
2654 "instantiate": nsi_instantiate,
2655 "terminate": None,
2656 }
2657
2658 def __init__(self, db, fs, msg, auth):
2659 BaseTopic.__init__(self, db, fs, msg, auth)
2660 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
2661
2662 def _check_nsi_operation(self, session, nsir, operation, indata):
2663 """
2664 Check that user has enter right parameters for the operation
2665 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2666 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2667 :param indata: descriptor with the parameters of the operation
2668 :return: None
2669 """
2670 nsds = {}
2671 nstd = nsir["network-slice-template"]
2672
2673 def check_valid_netslice_subnet_id(nstId):
2674 # TODO change to vnfR (??)
2675 for netslice_subnet in nstd["netslice-subnet"]:
2676 if nstId == netslice_subnet["id"]:
2677 nsd_id = netslice_subnet["nsd-ref"]
2678 if nsd_id not in nsds:
2679 _filter = self._get_project_filter(session)
2680 _filter["id"] = nsd_id
2681 nsds[nsd_id] = self.db.get_one("nsds", _filter)
2682 return nsds[nsd_id]
2683 else:
2684 raise EngineException(
2685 "Invalid parameter nstId='{}' is not one of the "
2686 "nst:netslice-subnet".format(nstId)
2687 )
2688
2689 if operation == "instantiate":
2690 # check the existance of netslice-subnet items
2691 for in_nst in get_iterable(indata.get("netslice-subnet")):
2692 check_valid_netslice_subnet_id(in_nst["id"])
2693
2694 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2695 now = time()
2696 _id = str(uuid4())
2697 nsilcmop = {
2698 "id": _id,
2699 "_id": _id,
2700 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2701 "statusEnteredTime": now,
2702 "netsliceInstanceId": netsliceInstanceId,
2703 "lcmOperationType": operation,
2704 "startTime": now,
2705 "isAutomaticInvocation": False,
2706 "operationParams": params,
2707 "isCancelPending": False,
2708 "links": {
2709 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
2710 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2711 + netsliceInstanceId,
2712 },
2713 }
2714 return nsilcmop
2715
2716 def add_shared_nsr_2vld(self, nsir, nsr_item):
2717 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2718 if nst_sb_item.get("is-shared-nss"):
2719 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2720 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2721 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
2722 for admin_vld_nss_cp_ref_item in admin_vld_item[
2723 "nss-connection-point-ref"
2724 ]:
2725 if (
2726 admin_subnet_item["nss-id"]
2727 == admin_vld_nss_cp_ref_item["nss-ref"]
2728 ):
2729 if (
2730 not nsr_item["nsrId"]
2731 in admin_vld_item["shared-nsrs-list"]
2732 ):
2733 admin_vld_item["shared-nsrs-list"].append(
2734 nsr_item["nsrId"]
2735 )
2736 break
2737 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2738 self.db.set_one(
2739 "nsis",
2740 {"_id": nsir["_id"]},
2741 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2742 )
2743
2744 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
2745 """
2746 Performs a new operation over a ns
2747 :param rollback: list to append created items at database in case a rollback must to be done
2748 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2749 :param indata: descriptor with the parameters of the operation. It must contains among others
2750 netsliceInstanceId: _id of the nsir to perform the operation
2751 operation: it can be: instantiate, terminate, action, TODO: update, heal
2752 :param kwargs: used to override the indata descriptor
2753 :param headers: http request headers
2754 :return: id of the nslcmops
2755 """
2756 try:
2757 # Override descriptor with query string kwargs
2758 self._update_input_with_kwargs(indata, kwargs)
2759 operation = indata["lcmOperationType"]
2760 netsliceInstanceId = indata["netsliceInstanceId"]
2761 validate_input(indata, self.operation_schema[operation])
2762
2763 # get nsi from netsliceInstanceId
2764 _filter = self._get_project_filter(session)
2765 _filter["_id"] = netsliceInstanceId
2766 nsir = self.db.get_one("nsis", _filter)
2767 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
2768 del _filter["_id"]
2769
2770 # initial checking
2771 if (
2772 not nsir["_admin"].get("nsiState")
2773 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2774 ):
2775 if operation == "terminate" and indata.get("autoremove"):
2776 # NSIR must be deleted
2777 return (
2778 None,
2779 None,
2780 ) # a none in this case is used to indicate not instantiated. It can be removed
2781 if operation != "instantiate":
2782 raise EngineException(
2783 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2784 netsliceInstanceId, operation
2785 ),
2786 HTTPStatus.CONFLICT,
2787 )
2788 else:
2789 if operation == "instantiate" and not session["force"]:
2790 raise EngineException(
2791 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2792 netsliceInstanceId, operation
2793 ),
2794 HTTPStatus.CONFLICT,
2795 )
2796
2797 # Creating all the NS_operation (nslcmop)
2798 # Get service list from db
2799 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2800 nslcmops = []
2801 # nslcmops_item = None
2802 for index, nsr_item in enumerate(nsrs_list):
2803 nsr_id = nsr_item["nsrId"]
2804 if nsr_item.get("shared"):
2805 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2806 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2807 _filter[
2808 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2809 ] = None
2810 _filter["_id.ne"] = netsliceInstanceId
2811 nsi = self.db.get_one(
2812 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2813 )
2814 if operation == "terminate":
2815 _update = {
2816 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2817 index
2818 ): None
2819 }
2820 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2821 if (
2822 nsi
2823 ): # other nsi is using this nsr and it needs this nsr instantiated
2824 continue # do not create nsilcmop
2825 else: # instantiate
2826 # looks the first nsi fulfilling the conditions but not being the current NSIR
2827 if nsi:
2828 nsi_nsr_item = next(
2829 n
2830 for n in nsi["_admin"]["nsrs-detailed-list"]
2831 if n["nsrId"] == nsr_id
2832 and n["shared"]
2833 and n["nslcmop_instantiate"]
2834 )
2835 self.add_shared_nsr_2vld(nsir, nsr_item)
2836 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
2837 _update = {
2838 "_admin.nsrs-detailed-list.{}".format(
2839 index
2840 ): nsi_nsr_item
2841 }
2842 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2843 # continue to not create nslcmop since nsrs is shared and nsrs was created
2844 continue
2845 else:
2846 self.add_shared_nsr_2vld(nsir, nsr_item)
2847
2848 # create operation
2849 try:
2850 indata_ns = {
2851 "lcmOperationType": operation,
2852 "nsInstanceId": nsr_id,
2853 # Including netslice_id in the ns instantiate Operation
2854 "netsliceInstanceId": netsliceInstanceId,
2855 }
2856 if operation == "instantiate":
2857 service = self.db.get_one("nsrs", {"_id": nsr_id})
2858 indata_ns.update(service["instantiate_params"])
2859
2860 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2861 # message via kafka bus
2862 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2863 rollback, session, indata_ns, None, headers, slice_object=True
2864 )
2865 nslcmops.append(nslcmop)
2866 if operation == "instantiate":
2867 _update = {
2868 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2869 index
2870 ): nslcmop
2871 }
2872 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2873 except (DbException, EngineException) as e:
2874 if e.http_code == HTTPStatus.NOT_FOUND:
2875 self.logger.info(
2876 logging_prefix
2877 + "skipping NS={} because not found".format(nsr_id)
2878 )
2879 pass
2880 else:
2881 raise
2882
2883 # Creates nsilcmop
2884 indata["nslcmops_ids"] = nslcmops
2885 self._check_nsi_operation(session, nsir, operation, indata)
2886
2887 nsilcmop_desc = self._create_nsilcmop(
2888 session, netsliceInstanceId, operation, indata
2889 )
2890 self.format_on_new(
2891 nsilcmop_desc, session["project_id"], make_public=session["public"]
2892 )
2893 _id = self.db.create("nsilcmops", nsilcmop_desc)
2894 rollback.append({"topic": "nsilcmops", "_id": _id})
2895 self.msg.write("nsi", operation, nsilcmop_desc)
2896 return _id, None
2897 except ValidationError as e:
2898 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2899
2900 def delete(self, session, _id, dry_run=False, not_send_msg=None):
2901 raise EngineException(
2902 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2903 )
2904
2905 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2906 raise EngineException(
2907 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2908 )