1 # -*- coding: utf-8 -*-
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
18 from uuid
import uuid4
19 from http
import HTTPStatus
21 from copy
import copy
, deepcopy
22 from osm_nbi
.validation
import (
33 from osm_nbi
.base_topic
import (
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
47 ) # For checking that additional parameter names are valid Jinja2 identifiers
49 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
52 class NsrTopic(BaseTopic
):
55 quota_name
= "ns_instances"
56 schema_new
= ns_instantiate
58 def __init__(self
, db
, fs
, msg
, auth
):
59 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
61 def _check_descriptor_dependencies(self
, session
, descriptor
):
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
68 if not descriptor
.get("nsdId"):
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(
76 http_code
=HTTPStatus
.CONFLICT
,
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"
85 def check_conflict_on_del(self
, session
, _id
, db_content
):
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
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
,
103 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
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
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
})
117 # set all used pdus as free
120 {"_admin.usage.nsr_id": _id
},
121 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
126 used_nsd_id
= nsr
.get("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
134 "nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"}
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(
144 {"vnfd-id": used_vnfd_id
},
151 {"_id": used_vnfd_id
},
152 {"_admin.usageState": "NOT_IN_USE"},
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)
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
166 def _format_additional_params(
167 ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None
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
176 additional_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(
188 for x
in ns_request
["additionalParamsForVnf"]
189 if x
["member-vnf-index"] == member_vnf_index
194 if not vdu_id
and not kdu_name
:
196 additional_params
= copy(item
.get("additionalParams")) or {}
197 if vdu_id
and item
.get("additionalParamsForVdu"):
201 for x
in item
["additionalParamsForVdu"]
202 if x
["vdu_id"] == vdu_id
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"]
211 additional_params
= {}
212 if item
.get("additionalParamsForKdu"):
216 for x
in item
["additionalParamsForKdu"]
217 if x
["kdu_name"] == kdu_name
221 other_params
= item_kdu
222 if item_kdu
and item_kdu
.get("additionalParams"):
223 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(
226 additional_params
= item_kdu
["additionalParams"]
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(
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(
246 raise EngineException(
247 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
251 if isinstance(v
, (dict, tuple, list)):
252 additional_params
[k
] = "!!yaml " + safe_dump(v
)
254 additional_params
= json
.dumps(additional_params
)
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
261 initial_primitives
= []
263 "lcm-operations-configuration" in df
264 and "operate-vnf-op-config"
265 in df
["lcm-operations-configuration"]
267 for config
in df
["lcm-operations-configuration"][
268 "operate-vnf-op-config"
270 for primitive
in get_iterable(
271 config
.get("initial-config-primitive")
273 initial_primitives
.append(primitive
)
275 initial_primitives
= deep_get(
276 descriptor
, ("ns-configuration", "initial-config-primitive")
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(
284 if param
["value"] in (
291 not additional_params
292 or param
["value"][1:-1] not in additional_params
294 raise EngineException(
295 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
296 "initial-config-primitive[name={}] not supplied".format(
299 initial_primitive
["name"],
303 return additional_params
or None, other_params
or None
305 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
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
318 step
= "checking quotas"
319 self
.check_quota(session
)
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"])
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
_k
8s
_namespace
(nsd
, ns_request
, session
)
330 step
= "checking nsdOperationalState"
331 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
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
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")
347 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
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"]
356 needed_vnfds
[vnfd_id
] = vnfd
357 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
359 vnfd
= needed_vnfds
[vnfd_id
]
361 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
364 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(
374 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
377 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
378 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
380 step
= "creating nsr at database"
381 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
383 step
= "creating nsr temporal folder"
384 self
.fs
.mkdir(nsr_id
)
394 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
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
)
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)
407 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
409 nsr_descriptor
, session
["project_id"], make_public
=session
["public"]
411 self
.db
.create("nsrs", nsr_descriptor
)
412 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
414 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
416 vnfr_descriptor
, session
["project_id"], make_public
=session
["public"]
418 self
.db
.create("vnfrs", vnfr_descriptor
)
419 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
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
,
429 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
430 additional_params
, _
= self
._format
_additional
_params
(
431 ns_request
, descriptor
=nsd
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"]
440 return ns_k8s_namespace
442 def _add_flavor_to_nsr(self
, vdu
, vnfd
, nsr_descriptor
):
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(
458 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"][
461 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
462 flavor_data
["memory-mb"] = (
463 float(vdu_virtual_compute
["virtual-memory"]["size"])
466 if vdu_virtual_storage
.get("size-of-storage"):
467 flavor_data
["storage-gb"] = vdu_virtual_storage
[
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"][
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
[
481 if vcpu_pinning
.get("policy"):
484 if vcpu_pinning
["policy"] == "dynamic"
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"][
492 if vdu_virtual_compute
.get("virtual-memory", {}).get(
495 guest_epa
["mempage-size"] = vdu_virtual_compute
[
498 if vdu_virtual_compute
.get("virtual-memory", {}).get(
501 guest_epa
["numa-node-policy"] = vdu_virtual_compute
[
503 ]["numa-node-policy"]
504 if vdu_virtual_storage
.get("disk-io-quota"):
505 guest_epa
["disk-io-quota"] = vdu_virtual_storage
[
510 flavor_data
["guest-epa"] = guest_epa
512 flavor_data
["name"] = vdu
["id"][:56] + "-flv"
513 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
514 nsr_descriptor
["flavor"].append(flavor_data
)
516 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
518 additional_params
, _
= self
._format
_additional
_params
(
519 ns_request
, descriptor
=nsd
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,
532 "deploymentStatus": None,
533 "configurationStatus": 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": {},
545 "nsd-name-ref": nsd
["name"],
546 "operational-events": [], # "id", "timestamp", "description", "event",
547 "nsd-ref": nsd
["id"],
548 "nsd-id": nsd
["_id"],
550 "instantiate_params": self
._format
_ns
_request
(ns_request
),
551 "additionalParamsForNs": additional_params
,
552 "ns-instance-config-ref": nsr_id
,
555 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
558 "affinity-or-anti-affinity-group": [],
560 ns_request
["nsr_id"] = nsr_id
561 if ns_request
and ns_request
.get("config-units"):
562 nsr_descriptor
["config-units"] = ns_request
["config-units"]
564 if nsd
.get("virtual-link-desc"):
565 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
566 # Fill each vld with vnfd-connection-point-ref data
567 # TODO: Change for multiple df support
568 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
569 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
570 for vnf_profile
in vnf_profiles
:
571 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
572 for cpd
in vlc
.get("constituent-cpd-id", ()):
573 all_vld_connection_point_data
[
574 vlc
.get("virtual-link-profile-id")
577 "member-vnf-index-ref": cpd
.get(
578 "constituent-base-element-id"
580 "vnfd-connection-point-ref": cpd
.get(
583 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
587 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
590 for vdu
in vnfd
.get("vdu", ()):
591 self
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr_descriptor
)
592 sw_image_id
= vdu
.get("sw-image-desc")
594 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
595 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
597 # also add alternative images to the list of images
598 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
599 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
600 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
602 # Add Affinity or Anti-affinity group information to NSR
603 vdu_profiles
= vnfd
.get("df", [[]])[0].get("vdu-profile", ())
604 affinity_group_prefix_name
= "{}-{}".format(
605 nsr_descriptor
["name"][:16], vnf_profile
.get("id")[:16]
608 for vdu_profile
in vdu_profiles
:
609 affinity_group_data
= {}
610 for affinity_group
in vdu_profile
.get(
611 "affinity-or-anti-affinity-group", ()
613 affinity_group_data
= (
614 self
._get
_affinity
_or
_anti
_affinity
_group
_data
_from
_vnfd
(
615 vnfd
, affinity_group
["id"]
618 affinity_group_data
["member-vnf-index"] = vnf_profile
.get("id")
619 self
._add
_affinity
_or
_anti
_affinity
_group
_to
_nsr
(
622 affinity_group_prefix_name
,
626 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
629 vld
["name"] = vld
["id"]
630 nsr_descriptor
["vld"] = nsr_vld
632 return nsr_descriptor
634 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
635 self
, vnfd
, affinity_group_id
638 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
640 affinity_group
= utils
.find_in_list(
641 vnfd
.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
642 lambda ag
: ag
["id"] == affinity_group_id
,
644 affinity_group_data
= {}
646 if affinity_group
.get("id"):
647 affinity_group_data
["ag-id"] = affinity_group
["id"]
648 if affinity_group
.get("type"):
649 affinity_group_data
["type"] = affinity_group
["type"]
650 if affinity_group
.get("scope"):
651 affinity_group_data
["scope"] = affinity_group
["scope"]
652 return affinity_group_data
654 def _add_affinity_or_anti_affinity_group_to_nsr(
655 self
, nsr_descriptor
, affinity_group_data
, affinity_group_prefix_name
658 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
660 affinity_group
= next(
663 for f
in nsr_descriptor
["affinity-or-anti-affinity-group"]
664 if all(f
.get(k
) == affinity_group_data
[k
] for k
in affinity_group_data
)
668 if not affinity_group
:
669 affinity_group_data
["id"] = str(
670 len(nsr_descriptor
["affinity-or-anti-affinity-group"])
672 affinity_group_data
["name"] = "{}-{}".format(
673 affinity_group_prefix_name
, affinity_group_data
["ag-id"][:32]
675 nsr_descriptor
["affinity-or-anti-affinity-group"].append(
679 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
680 sw_image_desc
= utils
.find_in_list(
681 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
684 if sw_image_desc
.get("image"):
685 image_data
["image"] = sw_image_desc
["image"]
686 if sw_image_desc
.get("checksum"):
687 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
688 if sw_image_desc
.get("vim-type"):
689 image_data
["vim-type"] = sw_image_desc
["vim-type"]
692 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
694 Adds image to nsr checking first it is not already added
699 for f
in nsr_descriptor
["image"]
700 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
705 image_data
["id"] = str(len(nsr_descriptor
["image"]))
706 nsr_descriptor
["image"].append(image_data
)
708 def _create_vnfr_descriptor_from_vnfd(
718 vnfr_id
= str(uuid4())
719 nsr_id
= nsr_descriptor
["id"]
721 additional_params
, vnf_params
= self
._format
_additional
_params
(
722 ns_request
, vnf_index
, descriptor
=vnfd
728 "nsr-id-ref": nsr_id
,
729 "member-vnf-index-ref": vnf_index
,
730 "additionalParamsForVnf": additional_params
,
732 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
734 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
735 "vim-account-id": None,
738 "connection-point": [],
739 "ip-address": None, # mgmt-interface filled by LCM
742 # Revision backwards compatility. Only specify the revision in the record if
743 # the original VNFD has a revision.
744 if "revision" in vnfd
:
745 vnfr_descriptor
["revision"] = vnfd
["revision"]
748 vnf_k8s_namespace
= ns_k8s_namespace
750 if vnf_params
.get("k8s-namespace"):
751 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
752 if vnf_params
.get("config-units"):
753 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
756 if vnfd
.get("int-virtual-link-desc"):
757 vnfr_descriptor
["vld"] = []
758 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
759 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
761 for cp
in vnfd
.get("ext-cpd", ()):
763 "name": cp
.get("id"),
764 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
765 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
767 # "ip-address", "mac-address" # filled by LCM
768 # vim-id # TODO it would be nice having a vim port id
770 vnfr_descriptor
["connection-point"].append(vnf_cp
)
772 # Create k8s-cluster information
773 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
774 if vnfd
.get("k8s-cluster"):
775 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
776 all_k8s_cluster_nets_cpds
= {}
777 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
778 if cpd
.get("k8s-cluster-net"):
779 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
782 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
783 if net
.get("id") in all_k8s_cluster_nets_cpds
:
784 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
789 for kdu
in get_iterable(vnfd
.get("kdu")):
790 additional_params
, kdu_params
= self
._format
_additional
_params
(
791 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
793 kdu_k8s_namespace
= vnf_k8s_namespace
794 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
795 if kdu_params
and kdu_params
.get("k8s-namespace"):
796 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
798 kdu_deployment_name
= ""
799 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
800 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
803 "additionalParams": additional_params
,
804 "k8s-namespace": kdu_k8s_namespace
,
805 "kdu-deployment-name": kdu_deployment_name
,
806 "kdu-name": kdu
["name"],
807 # TODO "name": "" Name of the VDU in the VIM
808 "ip-address": None, # mgmt-interface filled by LCM
811 if kdu_params
and kdu_params
.get("config-units"):
812 kdur
["config-units"] = kdu_params
["config-units"]
813 if kdu
.get("helm-version"):
814 kdur
["helm-version"] = kdu
["helm-version"]
815 for k8s_type
in ("helm-chart", "juju-bundle"):
816 if kdu
.get(k8s_type
):
817 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
818 if not vnfr_descriptor
.get("kdur"):
819 vnfr_descriptor
["kdur"] = []
820 vnfr_descriptor
["kdur"].append(kdur
)
822 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
824 for vdu
in vnfd
.get("vdu", ()):
827 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
828 "operate-vnf-op-config"
830 vdu_config
= utils
.find_in_list(
831 configs
, lambda config
: config
["id"] == vdu
["id"]
837 vdu_instantiation_level
= utils
.find_in_list(
838 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
839 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
842 vdu_instantiation_level
= None
845 external_connection_ee
= utils
.filter_in_list(
846 vdu_config
.get("execution-environment-list", []),
847 lambda ee
: "external-connection-point-ref" in ee
,
849 for ee
in external_connection_ee
:
850 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
852 additional_params
, vdu_params
= self
._format
_additional
_params
(
853 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
857 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
858 vnfd
.get("virtual-storage-desc", []),
859 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"]
862 vdu_virtual_storage_descriptors
= []
864 "vdu-id-ref": vdu
["id"],
865 # TODO "name": "" Name of the VDU in the VIM
866 "ip-address": None, # mgmt-interface filled by LCM
867 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
868 "internal-connection-point": [],
870 "additionalParams": additional_params
,
871 "vdu-name": vdu
["name"],
872 "virtual-storages": vdu_virtual_storage_descriptors
874 if vdu_params
and vdu_params
.get("config-units"):
875 vdur
["config-units"] = vdu_params
["config-units"]
876 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
877 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
880 if vdu
.get("pdu-type"):
881 vdur
["pdu-type"] = vdu
["pdu-type"]
882 vdur
["name"] = vdu
["pdu-type"]
883 # TODO volumes: name, volume-id
884 for icp
in vdu
.get("int-cpd", ()):
887 "connection-point-id": icp
["id"],
888 "name": icp
.get("id"),
891 vdur
["internal-connection-point"].append(vdu_icp
)
893 for iface
in icp
.get("virtual-network-interface-requirement", ()):
894 iface_fields
= ("name", "mac-address")
896 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
899 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
900 if "port-security-enabled" in icp
:
901 vdu_iface
["port-security-enabled"] = icp
[
902 "port-security-enabled"
905 if "port-security-disable-strategy" in icp
:
906 vdu_iface
["port-security-disable-strategy"] = icp
[
907 "port-security-disable-strategy"
910 for ext_cp
in vnfd
.get("ext-cpd", ()):
911 if not ext_cp
.get("int-cpd"):
913 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
915 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
916 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
920 if "port-security-enabled" in ext_cp
:
921 vdu_iface
["port-security-enabled"] = ext_cp
[
922 "port-security-enabled"
925 if "port-security-disable-strategy" in ext_cp
:
926 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
927 "port-security-disable-strategy"
934 and vdu_iface
.get("external-connection-point-ref")
937 vdu_iface
["mgmt-vnf"] = True
938 vdu_iface
["mgmt-interface"] = True
940 for ecp
in vdu_mgmt_cp
:
941 if vdu_iface
.get("external-connection-point-ref") == ecp
:
942 vdu_iface
["mgmt-interface"] = True
944 if iface
.get("virtual-interface"):
945 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
947 # look for network where this interface is connected
948 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
950 # TODO: Change for multiple df support
951 for df
in get_iterable(nsd
.get("df")):
952 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
953 for vlc_index
, vlc
in enumerate(
955 vnf_profile
.get("virtual-link-connectivity")
958 for cpd
in get_iterable(
959 vlc
.get("constituent-cpd-id")
962 cpd
.get("constituent-cpd-id")
965 vdu_iface
["ns-vld-id"] = vlc
.get(
966 "virtual-link-profile-id"
968 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
969 if vdu_iface
.get("type") in (
973 nsr_descriptor
["vld"][vlc_index
][
977 elif vdu_iface
.get("internal-connection-point-ref"):
978 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
979 # TODO: store fixed IP address in the record (if it exists in the ICP)
980 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
981 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
982 ivld_index
= utils
.find_index_in_list(
983 vnfd
.get("int-virtual-link-desc", ()),
984 lambda ivld
: ivld
["id"]
985 == icp
.get("int-virtual-link-desc"),
987 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
989 vdur
["interfaces"].append(vdu_iface
)
991 if vdu
.get("sw-image-desc"):
992 sw_image
= utils
.find_in_list(
993 vnfd
.get("sw-image-desc", ()),
994 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
996 nsr_sw_image_data
= utils
.find_in_list(
997 nsr_descriptor
["image"],
998 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
1000 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
1002 if vdu
.get("alternative-sw-image-desc"):
1004 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
1005 sw_image
= utils
.find_in_list(
1006 vnfd
.get("sw-image-desc", ()),
1007 lambda image
: image
["id"] == alt_image_id
,
1009 nsr_sw_image_data
= utils
.find_in_list(
1010 nsr_descriptor
["image"],
1012 nsr_image
.get("image") == sw_image
.get("image")
1015 alt_image_ids
.append(nsr_sw_image_data
["id"])
1016 vdur
["alt-image-ids"] = alt_image_ids
1018 flavor_data_name
= vdu
["id"][:56] + "-flv"
1019 nsr_flavor_desc
= utils
.find_in_list(
1020 nsr_descriptor
["flavor"],
1021 lambda flavor
: flavor
["name"] == flavor_data_name
,
1025 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
1027 # Adding Affinity groups information to vdur
1029 vdu_profile_affinity_group
= utils
.find_in_list(
1030 vnfd
.get("df")[0]["vdu-profile"],
1031 lambda a_vdu
: a_vdu
["id"] == vdu
["id"],
1034 vdu_profile_affinity_group
= None
1036 if vdu_profile_affinity_group
:
1037 affinity_group_ids
= []
1038 for affinity_group
in vdu_profile_affinity_group
.get(
1039 "affinity-or-anti-affinity-group", ()
1041 vdu_affinity_group
= utils
.find_in_list(
1042 vdu_profile_affinity_group
.get(
1043 "affinity-or-anti-affinity-group", ()
1045 lambda ag_fp
: ag_fp
["id"] == affinity_group
["id"],
1047 nsr_affinity_group
= utils
.find_in_list(
1048 nsr_descriptor
["affinity-or-anti-affinity-group"],
1050 nsr_ag
.get("ag-id") == vdu_affinity_group
.get("id")
1051 and nsr_ag
.get("member-vnf-index")
1052 == vnfr_descriptor
.get("member-vnf-index-ref")
1055 # Update Affinity Group VIM name if VDU instantiation parameter is present
1056 if vnf_params
and vnf_params
.get("affinity-or-anti-affinity-group"):
1057 vnf_params_affinity_group
= utils
.find_in_list(
1058 vnf_params
["affinity-or-anti-affinity-group"],
1060 vnfp_ag
.get("id") == vdu_affinity_group
.get("id")
1063 if vnf_params_affinity_group
.get("vim-affinity-group-id"):
1065 "vim-affinity-group-id"
1066 ] = vnf_params_affinity_group
["vim-affinity-group-id"]
1067 affinity_group_ids
.append(nsr_affinity_group
["id"])
1068 vdur
["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1070 if vdu_instantiation_level
:
1071 count
= vdu_instantiation_level
.get("number-of-instances")
1075 for index
in range(0, count
):
1076 vdur
= deepcopy(vdur
)
1077 for iface
in vdur
["interfaces"]:
1078 if iface
.get("ip-address") and index
!= 0:
1079 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
1080 if iface
.get("mac-address") and index
!= 0:
1081 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
1083 vdur
["_id"] = str(uuid4())
1084 vdur
["id"] = vdur
["_id"]
1085 vdur
["count-index"] = index
1086 vnfr_descriptor
["vdur"].append(vdur
)
1088 return vnfr_descriptor
1090 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
1092 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1093 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1094 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1095 :param ns_instance_content: ns instance content
1096 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1099 time_now
, time_delta
= time(), time() - ns_instance_content
["_admin"]["modified"]
1100 force_refresh
= isinstance(filter_q
, dict) and filter_q
.get('vcaStatusRefresh') == 'true'
1101 threshold_reached
= time_delta
> 120
1102 if force_refresh
or threshold_reached
:
1103 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
1104 ns_instance_content
["_admin"]["modified"] = time_now
1105 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
1106 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
1107 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1108 nslcmop_desc
["_admin"].pop("nsState")
1109 self
.msg
.write("ns", operation
, nslcmop_desc
)
1112 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1114 Get complete information on an ns instance.
1115 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1116 :param _id: string, ns instance id
1117 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1118 :param api_req: True if this call is serving an external API request. False if serving internal request.
1119 :return: dictionary, raise exception if not found.
1121 ns_instance_content
= super().show(session
, _id
, api_req
)
1122 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1123 return ns_instance_content
1125 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1126 raise EngineException(
1127 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1131 class VnfrTopic(BaseTopic
):
1135 def __init__(self
, db
, fs
, msg
, auth
):
1136 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1138 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1139 raise EngineException(
1140 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1143 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1144 raise EngineException(
1145 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1148 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1149 # Not used because vnfrs are created and deleted by NsrTopic class directly
1150 raise EngineException(
1151 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1155 class NsLcmOpTopic(BaseTopic
):
1158 operation_schema
= { # mapping between operation and jsonschema to validate
1159 "instantiate": ns_instantiate
,
1160 "action": ns_action
,
1161 "update": ns_update
,
1163 "terminate": ns_terminate
,
1164 "migrate": ns_migrate
,
1167 def __init__(self
, db
, fs
, msg
, auth
):
1168 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1169 self
.nsrtopic
= NsrTopic(db
, fs
, msg
, auth
)
1171 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1173 Check that user has enter right parameters for the operation
1174 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1175 :param operation: it can be: instantiate, terminate, action, update. TODO: heal
1176 :param indata: descriptor with the parameters of the operation
1179 if operation
== "action":
1180 self
._check
_action
_ns
_operation
(indata
, nsr
)
1181 elif operation
== "scale":
1182 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1183 elif operation
== "update":
1184 self
._check
_update
_ns
_operation
(indata
, nsr
)
1185 elif operation
== "instantiate":
1186 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1188 def _check_action_ns_operation(self
, indata
, nsr
):
1190 # check vnf_member_index
1191 if indata
.get("vnf_member_index"):
1192 indata
["member_vnf_index"] = indata
.pop(
1194 ) # for backward compatibility
1195 if indata
.get("member_vnf_index"):
1196 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1197 indata
["member_vnf_index"], nsr
["_id"]
1200 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1201 "operate-vnf-op-config"
1206 if indata
.get("vdu_id"):
1207 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1208 descriptor_configuration
= utils
.find_in_list(
1209 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1211 elif indata
.get("kdu_name"):
1212 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1213 descriptor_configuration
= utils
.find_in_list(
1214 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1217 descriptor_configuration
= utils
.find_in_list(
1218 configs
, lambda config
: config
["id"] == vnfd
["id"]
1220 if descriptor_configuration
is not None:
1221 descriptor_configuration
= descriptor_configuration
.get(
1225 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1229 # For k8s allows default primitives without validating the parameters
1230 if indata
.get("kdu_name") and indata
["primitive"] in (
1237 # TODO should be checked that rollback only can contains revsision_numbe????
1238 if not indata
.get("member_vnf_index"):
1239 raise EngineException(
1240 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1245 # if not, check primitive
1246 for config_primitive
in get_iterable(descriptor_configuration
):
1247 if indata
["primitive"] == config_primitive
["name"]:
1248 # check needed primitive_params are provided
1249 if indata
.get("primitive_params"):
1250 in_primitive_params_copy
= copy(indata
["primitive_params"])
1252 in_primitive_params_copy
= {}
1253 for paramd
in get_iterable(config_primitive
.get("parameter")):
1254 if paramd
["name"] in in_primitive_params_copy
:
1255 del in_primitive_params_copy
[paramd
["name"]]
1256 elif not paramd
.get("default-value"):
1257 raise EngineException(
1258 "Needed parameter {} not provided for primitive '{}'".format(
1259 paramd
["name"], indata
["primitive"]
1262 # check no extra primitive params are provided
1263 if in_primitive_params_copy
:
1264 raise EngineException(
1265 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1266 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1271 raise EngineException(
1272 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1277 def _check_update_ns_operation(self
, indata
, nsr
) -> None:
1278 """Validates the ns-update request according to updateType
1280 If updateType is CHANGE_VNFPKG:
1281 - it checks the vnfInstanceId, whether it's available under ns instance
1282 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1283 Otherwise exception will be raised.
1284 If updateType is REMOVE_VNF:
1285 - it checks if the vnfInstanceId is available in the ns instance
1286 - Otherwise exception will be raised.
1289 indata: includes updateType such as CHANGE_VNFPKG,
1290 nsr: network service record
1294 a meaningful error if given update parameters are not proper such as
1295 "Error in validating ns-update request: <ID> does not match
1296 with the vnfd-id of vnfinstance
1297 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1301 if indata
["updateType"] == "CHANGE_VNFPKG":
1302 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1303 vnf_instance_id
= indata
["changeVnfPackageData"]["vnfInstanceId"]
1304 ns_instance_id
= indata
["nsInstanceId"]
1305 vnfd_id_2update
= indata
["changeVnfPackageData"]["vnfdId"]
1307 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1309 raise EngineException(
1310 f
"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1311 f
"belong to NS {ns_instance_id}",
1312 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1315 # Getting vnfrs through the ns_instance_id
1316 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": ns_instance_id
})
1317 constituent_vnfd_id
= next(
1321 if vnfr
["id"] == vnf_instance_id
1326 # Check the given vnfd-id belongs to given vnf instance
1327 if constituent_vnfd_id
and (vnfd_id_2update
!= constituent_vnfd_id
):
1329 raise EngineException(
1330 f
"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1331 f
"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1332 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1335 # Validating the ns update timeout
1337 indata
.get("timeout_ns_update")
1338 and indata
["timeout_ns_update"] < 300
1340 raise EngineException(
1341 "Error in validating ns-update request: {} second is not enough "
1342 "to upgrade the VNF instance: {}".format(
1343 indata
["timeout_ns_update"], vnf_instance_id
1345 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1347 elif indata
["updateType"] == "REMOVE_VNF":
1348 vnf_instance_id
= indata
["removeVnfInstanceId"]
1349 ns_instance_id
= indata
["nsInstanceId"]
1350 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1351 raise EngineException(
1352 "Invalid VNF Instance Id. '{}' is not "
1353 "present in the NS '{}'".format(vnf_instance_id
, ns_instance_id
)
1364 "Ns update request could not be processed with error: {}.".format(e
)
1367 def _check_scale_ns_operation(self
, indata
, nsr
):
1368 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1369 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1371 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1373 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1374 == scaling_aspect
["id"]
1378 raise EngineException(
1379 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1380 "present at vnfd:scaling-aspect".format(
1381 indata
["scaleVnfData"]["scaleByStepData"][
1382 "scaling-group-descriptor"
1387 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1388 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1392 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1393 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1394 for in_vnf
in get_iterable(indata
.get("vnf")):
1395 member_vnf_index
= in_vnf
["member-vnf-index"]
1396 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1397 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1399 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1400 member_vnf_index
, nsr
["_id"]
1402 vnf_member_index_to_vnfd
[
1404 ] = vnfd
# add to cache, avoiding a later look for
1405 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1406 if in_vnf
.get("vimAccountId"):
1407 self
._check
_valid
_vim
_account
(
1408 in_vnf
["vimAccountId"], vim_accounts
, session
1411 for in_vld
in get_iterable(indata
.get("vld")):
1412 self
._check
_valid
_wim
_account
(
1413 in_vld
.get("wimAccountId"), wim_accounts
, session
1415 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1416 if in_vld
["name"] == vldd
["id"]:
1419 raise EngineException(
1420 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1425 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1426 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1427 vnfr
= self
.db
.get_one(
1429 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1430 fail_on_empty
=False,
1433 raise EngineException(
1434 "Invalid parameter member_vnf_index='{}' is not one of the "
1435 "nsd:constituent-vnfd".format(member_vnf_index
)
1438 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1439 if "revision" in vnfr
:
1440 vnfd_revision
= vnfr
["vnfd-id"] + ":" + str(vnfr
["revision"])
1441 vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": vnfd_revision
}, fail_on_empty
=False)
1443 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
1446 raise EngineException(
1447 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1453 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1454 for vdud
in get_iterable(vnfd
.get("vdu")):
1455 if vdud
["id"] == vdu_id
:
1458 raise EngineException(
1459 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1464 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1465 for kdud
in get_iterable(vnfd
.get("kdu")):
1466 if kdud
["name"] == kdu_name
:
1469 raise EngineException(
1470 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1475 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1476 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1477 for vdu
in get_iterable(vnfd
.get("vdu")):
1478 if in_vdu
["id"] == vdu
["id"]:
1479 for volume
in get_iterable(in_vdu
.get("volume")):
1480 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1481 if volumed
["id"] == volume
["name"]:
1484 raise EngineException(
1485 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1486 "volume:name='{}' is not present at "
1487 "vnfd:vdu:virtual-storage-desc list".format(
1488 in_vnf
["member-vnf-index"],
1494 vdu_if_names
= set()
1495 for cpd
in get_iterable(vdu
.get("int-cpd")):
1496 for iface
in get_iterable(
1497 cpd
.get("virtual-network-interface-requirement")
1499 vdu_if_names
.add(iface
.get("name"))
1501 for in_iface
in get_iterable(in_vdu
["interface"]):
1502 if in_iface
["name"] in vdu_if_names
:
1505 raise EngineException(
1506 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1507 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1508 in_vnf
["member-vnf-index"],
1516 raise EngineException(
1517 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1518 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1522 ivld
.get("id"): set()
1523 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1525 for vdu
in get_iterable(vnfd
.get("vdu")):
1526 for cpd
in get_iterable(vnfd
.get("int-cpd")):
1527 if cpd
.get("int-virtual-link-desc"):
1528 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1530 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1531 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1532 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1533 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1536 raise EngineException(
1537 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1538 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1539 "vnfd:internal-vld:name/id:internal-connection-point".format(
1540 in_vnf
["member-vnf-index"],
1546 raise EngineException(
1547 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1548 " is not present at vnfd '{}'".format(
1549 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1553 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1554 if vim_account
in vim_accounts
:
1557 db_filter
= self
._get
_project
_filter
(session
)
1558 db_filter
["_id"] = vim_account
1559 self
.db
.get_one("vim_accounts", db_filter
)
1561 raise EngineException(
1562 "Invalid vimAccountId='{}' not present for the project".format(
1566 vim_accounts
.append(vim_account
)
1568 def _get_vim_account(self
, vim_id
: str, session
):
1570 db_filter
= self
._get
_project
_filter
(session
)
1571 db_filter
["_id"] = vim_id
1572 return self
.db
.get_one("vim_accounts", db_filter
)
1574 raise EngineException(
1575 "Invalid vimAccountId='{}' not present for the project".format(
1580 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1581 if not isinstance(wim_account
, str):
1583 if wim_account
in wim_accounts
:
1586 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
1587 db_filter
["_id"] = wim_account
1588 self
.db
.get_one("wim_accounts", db_filter
)
1590 raise EngineException(
1591 "Invalid wimAccountId='{}' not present for the project".format(
1595 wim_accounts
.append(wim_account
)
1598 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1601 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1602 (ip_address, ...) information.
1603 Modifies PDU _admin.usageState to 'IN_USE'
1604 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1605 :param rollback: list with the database modifications to rollback if needed
1606 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1607 :param vim_account: vim_account where this vnfr should be deployed
1608 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1609 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1610 of the changed vnfr is needed
1612 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1613 "vim-network-name": used at VIM
1614 "name": interface name
1615 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1616 "ns-vld-id": NSD vld where this interface is connected.
1617 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1620 ifaces_forcing_vim_network
= []
1621 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1622 if not vdur
.get("pdu-type"):
1624 pdu_type
= vdur
.get("pdu-type")
1625 pdu_filter
= self
._get
_project
_filter
(session
)
1626 pdu_filter
["vim_accounts"] = vim_account
1627 pdu_filter
["type"] = pdu_type
1628 pdu_filter
["_admin.operationalState"] = "ENABLED"
1629 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1630 # TODO feature 1417: "shared": True,
1632 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1633 for pdu
in available_pdus
:
1634 # step 1 check if this pdu contains needed interfaces:
1635 match_interfaces
= True
1636 for vdur_interface
in vdur
["interfaces"]:
1637 for pdu_interface
in pdu
["interfaces"]:
1638 if pdu_interface
["name"] == vdur_interface
["name"]:
1639 # TODO feature 1417: match per mgmt type
1641 else: # no interface found for name
1642 match_interfaces
= False
1644 if match_interfaces
:
1647 raise EngineException(
1648 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1652 vnfr
["member-vnf-index-ref"],
1657 # step 2. Update pdu
1659 "_admin.usageState": pdu
["_admin"]["usageState"],
1660 "_admin.usage.vnfr_id": None,
1661 "_admin.usage.nsr_id": None,
1662 "_admin.usage.vdur": None,
1666 {"_id": pdu
["_id"]},
1668 "_admin.usageState": "IN_USE",
1670 "vnfr_id": vnfr
["_id"],
1671 "nsr_id": vnfr
["nsr-id-ref"],
1672 "vdur": vdur
["vdu-id-ref"],
1681 "content": rollback_pdu
,
1685 # step 3. Fill vnfr info by filling vdur
1686 vdu_text
= "vdur.{}".format(vdur_index
)
1687 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1688 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1689 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1690 for pdu_interface
in pdu
["interfaces"]:
1691 if pdu_interface
["name"] == vdur_interface
["name"]:
1692 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1693 for k
, v
in pdu_interface
.items():
1697 ): # TODO: switch-xxxxx must be inserted
1698 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1699 vnfr_update_rollback
[
1700 iface_text
+ ".{}".format(k
)
1701 ] = vdur_interface
.get(v
)
1702 if pdu_interface
.get("ip-address"):
1703 if vdur_interface
.get(
1705 ) or vdur_interface
.get("mgmt-vnf"):
1706 vnfr_update_rollback
[
1707 vdu_text
+ ".ip-address"
1708 ] = vdur
.get("ip-address")
1709 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1712 if vdur_interface
.get("mgmt-vnf"):
1713 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1716 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1717 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1720 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1723 ifaces_forcing_vim_network
.append(
1725 "name": vdur_interface
.get("vnf-vld-id")
1726 or vdur_interface
.get("ns-vld-id"),
1727 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1728 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1731 if pdu_interface
.get("vim-network-id"):
1732 ifaces_forcing_vim_network
[-1][
1734 ] = pdu_interface
["vim-network-id"]
1735 if pdu_interface
.get("vim-network-name"):
1736 ifaces_forcing_vim_network
[-1][
1738 ] = pdu_interface
["vim-network-name"]
1741 return ifaces_forcing_vim_network
1743 def _look_for_k8scluster(
1744 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1747 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1748 Fills vnfr.kdur with the selected k8scluster
1750 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1751 :param rollback: list with the database modifications to rollback if needed
1752 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1753 :param vim_account: vim_account where this vnfr should be deployed
1754 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1755 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1756 of the changed vnfr is needed
1758 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1759 "vim-network-name": used at VIM
1760 "name": interface name
1761 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1762 "ns-vld-id": NSD vld where this interface is connected.
1763 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1766 ifaces_forcing_vim_network
= []
1767 if not vnfr
.get("kdur"):
1768 return ifaces_forcing_vim_network
1770 kdu_filter
= self
._get
_project
_filter
(session
)
1771 kdu_filter
["vim_account"] = vim_account
1772 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1773 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1775 k8s_requirements
= {} # just for logging
1776 for k8scluster
in available_k8sclusters
:
1777 if not vnfr
.get("k8s-cluster"):
1780 if vnfr
["k8s-cluster"].get("cni"):
1781 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1782 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1783 k8scluster
.get("cni", ())
1786 # restrict by version
1787 if vnfr
["k8s-cluster"].get("version"):
1788 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1789 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1791 # restrict by number of networks
1792 if vnfr
["k8s-cluster"].get("nets"):
1793 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1794 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1795 vnfr
["k8s-cluster"]["nets"]
1800 raise EngineException(
1801 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1802 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1806 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1807 # step 3. Fill vnfr info by filling kdur
1808 kdu_text
= "kdur.{}.".format(kdur_index
)
1809 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1810 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1812 # step 4. Check VIM networks that forces the selected k8s_cluster
1813 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1814 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1815 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1816 # get a network from k8s_cluster nets. If name matches use this, if not use other
1817 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1818 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1819 k8scluster_net_list
.remove(kdur_net
["id"])
1821 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1822 k8scluster_net_list
.pop(0)
1823 vnfr_update_rollback
[
1824 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1826 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1828 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1830 ifaces_forcing_vim_network
.append(
1832 "name": kdur_net
.get("vnf-vld-id")
1833 or kdur_net
.get("ns-vld-id"),
1834 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1835 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1836 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1839 # TODO check that this forcing is not incompatible with other forcing
1840 return ifaces_forcing_vim_network
1842 def _update_vnfrs_from_nsd(self
, nsr
):
1847 step
= "Getting vnf_profiles from nsd"
1848 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
1849 vld_fixed_ip_connection_point_data
= {}
1851 step
= "Getting ip-address info from vnf_profile if it exists"
1852 for vnfp
in vnf_profiles
:
1853 # Checking ip-address info from nsd.vnf_profile and storing
1854 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
1855 for cpd
in vlc
.get("constituent-cpd-id", ()):
1856 if cpd
.get("ip-address"):
1857 step
= "Storing ip-address info"
1858 vld_fixed_ip_connection_point_data
.update({vlc
.get("virtual-link-profile-id") + '.' + cpd
.get("constituent-base-element-id"): {
1859 "vnfd-connection-point-ref": cpd
.get(
1860 "constituent-cpd-id"),
1861 "ip-address": cpd
.get(
1864 # Inserting ip address to vnfr
1865 if len(vld_fixed_ip_connection_point_data
) > 0:
1866 step
= "Getting vnfrs"
1867 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1868 for item
in vld_fixed_ip_connection_point_data
.keys():
1869 step
= "Filtering vnfrs"
1870 vnfr
= next(filter(lambda vnfr
: vnfr
["member-vnf-index-ref"] == item
.split('.')[1], vnfrs
), None)
1873 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1874 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1875 step
= "Looking for matched interface"
1877 iface
.get("external-connection-point-ref")
1878 == vld_fixed_ip_connection_point_data
[item
].get("vnfd-connection-point-ref") and
1879 iface
.get("ns-vld-id") == item
.split('.')[0]
1882 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1883 vdur_index
, iface_index
1885 step
= "Storing info in order to update vnfr"
1887 vnfr_update_text
+ ".ip-address"
1888 ] = increment_ip_mac(
1889 vld_fixed_ip_connection_point_data
[item
].get("ip-address"),
1890 vdur
.get("count-index", 0), )
1891 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1893 step
= "updating vnfr at database"
1894 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1902 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
1904 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1907 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1911 vnfr_update_rollback
= {}
1912 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1913 # update vim-account-id
1915 vim_account
= indata
["vimAccountId"]
1916 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1917 # check instantiate parameters
1918 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1919 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1921 if vnf_inst_params
.get("vimAccountId"):
1922 vim_account
= vnf_inst_params
.get("vimAccountId")
1923 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1925 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1926 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1927 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1928 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1930 for iface_inst_param
in get_iterable(
1931 vdu_inst_param
.get("interface")
1933 iface_index
, _
= next(
1935 for i
in enumerate(vdur
["interfaces"])
1936 if i
[1]["name"] == iface_inst_param
["name"]
1938 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1939 vdur_index
, iface_index
1941 if iface_inst_param
.get("ip-address"):
1943 vnfr_update_text
+ ".ip-address"
1944 ] = increment_ip_mac(
1945 iface_inst_param
.get("ip-address"),
1946 vdur
.get("count-index", 0),
1948 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1949 if iface_inst_param
.get("mac-address"):
1951 vnfr_update_text
+ ".mac-address"
1952 ] = increment_ip_mac(
1953 iface_inst_param
.get("mac-address"),
1954 vdur
.get("count-index", 0),
1956 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1957 if iface_inst_param
.get("floating-ip-required"):
1959 vnfr_update_text
+ ".floating-ip-required"
1961 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1962 # TODO update vld with the ip-profile
1963 for ivld_inst_param
in get_iterable(
1964 vnf_inst_params
.get("internal-vld")
1966 for icp_inst_param
in get_iterable(
1967 ivld_inst_param
.get("internal-connection-point")
1970 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1971 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1973 iface
.get("internal-connection-point-ref")
1974 == icp_inst_param
["id-ref"]
1976 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1977 vdur_index
, iface_index
1979 if icp_inst_param
.get("ip-address"):
1981 vnfr_update_text
+ ".ip-address"
1982 ] = increment_ip_mac(
1983 icp_inst_param
.get("ip-address"),
1984 vdur
.get("count-index", 0),
1987 vnfr_update_text
+ ".fixed-ip"
1989 if icp_inst_param
.get("mac-address"):
1991 vnfr_update_text
+ ".mac-address"
1992 ] = increment_ip_mac(
1993 icp_inst_param
.get("mac-address"),
1994 vdur
.get("count-index", 0),
1997 vnfr_update_text
+ ".fixed-mac"
2000 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2001 for vld_inst_param
in get_iterable(indata
.get("vld")):
2002 for vnfcp_inst_param
in get_iterable(
2003 vld_inst_param
.get("vnfd-connection-point-ref")
2005 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
2008 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2009 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2011 iface
.get("external-connection-point-ref")
2012 == vnfcp_inst_param
["vnfd-connection-point-ref"]
2014 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2015 vdur_index
, iface_index
2017 if vnfcp_inst_param
.get("ip-address"):
2019 vnfr_update_text
+ ".ip-address"
2020 ] = increment_ip_mac(
2021 vnfcp_inst_param
.get("ip-address"),
2022 vdur
.get("count-index", 0),
2024 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2025 if vnfcp_inst_param
.get("mac-address"):
2027 vnfr_update_text
+ ".mac-address"
2028 ] = increment_ip_mac(
2029 vnfcp_inst_param
.get("mac-address"),
2030 vdur
.get("count-index", 0),
2032 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2035 vnfr_update
["vim-account-id"] = vim_account
2036 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
2039 vnfr_update
["vca-id"] = vca_id
2040 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
2043 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
2044 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2048 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
2049 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2051 # update database vnfr
2052 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2058 "content": vnfr_update_rollback
,
2062 # Update indada in case pdu forces to use a concrete vim-network-name
2063 # TODO check if user has already insert a vim-network-name and raises an error
2064 if not ifaces_forcing_vim_network
:
2066 for iface_info
in ifaces_forcing_vim_network
:
2067 if iface_info
.get("ns-vld-id"):
2068 if "vld" not in indata
:
2070 indata
["vld"].append(
2072 key
: iface_info
[key
]
2073 for key
in ("name", "vim-network-name", "vim-network-id")
2074 if iface_info
.get(key
)
2078 elif iface_info
.get("vnf-vld-id"):
2079 if "vnf" not in indata
:
2081 indata
["vnf"].append(
2083 "member-vnf-index": member_vnf_index
,
2086 key
: iface_info
[key
]
2092 if iface_info
.get(key
)
2099 def _create_nslcmop(nsr_id
, operation
, params
):
2101 Creates a ns-lcm-opp content to be stored at database.
2102 :param nsr_id: internal id of the instance
2103 :param operation: instantiate, terminate, scale, action, update ...
2104 :param params: user parameters for the operation
2105 :return: dictionary following SOL005 format
2112 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2113 "queuePosition": None,
2115 "errorMessage": None,
2116 "detailedStatus": None,
2117 "statusEnteredTime": now
,
2118 "nsInstanceId": nsr_id
,
2119 "lcmOperationType": operation
,
2121 "isAutomaticInvocation": False,
2122 "operationParams": params
,
2123 "isCancelPending": False,
2125 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2126 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2131 def _get_enabled_vims(self
, session
):
2133 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2134 :param session: current session with user information
2136 db_filter
= self
._get
_project
_filter
(session
)
2137 db_filter
["_admin.operationalState"] = "ENABLED"
2138 vims
= self
.db
.get_list("vim_accounts", db_filter
)
2141 vimAccounts
.append(vim
["_id"])
2154 Performs a new operation over a ns
2155 :param rollback: list to append created items at database in case a rollback must to be done
2156 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2157 :param indata: descriptor with the parameters of the operation. It must contains among others
2158 nsInstanceId: _id of the nsr to perform the operation
2159 operation: it can be: instantiate, terminate, action, update TODO: heal
2160 :param kwargs: used to override the indata descriptor
2161 :param headers: http request headers
2162 :return: id of the nslcmops
2165 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
2167 db_filter
= self
._get
_project
_filter
(session
)
2168 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2169 nsis
= self
.db
.get_one(
2170 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
2173 raise EngineException(
2174 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2177 http_code
=HTTPStatus
.CONFLICT
,
2181 # Override descriptor with query string kwargs
2182 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2183 operation
= indata
["lcmOperationType"]
2184 nsInstanceId
= indata
["nsInstanceId"]
2186 validate_input(indata
, self
.operation_schema
[operation
])
2187 # get ns from nsr_id
2188 _filter
= BaseTopic
._get
_project
_filter
(session
)
2189 _filter
["_id"] = nsInstanceId
2190 nsr
= self
.db
.get_one("nsrs", _filter
)
2193 if operation
== "terminate" and slice_object
is False:
2194 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
2196 not nsr
["_admin"].get("nsState")
2197 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
2199 if operation
== "terminate" and indata
.get("autoremove"):
2200 # NSR must be deleted
2204 ) # a none in this case is used to indicate not instantiated. It can be removed
2205 if operation
!= "instantiate":
2206 raise EngineException(
2207 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2208 nsInstanceId
, operation
2210 HTTPStatus
.CONFLICT
,
2213 if operation
== "instantiate" and not session
["force"]:
2214 raise EngineException(
2215 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2216 nsInstanceId
, operation
2218 HTTPStatus
.CONFLICT
,
2220 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
2221 if (indata
.get("primitive_params")):
2222 indata
["primitive_params"] = json
.dumps(indata
["primitive_params"])
2223 elif (indata
.get("additionalParamsForVnf")):
2224 indata
["additionalParamsForVnf"] = json
.dumps(indata
["additionalParamsForVnf"])
2226 if operation
== "instantiate":
2227 self
._update
_vnfrs
_from
_nsd
(nsr
)
2228 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
2229 if (operation
== "update") and (indata
["updateType"] == "CHANGE_VNFPKG"):
2231 vnfd_id
= indata
["changeVnfPackageData"]["vnfdId"]
2232 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2233 nsd
= self
.db
.get_one("nsds", {"_id": nsr
["nsd-id"]})
2234 ns_request
= nsr
["instantiate_params"]
2235 vnfr
= self
.db
.get_one("vnfrs", {"_id": indata
["changeVnfPackageData"]["vnfInstanceId"]})
2236 latest_vnfd_revision
= vnfd
["_admin"].get("revision", 1)
2237 vnfr_vnfd_revision
= vnfr
.get("revision", 1)
2238 if latest_vnfd_revision
!= vnfr_vnfd_revision
:
2239 old_vnfd_id
= vnfd_id
+ ":" + str(vnfr_vnfd_revision
)
2240 old_db_vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": old_vnfd_id
})
2241 old_sw_version
= old_db_vnfd
.get("software-version", "1.0")
2242 new_sw_version
= vnfd
.get("software-version", "1.0")
2243 if new_sw_version
!= old_sw_version
:
2244 vnf_index
= vnfr
["member-vnf-index-ref"]
2245 self
.logger
.info("nsr {}".format(nsr
))
2246 for vdu
in vnfd
["vdu"]:
2247 self
.nsrtopic
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr
)
2248 sw_image_id
= vdu
.get("sw-image-desc")
2250 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
2251 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2252 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
2253 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
2254 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2255 nsr_update
["image"] = nsr
["image"]
2256 nsr_update
["flavor"] = nsr
["flavor"]
2257 self
.db
.set_one("nsrs", {"_id": nsr
["_id"]}, nsr_update
)
2258 ns_k8s_namespace
= self
.nsrtopic
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
2259 vnfr_descriptor
= self
.nsrtopic
._create
_vnfr
_descriptor
_from
_vnfd
(
2268 indata
["newVdur"] = vnfr_descriptor
["vdur"]
2269 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
2270 _id
= nslcmop_desc
["_id"]
2272 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2274 if indata
.get("placement-engine"):
2275 # Save valid vim accounts in lcm operation descriptor
2276 nslcmop_desc
["operationParams"][
2278 ] = self
._get
_enabled
_vims
(session
)
2279 self
.db
.create("nslcmops", nslcmop_desc
)
2280 rollback
.append({"topic": "nslcmops", "_id": _id
})
2281 if not slice_object
:
2282 self
.msg
.write("ns", operation
, nslcmop_desc
)
2284 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2285 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2286 # except DbException as e:
2287 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2289 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2290 raise EngineException(
2291 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2294 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2295 raise EngineException(
2296 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2300 class NsiTopic(BaseTopic
):
2303 quota_name
= "slice_instances"
2305 def __init__(self
, db
, fs
, msg
, auth
):
2306 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2307 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2310 def _format_ns_request(ns_request
):
2311 formated_request
= copy(ns_request
)
2312 # TODO: Add request params
2313 return formated_request
2316 def _format_addional_params(slice_request
):
2318 Get and format user additional params for NS or VNF
2319 :param slice_request: User instantiation additional parameters
2320 :return: a formatted copy of additional params or None if not supplied
2322 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2323 if additional_params
:
2324 for k
, v
in additional_params
.items():
2325 if not isinstance(k
, str):
2326 raise EngineException(
2327 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2331 if "." in k
or "$" in k
:
2332 raise EngineException(
2333 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2337 if isinstance(v
, (dict, tuple, list)):
2338 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2339 return additional_params
2341 def _check_descriptor_dependencies(self
, session
, descriptor
):
2343 Check that the dependent descriptors exist on a new descriptor or edition
2344 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2345 :param descriptor: descriptor to be inserted or edit
2346 :return: None or raises exception
2348 if not descriptor
.get("nst-ref"):
2350 nstd_id
= descriptor
["nst-ref"]
2351 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
2352 raise EngineException(
2353 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2356 http_code
=HTTPStatus
.CONFLICT
,
2359 def check_conflict_on_del(self
, session
, _id
, db_content
):
2361 Check that NSI is not instantiated
2362 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2363 :param _id: nsi internal id
2364 :param db_content: The database content of the _id
2365 :return: None or raises EngineException with the conflict
2367 if session
["force"]:
2370 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2371 raise EngineException(
2372 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2373 "Launch 'terminate' operation first; or force deletion".format(_id
),
2374 http_code
=HTTPStatus
.CONFLICT
,
2377 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2379 Deletes associated nsilcmops from database. Deletes associated filesystem.
2380 Set usageState of nst
2381 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2382 :param _id: server internal id
2383 :param db_content: The database content of the descriptor
2384 :param not_send_msg: To not send message (False) or store content (list) instead
2385 :return: None if ok or raises EngineException with the problem
2388 # Deleting the nsrs belonging to nsir
2390 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2391 nsr_id
= nsrs_detailed_item
["nsrId"]
2392 if nsrs_detailed_item
.get("shared"):
2394 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2395 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2396 "_id.ne": nsir
["_id"],
2398 nsi
= self
.db
.get_one(
2399 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2401 if nsi
: # last one using nsr
2404 self
.nsrTopic
.delete(
2405 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2407 except (DbException
, EngineException
) as e
:
2408 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2413 # delete related nsilcmops database entries
2414 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2416 # Check and set used NST usage state
2417 nsir_admin
= nsir
.get("_admin")
2418 if nsir_admin
and nsir_admin
.get("nst-id"):
2419 # check if used by another NSI
2420 nsis_list
= self
.db
.get_one(
2422 {"nst-id": nsir_admin
["nst-id"]},
2423 fail_on_empty
=False,
2429 {"_id": nsir_admin
["nst-id"]},
2430 {"_admin.usageState": "NOT_IN_USE"},
2433 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2435 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2436 :param rollback: list to append the created items at database in case a rollback must be done
2437 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2438 :param indata: params to be used for the nsir
2439 :param kwargs: used to override the indata descriptor
2440 :param headers: http request headers
2441 :return: the _id of nsi descriptor created at database
2445 step
= "checking quotas"
2446 self
.check_quota(session
)
2449 slice_request
= self
._remove
_envelop
(indata
)
2450 # Override descriptor with query string kwargs
2451 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2452 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2455 step
= "getting nstd id='{}' from database".format(
2456 slice_request
.get("nstId")
2458 _filter
= self
._get
_project
_filter
(session
)
2459 _filter
["_id"] = slice_request
["nstId"]
2460 nstd
= self
.db
.get_one("nsts", _filter
)
2461 # check NST is not disabled
2462 step
= "checking NST operationalState"
2463 if nstd
["_admin"]["operationalState"] == "DISABLED":
2464 raise EngineException(
2465 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2466 "instance".format(slice_request
["nstId"]),
2467 http_code
=HTTPStatus
.CONFLICT
,
2471 # check NSD is not disabled
2472 step
= "checking operationalState"
2473 if nstd
["_admin"]["operationalState"] == "DISABLED":
2474 raise EngineException(
2475 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2476 "a network slice".format(slice_request
["nstId"]),
2477 http_code
=HTTPStatus
.CONFLICT
,
2480 nstd
.pop("_admin", None)
2481 nstd_id
= nstd
.pop("_id", None)
2482 nsi_id
= str(uuid4())
2483 step
= "filling nsi_descriptor with input data"
2488 "name": slice_request
["nsiName"],
2489 "description": slice_request
.get("nsiDescription", ""),
2490 "datacenter": slice_request
["vimAccountId"],
2491 "nst-ref": nstd
["id"],
2492 "instantiation_parameters": slice_request
,
2493 "network-slice-template": nstd
,
2497 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2500 step
= "creating nsi at database"
2502 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2504 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2505 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2506 nsi_descriptor
["_admin"]["deployed"] = {}
2507 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2508 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2510 # Creating netslice-vld for the RO.
2511 step
= "creating netslice-vld at database"
2513 # Building the vlds list to be deployed
2514 # From netslice descriptors, creating the initial list
2517 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2518 # Getting template Instantiation parameters from NST
2519 nsi_vld
= deepcopy(netslice_vlds
)
2520 nsi_vld
["shared-nsrs-list"] = []
2521 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2522 nsi_vlds
.append(nsi_vld
)
2524 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2525 # Creating netslice-subnet_record.
2529 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2530 for member_ns
in nstd
["netslice-subnet"]:
2531 nsd_id
= member_ns
["nsd-ref"]
2532 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2533 member_ns
["nsd-ref"], member_ns
["id"]
2535 if nsd_id
not in needed_nsds
:
2537 _filter
["id"] = nsd_id
2538 nsd
= self
.db
.get_one(
2539 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2543 needed_nsds
[nsd_id
] = nsd
2545 nsd
= needed_nsds
[nsd_id
]
2546 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2547 services
.append(member_ns
)
2549 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2550 member_ns
["nsd-ref"], member_ns
["id"]
2553 # creates Network Services records (NSRs)
2554 step
= "creating nsrs at database using NsrTopic.new()"
2555 ns_params
= slice_request
.get("netslice-subnet")
2557 nsi_netslice_subnet
= []
2558 for service
in services
:
2559 # Check if the netslice-subnet is shared and if it is share if the nss exists
2562 # Is the nss shared and instantiated?
2563 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2564 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2567 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2568 nsi
= self
.db
.get_one(
2569 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2571 if nsi
and service
.get("is-shared-nss"):
2572 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2573 for nsrs_detailed_item
in nsrs_detailed_list
:
2574 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2575 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2576 _id_nsr
= nsrs_detailed_item
["nsrId"]
2578 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2579 if netslice_subnet
["nss-id"] == service
["id"]:
2580 indata_ns
= netslice_subnet
2584 if service
.get("instantiation-parameters"):
2585 indata_ns
= deepcopy(service
["instantiation-parameters"])
2586 # del service["instantiation-parameters"]
2588 indata_ns
["nsdId"] = service
["_id"]
2589 indata_ns
["nsName"] = (
2590 slice_request
.get("nsiName") + "." + service
["id"]
2592 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2593 indata_ns
["nsDescription"] = service
["description"]
2594 if slice_request
.get("ssh_keys"):
2595 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2598 for ns_param
in ns_params
:
2599 if ns_param
.get("id") == service
["id"]:
2600 copy_ns_param
= deepcopy(ns_param
)
2601 del copy_ns_param
["id"]
2602 indata_ns
.update(copy_ns_param
)
2605 # Creates Nsr objects
2606 _id_nsr
, _
= self
.nsrTopic
.new(
2607 rollback
, session
, indata_ns
, kwargs
, headers
2611 "shared": service
.get("is-shared-nss"),
2612 "nsd-id": service
["nsd-ref"],
2613 "nss-id": service
["id"],
2614 "nslcmop_instantiate": None,
2616 indata_ns
["nss-id"] = service
["id"]
2617 nsrs_list
.append(nsrs_item
)
2618 nsi_netslice_subnet
.append(indata_ns
)
2619 nsr_ref
= {"nsr-ref": _id_nsr
}
2620 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2622 # Adding the nsrs list to the nsi
2623 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2624 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2626 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2629 # Creating the entry in the database
2630 self
.db
.create("nsis", nsi_descriptor
)
2631 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2633 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2634 self
.logger
.exception(
2635 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2637 raise EngineException("Error {}: {}".format(step
, e
))
2638 except ValidationError
as e
:
2639 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2641 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2642 raise EngineException(
2643 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2647 class NsiLcmOpTopic(BaseTopic
):
2650 operation_schema
= { # mapping between operation and jsonschema to validate
2651 "instantiate": nsi_instantiate
,
2655 def __init__(self
, db
, fs
, msg
, auth
):
2656 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2657 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2659 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2661 Check that user has enter right parameters for the operation
2662 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2663 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2664 :param indata: descriptor with the parameters of the operation
2668 nstd
= nsir
["network-slice-template"]
2670 def check_valid_netslice_subnet_id(nstId
):
2671 # TODO change to vnfR (??)
2672 for netslice_subnet
in nstd
["netslice-subnet"]:
2673 if nstId
== netslice_subnet
["id"]:
2674 nsd_id
= netslice_subnet
["nsd-ref"]
2675 if nsd_id
not in nsds
:
2676 _filter
= self
._get
_project
_filter
(session
)
2677 _filter
["id"] = nsd_id
2678 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2681 raise EngineException(
2682 "Invalid parameter nstId='{}' is not one of the "
2683 "nst:netslice-subnet".format(nstId
)
2686 if operation
== "instantiate":
2687 # check the existance of netslice-subnet items
2688 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2689 check_valid_netslice_subnet_id(in_nst
["id"])
2691 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2697 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2698 "statusEnteredTime": now
,
2699 "netsliceInstanceId": netsliceInstanceId
,
2700 "lcmOperationType": operation
,
2702 "isAutomaticInvocation": False,
2703 "operationParams": params
,
2704 "isCancelPending": False,
2706 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2707 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2708 + netsliceInstanceId
,
2713 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2714 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2715 if nst_sb_item
.get("is-shared-nss"):
2716 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2717 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2718 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2719 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2720 "nss-connection-point-ref"
2723 admin_subnet_item
["nss-id"]
2724 == admin_vld_nss_cp_ref_item
["nss-ref"]
2727 not nsr_item
["nsrId"]
2728 in admin_vld_item
["shared-nsrs-list"]
2730 admin_vld_item
["shared-nsrs-list"].append(
2734 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2737 {"_id": nsir
["_id"]},
2738 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2741 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2743 Performs a new operation over a ns
2744 :param rollback: list to append created items at database in case a rollback must to be done
2745 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2746 :param indata: descriptor with the parameters of the operation. It must contains among others
2747 netsliceInstanceId: _id of the nsir to perform the operation
2748 operation: it can be: instantiate, terminate, action, TODO: update, heal
2749 :param kwargs: used to override the indata descriptor
2750 :param headers: http request headers
2751 :return: id of the nslcmops
2754 # Override descriptor with query string kwargs
2755 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2756 operation
= indata
["lcmOperationType"]
2757 netsliceInstanceId
= indata
["netsliceInstanceId"]
2758 validate_input(indata
, self
.operation_schema
[operation
])
2760 # get nsi from netsliceInstanceId
2761 _filter
= self
._get
_project
_filter
(session
)
2762 _filter
["_id"] = netsliceInstanceId
2763 nsir
= self
.db
.get_one("nsis", _filter
)
2764 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2769 not nsir
["_admin"].get("nsiState")
2770 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2772 if operation
== "terminate" and indata
.get("autoremove"):
2773 # NSIR must be deleted
2777 ) # a none in this case is used to indicate not instantiated. It can be removed
2778 if operation
!= "instantiate":
2779 raise EngineException(
2780 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2781 netsliceInstanceId
, operation
2783 HTTPStatus
.CONFLICT
,
2786 if operation
== "instantiate" and not session
["force"]:
2787 raise EngineException(
2788 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2789 netsliceInstanceId
, operation
2791 HTTPStatus
.CONFLICT
,
2794 # Creating all the NS_operation (nslcmop)
2795 # Get service list from db
2796 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2798 # nslcmops_item = None
2799 for index
, nsr_item
in enumerate(nsrs_list
):
2800 nsr_id
= nsr_item
["nsrId"]
2801 if nsr_item
.get("shared"):
2802 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2803 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2805 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2807 _filter
["_id.ne"] = netsliceInstanceId
2808 nsi
= self
.db
.get_one(
2809 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2811 if operation
== "terminate":
2813 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2817 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2820 ): # other nsi is using this nsr and it needs this nsr instantiated
2821 continue # do not create nsilcmop
2823 # looks the first nsi fulfilling the conditions but not being the current NSIR
2825 nsi_nsr_item
= next(
2827 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2828 if n
["nsrId"] == nsr_id
2830 and n
["nslcmop_instantiate"]
2832 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2833 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2835 "_admin.nsrs-detailed-list.{}".format(
2839 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2840 # continue to not create nslcmop since nsrs is shared and nsrs was created
2843 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2848 "lcmOperationType": operation
,
2849 "nsInstanceId": nsr_id
,
2850 # Including netslice_id in the ns instantiate Operation
2851 "netsliceInstanceId": netsliceInstanceId
,
2853 if operation
== "instantiate":
2854 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2855 indata_ns
.update(service
["instantiate_params"])
2857 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2858 # message via kafka bus
2859 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2860 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2862 nslcmops
.append(nslcmop
)
2863 if operation
== "instantiate":
2865 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2869 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2870 except (DbException
, EngineException
) as e
:
2871 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2874 + "skipping NS={} because not found".format(nsr_id
)
2881 indata
["nslcmops_ids"] = nslcmops
2882 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2884 nsilcmop_desc
= self
._create
_nsilcmop
(
2885 session
, netsliceInstanceId
, operation
, indata
2888 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2890 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2891 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2892 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2894 except ValidationError
as e
:
2895 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2897 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2898 raise EngineException(
2899 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2902 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2903 raise EngineException(
2904 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR