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 (
34 from osm_nbi
.base_topic
import (
41 from yaml
import safe_dump
42 from osm_common
.dbbase
import DbException
43 from osm_common
.msgbase
import MsgException
44 from osm_common
.fsbase
import FsException
45 from osm_nbi
import utils
48 ) # For checking that additional parameter names are valid Jinja2 identifiers
50 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
53 class NsrTopic(BaseTopic
):
56 quota_name
= "ns_instances"
57 schema_new
= ns_instantiate
59 def __init__(self
, db
, fs
, msg
, auth
):
60 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
62 def _check_descriptor_dependencies(self
, session
, descriptor
):
64 Check that the dependent descriptors exist on a new descriptor or edition
65 :param session: client session information
66 :param descriptor: descriptor to be inserted or edit
67 :return: None or raises exception
69 if not descriptor
.get("nsdId"):
71 nsd_id
= descriptor
["nsdId"]
72 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
73 raise EngineException(
74 "Descriptor error at nsdId='{}' references a non exist nsd".format(
77 http_code
=HTTPStatus
.CONFLICT
,
81 def format_on_new(content
, project_id
=None, make_public
=False):
82 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
83 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
86 def check_conflict_on_del(self
, session
, _id
, db_content
):
88 Check that NSR is not instantiated
89 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
90 :param _id: nsr internal id
91 :param db_content: The database content of the nsr
92 :return: None or raises EngineException with the conflict
97 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
98 raise EngineException(
99 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
100 "Launch 'terminate' operation first; or force deletion".format(_id
),
101 http_code
=HTTPStatus
.CONFLICT
,
104 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
106 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
107 Set usageState of pdu, vnfd, nsd
108 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
109 :param _id: server internal id
110 :param db_content: The database content of the descriptor
111 :param not_send_msg: To not send message (False) or store content (list) instead
112 :return: None if ok or raises EngineException with the problem
114 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
115 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
116 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
118 # set all used pdus as free
121 {"_admin.usage.nsr_id": _id
},
122 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
127 used_nsd_id
= nsr
.get("nsd-id")
129 # check if used by another NSR
130 nsrs_list
= self
.db
.get_one(
131 "nsrs", {"nsd-id": used_nsd_id
}, fail_on_empty
=False, fail_on_more
=False
135 "nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"}
138 # Set VNFD usageState
139 used_vnfd_id_list
= nsr
.get("vnfd-id")
140 if used_vnfd_id_list
:
141 for used_vnfd_id
in used_vnfd_id_list
:
142 # check if used by another NSR
143 nsrs_list
= self
.db
.get_one(
145 {"vnfd-id": used_vnfd_id
},
152 {"_id": used_vnfd_id
},
153 {"_admin.usageState": "NOT_IN_USE"},
156 # delete extra ro_nsrs used for internal RO module
157 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
160 def _format_ns_request(ns_request
):
161 formated_request
= copy(ns_request
)
162 formated_request
.pop("additionalParamsForNs", None)
163 formated_request
.pop("additionalParamsForVnf", None)
164 return formated_request
167 def _format_additional_params(
168 ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None
171 Get and format user additional params for NS or VNF
172 :param ns_request: User instantiation additional parameters
173 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
174 :param descriptor: If not None it check that needed parameters of descriptor are supplied
175 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
177 additional_params
= None
179 if not member_vnf_index
:
180 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
181 where_
= "additionalParamsForNs"
182 elif ns_request
.get("additionalParamsForVnf"):
183 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
189 for x
in ns_request
["additionalParamsForVnf"]
190 if x
["member-vnf-index"] == member_vnf_index
195 if not vdu_id
and not kdu_name
:
197 additional_params
= copy(item
.get("additionalParams")) or {}
198 if vdu_id
and item
.get("additionalParamsForVdu"):
202 for x
in item
["additionalParamsForVdu"]
203 if x
["vdu_id"] == vdu_id
207 other_params
= item_vdu
208 if item_vdu
and item_vdu
.get("additionalParams"):
209 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
210 additional_params
= item_vdu
["additionalParams"]
212 additional_params
= {}
213 if item
.get("additionalParamsForKdu"):
217 for x
in item
["additionalParamsForKdu"]
218 if x
["kdu_name"] == kdu_name
222 other_params
= item_kdu
223 if item_kdu
and item_kdu
.get("additionalParams"):
224 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(
227 additional_params
= item_kdu
["additionalParams"]
229 if additional_params
:
230 for k
, v
in additional_params
.items():
231 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
232 if not kdu_name
and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k
):
233 raise EngineException(
234 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
235 "and underscores, and cannot start with a digit".format(
239 # END Check that additional parameter names are valid Jinja2 identifiers
240 if not isinstance(k
, str):
241 raise EngineException(
242 "Invalid param at {}:{}. Only string keys are allowed".format(
247 raise EngineException(
248 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
252 if isinstance(v
, (dict, tuple, list)):
253 additional_params
[k
] = "!!yaml " + safe_dump(v
)
255 additional_params
= json
.dumps(additional_params
)
258 for df
in descriptor
.get("df", []):
259 # check that enough parameters are supplied for the initial-config-primitive
260 # TODO: check for cloud-init
262 initial_primitives
= []
264 "lcm-operations-configuration" in df
265 and "operate-vnf-op-config"
266 in df
["lcm-operations-configuration"]
268 for config
in df
["lcm-operations-configuration"][
269 "operate-vnf-op-config"
271 for primitive
in get_iterable(
272 config
.get("initial-config-primitive")
274 initial_primitives
.append(primitive
)
276 initial_primitives
= deep_get(
277 descriptor
, ("ns-configuration", "initial-config-primitive")
280 for initial_primitive
in get_iterable(initial_primitives
):
281 for param
in get_iterable(initial_primitive
.get("parameter")):
282 if param
["value"].startswith("<") and param
["value"].endswith(
285 if param
["value"] in (
292 not additional_params
293 or param
["value"][1:-1] not in additional_params
295 raise EngineException(
296 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
297 "initial-config-primitive[name={}] not supplied".format(
300 initial_primitive
["name"],
304 return additional_params
or None, other_params
or None
306 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
308 Creates a new nsr into database. It also creates needed vnfrs
309 :param rollback: list to append the created items at database in case a rollback must be done
310 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
311 :param indata: params to be used for the nsr
312 :param kwargs: used to override the indata descriptor
313 :param headers: http request headers
314 :return: the _id of nsr descriptor created at database. Or an exception of type
315 EngineException, ValidationError, DbException, FsException, MsgException.
316 Note: Exceptions are not captured on purpose. They should be captured at called
319 step
= "checking quotas"
320 self
.check_quota(session
)
322 step
= "validating input parameters"
323 ns_request
= self
._remove
_envelop
(indata
)
324 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
325 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
327 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
328 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
329 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
331 step
= "checking nsdOperationalState"
332 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
334 step
= "filling nsr from input data"
335 nsr_id
= str(uuid4())
336 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(
337 nsd
, ns_request
, nsr_id
, session
342 # TODO: Change for multiple df support
343 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
344 for vnfp
in vnf_profiles
:
345 vnfd_id
= vnfp
.get("vnfd-id")
346 vnf_index
= vnfp
.get("id")
348 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
352 if vnfd_id
not in needed_vnfds
:
353 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
354 if "revision" in vnfd
["_admin"]:
355 vnfd
["revision"] = vnfd
["_admin"]["revision"]
357 needed_vnfds
[vnfd_id
] = vnfd
358 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
360 vnfd
= needed_vnfds
[vnfd_id
]
362 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
365 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(
375 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
378 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
379 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
381 step
= "creating nsr at database"
382 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
384 step
= "creating nsr temporal folder"
385 self
.fs
.mkdir(nsr_id
)
395 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
397 def _get_nsd_from_db(self
, nsd_id
, session
):
398 _filter
= self
._get
_project
_filter
(session
)
399 _filter
["_id"] = nsd_id
400 return self
.db
.get_one("nsds", _filter
)
402 def _get_vnfd_from_db(self
, vnfd_id
, session
):
403 _filter
= self
._get
_project
_filter
(session
)
404 _filter
["id"] = vnfd_id
405 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
408 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
410 nsr_descriptor
, session
["project_id"], make_public
=session
["public"]
412 self
.db
.create("nsrs", nsr_descriptor
)
413 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
415 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
417 vnfr_descriptor
, session
["project_id"], make_public
=session
["public"]
419 self
.db
.create("vnfrs", vnfr_descriptor
)
420 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
422 def _check_nsd_operational_state(self
, nsd
, ns_request
):
423 if nsd
["_admin"]["operationalState"] == "DISABLED":
424 raise EngineException(
425 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
426 "a network service".format(ns_request
["nsdId"]),
427 http_code
=HTTPStatus
.CONFLICT
,
430 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
431 additional_params
, _
= self
._format
_additional
_params
(
432 ns_request
, descriptor
=nsd
434 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
435 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
436 if ns_request
and ns_request
.get("k8s-namespace"):
437 ns_k8s_namespace
= ns_request
["k8s-namespace"]
438 if additional_params
and additional_params
.get("k8s-namespace"):
439 ns_k8s_namespace
= additional_params
["k8s-namespace"]
441 return ns_k8s_namespace
443 def _add_flavor_to_nsr(self
, vdu
, vnfd
, nsr_descriptor
):
446 # Find this vdu compute and storage descriptors
447 vdu_virtual_compute
= {}
448 vdu_virtual_storage
= {}
449 for vcd
in vnfd
.get("virtual-compute-desc", ()):
450 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
451 vdu_virtual_compute
= vcd
452 for vsd
in vnfd
.get("virtual-storage-desc", ()):
453 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
454 vdu_virtual_storage
= vsd
455 # Get this vdu vcpus, memory and storage info for flavor_data
456 if vdu_virtual_compute
.get("virtual-cpu", {}).get(
459 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"][
462 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
463 flavor_data
["memory-mb"] = (
464 float(vdu_virtual_compute
["virtual-memory"]["size"])
467 if vdu_virtual_storage
.get("size-of-storage"):
468 flavor_data
["storage-gb"] = vdu_virtual_storage
[
471 # Get this vdu EPA info for guest_epa
472 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
473 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"][
476 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
477 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
478 if vcpu_pinning
.get("thread-policy"):
479 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
[
482 if vcpu_pinning
.get("policy"):
485 if vcpu_pinning
["policy"] == "dynamic"
488 guest_epa
["cpu-pinning-policy"] = cpu_policy
489 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
490 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"][
493 if vdu_virtual_compute
.get("virtual-memory", {}).get(
496 guest_epa
["mempage-size"] = vdu_virtual_compute
[
499 if vdu_virtual_compute
.get("virtual-memory", {}).get(
502 guest_epa
["numa-node-policy"] = vdu_virtual_compute
[
504 ]["numa-node-policy"]
505 if vdu_virtual_storage
.get("disk-io-quota"):
506 guest_epa
["disk-io-quota"] = vdu_virtual_storage
[
511 flavor_data
["guest-epa"] = guest_epa
513 flavor_data
["name"] = vdu
["id"][:56] + "-flv"
514 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
515 nsr_descriptor
["flavor"].append(flavor_data
)
517 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
519 additional_params
, _
= self
._format
_additional
_params
(
520 ns_request
, descriptor
=nsd
524 "name": ns_request
["nsName"],
525 "name-ref": ns_request
["nsName"],
526 "short-name": ns_request
["nsName"],
527 "admin-status": "ENABLED",
528 "nsState": "NOT_INSTANTIATED",
529 "currentOperation": "IDLE",
530 "currentOperationID": None,
531 "errorDescription": None,
533 "deploymentStatus": None,
534 "configurationStatus": None,
536 "nsd": {k
: v
for k
, v
in nsd
.items()},
537 "datacenter": ns_request
["vimAccountId"],
538 "resource-orchestrator": "osmopenmano",
539 "description": ns_request
.get("nsDescription", ""),
540 "constituent-vnfr-ref": [],
541 "operational-status": "init", # typedef ns-operational-
542 "config-status": "init", # typedef config-states
543 "detailed-status": "scheduled",
544 "orchestration-progress": {},
546 "nsd-name-ref": nsd
["name"],
547 "operational-events": [], # "id", "timestamp", "description", "event",
548 "nsd-ref": nsd
["id"],
549 "nsd-id": nsd
["_id"],
551 "instantiate_params": self
._format
_ns
_request
(ns_request
),
552 "additionalParamsForNs": additional_params
,
553 "ns-instance-config-ref": nsr_id
,
556 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
559 "affinity-or-anti-affinity-group": [],
561 if "revision" in nsd
["_admin"]:
562 nsr_descriptor
["revision"] = nsd
["_admin"]["revision"]
564 ns_request
["nsr_id"] = nsr_id
565 if ns_request
and ns_request
.get("config-units"):
566 nsr_descriptor
["config-units"] = ns_request
["config-units"]
568 if nsd
.get("virtual-link-desc"):
569 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
570 # Fill each vld with vnfd-connection-point-ref data
571 # TODO: Change for multiple df support
572 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
573 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
574 for vnf_profile
in vnf_profiles
:
575 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
576 for cpd
in vlc
.get("constituent-cpd-id", ()):
577 all_vld_connection_point_data
[
578 vlc
.get("virtual-link-profile-id")
581 "member-vnf-index-ref": cpd
.get(
582 "constituent-base-element-id"
584 "vnfd-connection-point-ref": cpd
.get(
587 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
591 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
594 for vdu
in vnfd
.get("vdu", ()):
595 self
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr_descriptor
)
596 sw_image_id
= vdu
.get("sw-image-desc")
598 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
599 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
601 # also add alternative images to the list of images
602 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
603 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
604 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
606 # Add Affinity or Anti-affinity group information to NSR
607 vdu_profiles
= vnfd
.get("df", [[]])[0].get("vdu-profile", ())
608 affinity_group_prefix_name
= "{}-{}".format(
609 nsr_descriptor
["name"][:16], vnf_profile
.get("id")[:16]
612 for vdu_profile
in vdu_profiles
:
613 affinity_group_data
= {}
614 for affinity_group
in vdu_profile
.get(
615 "affinity-or-anti-affinity-group", ()
617 affinity_group_data
= (
618 self
._get
_affinity
_or
_anti
_affinity
_group
_data
_from
_vnfd
(
619 vnfd
, affinity_group
["id"]
622 affinity_group_data
["member-vnf-index"] = vnf_profile
.get("id")
623 self
._add
_affinity
_or
_anti
_affinity
_group
_to
_nsr
(
626 affinity_group_prefix_name
,
630 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
633 vld
["name"] = vld
["id"]
634 nsr_descriptor
["vld"] = nsr_vld
636 return nsr_descriptor
638 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
639 self
, vnfd
, affinity_group_id
642 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
644 affinity_group
= utils
.find_in_list(
645 vnfd
.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
646 lambda ag
: ag
["id"] == affinity_group_id
,
648 affinity_group_data
= {}
650 if affinity_group
.get("id"):
651 affinity_group_data
["ag-id"] = affinity_group
["id"]
652 if affinity_group
.get("type"):
653 affinity_group_data
["type"] = affinity_group
["type"]
654 if affinity_group
.get("scope"):
655 affinity_group_data
["scope"] = affinity_group
["scope"]
656 return affinity_group_data
658 def _add_affinity_or_anti_affinity_group_to_nsr(
659 self
, nsr_descriptor
, affinity_group_data
, affinity_group_prefix_name
662 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
664 affinity_group
= next(
667 for f
in nsr_descriptor
["affinity-or-anti-affinity-group"]
668 if all(f
.get(k
) == affinity_group_data
[k
] for k
in affinity_group_data
)
672 if not affinity_group
:
673 affinity_group_data
["id"] = str(
674 len(nsr_descriptor
["affinity-or-anti-affinity-group"])
676 affinity_group_data
["name"] = "{}-{}".format(
677 affinity_group_prefix_name
, affinity_group_data
["ag-id"][:32]
679 nsr_descriptor
["affinity-or-anti-affinity-group"].append(
683 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
684 sw_image_desc
= utils
.find_in_list(
685 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
688 if sw_image_desc
.get("image"):
689 image_data
["image"] = sw_image_desc
["image"]
690 if sw_image_desc
.get("checksum"):
691 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
692 if sw_image_desc
.get("vim-type"):
693 image_data
["vim-type"] = sw_image_desc
["vim-type"]
696 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
698 Adds image to nsr checking first it is not already added
703 for f
in nsr_descriptor
["image"]
704 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
709 image_data
["id"] = str(len(nsr_descriptor
["image"]))
710 nsr_descriptor
["image"].append(image_data
)
712 def _create_vnfr_descriptor_from_vnfd(
722 vnfr_id
= str(uuid4())
723 nsr_id
= nsr_descriptor
["id"]
725 additional_params
, vnf_params
= self
._format
_additional
_params
(
726 ns_request
, vnf_index
, descriptor
=vnfd
732 "nsr-id-ref": nsr_id
,
733 "member-vnf-index-ref": vnf_index
,
734 "additionalParamsForVnf": additional_params
,
736 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
738 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
739 "vim-account-id": None,
742 "connection-point": [],
743 "ip-address": None, # mgmt-interface filled by LCM
746 # Revision backwards compatility. Only specify the revision in the record if
747 # the original VNFD has a revision.
748 if "revision" in vnfd
:
749 vnfr_descriptor
["revision"] = vnfd
["revision"]
752 vnf_k8s_namespace
= ns_k8s_namespace
754 if vnf_params
.get("k8s-namespace"):
755 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
756 if vnf_params
.get("config-units"):
757 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
760 if vnfd
.get("int-virtual-link-desc"):
761 vnfr_descriptor
["vld"] = []
762 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
763 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
765 for cp
in vnfd
.get("ext-cpd", ()):
767 "name": cp
.get("id"),
768 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
769 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
771 # "ip-address", "mac-address" # filled by LCM
772 # vim-id # TODO it would be nice having a vim port id
774 vnfr_descriptor
["connection-point"].append(vnf_cp
)
776 # Create k8s-cluster information
777 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
778 if vnfd
.get("k8s-cluster"):
779 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
780 all_k8s_cluster_nets_cpds
= {}
781 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
782 if cpd
.get("k8s-cluster-net"):
783 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
786 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
787 if net
.get("id") in all_k8s_cluster_nets_cpds
:
788 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
793 for kdu
in get_iterable(vnfd
.get("kdu")):
794 additional_params
, kdu_params
= self
._format
_additional
_params
(
795 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
797 kdu_k8s_namespace
= vnf_k8s_namespace
798 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
799 if kdu_params
and kdu_params
.get("k8s-namespace"):
800 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
802 kdu_deployment_name
= ""
803 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
804 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
807 "additionalParams": additional_params
,
808 "k8s-namespace": kdu_k8s_namespace
,
809 "kdu-deployment-name": kdu_deployment_name
,
810 "kdu-name": kdu
["name"],
811 # TODO "name": "" Name of the VDU in the VIM
812 "ip-address": None, # mgmt-interface filled by LCM
815 if kdu_params
and kdu_params
.get("config-units"):
816 kdur
["config-units"] = kdu_params
["config-units"]
817 if kdu
.get("helm-version"):
818 kdur
["helm-version"] = kdu
["helm-version"]
819 for k8s_type
in ("helm-chart", "juju-bundle"):
820 if kdu
.get(k8s_type
):
821 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
822 if not vnfr_descriptor
.get("kdur"):
823 vnfr_descriptor
["kdur"] = []
824 vnfr_descriptor
["kdur"].append(kdur
)
826 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
828 for vdu
in vnfd
.get("vdu", ()):
831 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
832 "operate-vnf-op-config"
834 vdu_config
= utils
.find_in_list(
835 configs
, lambda config
: config
["id"] == vdu
["id"]
841 vdu_instantiation_level
= utils
.find_in_list(
842 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
843 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
846 vdu_instantiation_level
= None
849 external_connection_ee
= utils
.filter_in_list(
850 vdu_config
.get("execution-environment-list", []),
851 lambda ee
: "external-connection-point-ref" in ee
,
853 for ee
in external_connection_ee
:
854 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
856 additional_params
, vdu_params
= self
._format
_additional
_params
(
857 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
861 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
862 vnfd
.get("virtual-storage-desc", []),
863 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"]
866 vdu_virtual_storage_descriptors
= []
868 "vdu-id-ref": vdu
["id"],
869 # TODO "name": "" Name of the VDU in the VIM
870 "ip-address": None, # mgmt-interface filled by LCM
871 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
872 "internal-connection-point": [],
874 "additionalParams": additional_params
,
875 "vdu-name": vdu
["name"],
876 "virtual-storages": vdu_virtual_storage_descriptors
878 if vdu_params
and vdu_params
.get("config-units"):
879 vdur
["config-units"] = vdu_params
["config-units"]
880 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
881 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
884 if vdu
.get("pdu-type"):
885 vdur
["pdu-type"] = vdu
["pdu-type"]
886 vdur
["name"] = vdu
["pdu-type"]
887 # TODO volumes: name, volume-id
888 for icp
in vdu
.get("int-cpd", ()):
891 "connection-point-id": icp
["id"],
892 "name": icp
.get("id"),
895 vdur
["internal-connection-point"].append(vdu_icp
)
897 for iface
in icp
.get("virtual-network-interface-requirement", ()):
898 iface_fields
= ("name", "mac-address")
900 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
903 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
904 if "port-security-enabled" in icp
:
905 vdu_iface
["port-security-enabled"] = icp
[
906 "port-security-enabled"
909 if "port-security-disable-strategy" in icp
:
910 vdu_iface
["port-security-disable-strategy"] = icp
[
911 "port-security-disable-strategy"
914 for ext_cp
in vnfd
.get("ext-cpd", ()):
915 if not ext_cp
.get("int-cpd"):
917 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
919 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
920 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
924 if "port-security-enabled" in ext_cp
:
925 vdu_iface
["port-security-enabled"] = ext_cp
[
926 "port-security-enabled"
929 if "port-security-disable-strategy" in ext_cp
:
930 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
931 "port-security-disable-strategy"
938 and vdu_iface
.get("external-connection-point-ref")
941 vdu_iface
["mgmt-vnf"] = True
942 vdu_iface
["mgmt-interface"] = True
944 for ecp
in vdu_mgmt_cp
:
945 if vdu_iface
.get("external-connection-point-ref") == ecp
:
946 vdu_iface
["mgmt-interface"] = True
948 if iface
.get("virtual-interface"):
949 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
951 # look for network where this interface is connected
952 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
954 # TODO: Change for multiple df support
955 for df
in get_iterable(nsd
.get("df")):
956 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
957 for vlc_index
, vlc
in enumerate(
959 vnf_profile
.get("virtual-link-connectivity")
962 for cpd
in get_iterable(
963 vlc
.get("constituent-cpd-id")
966 cpd
.get("constituent-cpd-id")
969 vdu_iface
["ns-vld-id"] = vlc
.get(
970 "virtual-link-profile-id"
972 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
973 if vdu_iface
.get("type") in (
977 nsr_descriptor
["vld"][vlc_index
][
981 elif vdu_iface
.get("internal-connection-point-ref"):
982 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
983 # TODO: store fixed IP address in the record (if it exists in the ICP)
984 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
985 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
986 ivld_index
= utils
.find_index_in_list(
987 vnfd
.get("int-virtual-link-desc", ()),
988 lambda ivld
: ivld
["id"]
989 == icp
.get("int-virtual-link-desc"),
991 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
993 vdur
["interfaces"].append(vdu_iface
)
995 if vdu
.get("sw-image-desc"):
996 sw_image
= utils
.find_in_list(
997 vnfd
.get("sw-image-desc", ()),
998 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
1000 nsr_sw_image_data
= utils
.find_in_list(
1001 nsr_descriptor
["image"],
1002 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
1004 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
1006 if vdu
.get("alternative-sw-image-desc"):
1008 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
1009 sw_image
= utils
.find_in_list(
1010 vnfd
.get("sw-image-desc", ()),
1011 lambda image
: image
["id"] == alt_image_id
,
1013 nsr_sw_image_data
= utils
.find_in_list(
1014 nsr_descriptor
["image"],
1016 nsr_image
.get("image") == sw_image
.get("image")
1019 alt_image_ids
.append(nsr_sw_image_data
["id"])
1020 vdur
["alt-image-ids"] = alt_image_ids
1022 flavor_data_name
= vdu
["id"][:56] + "-flv"
1023 nsr_flavor_desc
= utils
.find_in_list(
1024 nsr_descriptor
["flavor"],
1025 lambda flavor
: flavor
["name"] == flavor_data_name
,
1029 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
1031 # Adding Affinity groups information to vdur
1033 vdu_profile_affinity_group
= utils
.find_in_list(
1034 vnfd
.get("df")[0]["vdu-profile"],
1035 lambda a_vdu
: a_vdu
["id"] == vdu
["id"],
1038 vdu_profile_affinity_group
= None
1040 if vdu_profile_affinity_group
:
1041 affinity_group_ids
= []
1042 for affinity_group
in vdu_profile_affinity_group
.get(
1043 "affinity-or-anti-affinity-group", ()
1045 vdu_affinity_group
= utils
.find_in_list(
1046 vdu_profile_affinity_group
.get(
1047 "affinity-or-anti-affinity-group", ()
1049 lambda ag_fp
: ag_fp
["id"] == affinity_group
["id"],
1051 nsr_affinity_group
= utils
.find_in_list(
1052 nsr_descriptor
["affinity-or-anti-affinity-group"],
1054 nsr_ag
.get("ag-id") == vdu_affinity_group
.get("id")
1055 and nsr_ag
.get("member-vnf-index")
1056 == vnfr_descriptor
.get("member-vnf-index-ref")
1059 # Update Affinity Group VIM name if VDU instantiation parameter is present
1060 if vnf_params
and vnf_params
.get("affinity-or-anti-affinity-group"):
1061 vnf_params_affinity_group
= utils
.find_in_list(
1062 vnf_params
["affinity-or-anti-affinity-group"],
1064 vnfp_ag
.get("id") == vdu_affinity_group
.get("id")
1067 if vnf_params_affinity_group
.get("vim-affinity-group-id"):
1069 "vim-affinity-group-id"
1070 ] = vnf_params_affinity_group
["vim-affinity-group-id"]
1071 affinity_group_ids
.append(nsr_affinity_group
["id"])
1072 vdur
["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1074 if vdu_instantiation_level
:
1075 count
= vdu_instantiation_level
.get("number-of-instances")
1079 for index
in range(0, count
):
1080 vdur
= deepcopy(vdur
)
1081 for iface
in vdur
["interfaces"]:
1082 if iface
.get("ip-address") and index
!= 0:
1083 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
1084 if iface
.get("mac-address") and index
!= 0:
1085 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
1087 vdur
["_id"] = str(uuid4())
1088 vdur
["id"] = vdur
["_id"]
1089 vdur
["count-index"] = index
1090 vnfr_descriptor
["vdur"].append(vdur
)
1092 return vnfr_descriptor
1094 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
1096 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1097 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1098 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1099 :param ns_instance_content: ns instance content
1100 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1103 time_now
, time_delta
= time(), time() - ns_instance_content
["_admin"]["modified"]
1104 force_refresh
= isinstance(filter_q
, dict) and filter_q
.get('vcaStatusRefresh') == 'true'
1105 threshold_reached
= time_delta
> 120
1106 if force_refresh
or threshold_reached
:
1107 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
1108 ns_instance_content
["_admin"]["modified"] = time_now
1109 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
1110 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
1111 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1112 nslcmop_desc
["_admin"].pop("nsState")
1113 self
.msg
.write("ns", operation
, nslcmop_desc
)
1116 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1118 Get complete information on an ns instance.
1119 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1120 :param _id: string, ns instance id
1121 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1122 :param api_req: True if this call is serving an external API request. False if serving internal request.
1123 :return: dictionary, raise exception if not found.
1125 ns_instance_content
= super().show(session
, _id
, api_req
)
1126 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1127 return ns_instance_content
1129 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1130 raise EngineException(
1131 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1135 class VnfrTopic(BaseTopic
):
1139 def __init__(self
, db
, fs
, msg
, auth
):
1140 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1142 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1143 raise EngineException(
1144 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1147 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1148 raise EngineException(
1149 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1152 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1153 # Not used because vnfrs are created and deleted by NsrTopic class directly
1154 raise EngineException(
1155 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1159 class NsLcmOpTopic(BaseTopic
):
1162 operation_schema
= { # mapping between operation and jsonschema to validate
1163 "instantiate": ns_instantiate
,
1164 "action": ns_action
,
1165 "update": ns_update
,
1168 "terminate": ns_terminate
,
1169 "migrate": ns_migrate
,
1172 def __init__(self
, db
, fs
, msg
, auth
):
1173 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1174 self
.nsrtopic
= NsrTopic(db
, fs
, msg
, auth
)
1176 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1178 Check that user has enter right parameters for the operation
1179 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1180 :param operation: it can be: instantiate, terminate, action, update, heal
1181 :param indata: descriptor with the parameters of the operation
1184 if operation
== "action":
1185 self
._check
_action
_ns
_operation
(indata
, nsr
)
1186 elif operation
== "scale":
1187 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1188 elif operation
== "update":
1189 self
._check
_update
_ns
_operation
(indata
, nsr
)
1190 elif operation
== "heal":
1191 self
._check
_heal
_ns
_operation
(indata
, nsr
)
1192 elif operation
== "instantiate":
1193 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1195 def _check_action_ns_operation(self
, indata
, nsr
):
1197 # check vnf_member_index
1198 if indata
.get("vnf_member_index"):
1199 indata
["member_vnf_index"] = indata
.pop(
1201 ) # for backward compatibility
1202 if indata
.get("member_vnf_index"):
1203 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1204 indata
["member_vnf_index"], nsr
["_id"]
1207 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1208 "operate-vnf-op-config"
1213 if indata
.get("vdu_id"):
1214 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1215 descriptor_configuration
= utils
.find_in_list(
1216 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1218 elif indata
.get("kdu_name"):
1219 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1220 descriptor_configuration
= utils
.find_in_list(
1221 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1224 descriptor_configuration
= utils
.find_in_list(
1225 configs
, lambda config
: config
["id"] == vnfd
["id"]
1227 if descriptor_configuration
is not None:
1228 descriptor_configuration
= descriptor_configuration
.get(
1232 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1236 # For k8s allows default primitives without validating the parameters
1237 if indata
.get("kdu_name") and indata
["primitive"] in (
1244 # TODO should be checked that rollback only can contains revsision_numbe????
1245 if not indata
.get("member_vnf_index"):
1246 raise EngineException(
1247 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1252 # if not, check primitive
1253 for config_primitive
in get_iterable(descriptor_configuration
):
1254 if indata
["primitive"] == config_primitive
["name"]:
1255 # check needed primitive_params are provided
1256 if indata
.get("primitive_params"):
1257 in_primitive_params_copy
= copy(indata
["primitive_params"])
1259 in_primitive_params_copy
= {}
1260 for paramd
in get_iterable(config_primitive
.get("parameter")):
1261 if paramd
["name"] in in_primitive_params_copy
:
1262 del in_primitive_params_copy
[paramd
["name"]]
1263 elif not paramd
.get("default-value"):
1264 raise EngineException(
1265 "Needed parameter {} not provided for primitive '{}'".format(
1266 paramd
["name"], indata
["primitive"]
1269 # check no extra primitive params are provided
1270 if in_primitive_params_copy
:
1271 raise EngineException(
1272 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1273 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1278 raise EngineException(
1279 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1284 def _check_update_ns_operation(self
, indata
, nsr
) -> None:
1285 """Validates the ns-update request according to updateType
1287 If updateType is CHANGE_VNFPKG:
1288 - it checks the vnfInstanceId, whether it's available under ns instance
1289 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1290 Otherwise exception will be raised.
1291 If updateType is REMOVE_VNF:
1292 - it checks if the vnfInstanceId is available in the ns instance
1293 - Otherwise exception will be raised.
1296 indata: includes updateType such as CHANGE_VNFPKG,
1297 nsr: network service record
1301 a meaningful error if given update parameters are not proper such as
1302 "Error in validating ns-update request: <ID> does not match
1303 with the vnfd-id of vnfinstance
1304 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1308 if indata
["updateType"] == "CHANGE_VNFPKG":
1309 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1310 vnf_instance_id
= indata
["changeVnfPackageData"]["vnfInstanceId"]
1311 ns_instance_id
= indata
["nsInstanceId"]
1312 vnfd_id_2update
= indata
["changeVnfPackageData"]["vnfdId"]
1314 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1316 raise EngineException(
1317 f
"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1318 f
"belong to NS {ns_instance_id}",
1319 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1322 # Getting vnfrs through the ns_instance_id
1323 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": ns_instance_id
})
1324 constituent_vnfd_id
= next(
1328 if vnfr
["id"] == vnf_instance_id
1333 # Check the given vnfd-id belongs to given vnf instance
1334 if constituent_vnfd_id
and (vnfd_id_2update
!= constituent_vnfd_id
):
1336 raise EngineException(
1337 f
"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1338 f
"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1339 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1342 # Validating the ns update timeout
1344 indata
.get("timeout_ns_update")
1345 and indata
["timeout_ns_update"] < 300
1347 raise EngineException(
1348 "Error in validating ns-update request: {} second is not enough "
1349 "to upgrade the VNF instance: {}".format(
1350 indata
["timeout_ns_update"], vnf_instance_id
1352 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1354 elif indata
["updateType"] == "REMOVE_VNF":
1355 vnf_instance_id
= indata
["removeVnfInstanceId"]
1356 ns_instance_id
= indata
["nsInstanceId"]
1357 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1358 raise EngineException(
1359 "Invalid VNF Instance Id. '{}' is not "
1360 "present in the NS '{}'".format(vnf_instance_id
, ns_instance_id
)
1371 "Ns update request could not be processed with error: {}.".format(e
)
1374 def _check_scale_ns_operation(self
, indata
, nsr
):
1375 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1376 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1378 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1380 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1381 == scaling_aspect
["id"]
1385 raise EngineException(
1386 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1387 "present at vnfd:scaling-aspect".format(
1388 indata
["scaleVnfData"]["scaleByStepData"][
1389 "scaling-group-descriptor"
1394 def _check_heal_ns_operation(self
, indata
, nsr
):
1397 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1398 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1402 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1403 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1404 for in_vnf
in get_iterable(indata
.get("vnf")):
1405 member_vnf_index
= in_vnf
["member-vnf-index"]
1406 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1407 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1409 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1410 member_vnf_index
, nsr
["_id"]
1412 vnf_member_index_to_vnfd
[
1414 ] = vnfd
# add to cache, avoiding a later look for
1415 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1416 if in_vnf
.get("vimAccountId"):
1417 self
._check
_valid
_vim
_account
(
1418 in_vnf
["vimAccountId"], vim_accounts
, session
1421 for in_vld
in get_iterable(indata
.get("vld")):
1422 self
._check
_valid
_wim
_account
(
1423 in_vld
.get("wimAccountId"), wim_accounts
, session
1425 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1426 if in_vld
["name"] == vldd
["id"]:
1429 raise EngineException(
1430 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1435 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1436 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1437 vnfr
= self
.db
.get_one(
1439 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1440 fail_on_empty
=False,
1443 raise EngineException(
1444 "Invalid parameter member_vnf_index='{}' is not one of the "
1445 "nsd:constituent-vnfd".format(member_vnf_index
)
1448 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1449 if "revision" in vnfr
:
1450 vnfd_revision
= vnfr
["vnfd-id"] + ":" + str(vnfr
["revision"])
1451 vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": vnfd_revision
}, fail_on_empty
=False)
1453 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
1456 raise EngineException(
1457 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1463 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1464 for vdud
in get_iterable(vnfd
.get("vdu")):
1465 if vdud
["id"] == vdu_id
:
1468 raise EngineException(
1469 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1474 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1475 for kdud
in get_iterable(vnfd
.get("kdu")):
1476 if kdud
["name"] == kdu_name
:
1479 raise EngineException(
1480 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1485 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1486 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1487 for vdu
in get_iterable(vnfd
.get("vdu")):
1488 if in_vdu
["id"] == vdu
["id"]:
1489 for volume
in get_iterable(in_vdu
.get("volume")):
1490 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1491 if volumed
== volume
["name"]:
1494 raise EngineException(
1495 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1496 "volume:name='{}' is not present at "
1497 "vnfd:vdu:virtual-storage-desc list".format(
1498 in_vnf
["member-vnf-index"],
1504 vdu_if_names
= set()
1505 for cpd
in get_iterable(vdu
.get("int-cpd")):
1506 for iface
in get_iterable(
1507 cpd
.get("virtual-network-interface-requirement")
1509 vdu_if_names
.add(iface
.get("name"))
1511 for in_iface
in get_iterable(in_vdu
.get("interface")):
1512 if in_iface
["name"] in vdu_if_names
:
1515 raise EngineException(
1516 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1517 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1518 in_vnf
["member-vnf-index"],
1526 raise EngineException(
1527 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1528 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1532 ivld
.get("id"): set()
1533 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1535 for vdu
in get_iterable(vnfd
.get("vdu")):
1536 for cpd
in get_iterable(vnfd
.get("int-cpd")):
1537 if cpd
.get("int-virtual-link-desc"):
1538 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1540 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1541 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1542 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1543 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1546 raise EngineException(
1547 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1548 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1549 "vnfd:internal-vld:name/id:internal-connection-point".format(
1550 in_vnf
["member-vnf-index"],
1556 raise EngineException(
1557 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1558 " is not present at vnfd '{}'".format(
1559 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1563 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1564 if vim_account
in vim_accounts
:
1567 db_filter
= self
._get
_project
_filter
(session
)
1568 db_filter
["_id"] = vim_account
1569 self
.db
.get_one("vim_accounts", db_filter
)
1571 raise EngineException(
1572 "Invalid vimAccountId='{}' not present for the project".format(
1576 vim_accounts
.append(vim_account
)
1578 def _get_vim_account(self
, vim_id
: str, session
):
1580 db_filter
= self
._get
_project
_filter
(session
)
1581 db_filter
["_id"] = vim_id
1582 return self
.db
.get_one("vim_accounts", db_filter
)
1584 raise EngineException(
1585 "Invalid vimAccountId='{}' not present for the project".format(
1590 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1591 if not isinstance(wim_account
, str):
1593 if wim_account
in wim_accounts
:
1596 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
1597 db_filter
["_id"] = wim_account
1598 self
.db
.get_one("wim_accounts", db_filter
)
1600 raise EngineException(
1601 "Invalid wimAccountId='{}' not present for the project".format(
1605 wim_accounts
.append(wim_account
)
1608 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1611 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1612 (ip_address, ...) information.
1613 Modifies PDU _admin.usageState to 'IN_USE'
1614 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1615 :param rollback: list with the database modifications to rollback if needed
1616 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1617 :param vim_account: vim_account where this vnfr should be deployed
1618 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1619 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1620 of the changed vnfr is needed
1622 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1623 "vim-network-name": used at VIM
1624 "name": interface name
1625 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1626 "ns-vld-id": NSD vld where this interface is connected.
1627 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1630 ifaces_forcing_vim_network
= []
1631 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1632 if not vdur
.get("pdu-type"):
1634 pdu_type
= vdur
.get("pdu-type")
1635 pdu_filter
= self
._get
_project
_filter
(session
)
1636 pdu_filter
["vim_accounts"] = vim_account
1637 pdu_filter
["type"] = pdu_type
1638 pdu_filter
["_admin.operationalState"] = "ENABLED"
1639 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1640 # TODO feature 1417: "shared": True,
1642 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1643 for pdu
in available_pdus
:
1644 # step 1 check if this pdu contains needed interfaces:
1645 match_interfaces
= True
1646 for vdur_interface
in vdur
["interfaces"]:
1647 for pdu_interface
in pdu
["interfaces"]:
1648 if pdu_interface
["name"] == vdur_interface
["name"]:
1649 # TODO feature 1417: match per mgmt type
1651 else: # no interface found for name
1652 match_interfaces
= False
1654 if match_interfaces
:
1657 raise EngineException(
1658 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1662 vnfr
["member-vnf-index-ref"],
1667 # step 2. Update pdu
1669 "_admin.usageState": pdu
["_admin"]["usageState"],
1670 "_admin.usage.vnfr_id": None,
1671 "_admin.usage.nsr_id": None,
1672 "_admin.usage.vdur": None,
1676 {"_id": pdu
["_id"]},
1678 "_admin.usageState": "IN_USE",
1680 "vnfr_id": vnfr
["_id"],
1681 "nsr_id": vnfr
["nsr-id-ref"],
1682 "vdur": vdur
["vdu-id-ref"],
1691 "content": rollback_pdu
,
1695 # step 3. Fill vnfr info by filling vdur
1696 vdu_text
= "vdur.{}".format(vdur_index
)
1697 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1698 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1699 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1700 for pdu_interface
in pdu
["interfaces"]:
1701 if pdu_interface
["name"] == vdur_interface
["name"]:
1702 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1703 for k
, v
in pdu_interface
.items():
1707 ): # TODO: switch-xxxxx must be inserted
1708 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1709 vnfr_update_rollback
[
1710 iface_text
+ ".{}".format(k
)
1711 ] = vdur_interface
.get(v
)
1712 if pdu_interface
.get("ip-address"):
1713 if vdur_interface
.get(
1715 ) or vdur_interface
.get("mgmt-vnf"):
1716 vnfr_update_rollback
[
1717 vdu_text
+ ".ip-address"
1718 ] = vdur
.get("ip-address")
1719 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1722 if vdur_interface
.get("mgmt-vnf"):
1723 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1726 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1727 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1730 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1733 ifaces_forcing_vim_network
.append(
1735 "name": vdur_interface
.get("vnf-vld-id")
1736 or vdur_interface
.get("ns-vld-id"),
1737 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1738 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1741 if pdu_interface
.get("vim-network-id"):
1742 ifaces_forcing_vim_network
[-1][
1744 ] = pdu_interface
["vim-network-id"]
1745 if pdu_interface
.get("vim-network-name"):
1746 ifaces_forcing_vim_network
[-1][
1748 ] = pdu_interface
["vim-network-name"]
1751 return ifaces_forcing_vim_network
1753 def _look_for_k8scluster(
1754 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1757 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1758 Fills vnfr.kdur with the selected k8scluster
1760 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1761 :param rollback: list with the database modifications to rollback if needed
1762 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1763 :param vim_account: vim_account where this vnfr should be deployed
1764 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1765 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1766 of the changed vnfr is needed
1768 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1769 "vim-network-name": used at VIM
1770 "name": interface name
1771 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1772 "ns-vld-id": NSD vld where this interface is connected.
1773 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1776 ifaces_forcing_vim_network
= []
1777 if not vnfr
.get("kdur"):
1778 return ifaces_forcing_vim_network
1780 kdu_filter
= self
._get
_project
_filter
(session
)
1781 kdu_filter
["vim_account"] = vim_account
1782 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1783 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1785 k8s_requirements
= {} # just for logging
1786 for k8scluster
in available_k8sclusters
:
1787 if not vnfr
.get("k8s-cluster"):
1790 if vnfr
["k8s-cluster"].get("cni"):
1791 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1792 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1793 k8scluster
.get("cni", ())
1796 # restrict by version
1797 if vnfr
["k8s-cluster"].get("version"):
1798 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1799 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1801 # restrict by number of networks
1802 if vnfr
["k8s-cluster"].get("nets"):
1803 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1804 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1805 vnfr
["k8s-cluster"]["nets"]
1810 raise EngineException(
1811 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1812 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1816 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1817 # step 3. Fill vnfr info by filling kdur
1818 kdu_text
= "kdur.{}.".format(kdur_index
)
1819 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1820 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1822 # step 4. Check VIM networks that forces the selected k8s_cluster
1823 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1824 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1825 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1826 # get a network from k8s_cluster nets. If name matches use this, if not use other
1827 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1828 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1829 k8scluster_net_list
.remove(kdur_net
["id"])
1831 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1832 k8scluster_net_list
.pop(0)
1833 vnfr_update_rollback
[
1834 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1836 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1838 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1840 ifaces_forcing_vim_network
.append(
1842 "name": kdur_net
.get("vnf-vld-id")
1843 or kdur_net
.get("ns-vld-id"),
1844 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1845 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1846 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1849 # TODO check that this forcing is not incompatible with other forcing
1850 return ifaces_forcing_vim_network
1852 def _update_vnfrs_from_nsd(self
, nsr
):
1857 step
= "Getting vnf_profiles from nsd"
1858 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
1859 vld_fixed_ip_connection_point_data
= {}
1861 step
= "Getting ip-address info from vnf_profile if it exists"
1862 for vnfp
in vnf_profiles
:
1863 # Checking ip-address info from nsd.vnf_profile and storing
1864 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
1865 for cpd
in vlc
.get("constituent-cpd-id", ()):
1866 if cpd
.get("ip-address"):
1867 step
= "Storing ip-address info"
1868 vld_fixed_ip_connection_point_data
.update({vlc
.get("virtual-link-profile-id") + '.' + cpd
.get("constituent-base-element-id"): {
1869 "vnfd-connection-point-ref": cpd
.get(
1870 "constituent-cpd-id"),
1871 "ip-address": cpd
.get(
1874 # Inserting ip address to vnfr
1875 if len(vld_fixed_ip_connection_point_data
) > 0:
1876 step
= "Getting vnfrs"
1877 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1878 for item
in vld_fixed_ip_connection_point_data
.keys():
1879 step
= "Filtering vnfrs"
1880 vnfr
= next(filter(lambda vnfr
: vnfr
["member-vnf-index-ref"] == item
.split('.')[1], vnfrs
), None)
1883 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1884 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1885 step
= "Looking for matched interface"
1887 iface
.get("external-connection-point-ref")
1888 == vld_fixed_ip_connection_point_data
[item
].get("vnfd-connection-point-ref") and
1889 iface
.get("ns-vld-id") == item
.split('.')[0]
1892 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1893 vdur_index
, iface_index
1895 step
= "Storing info in order to update vnfr"
1897 vnfr_update_text
+ ".ip-address"
1898 ] = increment_ip_mac(
1899 vld_fixed_ip_connection_point_data
[item
].get("ip-address"),
1900 vdur
.get("count-index", 0), )
1901 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1903 step
= "updating vnfr at database"
1904 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1912 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
1914 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1917 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1921 vnfr_update_rollback
= {}
1922 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1923 # update vim-account-id
1925 vim_account
= indata
["vimAccountId"]
1926 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1927 # check instantiate parameters
1928 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1929 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1931 if vnf_inst_params
.get("vimAccountId"):
1932 vim_account
= vnf_inst_params
.get("vimAccountId")
1933 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1935 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1936 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1937 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1938 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1940 for iface_inst_param
in get_iterable(
1941 vdu_inst_param
.get("interface")
1943 iface_index
, _
= next(
1945 for i
in enumerate(vdur
["interfaces"])
1946 if i
[1]["name"] == iface_inst_param
["name"]
1948 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1949 vdur_index
, iface_index
1951 if iface_inst_param
.get("ip-address"):
1953 vnfr_update_text
+ ".ip-address"
1954 ] = increment_ip_mac(
1955 iface_inst_param
.get("ip-address"),
1956 vdur
.get("count-index", 0),
1958 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1959 if iface_inst_param
.get("mac-address"):
1961 vnfr_update_text
+ ".mac-address"
1962 ] = increment_ip_mac(
1963 iface_inst_param
.get("mac-address"),
1964 vdur
.get("count-index", 0),
1966 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1967 if iface_inst_param
.get("floating-ip-required"):
1969 vnfr_update_text
+ ".floating-ip-required"
1971 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1972 # TODO update vld with the ip-profile
1973 for ivld_inst_param
in get_iterable(
1974 vnf_inst_params
.get("internal-vld")
1976 for icp_inst_param
in get_iterable(
1977 ivld_inst_param
.get("internal-connection-point")
1980 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1981 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1983 iface
.get("internal-connection-point-ref")
1984 == icp_inst_param
["id-ref"]
1986 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1987 vdur_index
, iface_index
1989 if icp_inst_param
.get("ip-address"):
1991 vnfr_update_text
+ ".ip-address"
1992 ] = increment_ip_mac(
1993 icp_inst_param
.get("ip-address"),
1994 vdur
.get("count-index", 0),
1997 vnfr_update_text
+ ".fixed-ip"
1999 if icp_inst_param
.get("mac-address"):
2001 vnfr_update_text
+ ".mac-address"
2002 ] = increment_ip_mac(
2003 icp_inst_param
.get("mac-address"),
2004 vdur
.get("count-index", 0),
2007 vnfr_update_text
+ ".fixed-mac"
2010 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2011 for vld_inst_param
in get_iterable(indata
.get("vld")):
2012 for vnfcp_inst_param
in get_iterable(
2013 vld_inst_param
.get("vnfd-connection-point-ref")
2015 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
2018 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2019 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2021 iface
.get("external-connection-point-ref")
2022 == vnfcp_inst_param
["vnfd-connection-point-ref"]
2024 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2025 vdur_index
, iface_index
2027 if vnfcp_inst_param
.get("ip-address"):
2029 vnfr_update_text
+ ".ip-address"
2030 ] = increment_ip_mac(
2031 vnfcp_inst_param
.get("ip-address"),
2032 vdur
.get("count-index", 0),
2034 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2035 if vnfcp_inst_param
.get("mac-address"):
2037 vnfr_update_text
+ ".mac-address"
2038 ] = increment_ip_mac(
2039 vnfcp_inst_param
.get("mac-address"),
2040 vdur
.get("count-index", 0),
2042 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2045 vnfr_update
["vim-account-id"] = vim_account
2046 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
2049 vnfr_update
["vca-id"] = vca_id
2050 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
2053 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
2054 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2058 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
2059 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2061 # update database vnfr
2062 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2068 "content": vnfr_update_rollback
,
2072 # Update indada in case pdu forces to use a concrete vim-network-name
2073 # TODO check if user has already insert a vim-network-name and raises an error
2074 if not ifaces_forcing_vim_network
:
2076 for iface_info
in ifaces_forcing_vim_network
:
2077 if iface_info
.get("ns-vld-id"):
2078 if "vld" not in indata
:
2080 indata
["vld"].append(
2082 key
: iface_info
[key
]
2083 for key
in ("name", "vim-network-name", "vim-network-id")
2084 if iface_info
.get(key
)
2088 elif iface_info
.get("vnf-vld-id"):
2089 if "vnf" not in indata
:
2091 indata
["vnf"].append(
2093 "member-vnf-index": member_vnf_index
,
2096 key
: iface_info
[key
]
2102 if iface_info
.get(key
)
2109 def _create_nslcmop(nsr_id
, operation
, params
):
2111 Creates a ns-lcm-opp content to be stored at database.
2112 :param nsr_id: internal id of the instance
2113 :param operation: instantiate, terminate, scale, action, update ...
2114 :param params: user parameters for the operation
2115 :return: dictionary following SOL005 format
2122 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2123 "queuePosition": None,
2125 "errorMessage": None,
2126 "detailedStatus": None,
2127 "statusEnteredTime": now
,
2128 "nsInstanceId": nsr_id
,
2129 "lcmOperationType": operation
,
2131 "isAutomaticInvocation": False,
2132 "operationParams": params
,
2133 "isCancelPending": False,
2135 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2136 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2141 def _get_enabled_vims(self
, session
):
2143 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2144 :param session: current session with user information
2146 db_filter
= self
._get
_project
_filter
(session
)
2147 db_filter
["_admin.operationalState"] = "ENABLED"
2148 vims
= self
.db
.get_list("vim_accounts", db_filter
)
2151 vimAccounts
.append(vim
["_id"])
2164 Performs a new operation over a ns
2165 :param rollback: list to append created items at database in case a rollback must to be done
2166 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2167 :param indata: descriptor with the parameters of the operation. It must contains among others
2168 nsInstanceId: _id of the nsr to perform the operation
2169 operation: it can be: instantiate, terminate, action, update TODO: heal
2170 :param kwargs: used to override the indata descriptor
2171 :param headers: http request headers
2172 :return: id of the nslcmops
2175 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
2177 db_filter
= self
._get
_project
_filter
(session
)
2178 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2179 nsis
= self
.db
.get_one(
2180 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
2183 raise EngineException(
2184 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2187 http_code
=HTTPStatus
.CONFLICT
,
2191 # Override descriptor with query string kwargs
2192 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2193 operation
= indata
["lcmOperationType"]
2194 nsInstanceId
= indata
["nsInstanceId"]
2196 validate_input(indata
, self
.operation_schema
[operation
])
2197 # get ns from nsr_id
2198 _filter
= BaseTopic
._get
_project
_filter
(session
)
2199 _filter
["_id"] = nsInstanceId
2200 nsr
= self
.db
.get_one("nsrs", _filter
)
2203 if operation
== "terminate" and slice_object
is False:
2204 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
2206 not nsr
["_admin"].get("nsState")
2207 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
2209 if operation
== "terminate" and indata
.get("autoremove"):
2210 # NSR must be deleted
2214 ) # a none in this case is used to indicate not instantiated. It can be removed
2215 if operation
!= "instantiate":
2216 raise EngineException(
2217 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2218 nsInstanceId
, operation
2220 HTTPStatus
.CONFLICT
,
2223 if operation
== "instantiate" and not session
["force"]:
2224 raise EngineException(
2225 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2226 nsInstanceId
, operation
2228 HTTPStatus
.CONFLICT
,
2230 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
2231 if (indata
.get("primitive_params")):
2232 indata
["primitive_params"] = json
.dumps(indata
["primitive_params"])
2233 elif (indata
.get("additionalParamsForVnf")):
2234 indata
["additionalParamsForVnf"] = json
.dumps(indata
["additionalParamsForVnf"])
2236 if operation
== "instantiate":
2237 self
._update
_vnfrs
_from
_nsd
(nsr
)
2238 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
2239 if (operation
== "update") and (indata
["updateType"] == "CHANGE_VNFPKG"):
2241 vnfd_id
= indata
["changeVnfPackageData"]["vnfdId"]
2242 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2243 nsd
= self
.db
.get_one("nsds", {"_id": nsr
["nsd-id"]})
2244 ns_request
= nsr
["instantiate_params"]
2245 vnfr
= self
.db
.get_one("vnfrs", {"_id": indata
["changeVnfPackageData"]["vnfInstanceId"]})
2246 latest_vnfd_revision
= vnfd
["_admin"].get("revision", 1)
2247 vnfr_vnfd_revision
= vnfr
.get("revision", 1)
2248 if latest_vnfd_revision
!= vnfr_vnfd_revision
:
2249 old_vnfd_id
= vnfd_id
+ ":" + str(vnfr_vnfd_revision
)
2250 old_db_vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": old_vnfd_id
})
2251 old_sw_version
= old_db_vnfd
.get("software-version", "1.0")
2252 new_sw_version
= vnfd
.get("software-version", "1.0")
2253 if new_sw_version
!= old_sw_version
:
2254 vnf_index
= vnfr
["member-vnf-index-ref"]
2255 self
.logger
.info("nsr {}".format(nsr
))
2256 for vdu
in vnfd
["vdu"]:
2257 self
.nsrtopic
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr
)
2258 sw_image_id
= vdu
.get("sw-image-desc")
2260 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
2261 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2262 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
2263 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
2264 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2265 nsr_update
["image"] = nsr
["image"]
2266 nsr_update
["flavor"] = nsr
["flavor"]
2267 self
.db
.set_one("nsrs", {"_id": nsr
["_id"]}, nsr_update
)
2268 ns_k8s_namespace
= self
.nsrtopic
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
2269 vnfr_descriptor
= self
.nsrtopic
._create
_vnfr
_descriptor
_from
_vnfd
(
2278 indata
["newVdur"] = vnfr_descriptor
["vdur"]
2279 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
2280 _id
= nslcmop_desc
["_id"]
2282 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2284 if indata
.get("placement-engine"):
2285 # Save valid vim accounts in lcm operation descriptor
2286 nslcmop_desc
["operationParams"][
2288 ] = self
._get
_enabled
_vims
(session
)
2289 self
.db
.create("nslcmops", nslcmop_desc
)
2290 rollback
.append({"topic": "nslcmops", "_id": _id
})
2291 if not slice_object
:
2292 self
.msg
.write("ns", operation
, nslcmop_desc
)
2294 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2295 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2296 # except DbException as e:
2297 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2299 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2300 raise EngineException(
2301 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2304 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2305 raise EngineException(
2306 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2310 class NsiTopic(BaseTopic
):
2313 quota_name
= "slice_instances"
2315 def __init__(self
, db
, fs
, msg
, auth
):
2316 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2317 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2320 def _format_ns_request(ns_request
):
2321 formated_request
= copy(ns_request
)
2322 # TODO: Add request params
2323 return formated_request
2326 def _format_addional_params(slice_request
):
2328 Get and format user additional params for NS or VNF
2329 :param slice_request: User instantiation additional parameters
2330 :return: a formatted copy of additional params or None if not supplied
2332 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2333 if additional_params
:
2334 for k
, v
in additional_params
.items():
2335 if not isinstance(k
, str):
2336 raise EngineException(
2337 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2341 if "." in k
or "$" in k
:
2342 raise EngineException(
2343 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2347 if isinstance(v
, (dict, tuple, list)):
2348 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2349 return additional_params
2351 def _check_descriptor_dependencies(self
, session
, descriptor
):
2353 Check that the dependent descriptors exist on a new descriptor or edition
2354 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2355 :param descriptor: descriptor to be inserted or edit
2356 :return: None or raises exception
2358 if not descriptor
.get("nst-ref"):
2360 nstd_id
= descriptor
["nst-ref"]
2361 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
2362 raise EngineException(
2363 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2366 http_code
=HTTPStatus
.CONFLICT
,
2369 def check_conflict_on_del(self
, session
, _id
, db_content
):
2371 Check that NSI is not instantiated
2372 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2373 :param _id: nsi internal id
2374 :param db_content: The database content of the _id
2375 :return: None or raises EngineException with the conflict
2377 if session
["force"]:
2380 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2381 raise EngineException(
2382 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2383 "Launch 'terminate' operation first; or force deletion".format(_id
),
2384 http_code
=HTTPStatus
.CONFLICT
,
2387 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2389 Deletes associated nsilcmops from database. Deletes associated filesystem.
2390 Set usageState of nst
2391 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2392 :param _id: server internal id
2393 :param db_content: The database content of the descriptor
2394 :param not_send_msg: To not send message (False) or store content (list) instead
2395 :return: None if ok or raises EngineException with the problem
2398 # Deleting the nsrs belonging to nsir
2400 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2401 nsr_id
= nsrs_detailed_item
["nsrId"]
2402 if nsrs_detailed_item
.get("shared"):
2404 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2405 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2406 "_id.ne": nsir
["_id"],
2408 nsi
= self
.db
.get_one(
2409 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2411 if nsi
: # last one using nsr
2414 self
.nsrTopic
.delete(
2415 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2417 except (DbException
, EngineException
) as e
:
2418 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2423 # delete related nsilcmops database entries
2424 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2426 # Check and set used NST usage state
2427 nsir_admin
= nsir
.get("_admin")
2428 if nsir_admin
and nsir_admin
.get("nst-id"):
2429 # check if used by another NSI
2430 nsis_list
= self
.db
.get_one(
2432 {"nst-id": nsir_admin
["nst-id"]},
2433 fail_on_empty
=False,
2439 {"_id": nsir_admin
["nst-id"]},
2440 {"_admin.usageState": "NOT_IN_USE"},
2443 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2445 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2446 :param rollback: list to append the created items at database in case a rollback must be done
2447 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2448 :param indata: params to be used for the nsir
2449 :param kwargs: used to override the indata descriptor
2450 :param headers: http request headers
2451 :return: the _id of nsi descriptor created at database
2455 step
= "checking quotas"
2456 self
.check_quota(session
)
2459 slice_request
= self
._remove
_envelop
(indata
)
2460 # Override descriptor with query string kwargs
2461 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2462 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2465 step
= "getting nstd id='{}' from database".format(
2466 slice_request
.get("nstId")
2468 _filter
= self
._get
_project
_filter
(session
)
2469 _filter
["_id"] = slice_request
["nstId"]
2470 nstd
= self
.db
.get_one("nsts", _filter
)
2471 # check NST is not disabled
2472 step
= "checking NST operationalState"
2473 if nstd
["_admin"]["operationalState"] == "DISABLED":
2474 raise EngineException(
2475 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2476 "instance".format(slice_request
["nstId"]),
2477 http_code
=HTTPStatus
.CONFLICT
,
2481 # check NSD is not disabled
2482 step
= "checking operationalState"
2483 if nstd
["_admin"]["operationalState"] == "DISABLED":
2484 raise EngineException(
2485 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2486 "a network slice".format(slice_request
["nstId"]),
2487 http_code
=HTTPStatus
.CONFLICT
,
2490 nstd
.pop("_admin", None)
2491 nstd_id
= nstd
.pop("_id", None)
2492 nsi_id
= str(uuid4())
2493 step
= "filling nsi_descriptor with input data"
2498 "name": slice_request
["nsiName"],
2499 "description": slice_request
.get("nsiDescription", ""),
2500 "datacenter": slice_request
["vimAccountId"],
2501 "nst-ref": nstd
["id"],
2502 "instantiation_parameters": slice_request
,
2503 "network-slice-template": nstd
,
2507 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2510 step
= "creating nsi at database"
2512 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2514 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2515 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2516 nsi_descriptor
["_admin"]["deployed"] = {}
2517 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2518 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2520 # Creating netslice-vld for the RO.
2521 step
= "creating netslice-vld at database"
2523 # Building the vlds list to be deployed
2524 # From netslice descriptors, creating the initial list
2527 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2528 # Getting template Instantiation parameters from NST
2529 nsi_vld
= deepcopy(netslice_vlds
)
2530 nsi_vld
["shared-nsrs-list"] = []
2531 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2532 nsi_vlds
.append(nsi_vld
)
2534 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2535 # Creating netslice-subnet_record.
2539 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2540 for member_ns
in nstd
["netslice-subnet"]:
2541 nsd_id
= member_ns
["nsd-ref"]
2542 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2543 member_ns
["nsd-ref"], member_ns
["id"]
2545 if nsd_id
not in needed_nsds
:
2547 _filter
["id"] = nsd_id
2548 nsd
= self
.db
.get_one(
2549 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2553 needed_nsds
[nsd_id
] = nsd
2555 nsd
= needed_nsds
[nsd_id
]
2556 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2557 services
.append(member_ns
)
2559 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2560 member_ns
["nsd-ref"], member_ns
["id"]
2563 # creates Network Services records (NSRs)
2564 step
= "creating nsrs at database using NsrTopic.new()"
2565 ns_params
= slice_request
.get("netslice-subnet")
2567 nsi_netslice_subnet
= []
2568 for service
in services
:
2569 # Check if the netslice-subnet is shared and if it is share if the nss exists
2572 # Is the nss shared and instantiated?
2573 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2574 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2577 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2578 nsi
= self
.db
.get_one(
2579 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2581 if nsi
and service
.get("is-shared-nss"):
2582 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2583 for nsrs_detailed_item
in nsrs_detailed_list
:
2584 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2585 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2586 _id_nsr
= nsrs_detailed_item
["nsrId"]
2588 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2589 if netslice_subnet
["nss-id"] == service
["id"]:
2590 indata_ns
= netslice_subnet
2594 if service
.get("instantiation-parameters"):
2595 indata_ns
= deepcopy(service
["instantiation-parameters"])
2596 # del service["instantiation-parameters"]
2598 indata_ns
["nsdId"] = service
["_id"]
2599 indata_ns
["nsName"] = (
2600 slice_request
.get("nsiName") + "." + service
["id"]
2602 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2603 indata_ns
["nsDescription"] = service
["description"]
2604 if slice_request
.get("ssh_keys"):
2605 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2608 for ns_param
in ns_params
:
2609 if ns_param
.get("id") == service
["id"]:
2610 copy_ns_param
= deepcopy(ns_param
)
2611 del copy_ns_param
["id"]
2612 indata_ns
.update(copy_ns_param
)
2615 # Creates Nsr objects
2616 _id_nsr
, _
= self
.nsrTopic
.new(
2617 rollback
, session
, indata_ns
, kwargs
, headers
2621 "shared": service
.get("is-shared-nss"),
2622 "nsd-id": service
["nsd-ref"],
2623 "nss-id": service
["id"],
2624 "nslcmop_instantiate": None,
2626 indata_ns
["nss-id"] = service
["id"]
2627 nsrs_list
.append(nsrs_item
)
2628 nsi_netslice_subnet
.append(indata_ns
)
2629 nsr_ref
= {"nsr-ref": _id_nsr
}
2630 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2632 # Adding the nsrs list to the nsi
2633 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2634 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2636 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2639 # Creating the entry in the database
2640 self
.db
.create("nsis", nsi_descriptor
)
2641 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2643 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2644 self
.logger
.exception(
2645 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2647 raise EngineException("Error {}: {}".format(step
, e
))
2648 except ValidationError
as e
:
2649 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2651 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2652 raise EngineException(
2653 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2657 class NsiLcmOpTopic(BaseTopic
):
2660 operation_schema
= { # mapping between operation and jsonschema to validate
2661 "instantiate": nsi_instantiate
,
2665 def __init__(self
, db
, fs
, msg
, auth
):
2666 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2667 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2669 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2671 Check that user has enter right parameters for the operation
2672 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2673 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2674 :param indata: descriptor with the parameters of the operation
2678 nstd
= nsir
["network-slice-template"]
2680 def check_valid_netslice_subnet_id(nstId
):
2681 # TODO change to vnfR (??)
2682 for netslice_subnet
in nstd
["netslice-subnet"]:
2683 if nstId
== netslice_subnet
["id"]:
2684 nsd_id
= netslice_subnet
["nsd-ref"]
2685 if nsd_id
not in nsds
:
2686 _filter
= self
._get
_project
_filter
(session
)
2687 _filter
["id"] = nsd_id
2688 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2691 raise EngineException(
2692 "Invalid parameter nstId='{}' is not one of the "
2693 "nst:netslice-subnet".format(nstId
)
2696 if operation
== "instantiate":
2697 # check the existance of netslice-subnet items
2698 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2699 check_valid_netslice_subnet_id(in_nst
["id"])
2701 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2707 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2708 "statusEnteredTime": now
,
2709 "netsliceInstanceId": netsliceInstanceId
,
2710 "lcmOperationType": operation
,
2712 "isAutomaticInvocation": False,
2713 "operationParams": params
,
2714 "isCancelPending": False,
2716 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2717 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2718 + netsliceInstanceId
,
2723 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2724 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2725 if nst_sb_item
.get("is-shared-nss"):
2726 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2727 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2728 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2729 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2730 "nss-connection-point-ref"
2733 admin_subnet_item
["nss-id"]
2734 == admin_vld_nss_cp_ref_item
["nss-ref"]
2737 not nsr_item
["nsrId"]
2738 in admin_vld_item
["shared-nsrs-list"]
2740 admin_vld_item
["shared-nsrs-list"].append(
2744 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2747 {"_id": nsir
["_id"]},
2748 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2751 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2753 Performs a new operation over a ns
2754 :param rollback: list to append created items at database in case a rollback must to be done
2755 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2756 :param indata: descriptor with the parameters of the operation. It must contains among others
2757 netsliceInstanceId: _id of the nsir to perform the operation
2758 operation: it can be: instantiate, terminate, action, TODO: update, heal
2759 :param kwargs: used to override the indata descriptor
2760 :param headers: http request headers
2761 :return: id of the nslcmops
2764 # Override descriptor with query string kwargs
2765 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2766 operation
= indata
["lcmOperationType"]
2767 netsliceInstanceId
= indata
["netsliceInstanceId"]
2768 validate_input(indata
, self
.operation_schema
[operation
])
2770 # get nsi from netsliceInstanceId
2771 _filter
= self
._get
_project
_filter
(session
)
2772 _filter
["_id"] = netsliceInstanceId
2773 nsir
= self
.db
.get_one("nsis", _filter
)
2774 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2779 not nsir
["_admin"].get("nsiState")
2780 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2782 if operation
== "terminate" and indata
.get("autoremove"):
2783 # NSIR must be deleted
2787 ) # a none in this case is used to indicate not instantiated. It can be removed
2788 if operation
!= "instantiate":
2789 raise EngineException(
2790 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2791 netsliceInstanceId
, operation
2793 HTTPStatus
.CONFLICT
,
2796 if operation
== "instantiate" and not session
["force"]:
2797 raise EngineException(
2798 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2799 netsliceInstanceId
, operation
2801 HTTPStatus
.CONFLICT
,
2804 # Creating all the NS_operation (nslcmop)
2805 # Get service list from db
2806 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2808 # nslcmops_item = None
2809 for index
, nsr_item
in enumerate(nsrs_list
):
2810 nsr_id
= nsr_item
["nsrId"]
2811 if nsr_item
.get("shared"):
2812 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2813 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2815 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2817 _filter
["_id.ne"] = netsliceInstanceId
2818 nsi
= self
.db
.get_one(
2819 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2821 if operation
== "terminate":
2823 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2827 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2830 ): # other nsi is using this nsr and it needs this nsr instantiated
2831 continue # do not create nsilcmop
2833 # looks the first nsi fulfilling the conditions but not being the current NSIR
2835 nsi_nsr_item
= next(
2837 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2838 if n
["nsrId"] == nsr_id
2840 and n
["nslcmop_instantiate"]
2842 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2843 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2845 "_admin.nsrs-detailed-list.{}".format(
2849 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2850 # continue to not create nslcmop since nsrs is shared and nsrs was created
2853 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2858 "lcmOperationType": operation
,
2859 "nsInstanceId": nsr_id
,
2860 # Including netslice_id in the ns instantiate Operation
2861 "netsliceInstanceId": netsliceInstanceId
,
2863 if operation
== "instantiate":
2864 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2865 indata_ns
.update(service
["instantiate_params"])
2867 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2868 # message via kafka bus
2869 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2870 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2872 nslcmops
.append(nslcmop
)
2873 if operation
== "instantiate":
2875 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2879 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2880 except (DbException
, EngineException
) as e
:
2881 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2884 + "skipping NS={} because not found".format(nsr_id
)
2891 indata
["nslcmops_ids"] = nslcmops
2892 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2894 nsilcmop_desc
= self
._create
_nsilcmop
(
2895 session
, netsliceInstanceId
, operation
, indata
2898 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2900 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2901 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2902 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2904 except ValidationError
as e
:
2905 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2907 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2908 raise EngineException(
2909 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2912 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2913 raise EngineException(
2914 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR