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 (
35 from osm_nbi
.base_topic
import (
41 update_descriptor_usage_state
,
43 from yaml
import safe_dump
44 from osm_common
.dbbase
import DbException
45 from osm_common
.msgbase
import MsgException
46 from osm_common
.fsbase
import FsException
47 from osm_nbi
import utils
50 ) # For checking that additional parameter names are valid Jinja2 identifiers
52 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
55 class NsrTopic(BaseTopic
):
58 quota_name
= "ns_instances"
59 schema_new
= ns_instantiate
61 def __init__(self
, db
, fs
, msg
, auth
):
62 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
64 def _check_descriptor_dependencies(self
, session
, descriptor
):
66 Check that the dependent descriptors exist on a new descriptor or edition
67 :param session: client session information
68 :param descriptor: descriptor to be inserted or edit
69 :return: None or raises exception
71 if not descriptor
.get("nsdId"):
73 nsd_id
= descriptor
["nsdId"]
74 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
75 raise EngineException(
76 "Descriptor error at nsdId='{}' references a non exist nsd".format(
79 http_code
=HTTPStatus
.CONFLICT
,
83 def format_on_new(content
, project_id
=None, make_public
=False):
84 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
85 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
88 def check_conflict_on_del(self
, session
, _id
, db_content
):
90 Check that NSR is not instantiated
91 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
92 :param _id: nsr internal id
93 :param db_content: The database content of the nsr
94 :return: None or raises EngineException with the conflict
99 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
100 raise EngineException(
101 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
102 "Launch 'terminate' operation first; or force deletion".format(_id
),
103 http_code
=HTTPStatus
.CONFLICT
,
106 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
108 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
109 Set usageState of pdu, vnfd, nsd
110 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
111 :param _id: server internal id
112 :param db_content: The database content of the descriptor
113 :param not_send_msg: To not send message (False) or store content (list) instead
114 :return: None if ok or raises EngineException with the problem
116 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
117 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
118 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
120 # set all used pdus as free
123 {"_admin.usage.nsr_id": _id
},
124 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
129 used_nsd_id
= nsr
.get("nsd-id")
131 # check if used by another NSR
132 nsrs_list
= self
.db
.get_one(
133 "nsrs", {"nsd-id": used_nsd_id
}, fail_on_empty
=False, fail_on_more
=False
137 "nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"}
140 # Set VNFD usageState
141 used_vnfd_id_list
= nsr
.get("vnfd-id")
142 if used_vnfd_id_list
:
143 for used_vnfd_id
in used_vnfd_id_list
:
144 # check if used by another NSR
145 nsrs_list
= self
.db
.get_one(
147 {"vnfd-id": used_vnfd_id
},
154 {"_id": used_vnfd_id
},
155 {"_admin.usageState": "NOT_IN_USE"},
158 # delete extra ro_nsrs used for internal RO module
159 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
162 def _format_ns_request(ns_request
):
163 formated_request
= copy(ns_request
)
164 formated_request
.pop("additionalParamsForNs", None)
165 formated_request
.pop("additionalParamsForVnf", None)
166 return formated_request
169 def _format_additional_params(
170 ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None
173 Get and format user additional params for NS or VNF.
174 The vdu_id and kdu_name params are mutually exclusive! If none of them are given, then the method will
175 exclusively search for the VNF/NS LCM additional params.
177 :param ns_request: User instantiation additional parameters
178 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
179 :vdu_id: VDU's ID against which we want to format the additional params
180 :kdu_name: KDU's name against which we want to format the additional params
181 :param descriptor: If not None it check that needed parameters of descriptor are supplied
182 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
184 additional_params
= None
186 if not member_vnf_index
:
187 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
188 where_
= "additionalParamsForNs"
189 elif ns_request
.get("additionalParamsForVnf"):
190 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
196 for x
in ns_request
["additionalParamsForVnf"]
197 if x
["member-vnf-index"] == member_vnf_index
202 if not vdu_id
and not kdu_name
:
204 additional_params
= copy(item
.get("additionalParams")) or {}
205 if vdu_id
and item
.get("additionalParamsForVdu"):
209 for x
in item
["additionalParamsForVdu"]
210 if x
["vdu_id"] == vdu_id
214 other_params
= item_vdu
215 if item_vdu
and item_vdu
.get("additionalParams"):
216 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
217 additional_params
= item_vdu
["additionalParams"]
219 additional_params
= {}
220 if item
.get("additionalParamsForKdu"):
224 for x
in item
["additionalParamsForKdu"]
225 if x
["kdu_name"] == kdu_name
229 other_params
= item_kdu
230 if item_kdu
and item_kdu
.get("additionalParams"):
231 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(
234 additional_params
= item_kdu
["additionalParams"]
236 if additional_params
:
237 for k
, v
in additional_params
.items():
238 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
239 if not kdu_name
and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k
):
240 raise EngineException(
241 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
242 "and underscores, and cannot start with a digit".format(
246 # END Check that additional parameter names are valid Jinja2 identifiers
247 if not isinstance(k
, str):
248 raise EngineException(
249 "Invalid param at {}:{}. Only string keys are allowed".format(
254 raise EngineException(
255 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
259 if isinstance(v
, (dict, tuple, list)):
260 additional_params
[k
] = "!!yaml " + safe_dump(v
)
262 additional_params
= json
.dumps(additional_params
)
264 # Select the VDU ID, KDU name or NS/VNF ID, depending on the method's call intent
265 selector
= vdu_id
if vdu_id
else kdu_name
if kdu_name
else descriptor
.get("id")
268 for df
in descriptor
.get("df", []):
269 # check that enough parameters are supplied for the initial-config-primitive
270 # TODO: check for cloud-init
272 initial_primitives
= []
274 "lcm-operations-configuration" in df
275 and "operate-vnf-op-config"
276 in df
["lcm-operations-configuration"]
278 for config
in df
["lcm-operations-configuration"][
279 "operate-vnf-op-config"
281 # Verify the target object (VNF|NS|VDU|KDU) where we need to populate
282 # the params with the additional ones given by the user
283 if config
.get("id") == selector
:
284 for primitive
in get_iterable(
285 config
.get("initial-config-primitive")
287 initial_primitives
.append(primitive
)
289 initial_primitives
= deep_get(
290 descriptor
, ("ns-configuration", "initial-config-primitive")
293 for initial_primitive
in get_iterable(initial_primitives
):
294 for param
in get_iterable(initial_primitive
.get("parameter")):
295 if param
["value"].startswith("<") and param
["value"].endswith(
298 if param
["value"] in (
306 not additional_params
307 or param
["value"][1:-1] not in additional_params
309 raise EngineException(
310 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
311 "initial-config-primitive[name={}] not supplied".format(
314 initial_primitive
["name"],
318 return additional_params
or None, other_params
or None
320 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
322 Creates a new nsr into database. It also creates needed vnfrs
323 :param rollback: list to append the created items at database in case a rollback must be done
324 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
325 :param indata: params to be used for the nsr
326 :param kwargs: used to override the indata descriptor
327 :param headers: http request headers
328 :return: the _id of nsr descriptor created at database. Or an exception of type
329 EngineException, ValidationError, DbException, FsException, MsgException.
330 Note: Exceptions are not captured on purpose. They should be captured at called
333 step
= "checking quotas"
334 self
.check_quota(session
)
336 step
= "validating input parameters"
337 ns_request
= self
._remove
_envelop
(indata
)
338 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
339 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
341 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
342 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
343 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
345 step
= "checking nsdOperationalState"
346 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
348 step
= "filling nsr from input data"
349 nsr_id
= str(uuid4())
350 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(
351 nsd
, ns_request
, nsr_id
, session
356 # TODO: Change for multiple df support
357 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
358 for vnfp
in vnf_profiles
:
359 vnfd_id
= vnfp
.get("vnfd-id")
360 vnf_index
= vnfp
.get("id")
362 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
366 if vnfd_id
not in needed_vnfds
:
367 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
368 if "revision" in vnfd
["_admin"]:
369 vnfd
["revision"] = vnfd
["_admin"]["revision"]
371 needed_vnfds
[vnfd_id
] = vnfd
372 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
374 vnfd
= needed_vnfds
[vnfd_id
]
376 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
379 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(
389 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
392 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
393 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
394 step
= "Updating VNFD usageState"
395 update_descriptor_usage_state(vnfd
, "vnfds", self
.db
)
397 step
= "creating nsr at database"
398 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
399 step
= "Updating NSD usageState"
400 update_descriptor_usage_state(nsd
, "nsds", self
.db
)
402 step
= "creating nsr temporal folder"
403 self
.fs
.mkdir(nsr_id
)
413 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
415 def _get_nsd_from_db(self
, nsd_id
, session
):
416 _filter
= self
._get
_project
_filter
(session
)
417 _filter
["_id"] = nsd_id
418 return self
.db
.get_one("nsds", _filter
)
420 def _get_vnfd_from_db(self
, vnfd_id
, session
):
421 _filter
= self
._get
_project
_filter
(session
)
422 _filter
["id"] = vnfd_id
423 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
426 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
428 nsr_descriptor
, session
["project_id"], make_public
=session
["public"]
430 self
.db
.create("nsrs", nsr_descriptor
)
431 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
433 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
435 vnfr_descriptor
, session
["project_id"], make_public
=session
["public"]
437 self
.db
.create("vnfrs", vnfr_descriptor
)
438 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
440 def _check_nsd_operational_state(self
, nsd
, ns_request
):
441 if nsd
["_admin"]["operationalState"] == "DISABLED":
442 raise EngineException(
443 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
444 "a network service".format(ns_request
["nsdId"]),
445 http_code
=HTTPStatus
.CONFLICT
,
448 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
449 additional_params
, _
= self
._format
_additional
_params
(
450 ns_request
, descriptor
=nsd
452 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
453 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
454 if ns_request
and ns_request
.get("k8s-namespace"):
455 ns_k8s_namespace
= ns_request
["k8s-namespace"]
456 if additional_params
and additional_params
.get("k8s-namespace"):
457 ns_k8s_namespace
= additional_params
["k8s-namespace"]
459 return ns_k8s_namespace
461 def _add_flavor_to_nsr(self
, vdu
, vnfd
, nsr_descriptor
, member_vnf_index
, revision
=None):
464 # Find this vdu compute and storage descriptors
465 vdu_virtual_compute
= {}
466 vdu_virtual_storage
= {}
467 for vcd
in vnfd
.get("virtual-compute-desc", ()):
468 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
469 vdu_virtual_compute
= vcd
470 for vsd
in vnfd
.get("virtual-storage-desc", ()):
471 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
472 vdu_virtual_storage
= vsd
473 # Get this vdu vcpus, memory and storage info for flavor_data
474 if vdu_virtual_compute
.get("virtual-cpu", {}).get(
477 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"][
480 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
481 flavor_data
["memory-mb"] = (
482 float(vdu_virtual_compute
["virtual-memory"]["size"])
485 if vdu_virtual_storage
.get("size-of-storage"):
486 flavor_data
["storage-gb"] = vdu_virtual_storage
[
489 # Get this vdu EPA info for guest_epa
490 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
491 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"][
494 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
495 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
496 if vcpu_pinning
.get("thread-policy"):
497 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
[
500 if vcpu_pinning
.get("policy"):
503 if vcpu_pinning
["policy"] == "dynamic"
506 guest_epa
["cpu-pinning-policy"] = cpu_policy
507 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
508 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"][
511 if vdu_virtual_compute
.get("virtual-memory", {}).get(
514 guest_epa
["mempage-size"] = vdu_virtual_compute
[
517 if vdu_virtual_compute
.get("virtual-memory", {}).get(
520 guest_epa
["numa-node-policy"] = vdu_virtual_compute
[
522 ]["numa-node-policy"]
523 if vdu_virtual_storage
.get("disk-io-quota"):
524 guest_epa
["disk-io-quota"] = vdu_virtual_storage
[
529 flavor_data
["guest-epa"] = guest_epa
531 revision
= revision
if revision
is not None else 1
532 flavor_data
["name"] = vdu
["id"][:56] + "-" + member_vnf_index
+ "-" + str(revision
) + "-flv"
533 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
534 nsr_descriptor
["flavor"].append(flavor_data
)
536 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
538 additional_params
, _
= self
._format
_additional
_params
(
539 ns_request
, descriptor
=nsd
543 "name": ns_request
["nsName"],
544 "name-ref": ns_request
["nsName"],
545 "short-name": ns_request
["nsName"],
546 "admin-status": "ENABLED",
547 "nsState": "NOT_INSTANTIATED",
548 "currentOperation": "IDLE",
549 "currentOperationID": None,
550 "errorDescription": None,
552 "deploymentStatus": None,
553 "configurationStatus": None,
555 "nsd": {k
: v
for k
, v
in nsd
.items()},
556 "datacenter": ns_request
["vimAccountId"],
557 "resource-orchestrator": "osmopenmano",
558 "description": ns_request
.get("nsDescription", ""),
559 "constituent-vnfr-ref": [],
560 "operational-status": "init", # typedef ns-operational-
561 "config-status": "init", # typedef config-states
562 "detailed-status": "scheduled",
563 "orchestration-progress": {},
565 "nsd-name-ref": nsd
["name"],
566 "operational-events": [], # "id", "timestamp", "description", "event",
567 "nsd-ref": nsd
["id"],
568 "nsd-id": nsd
["_id"],
570 "instantiate_params": self
._format
_ns
_request
(ns_request
),
571 "additionalParamsForNs": additional_params
,
572 "ns-instance-config-ref": nsr_id
,
575 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
578 "affinity-or-anti-affinity-group": [],
580 if "revision" in nsd
["_admin"]:
581 nsr_descriptor
["revision"] = nsd
["_admin"]["revision"]
583 ns_request
["nsr_id"] = nsr_id
584 if ns_request
and ns_request
.get("config-units"):
585 nsr_descriptor
["config-units"] = ns_request
["config-units"]
587 if nsd
.get("virtual-link-desc"):
588 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
589 # Fill each vld with vnfd-connection-point-ref data
590 # TODO: Change for multiple df support
591 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
592 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
593 for vnf_profile
in vnf_profiles
:
594 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
595 for cpd
in vlc
.get("constituent-cpd-id", ()):
596 all_vld_connection_point_data
[
597 vlc
.get("virtual-link-profile-id")
600 "member-vnf-index-ref": cpd
.get(
601 "constituent-base-element-id"
603 "vnfd-connection-point-ref": cpd
.get(
606 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
610 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
613 for vdu
in vnfd
.get("vdu", ()):
614 member_vnf_index
= vnf_profile
.get("id")
615 self
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr_descriptor
, member_vnf_index
)
616 sw_image_id
= vdu
.get("sw-image-desc")
618 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
619 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
621 # also add alternative images to the list of images
622 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
623 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
624 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
626 # Add Affinity or Anti-affinity group information to NSR
627 vdu_profiles
= vnfd
.get("df", [[]])[0].get("vdu-profile", ())
628 affinity_group_prefix_name
= "{}-{}".format(
629 nsr_descriptor
["name"][:16], vnf_profile
.get("id")[:16]
632 for vdu_profile
in vdu_profiles
:
633 affinity_group_data
= {}
634 for affinity_group
in vdu_profile
.get(
635 "affinity-or-anti-affinity-group", ()
637 affinity_group_data
= (
638 self
._get
_affinity
_or
_anti
_affinity
_group
_data
_from
_vnfd
(
639 vnfd
, affinity_group
["id"]
642 affinity_group_data
["member-vnf-index"] = vnf_profile
.get("id")
643 self
._add
_affinity
_or
_anti
_affinity
_group
_to
_nsr
(
646 affinity_group_prefix_name
,
650 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
653 vld
["name"] = vld
["id"]
654 nsr_descriptor
["vld"] = nsr_vld
656 return nsr_descriptor
658 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
659 self
, vnfd
, affinity_group_id
662 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
664 affinity_group
= utils
.find_in_list(
665 vnfd
.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
666 lambda ag
: ag
["id"] == affinity_group_id
,
668 affinity_group_data
= {}
670 if affinity_group
.get("id"):
671 affinity_group_data
["ag-id"] = affinity_group
["id"]
672 if affinity_group
.get("type"):
673 affinity_group_data
["type"] = affinity_group
["type"]
674 if affinity_group
.get("scope"):
675 affinity_group_data
["scope"] = affinity_group
["scope"]
676 return affinity_group_data
678 def _add_affinity_or_anti_affinity_group_to_nsr(
679 self
, nsr_descriptor
, affinity_group_data
, affinity_group_prefix_name
682 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
684 affinity_group
= next(
687 for f
in nsr_descriptor
["affinity-or-anti-affinity-group"]
688 if all(f
.get(k
) == affinity_group_data
[k
] for k
in affinity_group_data
)
692 if not affinity_group
:
693 affinity_group_data
["id"] = str(
694 len(nsr_descriptor
["affinity-or-anti-affinity-group"])
696 affinity_group_data
["name"] = "{}-{}".format(
697 affinity_group_prefix_name
, affinity_group_data
["ag-id"][:32]
699 nsr_descriptor
["affinity-or-anti-affinity-group"].append(
703 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
704 sw_image_desc
= utils
.find_in_list(
705 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
708 if sw_image_desc
.get("image"):
709 image_data
["image"] = sw_image_desc
["image"]
710 if sw_image_desc
.get("checksum"):
711 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
712 if sw_image_desc
.get("vim-type"):
713 image_data
["vim-type"] = sw_image_desc
["vim-type"]
716 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
718 Adds image to nsr checking first it is not already added
723 for f
in nsr_descriptor
["image"]
724 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
729 image_data
["id"] = str(len(nsr_descriptor
["image"]))
730 nsr_descriptor
["image"].append(image_data
)
732 def _create_vnfr_descriptor_from_vnfd(
743 vnfr_id
= str(uuid4())
744 nsr_id
= nsr_descriptor
["id"]
746 additional_params
, vnf_params
= self
._format
_additional
_params
(
747 ns_request
, vnf_index
, descriptor
=vnfd
753 "nsr-id-ref": nsr_id
,
754 "member-vnf-index-ref": vnf_index
,
755 "additionalParamsForVnf": additional_params
,
757 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
759 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
760 "vim-account-id": None,
763 "connection-point": [],
764 "ip-address": None, # mgmt-interface filled by LCM
767 # Revision backwards compatility. Only specify the revision in the record if
768 # the original VNFD has a revision.
769 if "revision" in vnfd
:
770 vnfr_descriptor
["revision"] = vnfd
["revision"]
773 vnf_k8s_namespace
= ns_k8s_namespace
775 if vnf_params
.get("k8s-namespace"):
776 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
777 if vnf_params
.get("config-units"):
778 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
781 if vnfd
.get("int-virtual-link-desc"):
782 vnfr_descriptor
["vld"] = []
783 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
784 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
786 for cp
in vnfd
.get("ext-cpd", ()):
788 "name": cp
.get("id"),
789 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
790 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
792 # "ip-address", "mac-address" # filled by LCM
793 # vim-id # TODO it would be nice having a vim port id
795 vnfr_descriptor
["connection-point"].append(vnf_cp
)
797 # Create k8s-cluster information
798 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
799 if vnfd
.get("k8s-cluster"):
800 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
801 all_k8s_cluster_nets_cpds
= {}
802 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
803 if cpd
.get("k8s-cluster-net"):
804 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
807 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
808 if net
.get("id") in all_k8s_cluster_nets_cpds
:
809 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
814 for kdu
in get_iterable(vnfd
.get("kdu")):
815 additional_params
, kdu_params
= self
._format
_additional
_params
(
816 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
818 kdu_k8s_namespace
= vnf_k8s_namespace
819 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
820 if kdu_params
and kdu_params
.get("k8s-namespace"):
821 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
823 kdu_deployment_name
= ""
824 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
825 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
828 "additionalParams": additional_params
,
829 "k8s-namespace": kdu_k8s_namespace
,
830 "kdu-deployment-name": kdu_deployment_name
,
831 "kdu-name": kdu
["name"],
832 # TODO "name": "" Name of the VDU in the VIM
833 "ip-address": None, # mgmt-interface filled by LCM
836 if kdu_params
and kdu_params
.get("config-units"):
837 kdur
["config-units"] = kdu_params
["config-units"]
838 if kdu
.get("helm-version"):
839 kdur
["helm-version"] = kdu
["helm-version"]
840 for k8s_type
in ("helm-chart", "juju-bundle"):
841 if kdu
.get(k8s_type
):
842 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
843 if not vnfr_descriptor
.get("kdur"):
844 vnfr_descriptor
["kdur"] = []
845 vnfr_descriptor
["kdur"].append(kdur
)
847 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
849 for vdu
in vnfd
.get("vdu", ()):
852 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
853 "operate-vnf-op-config"
855 vdu_config
= utils
.find_in_list(
856 configs
, lambda config
: config
["id"] == vdu
["id"]
862 vdu_instantiation_level
= utils
.find_in_list(
863 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
864 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
867 vdu_instantiation_level
= None
870 external_connection_ee
= utils
.filter_in_list(
871 vdu_config
.get("execution-environment-list", []),
872 lambda ee
: "external-connection-point-ref" in ee
,
874 for ee
in external_connection_ee
:
875 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
877 additional_params
, vdu_params
= self
._format
_additional
_params
(
878 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
882 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
883 vnfd
.get("virtual-storage-desc", []),
884 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"]
887 vdu_virtual_storage_descriptors
= []
889 "vdu-id-ref": vdu
["id"],
890 # TODO "name": "" Name of the VDU in the VIM
891 "ip-address": None, # mgmt-interface filled by LCM
892 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
893 "internal-connection-point": [],
895 "additionalParams": additional_params
,
896 "vdu-name": vdu
["name"],
897 "virtual-storages": vdu_virtual_storage_descriptors
899 if vdu_params
and vdu_params
.get("config-units"):
900 vdur
["config-units"] = vdu_params
["config-units"]
901 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
902 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
905 if vdu
.get("pdu-type"):
906 vdur
["pdu-type"] = vdu
["pdu-type"]
907 vdur
["name"] = vdu
["pdu-type"]
908 # TODO volumes: name, volume-id
909 for icp
in vdu
.get("int-cpd", ()):
912 "connection-point-id": icp
["id"],
913 "name": icp
.get("id"),
916 vdur
["internal-connection-point"].append(vdu_icp
)
918 for iface
in icp
.get("virtual-network-interface-requirement", ()):
919 # Name, mac-address and interface position is taken from VNFD
920 # and included into VNFR. By this way RO can process this information
921 # while creating the VDU.
922 iface_fields
= ("name", "mac-address", "position", "ip-address")
924 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
927 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
928 if "port-security-enabled" in icp
:
929 vdu_iface
["port-security-enabled"] = icp
[
930 "port-security-enabled"
933 if "port-security-disable-strategy" in icp
:
934 vdu_iface
["port-security-disable-strategy"] = icp
[
935 "port-security-disable-strategy"
938 for ext_cp
in vnfd
.get("ext-cpd", ()):
939 if not ext_cp
.get("int-cpd"):
941 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
943 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
944 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
948 if "port-security-enabled" in ext_cp
:
949 vdu_iface
["port-security-enabled"] = ext_cp
[
950 "port-security-enabled"
953 if "port-security-disable-strategy" in ext_cp
:
954 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
955 "port-security-disable-strategy"
962 and vdu_iface
.get("external-connection-point-ref")
965 vdu_iface
["mgmt-vnf"] = True
966 vdu_iface
["mgmt-interface"] = True
968 for ecp
in vdu_mgmt_cp
:
969 if vdu_iface
.get("external-connection-point-ref") == ecp
:
970 vdu_iface
["mgmt-interface"] = True
972 if iface
.get("virtual-interface"):
973 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
975 # look for network where this interface is connected
976 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
978 # TODO: Change for multiple df support
979 for df
in get_iterable(nsd
.get("df")):
980 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
981 for vlc_index
, vlc
in enumerate(
983 vnf_profile
.get("virtual-link-connectivity")
986 for cpd
in get_iterable(
987 vlc
.get("constituent-cpd-id")
990 cpd
.get("constituent-cpd-id")
993 vdu_iface
["ns-vld-id"] = vlc
.get(
994 "virtual-link-profile-id"
996 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
997 if vdu_iface
.get("type") in (
1001 nsr_descriptor
["vld"][vlc_index
][
1005 elif vdu_iface
.get("internal-connection-point-ref"):
1006 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
1007 # TODO: store fixed IP address in the record (if it exists in the ICP)
1008 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
1009 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1010 ivld_index
= utils
.find_index_in_list(
1011 vnfd
.get("int-virtual-link-desc", ()),
1012 lambda ivld
: ivld
["id"]
1013 == icp
.get("int-virtual-link-desc"),
1015 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
1017 vdur
["interfaces"].append(vdu_iface
)
1019 if vdu
.get("sw-image-desc"):
1020 sw_image
= utils
.find_in_list(
1021 vnfd
.get("sw-image-desc", ()),
1022 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
1024 nsr_sw_image_data
= utils
.find_in_list(
1025 nsr_descriptor
["image"],
1026 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
1028 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
1030 if vdu
.get("alternative-sw-image-desc"):
1032 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
1033 sw_image
= utils
.find_in_list(
1034 vnfd
.get("sw-image-desc", ()),
1035 lambda image
: image
["id"] == alt_image_id
,
1037 nsr_sw_image_data
= utils
.find_in_list(
1038 nsr_descriptor
["image"],
1040 nsr_image
.get("image") == sw_image
.get("image")
1043 alt_image_ids
.append(nsr_sw_image_data
["id"])
1044 vdur
["alt-image-ids"] = alt_image_ids
1046 revision
= revision
if revision
is not None else 1
1047 flavor_data_name
= vdu
["id"][:56] + "-" + vnf_index
+ "-" + str(revision
) + "-flv"
1048 nsr_flavor_desc
= utils
.find_in_list(
1049 nsr_descriptor
["flavor"],
1050 lambda flavor
: flavor
["name"] == flavor_data_name
,
1054 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
1056 # Adding Affinity groups information to vdur
1058 vdu_profile_affinity_group
= utils
.find_in_list(
1059 vnfd
.get("df")[0]["vdu-profile"],
1060 lambda a_vdu
: a_vdu
["id"] == vdu
["id"],
1063 vdu_profile_affinity_group
= None
1065 if vdu_profile_affinity_group
:
1066 affinity_group_ids
= []
1067 for affinity_group
in vdu_profile_affinity_group
.get(
1068 "affinity-or-anti-affinity-group", ()
1070 vdu_affinity_group
= utils
.find_in_list(
1071 vdu_profile_affinity_group
.get(
1072 "affinity-or-anti-affinity-group", ()
1074 lambda ag_fp
: ag_fp
["id"] == affinity_group
["id"],
1076 nsr_affinity_group
= utils
.find_in_list(
1077 nsr_descriptor
["affinity-or-anti-affinity-group"],
1079 nsr_ag
.get("ag-id") == vdu_affinity_group
.get("id")
1080 and nsr_ag
.get("member-vnf-index")
1081 == vnfr_descriptor
.get("member-vnf-index-ref")
1084 # Update Affinity Group VIM name if VDU instantiation parameter is present
1085 if vnf_params
and vnf_params
.get("affinity-or-anti-affinity-group"):
1086 vnf_params_affinity_group
= utils
.find_in_list(
1087 vnf_params
["affinity-or-anti-affinity-group"],
1089 vnfp_ag
.get("id") == vdu_affinity_group
.get("id")
1092 if vnf_params_affinity_group
.get("vim-affinity-group-id"):
1094 "vim-affinity-group-id"
1095 ] = vnf_params_affinity_group
["vim-affinity-group-id"]
1096 affinity_group_ids
.append(nsr_affinity_group
["id"])
1097 vdur
["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1099 if vdu_instantiation_level
:
1100 count
= vdu_instantiation_level
.get("number-of-instances")
1104 for index
in range(0, count
):
1105 vdur
= deepcopy(vdur
)
1106 for iface
in vdur
["interfaces"]:
1107 if iface
.get("ip-address") and index
!= 0:
1108 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
1109 if iface
.get("mac-address") and index
!= 0:
1110 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
1112 vdur
["_id"] = str(uuid4())
1113 vdur
["id"] = vdur
["_id"]
1114 vdur
["count-index"] = index
1115 vnfr_descriptor
["vdur"].append(vdur
)
1117 return vnfr_descriptor
1119 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
1121 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1122 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1123 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1124 :param ns_instance_content: ns instance content
1125 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1128 time_now
, time_delta
= time(), time() - ns_instance_content
["_admin"]["modified"]
1129 force_refresh
= isinstance(filter_q
, dict) and filter_q
.get('vcaStatusRefresh') == 'true'
1130 threshold_reached
= time_delta
> 120
1131 if force_refresh
or threshold_reached
:
1132 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
1133 ns_instance_content
["_admin"]["modified"] = time_now
1134 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
1135 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
1136 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1137 nslcmop_desc
["_admin"].pop("nsState")
1138 self
.msg
.write("ns", operation
, nslcmop_desc
)
1141 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1143 Get complete information on an ns instance.
1144 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1145 :param _id: string, ns instance id
1146 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1147 :param api_req: True if this call is serving an external API request. False if serving internal request.
1148 :return: dictionary, raise exception if not found.
1150 ns_instance_content
= super().show(session
, _id
, api_req
)
1151 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1152 return ns_instance_content
1154 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1155 raise EngineException(
1156 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1160 class VnfrTopic(BaseTopic
):
1164 def __init__(self
, db
, fs
, msg
, auth
):
1165 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1167 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1168 raise EngineException(
1169 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1172 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1173 raise EngineException(
1174 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1177 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1178 # Not used because vnfrs are created and deleted by NsrTopic class directly
1179 raise EngineException(
1180 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1184 class NsLcmOpTopic(BaseTopic
):
1187 operation_schema
= { # mapping between operation and jsonschema to validate
1188 "instantiate": ns_instantiate
,
1189 "action": ns_action
,
1190 "update": ns_update
,
1193 "terminate": ns_terminate
,
1194 "migrate": ns_migrate
,
1195 "verticalscale": ns_verticalscale
,
1198 def __init__(self
, db
, fs
, msg
, auth
):
1199 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1200 self
.nsrtopic
= NsrTopic(db
, fs
, msg
, auth
)
1202 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1204 Check that user has enter right parameters for the operation
1205 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1206 :param operation: it can be: instantiate, terminate, action, update, heal
1207 :param indata: descriptor with the parameters of the operation
1210 if operation
== "action":
1211 self
._check
_action
_ns
_operation
(indata
, nsr
)
1212 elif operation
== "scale":
1213 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1214 elif operation
== "update":
1215 self
._check
_update
_ns
_operation
(indata
, nsr
)
1216 elif operation
== "heal":
1217 self
._check
_heal
_ns
_operation
(indata
, nsr
)
1218 elif operation
== "instantiate":
1219 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1221 def _check_action_ns_operation(self
, indata
, nsr
):
1223 # check vnf_member_index
1224 if indata
.get("vnf_member_index"):
1225 indata
["member_vnf_index"] = indata
.pop(
1227 ) # for backward compatibility
1228 if indata
.get("member_vnf_index"):
1229 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1230 indata
["member_vnf_index"], nsr
["_id"]
1233 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1234 "operate-vnf-op-config"
1239 if indata
.get("vdu_id"):
1240 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1241 descriptor_configuration
= utils
.find_in_list(
1242 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1244 elif indata
.get("kdu_name"):
1245 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1246 descriptor_configuration
= utils
.find_in_list(
1247 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1250 descriptor_configuration
= utils
.find_in_list(
1251 configs
, lambda config
: config
["id"] == vnfd
["id"]
1253 if descriptor_configuration
is not None:
1254 descriptor_configuration
= descriptor_configuration
.get(
1258 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1262 # For k8s allows default primitives without validating the parameters
1263 if indata
.get("kdu_name") and indata
["primitive"] in (
1270 # TODO should be checked that rollback only can contains revsision_numbe????
1271 if not indata
.get("member_vnf_index"):
1272 raise EngineException(
1273 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1278 # if not, check primitive
1279 for config_primitive
in get_iterable(descriptor_configuration
):
1280 if indata
["primitive"] == config_primitive
["name"]:
1281 # check needed primitive_params are provided
1282 if indata
.get("primitive_params"):
1283 in_primitive_params_copy
= copy(indata
["primitive_params"])
1285 in_primitive_params_copy
= {}
1286 for paramd
in get_iterable(config_primitive
.get("parameter")):
1287 if paramd
["name"] in in_primitive_params_copy
:
1288 del in_primitive_params_copy
[paramd
["name"]]
1289 elif not paramd
.get("default-value"):
1290 raise EngineException(
1291 "Needed parameter {} not provided for primitive '{}'".format(
1292 paramd
["name"], indata
["primitive"]
1295 # check no extra primitive params are provided
1296 if in_primitive_params_copy
:
1297 raise EngineException(
1298 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1299 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1304 raise EngineException(
1305 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1310 def _check_update_ns_operation(self
, indata
, nsr
) -> None:
1311 """Validates the ns-update request according to updateType
1313 If updateType is CHANGE_VNFPKG:
1314 - it checks the vnfInstanceId, whether it's available under ns instance
1315 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1316 Otherwise exception will be raised.
1317 If updateType is REMOVE_VNF:
1318 - it checks if the vnfInstanceId is available in the ns instance
1319 - Otherwise exception will be raised.
1322 indata: includes updateType such as CHANGE_VNFPKG,
1323 nsr: network service record
1327 a meaningful error if given update parameters are not proper such as
1328 "Error in validating ns-update request: <ID> does not match
1329 with the vnfd-id of vnfinstance
1330 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1334 if indata
["updateType"] == "CHANGE_VNFPKG":
1335 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1336 vnf_instance_id
= indata
["changeVnfPackageData"]["vnfInstanceId"]
1337 ns_instance_id
= indata
["nsInstanceId"]
1338 vnfd_id_2update
= indata
["changeVnfPackageData"]["vnfdId"]
1340 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1342 raise EngineException(
1343 f
"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1344 f
"belong to NS {ns_instance_id}",
1345 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1348 # Getting vnfrs through the ns_instance_id
1349 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": ns_instance_id
})
1350 constituent_vnfd_id
= next(
1354 if vnfr
["id"] == vnf_instance_id
1359 # Check the given vnfd-id belongs to given vnf instance
1360 if constituent_vnfd_id
and (vnfd_id_2update
!= constituent_vnfd_id
):
1362 raise EngineException(
1363 f
"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1364 f
"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1365 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1368 # Validating the ns update timeout
1370 indata
.get("timeout_ns_update")
1371 and indata
["timeout_ns_update"] < 300
1373 raise EngineException(
1374 "Error in validating ns-update request: {} second is not enough "
1375 "to upgrade the VNF instance: {}".format(
1376 indata
["timeout_ns_update"], vnf_instance_id
1378 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1380 elif indata
["updateType"] == "REMOVE_VNF":
1381 vnf_instance_id
= indata
["removeVnfInstanceId"]
1382 ns_instance_id
= indata
["nsInstanceId"]
1383 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1384 raise EngineException(
1385 "Invalid VNF Instance Id. '{}' is not "
1386 "present in the NS '{}'".format(vnf_instance_id
, ns_instance_id
)
1397 "Ns update request could not be processed with error: {}.".format(e
)
1400 def _check_scale_ns_operation(self
, indata
, nsr
):
1401 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1402 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1404 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1406 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1407 == scaling_aspect
["id"]
1411 raise EngineException(
1412 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1413 "present at vnfd:scaling-aspect".format(
1414 indata
["scaleVnfData"]["scaleByStepData"][
1415 "scaling-group-descriptor"
1420 def _check_heal_ns_operation(self
, indata
, nsr
):
1423 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1424 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1428 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1429 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1430 for in_vnf
in get_iterable(indata
.get("vnf")):
1431 member_vnf_index
= in_vnf
["member-vnf-index"]
1432 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1433 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1435 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1436 member_vnf_index
, nsr
["_id"]
1438 vnf_member_index_to_vnfd
[
1440 ] = vnfd
# add to cache, avoiding a later look for
1441 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1442 if in_vnf
.get("vimAccountId"):
1443 self
._check
_valid
_vim
_account
(
1444 in_vnf
["vimAccountId"], vim_accounts
, session
1447 for in_vld
in get_iterable(indata
.get("vld")):
1448 self
._check
_valid
_wim
_account
(
1449 in_vld
.get("wimAccountId"), wim_accounts
, session
1451 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1452 if in_vld
["name"] == vldd
["id"]:
1455 raise EngineException(
1456 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1461 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1462 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1463 vnfr
= self
.db
.get_one(
1465 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1466 fail_on_empty
=False,
1469 raise EngineException(
1470 "Invalid parameter member_vnf_index='{}' is not one of the "
1471 "nsd:constituent-vnfd".format(member_vnf_index
)
1474 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1475 if "revision" in vnfr
:
1476 vnfd_revision
= vnfr
["vnfd-id"] + ":" + str(vnfr
["revision"])
1477 vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": vnfd_revision
}, fail_on_empty
=False)
1479 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
1482 raise EngineException(
1483 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1489 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1490 for vdud
in get_iterable(vnfd
.get("vdu")):
1491 if vdud
["id"] == vdu_id
:
1494 raise EngineException(
1495 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1500 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1501 for kdud
in get_iterable(vnfd
.get("kdu")):
1502 if kdud
["name"] == kdu_name
:
1505 raise EngineException(
1506 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1511 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1512 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1513 for vdu
in get_iterable(vnfd
.get("vdu")):
1514 if in_vdu
["id"] == vdu
["id"]:
1515 for volume
in get_iterable(in_vdu
.get("volume")):
1516 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1517 if volumed
== volume
["name"]:
1520 raise EngineException(
1521 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1522 "volume:name='{}' is not present at "
1523 "vnfd:vdu:virtual-storage-desc list".format(
1524 in_vnf
["member-vnf-index"],
1530 vdu_if_names
= set()
1531 for cpd
in get_iterable(vdu
.get("int-cpd")):
1532 for iface
in get_iterable(
1533 cpd
.get("virtual-network-interface-requirement")
1535 vdu_if_names
.add(iface
.get("name"))
1537 for in_iface
in get_iterable(in_vdu
.get("interface")):
1538 if in_iface
["name"] in vdu_if_names
:
1541 raise EngineException(
1542 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1543 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1544 in_vnf
["member-vnf-index"],
1552 raise EngineException(
1553 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1554 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1558 ivld
.get("id"): set()
1559 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1561 for vdu
in vnfd
.get("vdu", {}):
1562 for cpd
in vdu
.get("int-cpd", {}):
1563 if cpd
.get("int-virtual-link-desc"):
1564 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1566 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1567 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1568 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1569 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1572 raise EngineException(
1573 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1574 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1575 "vnfd:internal-vld:name/id:internal-connection-point".format(
1576 in_vnf
["member-vnf-index"],
1582 raise EngineException(
1583 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1584 " is not present at vnfd '{}'".format(
1585 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1589 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1590 if vim_account
in vim_accounts
:
1593 db_filter
= self
._get
_project
_filter
(session
)
1594 db_filter
["_id"] = vim_account
1595 self
.db
.get_one("vim_accounts", db_filter
)
1597 raise EngineException(
1598 "Invalid vimAccountId='{}' not present for the project".format(
1602 vim_accounts
.append(vim_account
)
1604 def _get_vim_account(self
, vim_id
: str, session
):
1606 db_filter
= self
._get
_project
_filter
(session
)
1607 db_filter
["_id"] = vim_id
1608 return self
.db
.get_one("vim_accounts", db_filter
)
1610 raise EngineException(
1611 "Invalid vimAccountId='{}' not present for the project".format(
1616 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1617 if not isinstance(wim_account
, str):
1619 if wim_account
in wim_accounts
:
1622 db_filter
= self
._get
_project
_filter
(session
)
1623 db_filter
["_id"] = wim_account
1624 self
.db
.get_one("wim_accounts", db_filter
)
1626 raise EngineException(
1627 "Invalid wimAccountId='{}' not present for the project".format(
1631 wim_accounts
.append(wim_account
)
1634 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1637 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1638 (ip_address, ...) information.
1639 Modifies PDU _admin.usageState to 'IN_USE'
1640 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1641 :param rollback: list with the database modifications to rollback if needed
1642 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1643 :param vim_account: vim_account where this vnfr should be deployed
1644 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1645 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1646 of the changed vnfr is needed
1648 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1649 "vim-network-name": used at VIM
1650 "name": interface name
1651 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1652 "ns-vld-id": NSD vld where this interface is connected.
1653 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1656 ifaces_forcing_vim_network
= []
1657 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1658 if not vdur
.get("pdu-type"):
1660 pdu_type
= vdur
.get("pdu-type")
1661 pdu_filter
= self
._get
_project
_filter
(session
)
1662 pdu_filter
["vim_accounts"] = vim_account
1663 pdu_filter
["type"] = pdu_type
1664 pdu_filter
["_admin.operationalState"] = "ENABLED"
1665 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1666 # TODO feature 1417: "shared": True,
1668 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1669 for pdu
in available_pdus
:
1670 # step 1 check if this pdu contains needed interfaces:
1671 match_interfaces
= True
1672 for vdur_interface
in vdur
["interfaces"]:
1673 for pdu_interface
in pdu
["interfaces"]:
1674 if pdu_interface
["name"] == vdur_interface
["name"]:
1675 # TODO feature 1417: match per mgmt type
1677 else: # no interface found for name
1678 match_interfaces
= False
1680 if match_interfaces
:
1683 raise EngineException(
1684 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1688 vnfr
["member-vnf-index-ref"],
1693 # step 2. Update pdu
1695 "_admin.usageState": pdu
["_admin"]["usageState"],
1696 "_admin.usage.vnfr_id": None,
1697 "_admin.usage.nsr_id": None,
1698 "_admin.usage.vdur": None,
1702 {"_id": pdu
["_id"]},
1704 "_admin.usageState": "IN_USE",
1706 "vnfr_id": vnfr
["_id"],
1707 "nsr_id": vnfr
["nsr-id-ref"],
1708 "vdur": vdur
["vdu-id-ref"],
1717 "content": rollback_pdu
,
1721 # step 3. Fill vnfr info by filling vdur
1722 vdu_text
= "vdur.{}".format(vdur_index
)
1723 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1724 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1725 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1726 for pdu_interface
in pdu
["interfaces"]:
1727 if pdu_interface
["name"] == vdur_interface
["name"]:
1728 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1729 for k
, v
in pdu_interface
.items():
1733 ): # TODO: switch-xxxxx must be inserted
1734 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1735 vnfr_update_rollback
[
1736 iface_text
+ ".{}".format(k
)
1737 ] = vdur_interface
.get(v
)
1738 if pdu_interface
.get("ip-address"):
1739 if vdur_interface
.get(
1741 ) or vdur_interface
.get("mgmt-vnf"):
1742 vnfr_update_rollback
[
1743 vdu_text
+ ".ip-address"
1744 ] = vdur
.get("ip-address")
1745 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1748 if vdur_interface
.get("mgmt-vnf"):
1749 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1752 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1753 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1756 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1759 ifaces_forcing_vim_network
.append(
1761 "name": vdur_interface
.get("vnf-vld-id")
1762 or vdur_interface
.get("ns-vld-id"),
1763 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1764 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1767 if pdu_interface
.get("vim-network-id"):
1768 ifaces_forcing_vim_network
[-1][
1770 ] = pdu_interface
["vim-network-id"]
1771 if pdu_interface
.get("vim-network-name"):
1772 ifaces_forcing_vim_network
[-1][
1774 ] = pdu_interface
["vim-network-name"]
1777 return ifaces_forcing_vim_network
1779 def _look_for_k8scluster(
1780 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1783 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1784 Fills vnfr.kdur with the selected k8scluster
1786 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1787 :param rollback: list with the database modifications to rollback if needed
1788 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1789 :param vim_account: vim_account where this vnfr should be deployed
1790 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1791 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1792 of the changed vnfr is needed
1794 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1795 "vim-network-name": used at VIM
1796 "name": interface name
1797 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1798 "ns-vld-id": NSD vld where this interface is connected.
1799 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1802 ifaces_forcing_vim_network
= []
1803 if not vnfr
.get("kdur"):
1804 return ifaces_forcing_vim_network
1806 kdu_filter
= self
._get
_project
_filter
(session
)
1807 kdu_filter
["vim_account"] = vim_account
1808 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1809 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1811 k8s_requirements
= {} # just for logging
1812 for k8scluster
in available_k8sclusters
:
1813 if not vnfr
.get("k8s-cluster"):
1816 if vnfr
["k8s-cluster"].get("cni"):
1817 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1818 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1819 k8scluster
.get("cni", ())
1822 # restrict by version
1823 if vnfr
["k8s-cluster"].get("version"):
1824 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1825 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1827 # restrict by number of networks
1828 if vnfr
["k8s-cluster"].get("nets"):
1829 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1830 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1831 vnfr
["k8s-cluster"]["nets"]
1836 raise EngineException(
1837 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1838 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1842 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1843 # step 3. Fill vnfr info by filling kdur
1844 kdu_text
= "kdur.{}.".format(kdur_index
)
1845 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1846 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1848 # step 4. Check VIM networks that forces the selected k8s_cluster
1849 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1850 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1851 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1852 # get a network from k8s_cluster nets. If name matches use this, if not use other
1853 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1854 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1855 k8scluster_net_list
.remove(kdur_net
["id"])
1857 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1858 k8scluster_net_list
.pop(0)
1859 vnfr_update_rollback
[
1860 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1862 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1864 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1866 ifaces_forcing_vim_network
.append(
1868 "name": kdur_net
.get("vnf-vld-id")
1869 or kdur_net
.get("ns-vld-id"),
1870 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1871 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1872 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1875 # TODO check that this forcing is not incompatible with other forcing
1876 return ifaces_forcing_vim_network
1878 def _update_vnfrs_from_nsd(self
, nsr
):
1883 step
= "Getting vnf_profiles from nsd"
1884 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
1885 vld_fixed_ip_connection_point_data
= {}
1887 step
= "Getting ip-address info from vnf_profile if it exists"
1888 for vnfp
in vnf_profiles
:
1889 # Checking ip-address info from nsd.vnf_profile and storing
1890 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
1891 for cpd
in vlc
.get("constituent-cpd-id", ()):
1892 if cpd
.get("ip-address"):
1893 step
= "Storing ip-address info"
1894 vld_fixed_ip_connection_point_data
.update({vlc
.get("virtual-link-profile-id") + '.' + cpd
.get("constituent-base-element-id"): {
1895 "vnfd-connection-point-ref": cpd
.get(
1896 "constituent-cpd-id"),
1897 "ip-address": cpd
.get(
1900 # Inserting ip address to vnfr
1901 if len(vld_fixed_ip_connection_point_data
) > 0:
1902 step
= "Getting vnfrs"
1903 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1904 for item
in vld_fixed_ip_connection_point_data
.keys():
1905 step
= "Filtering vnfrs"
1906 vnfr
= next(filter(lambda vnfr
: vnfr
["member-vnf-index-ref"] == item
.split('.')[1], vnfrs
), None)
1909 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1910 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1911 step
= "Looking for matched interface"
1913 iface
.get("external-connection-point-ref")
1914 == vld_fixed_ip_connection_point_data
[item
].get("vnfd-connection-point-ref") and
1915 iface
.get("ns-vld-id") == item
.split('.')[0]
1918 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1919 vdur_index
, iface_index
1921 step
= "Storing info in order to update vnfr"
1923 vnfr_update_text
+ ".ip-address"
1924 ] = increment_ip_mac(
1925 vld_fixed_ip_connection_point_data
[item
].get("ip-address"),
1926 vdur
.get("count-index", 0), )
1927 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1929 step
= "updating vnfr at database"
1930 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1938 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
1940 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1943 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1947 vnfr_update_rollback
= {}
1948 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1949 # update vim-account-id
1951 vim_account
= indata
["vimAccountId"]
1952 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1953 # check instantiate parameters
1954 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1955 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1957 if vnf_inst_params
.get("vimAccountId"):
1958 vim_account
= vnf_inst_params
.get("vimAccountId")
1959 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1961 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1962 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1963 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1964 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1966 for iface_inst_param
in get_iterable(
1967 vdu_inst_param
.get("interface")
1969 iface_index
, _
= next(
1971 for i
in enumerate(vdur
["interfaces"])
1972 if i
[1]["name"] == iface_inst_param
["name"]
1974 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1975 vdur_index
, iface_index
1977 if iface_inst_param
.get("ip-address"):
1979 vnfr_update_text
+ ".ip-address"
1980 ] = increment_ip_mac(
1981 iface_inst_param
.get("ip-address"),
1982 vdur
.get("count-index", 0),
1984 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1985 if iface_inst_param
.get("mac-address"):
1987 vnfr_update_text
+ ".mac-address"
1988 ] = increment_ip_mac(
1989 iface_inst_param
.get("mac-address"),
1990 vdur
.get("count-index", 0),
1992 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1993 if iface_inst_param
.get("floating-ip-required"):
1995 vnfr_update_text
+ ".floating-ip-required"
1997 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1998 # TODO update vld with the ip-profile
1999 for ivld_inst_param
in get_iterable(
2000 vnf_inst_params
.get("internal-vld")
2002 for icp_inst_param
in get_iterable(
2003 ivld_inst_param
.get("internal-connection-point")
2006 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2007 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2009 iface
.get("internal-connection-point-ref")
2010 == icp_inst_param
["id-ref"]
2012 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2013 vdur_index
, iface_index
2015 if icp_inst_param
.get("ip-address"):
2017 vnfr_update_text
+ ".ip-address"
2018 ] = increment_ip_mac(
2019 icp_inst_param
.get("ip-address"),
2020 vdur
.get("count-index", 0),
2023 vnfr_update_text
+ ".fixed-ip"
2025 if icp_inst_param
.get("mac-address"):
2027 vnfr_update_text
+ ".mac-address"
2028 ] = increment_ip_mac(
2029 icp_inst_param
.get("mac-address"),
2030 vdur
.get("count-index", 0),
2033 vnfr_update_text
+ ".fixed-mac"
2036 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2037 for vld_inst_param
in get_iterable(indata
.get("vld")):
2038 for vnfcp_inst_param
in get_iterable(
2039 vld_inst_param
.get("vnfd-connection-point-ref")
2041 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
2044 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2045 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2047 iface
.get("external-connection-point-ref")
2048 == vnfcp_inst_param
["vnfd-connection-point-ref"]
2050 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2051 vdur_index
, iface_index
2053 if vnfcp_inst_param
.get("ip-address"):
2055 vnfr_update_text
+ ".ip-address"
2056 ] = increment_ip_mac(
2057 vnfcp_inst_param
.get("ip-address"),
2058 vdur
.get("count-index", 0),
2060 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2061 if vnfcp_inst_param
.get("mac-address"):
2063 vnfr_update_text
+ ".mac-address"
2064 ] = increment_ip_mac(
2065 vnfcp_inst_param
.get("mac-address"),
2066 vdur
.get("count-index", 0),
2068 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2071 vnfr_update
["vim-account-id"] = vim_account
2072 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
2075 vnfr_update
["vca-id"] = vca_id
2076 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
2079 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
2080 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2084 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
2085 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2087 # update database vnfr
2088 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2094 "content": vnfr_update_rollback
,
2098 # Update indada in case pdu forces to use a concrete vim-network-name
2099 # TODO check if user has already insert a vim-network-name and raises an error
2100 if not ifaces_forcing_vim_network
:
2102 for iface_info
in ifaces_forcing_vim_network
:
2103 if iface_info
.get("ns-vld-id"):
2104 if "vld" not in indata
:
2106 indata
["vld"].append(
2108 key
: iface_info
[key
]
2109 for key
in ("name", "vim-network-name", "vim-network-id")
2110 if iface_info
.get(key
)
2114 elif iface_info
.get("vnf-vld-id"):
2115 if "vnf" not in indata
:
2117 indata
["vnf"].append(
2119 "member-vnf-index": member_vnf_index
,
2122 key
: iface_info
[key
]
2128 if iface_info
.get(key
)
2135 def _create_nslcmop(nsr_id
, operation
, params
):
2137 Creates a ns-lcm-opp content to be stored at database.
2138 :param nsr_id: internal id of the instance
2139 :param operation: instantiate, terminate, scale, action, update ...
2140 :param params: user parameters for the operation
2141 :return: dictionary following SOL005 format
2148 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2149 "queuePosition": None,
2151 "errorMessage": None,
2152 "detailedStatus": None,
2153 "statusEnteredTime": now
,
2154 "nsInstanceId": nsr_id
,
2155 "lcmOperationType": operation
,
2157 "isAutomaticInvocation": False,
2158 "operationParams": params
,
2159 "isCancelPending": False,
2161 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2162 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2167 def _get_enabled_vims(self
, session
):
2169 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2170 :param session: current session with user information
2172 db_filter
= self
._get
_project
_filter
(session
)
2173 db_filter
["_admin.operationalState"] = "ENABLED"
2174 vims
= self
.db
.get_list("vim_accounts", db_filter
)
2177 vimAccounts
.append(vim
["_id"])
2190 Performs a new operation over a ns
2191 :param rollback: list to append created items at database in case a rollback must to be done
2192 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2193 :param indata: descriptor with the parameters of the operation. It must contains among others
2194 nsInstanceId: _id of the nsr to perform the operation
2195 operation: it can be: instantiate, terminate, action, update TODO: heal
2196 :param kwargs: used to override the indata descriptor
2197 :param headers: http request headers
2198 :return: id of the nslcmops
2201 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
2203 db_filter
= self
._get
_project
_filter
(session
)
2204 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2205 nsis
= self
.db
.get_one(
2206 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
2209 raise EngineException(
2210 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2213 http_code
=HTTPStatus
.CONFLICT
,
2217 # Override descriptor with query string kwargs
2218 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2219 operation
= indata
["lcmOperationType"]
2220 nsInstanceId
= indata
["nsInstanceId"]
2222 validate_input(indata
, self
.operation_schema
[operation
])
2223 # get ns from nsr_id
2224 _filter
= BaseTopic
._get
_project
_filter
(session
)
2225 _filter
["_id"] = nsInstanceId
2226 nsr
= self
.db
.get_one("nsrs", _filter
)
2229 if operation
== "terminate" and slice_object
is False:
2230 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
2232 not nsr
["_admin"].get("nsState")
2233 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
2235 if operation
== "terminate" and indata
.get("autoremove"):
2236 # NSR must be deleted
2240 ) # a none in this case is used to indicate not instantiated. It can be removed
2241 if operation
!= "instantiate":
2242 raise EngineException(
2243 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2244 nsInstanceId
, operation
2246 HTTPStatus
.CONFLICT
,
2249 if operation
== "instantiate" and not session
["force"]:
2250 raise EngineException(
2251 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2252 nsInstanceId
, operation
2254 HTTPStatus
.CONFLICT
,
2256 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
2257 if (indata
.get("primitive_params")):
2258 indata
["primitive_params"] = json
.dumps(indata
["primitive_params"])
2259 elif (indata
.get("additionalParamsForVnf")):
2260 indata
["additionalParamsForVnf"] = json
.dumps(indata
["additionalParamsForVnf"])
2262 if operation
== "instantiate":
2263 self
._update
_vnfrs
_from
_nsd
(nsr
)
2264 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
2265 if (operation
== "update") and (indata
["updateType"] == "CHANGE_VNFPKG"):
2267 vnfd_id
= indata
["changeVnfPackageData"]["vnfdId"]
2268 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2269 nsd
= self
.db
.get_one("nsds", {"_id": nsr
["nsd-id"]})
2270 ns_request
= nsr
["instantiate_params"]
2271 vnfr
= self
.db
.get_one("vnfrs", {"_id": indata
["changeVnfPackageData"]["vnfInstanceId"]})
2272 latest_vnfd_revision
= vnfd
["_admin"].get("revision", 1)
2273 vnfr_vnfd_revision
= vnfr
.get("revision", 1)
2274 if latest_vnfd_revision
!= vnfr_vnfd_revision
:
2275 old_vnfd_id
= vnfd_id
+ ":" + str(vnfr_vnfd_revision
)
2276 old_db_vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": old_vnfd_id
})
2277 old_sw_version
= old_db_vnfd
.get("software-version", "1.0")
2278 new_sw_version
= vnfd
.get("software-version", "1.0")
2279 if new_sw_version
!= old_sw_version
:
2280 vnf_index
= vnfr
["member-vnf-index-ref"]
2281 self
.logger
.info("nsr {}".format(nsr
))
2282 for vdu
in vnfd
["vdu"]:
2283 self
.nsrtopic
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr
, vnf_index
, latest_vnfd_revision
)
2284 sw_image_id
= vdu
.get("sw-image-desc")
2286 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
2287 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2288 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
2289 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
2290 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2291 nsr_update
["image"] = nsr
["image"]
2292 nsr_update
["flavor"] = nsr
["flavor"]
2293 self
.db
.set_one("nsrs", {"_id": nsr
["_id"]}, nsr_update
)
2294 ns_k8s_namespace
= self
.nsrtopic
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
2295 vnfr_descriptor
= self
.nsrtopic
._create
_vnfr
_descriptor
_from
_vnfd
(
2303 latest_vnfd_revision
,
2305 indata
["newVdur"] = vnfr_descriptor
["vdur"]
2306 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
2307 _id
= nslcmop_desc
["_id"]
2309 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2311 if indata
.get("placement-engine"):
2312 # Save valid vim accounts in lcm operation descriptor
2313 nslcmop_desc
["operationParams"][
2315 ] = self
._get
_enabled
_vims
(session
)
2316 self
.db
.create("nslcmops", nslcmop_desc
)
2317 rollback
.append({"topic": "nslcmops", "_id": _id
})
2318 if not slice_object
:
2319 self
.msg
.write("ns", operation
, nslcmop_desc
)
2321 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2322 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2323 # except DbException as e:
2324 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2326 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2327 raise EngineException(
2328 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2331 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2332 raise EngineException(
2333 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2337 class NsiTopic(BaseTopic
):
2340 quota_name
= "slice_instances"
2342 def __init__(self
, db
, fs
, msg
, auth
):
2343 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2344 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2347 def _format_ns_request(ns_request
):
2348 formated_request
= copy(ns_request
)
2349 # TODO: Add request params
2350 return formated_request
2353 def _format_addional_params(slice_request
):
2355 Get and format user additional params for NS or VNF
2356 :param slice_request: User instantiation additional parameters
2357 :return: a formatted copy of additional params or None if not supplied
2359 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2360 if additional_params
:
2361 for k
, v
in additional_params
.items():
2362 if not isinstance(k
, str):
2363 raise EngineException(
2364 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2368 if "." in k
or "$" in k
:
2369 raise EngineException(
2370 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2374 if isinstance(v
, (dict, tuple, list)):
2375 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2376 return additional_params
2378 def _check_descriptor_dependencies(self
, session
, descriptor
):
2380 Check that the dependent descriptors exist on a new descriptor or edition
2381 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2382 :param descriptor: descriptor to be inserted or edit
2383 :return: None or raises exception
2385 if not descriptor
.get("nst-ref"):
2387 nstd_id
= descriptor
["nst-ref"]
2388 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
2389 raise EngineException(
2390 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2393 http_code
=HTTPStatus
.CONFLICT
,
2396 def check_conflict_on_del(self
, session
, _id
, db_content
):
2398 Check that NSI is not instantiated
2399 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2400 :param _id: nsi internal id
2401 :param db_content: The database content of the _id
2402 :return: None or raises EngineException with the conflict
2404 if session
["force"]:
2407 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2408 raise EngineException(
2409 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2410 "Launch 'terminate' operation first; or force deletion".format(_id
),
2411 http_code
=HTTPStatus
.CONFLICT
,
2414 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2416 Deletes associated nsilcmops from database. Deletes associated filesystem.
2417 Set usageState of nst
2418 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2419 :param _id: server internal id
2420 :param db_content: The database content of the descriptor
2421 :param not_send_msg: To not send message (False) or store content (list) instead
2422 :return: None if ok or raises EngineException with the problem
2425 # Deleting the nsrs belonging to nsir
2427 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2428 nsr_id
= nsrs_detailed_item
["nsrId"]
2429 if nsrs_detailed_item
.get("shared"):
2431 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2432 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2433 "_id.ne": nsir
["_id"],
2435 nsi
= self
.db
.get_one(
2436 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2438 if nsi
: # last one using nsr
2441 self
.nsrTopic
.delete(
2442 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2444 except (DbException
, EngineException
) as e
:
2445 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2450 # delete related nsilcmops database entries
2451 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2453 # Check and set used NST usage state
2454 nsir_admin
= nsir
.get("_admin")
2455 if nsir_admin
and nsir_admin
.get("nst-id"):
2456 # check if used by another NSI
2457 nsis_list
= self
.db
.get_one(
2459 {"nst-id": nsir_admin
["nst-id"]},
2460 fail_on_empty
=False,
2466 {"_id": nsir_admin
["nst-id"]},
2467 {"_admin.usageState": "NOT_IN_USE"},
2470 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2472 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2473 :param rollback: list to append the created items at database in case a rollback must be done
2474 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2475 :param indata: params to be used for the nsir
2476 :param kwargs: used to override the indata descriptor
2477 :param headers: http request headers
2478 :return: the _id of nsi descriptor created at database
2482 step
= "checking quotas"
2483 self
.check_quota(session
)
2486 slice_request
= self
._remove
_envelop
(indata
)
2487 # Override descriptor with query string kwargs
2488 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2489 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2492 step
= "getting nstd id='{}' from database".format(
2493 slice_request
.get("nstId")
2495 _filter
= self
._get
_project
_filter
(session
)
2496 _filter
["_id"] = slice_request
["nstId"]
2497 nstd
= self
.db
.get_one("nsts", _filter
)
2498 # check NST is not disabled
2499 step
= "checking NST operationalState"
2500 if nstd
["_admin"]["operationalState"] == "DISABLED":
2501 raise EngineException(
2502 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2503 "instance".format(slice_request
["nstId"]),
2504 http_code
=HTTPStatus
.CONFLICT
,
2508 # check NSD is not disabled
2509 step
= "checking operationalState"
2510 if nstd
["_admin"]["operationalState"] == "DISABLED":
2511 raise EngineException(
2512 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2513 "a network slice".format(slice_request
["nstId"]),
2514 http_code
=HTTPStatus
.CONFLICT
,
2517 nstd
.pop("_admin", None)
2518 nstd_id
= nstd
.pop("_id", None)
2519 nsi_id
= str(uuid4())
2520 step
= "filling nsi_descriptor with input data"
2525 "name": slice_request
["nsiName"],
2526 "description": slice_request
.get("nsiDescription", ""),
2527 "datacenter": slice_request
["vimAccountId"],
2528 "nst-ref": nstd
["id"],
2529 "instantiation_parameters": slice_request
,
2530 "network-slice-template": nstd
,
2534 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2537 step
= "creating nsi at database"
2539 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2541 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2542 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2543 nsi_descriptor
["_admin"]["deployed"] = {}
2544 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2545 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2547 # Creating netslice-vld for the RO.
2548 step
= "creating netslice-vld at database"
2550 # Building the vlds list to be deployed
2551 # From netslice descriptors, creating the initial list
2554 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2555 # Getting template Instantiation parameters from NST
2556 nsi_vld
= deepcopy(netslice_vlds
)
2557 nsi_vld
["shared-nsrs-list"] = []
2558 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2559 nsi_vlds
.append(nsi_vld
)
2561 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2562 # Creating netslice-subnet_record.
2566 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2567 for member_ns
in nstd
["netslice-subnet"]:
2568 nsd_id
= member_ns
["nsd-ref"]
2569 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2570 member_ns
["nsd-ref"], member_ns
["id"]
2572 if nsd_id
not in needed_nsds
:
2574 _filter
["id"] = nsd_id
2575 nsd
= self
.db
.get_one(
2576 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2580 needed_nsds
[nsd_id
] = nsd
2582 nsd
= needed_nsds
[nsd_id
]
2583 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2584 services
.append(member_ns
)
2586 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2587 member_ns
["nsd-ref"], member_ns
["id"]
2590 # creates Network Services records (NSRs)
2591 step
= "creating nsrs at database using NsrTopic.new()"
2592 ns_params
= slice_request
.get("netslice-subnet")
2594 nsi_netslice_subnet
= []
2595 for service
in services
:
2596 # Check if the netslice-subnet is shared and if it is share if the nss exists
2599 # Is the nss shared and instantiated?
2600 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2601 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2604 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2605 nsi
= self
.db
.get_one(
2606 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2608 if nsi
and service
.get("is-shared-nss"):
2609 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2610 for nsrs_detailed_item
in nsrs_detailed_list
:
2611 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2612 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2613 _id_nsr
= nsrs_detailed_item
["nsrId"]
2615 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2616 if netslice_subnet
["nss-id"] == service
["id"]:
2617 indata_ns
= netslice_subnet
2621 if service
.get("instantiation-parameters"):
2622 indata_ns
= deepcopy(service
["instantiation-parameters"])
2623 # del service["instantiation-parameters"]
2625 indata_ns
["nsdId"] = service
["_id"]
2626 indata_ns
["nsName"] = (
2627 slice_request
.get("nsiName") + "." + service
["id"]
2629 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2630 indata_ns
["nsDescription"] = service
["description"]
2631 if slice_request
.get("ssh_keys"):
2632 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2635 for ns_param
in ns_params
:
2636 if ns_param
.get("id") == service
["id"]:
2637 copy_ns_param
= deepcopy(ns_param
)
2638 del copy_ns_param
["id"]
2639 indata_ns
.update(copy_ns_param
)
2642 # Creates Nsr objects
2643 _id_nsr
, _
= self
.nsrTopic
.new(
2644 rollback
, session
, indata_ns
, kwargs
, headers
2648 "shared": service
.get("is-shared-nss"),
2649 "nsd-id": service
["nsd-ref"],
2650 "nss-id": service
["id"],
2651 "nslcmop_instantiate": None,
2653 indata_ns
["nss-id"] = service
["id"]
2654 nsrs_list
.append(nsrs_item
)
2655 nsi_netslice_subnet
.append(indata_ns
)
2656 nsr_ref
= {"nsr-ref": _id_nsr
}
2657 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2659 # Adding the nsrs list to the nsi
2660 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2661 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2663 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2666 # Creating the entry in the database
2667 self
.db
.create("nsis", nsi_descriptor
)
2668 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2670 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2671 self
.logger
.exception(
2672 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2674 raise EngineException("Error {}: {}".format(step
, e
))
2675 except ValidationError
as e
:
2676 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2678 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2679 raise EngineException(
2680 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2684 class NsiLcmOpTopic(BaseTopic
):
2687 operation_schema
= { # mapping between operation and jsonschema to validate
2688 "instantiate": nsi_instantiate
,
2692 def __init__(self
, db
, fs
, msg
, auth
):
2693 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2694 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2696 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2698 Check that user has enter right parameters for the operation
2699 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2700 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2701 :param indata: descriptor with the parameters of the operation
2705 nstd
= nsir
["network-slice-template"]
2707 def check_valid_netslice_subnet_id(nstId
):
2708 # TODO change to vnfR (??)
2709 for netslice_subnet
in nstd
["netslice-subnet"]:
2710 if nstId
== netslice_subnet
["id"]:
2711 nsd_id
= netslice_subnet
["nsd-ref"]
2712 if nsd_id
not in nsds
:
2713 _filter
= self
._get
_project
_filter
(session
)
2714 _filter
["id"] = nsd_id
2715 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2718 raise EngineException(
2719 "Invalid parameter nstId='{}' is not one of the "
2720 "nst:netslice-subnet".format(nstId
)
2723 if operation
== "instantiate":
2724 # check the existance of netslice-subnet items
2725 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2726 check_valid_netslice_subnet_id(in_nst
["id"])
2728 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2734 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2735 "statusEnteredTime": now
,
2736 "netsliceInstanceId": netsliceInstanceId
,
2737 "lcmOperationType": operation
,
2739 "isAutomaticInvocation": False,
2740 "operationParams": params
,
2741 "isCancelPending": False,
2743 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2744 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2745 + netsliceInstanceId
,
2750 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2751 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2752 if nst_sb_item
.get("is-shared-nss"):
2753 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2754 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2755 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2756 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2757 "nss-connection-point-ref"
2760 admin_subnet_item
["nss-id"]
2761 == admin_vld_nss_cp_ref_item
["nss-ref"]
2764 not nsr_item
["nsrId"]
2765 in admin_vld_item
["shared-nsrs-list"]
2767 admin_vld_item
["shared-nsrs-list"].append(
2771 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2774 {"_id": nsir
["_id"]},
2775 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2778 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2780 Performs a new operation over a ns
2781 :param rollback: list to append created items at database in case a rollback must to be done
2782 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2783 :param indata: descriptor with the parameters of the operation. It must contains among others
2784 netsliceInstanceId: _id of the nsir to perform the operation
2785 operation: it can be: instantiate, terminate, action, TODO: update, heal
2786 :param kwargs: used to override the indata descriptor
2787 :param headers: http request headers
2788 :return: id of the nslcmops
2791 # Override descriptor with query string kwargs
2792 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2793 operation
= indata
["lcmOperationType"]
2794 netsliceInstanceId
= indata
["netsliceInstanceId"]
2795 validate_input(indata
, self
.operation_schema
[operation
])
2797 # get nsi from netsliceInstanceId
2798 _filter
= self
._get
_project
_filter
(session
)
2799 _filter
["_id"] = netsliceInstanceId
2800 nsir
= self
.db
.get_one("nsis", _filter
)
2801 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2806 not nsir
["_admin"].get("nsiState")
2807 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2809 if operation
== "terminate" and indata
.get("autoremove"):
2810 # NSIR must be deleted
2814 ) # a none in this case is used to indicate not instantiated. It can be removed
2815 if operation
!= "instantiate":
2816 raise EngineException(
2817 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2818 netsliceInstanceId
, operation
2820 HTTPStatus
.CONFLICT
,
2823 if operation
== "instantiate" and not session
["force"]:
2824 raise EngineException(
2825 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2826 netsliceInstanceId
, operation
2828 HTTPStatus
.CONFLICT
,
2831 # Creating all the NS_operation (nslcmop)
2832 # Get service list from db
2833 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2835 # nslcmops_item = None
2836 for index
, nsr_item
in enumerate(nsrs_list
):
2837 nsr_id
= nsr_item
["nsrId"]
2838 if nsr_item
.get("shared"):
2839 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2840 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2842 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2844 _filter
["_id.ne"] = netsliceInstanceId
2845 nsi
= self
.db
.get_one(
2846 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2848 if operation
== "terminate":
2850 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2854 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2857 ): # other nsi is using this nsr and it needs this nsr instantiated
2858 continue # do not create nsilcmop
2860 # looks the first nsi fulfilling the conditions but not being the current NSIR
2862 nsi_nsr_item
= next(
2864 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2865 if n
["nsrId"] == nsr_id
2867 and n
["nslcmop_instantiate"]
2869 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2870 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2872 "_admin.nsrs-detailed-list.{}".format(
2876 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2877 # continue to not create nslcmop since nsrs is shared and nsrs was created
2880 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2885 "lcmOperationType": operation
,
2886 "nsInstanceId": nsr_id
,
2887 # Including netslice_id in the ns instantiate Operation
2888 "netsliceInstanceId": netsliceInstanceId
,
2890 if operation
== "instantiate":
2891 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2892 indata_ns
.update(service
["instantiate_params"])
2894 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2895 # message via kafka bus
2896 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2897 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2899 nslcmops
.append(nslcmop
)
2900 if operation
== "instantiate":
2902 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2906 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2907 except (DbException
, EngineException
) as e
:
2908 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2911 + "skipping NS={} because not found".format(nsr_id
)
2918 indata
["nslcmops_ids"] = nslcmops
2919 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2921 nsilcmop_desc
= self
._create
_nsilcmop
(
2922 session
, netsliceInstanceId
, operation
, indata
2925 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2927 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2928 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2929 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2931 except ValidationError
as e
:
2932 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2934 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2935 raise EngineException(
2936 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2939 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2940 raise EngineException(
2941 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR