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 (
36 from osm_nbi
.base_topic
import (
42 update_descriptor_usage_state
,
44 from yaml
import safe_dump
45 from osm_common
.dbbase
import DbException
46 from osm_common
.msgbase
import MsgException
47 from osm_common
.fsbase
import FsException
48 from osm_nbi
import utils
51 ) # For checking that additional parameter names are valid Jinja2 identifiers
53 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
56 class NsrTopic(BaseTopic
):
59 quota_name
= "ns_instances"
60 schema_new
= ns_instantiate
62 def __init__(self
, db
, fs
, msg
, auth
):
63 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
66 def format_on_new(content
, project_id
=None, make_public
=False):
67 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
68 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
71 def check_conflict_on_del(self
, session
, _id
, db_content
):
73 Check that NSR is not instantiated
74 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
75 :param _id: nsr internal id
76 :param db_content: The database content of the nsr
77 :return: None or raises EngineException with the conflict
82 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
83 raise EngineException(
84 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
85 "Launch 'terminate' operation first; or force deletion".format(_id
),
86 http_code
=HTTPStatus
.CONFLICT
,
89 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
91 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
92 Set usageState of pdu, vnfd, nsd
93 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
94 :param _id: server internal id
95 :param db_content: The database content of the descriptor
96 :param not_send_msg: To not send message (False) or store content (list) instead
97 :return: None if ok or raises EngineException with the problem
99 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
100 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
101 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
103 # set all used pdus as free
106 {"_admin.usage.nsr_id": _id
},
107 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
112 used_nsd_id
= nsr
.get("nsd-id")
114 # check if used by another NSR
115 nsrs_list
= self
.db
.get_one(
116 "nsrs", {"nsd-id": used_nsd_id
}, fail_on_empty
=False, fail_on_more
=False
120 "nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"}
123 # Set VNFD usageState
124 used_vnfd_id_list
= nsr
.get("vnfd-id")
125 if used_vnfd_id_list
:
126 for used_vnfd_id
in used_vnfd_id_list
:
127 # check if used by another NSR
128 nsrs_list
= self
.db
.get_one(
130 {"vnfd-id": used_vnfd_id
},
137 {"_id": used_vnfd_id
},
138 {"_admin.usageState": "NOT_IN_USE"},
141 # delete extra ro_nsrs used for internal RO module
142 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
145 def _format_ns_request(ns_request
):
146 formated_request
= copy(ns_request
)
147 formated_request
.pop("additionalParamsForNs", None)
148 formated_request
.pop("additionalParamsForVnf", None)
149 return formated_request
152 def _format_additional_params(
153 ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None
156 Get and format user additional params for NS or VNF.
157 The vdu_id and kdu_name params are mutually exclusive! If none of them are given, then the method will
158 exclusively search for the VNF/NS LCM additional params.
160 :param ns_request: User instantiation additional parameters
161 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
162 :vdu_id: VDU's ID against which we want to format the additional params
163 :kdu_name: KDU's name against which we want to format the additional params
164 :param descriptor: If not None it check that needed parameters of descriptor are supplied
165 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
167 additional_params
= None
169 if not member_vnf_index
:
170 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
171 where_
= "additionalParamsForNs"
172 elif ns_request
.get("additionalParamsForVnf"):
173 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
179 for x
in ns_request
["additionalParamsForVnf"]
180 if x
["member-vnf-index"] == member_vnf_index
185 if not vdu_id
and not kdu_name
:
187 additional_params
= copy(item
.get("additionalParams")) or {}
188 if vdu_id
and item
.get("additionalParamsForVdu"):
192 for x
in item
["additionalParamsForVdu"]
193 if x
["vdu_id"] == vdu_id
197 other_params
= item_vdu
198 if item_vdu
and item_vdu
.get("additionalParams"):
199 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
200 additional_params
= item_vdu
["additionalParams"]
202 additional_params
= {}
203 if item
.get("additionalParamsForKdu"):
207 for x
in item
["additionalParamsForKdu"]
208 if x
["kdu_name"] == kdu_name
212 other_params
= item_kdu
213 if item_kdu
and item_kdu
.get("additionalParams"):
214 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(
217 additional_params
= item_kdu
["additionalParams"]
219 if additional_params
:
220 for k
, v
in additional_params
.items():
221 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
222 if not kdu_name
and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k
):
223 raise EngineException(
224 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
225 "and underscores, and cannot start with a digit".format(
229 # END Check that additional parameter names are valid Jinja2 identifiers
230 if not isinstance(k
, str):
231 raise EngineException(
232 "Invalid param at {}:{}. Only string keys are allowed".format(
237 raise EngineException(
238 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
242 if isinstance(v
, (dict, tuple, list)):
243 additional_params
[k
] = "!!yaml " + safe_dump(v
)
245 additional_params
= json
.dumps(additional_params
)
247 # Select the VDU ID, KDU name or NS/VNF ID, depending on the method's call intent
248 selector
= vdu_id
if vdu_id
else kdu_name
if kdu_name
else descriptor
.get("id")
251 for df
in descriptor
.get("df", []):
252 # check that enough parameters are supplied for the initial-config-primitive
253 # TODO: check for cloud-init
255 initial_primitives
= []
257 "lcm-operations-configuration" in df
258 and "operate-vnf-op-config"
259 in df
["lcm-operations-configuration"]
261 for config
in df
["lcm-operations-configuration"][
262 "operate-vnf-op-config"
264 # Verify the target object (VNF|NS|VDU|KDU) where we need to populate
265 # the params with the additional ones given by the user
266 if config
.get("id") == selector
:
267 for primitive
in get_iterable(
268 config
.get("initial-config-primitive")
270 initial_primitives
.append(primitive
)
272 initial_primitives
= deep_get(
273 descriptor
, ("ns-configuration", "initial-config-primitive")
276 for initial_primitive
in get_iterable(initial_primitives
):
277 for param
in get_iterable(initial_primitive
.get("parameter")):
278 if param
["value"].startswith("<") and param
["value"].endswith(
281 if param
["value"] in (
289 not additional_params
290 or param
["value"][1:-1] not in additional_params
292 raise EngineException(
293 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
294 "initial-config-primitive[name={}] not supplied".format(
297 initial_primitive
["name"],
301 return additional_params
or None, other_params
or None
303 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
305 Creates a new nsr into database. It also creates needed vnfrs
306 :param rollback: list to append the created items at database in case a rollback must be done
307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
308 :param indata: params to be used for the nsr
309 :param kwargs: used to override the indata descriptor
310 :param headers: http request headers
311 :return: the _id of nsr descriptor created at database. Or an exception of type
312 EngineException, ValidationError, DbException, FsException, MsgException.
313 Note: Exceptions are not captured on purpose. They should be captured at called
315 step
= "checking quotas" # first step must be defined outside try
317 self
.check_quota(session
)
319 step
= "validating input parameters"
320 ns_request
= self
._remove
_envelop
(indata
)
321 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
322 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
324 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
325 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
326 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
328 step
= "checking nsdOperationalState"
329 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
331 step
= "filling nsr from input data"
332 nsr_id
= str(uuid4())
333 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(
334 nsd
, ns_request
, nsr_id
, session
339 # TODO: Change for multiple df support
340 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
341 for vnfp
in vnf_profiles
:
342 vnfd_id
= vnfp
.get("vnfd-id")
343 vnf_index
= vnfp
.get("id")
345 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
349 if vnfd_id
not in needed_vnfds
:
350 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
351 if "revision" in vnfd
["_admin"]:
352 vnfd
["revision"] = vnfd
["_admin"]["revision"]
354 needed_vnfds
[vnfd_id
] = vnfd
355 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
357 vnfd
= needed_vnfds
[vnfd_id
]
359 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
362 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(
372 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
375 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
376 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
377 step
= "Updating VNFD usageState"
378 update_descriptor_usage_state(vnfd
, "vnfds", self
.db
)
380 step
= "creating nsr at database"
381 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
382 step
= "Updating NSD usageState"
383 update_descriptor_usage_state(nsd
, "nsds", self
.db
)
385 step
= "creating nsr temporal folder"
386 self
.fs
.mkdir(nsr_id
)
396 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
398 def _get_nsd_from_db(self
, nsd_id
, session
):
399 _filter
= self
._get
_project
_filter
(session
)
400 _filter
["_id"] = nsd_id
401 return self
.db
.get_one("nsds", _filter
)
403 def _get_vnfd_from_db(self
, vnfd_id
, session
):
404 _filter
= self
._get
_project
_filter
(session
)
405 _filter
["id"] = vnfd_id
406 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
409 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
411 nsr_descriptor
, session
["project_id"], make_public
=session
["public"]
413 self
.db
.create("nsrs", nsr_descriptor
)
414 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
416 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
418 vnfr_descriptor
, session
["project_id"], make_public
=session
["public"]
420 self
.db
.create("vnfrs", vnfr_descriptor
)
421 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
423 def _check_nsd_operational_state(self
, nsd
, ns_request
):
424 if nsd
["_admin"]["operationalState"] == "DISABLED":
425 raise EngineException(
426 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
427 "a network service".format(ns_request
["nsdId"]),
428 http_code
=HTTPStatus
.CONFLICT
,
431 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
432 additional_params
, _
= self
._format
_additional
_params
(
433 ns_request
, descriptor
=nsd
435 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
436 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
437 if ns_request
and ns_request
.get("k8s-namespace"):
438 ns_k8s_namespace
= ns_request
["k8s-namespace"]
439 if additional_params
and additional_params
.get("k8s-namespace"):
440 ns_k8s_namespace
= additional_params
["k8s-namespace"]
442 return ns_k8s_namespace
444 def _add_shared_volumes_to_nsr(
445 self
, vdu
, vnfd
, nsr_descriptor
, member_vnf_index
, revision
=None
448 for vsd
in vnfd
.get("virtual-storage-desc", ()):
449 if vsd
.get("vdu-storage-requirements"):
451 vsd
.get("vdu-storage-requirements")[0].get("key") == "multiattach"
452 and vsd
.get("vdu-storage-requirements")[0].get("value") == "True"
454 # Avoid setting the volume name multiple times
455 if not match(f
"shared-.*-{vnfd['id']}", vsd
["id"]):
456 vsd
["id"] = f
"shared-{vsd['id']}-{vnfd['id']}"
459 nsr_descriptor
["shared-volumes"] = svsd
461 def _add_flavor_to_nsr(
462 self
, vdu
, vnfd
, nsr_descriptor
, member_vnf_index
, revision
=None
466 # Find this vdu compute and storage descriptors
467 vdu_virtual_compute
= {}
468 vdu_virtual_storage
= {}
469 for vcd
in vnfd
.get("virtual-compute-desc", ()):
470 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
471 vdu_virtual_compute
= vcd
472 for vsd
in vnfd
.get("virtual-storage-desc", ()):
473 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
474 vdu_virtual_storage
= vsd
475 # Get this vdu vcpus, memory and storage info for flavor_data
476 if vdu_virtual_compute
.get("virtual-cpu", {}).get("num-virtual-cpu"):
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"]) * 1024.0
484 if vdu_virtual_storage
.get("size-of-storage"):
485 flavor_data
["storage-gb"] = vdu_virtual_storage
["size-of-storage"]
486 # Get this vdu EPA info for guest_epa
487 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
488 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"]["cpu-quota"]
489 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
490 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
491 if vcpu_pinning
.get("thread-policy"):
492 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
["thread-policy"]
493 if vcpu_pinning
.get("policy"):
495 "SHARED" if vcpu_pinning
["policy"] == "dynamic" else "DEDICATED"
497 guest_epa
["cpu-pinning-policy"] = cpu_policy
498 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
499 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"]["mem-quota"]
500 if vdu_virtual_compute
.get("virtual-memory", {}).get("mempage-size"):
501 guest_epa
["mempage-size"] = vdu_virtual_compute
["virtual-memory"][
504 if vdu_virtual_compute
.get("virtual-memory", {}).get("numa-node-policy"):
505 guest_epa
["numa-node-policy"] = vdu_virtual_compute
["virtual-memory"][
508 if vdu_virtual_storage
.get("disk-io-quota"):
509 guest_epa
["disk-io-quota"] = vdu_virtual_storage
["disk-io-quota"]
512 flavor_data
["guest-epa"] = guest_epa
514 revision
= revision
if revision
is not None else 1
515 flavor_data
["name"] = (
516 vdu
["id"][:56] + "-" + member_vnf_index
+ "-" + str(revision
) + "-flv"
518 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
519 nsr_descriptor
["flavor"].append(flavor_data
)
521 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
523 additional_params
, _
= self
._format
_additional
_params
(
524 ns_request
, descriptor
=nsd
528 "name": ns_request
["nsName"],
529 "name-ref": ns_request
["nsName"],
530 "short-name": ns_request
["nsName"],
531 "admin-status": "ENABLED",
532 "nsState": "NOT_INSTANTIATED",
533 "currentOperation": "IDLE",
534 "currentOperationID": None,
535 "errorDescription": None,
537 "deploymentStatus": None,
538 "configurationStatus": None,
540 "nsd": {k
: v
for k
, v
in nsd
.items()},
541 "datacenter": ns_request
["vimAccountId"],
542 "resource-orchestrator": "osmopenmano",
543 "description": ns_request
.get("nsDescription", ""),
544 "constituent-vnfr-ref": [],
545 "operational-status": "init", # typedef ns-operational-
546 "config-status": "init", # typedef config-states
547 "detailed-status": "scheduled",
548 "orchestration-progress": {},
550 "nsd-name-ref": nsd
["name"],
551 "operational-events": [], # "id", "timestamp", "description", "event",
552 "nsd-ref": nsd
["id"],
553 "nsd-id": nsd
["_id"],
555 "instantiate_params": self
._format
_ns
_request
(ns_request
),
556 "additionalParamsForNs": additional_params
,
557 "ns-instance-config-ref": nsr_id
,
560 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
563 "affinity-or-anti-affinity-group": [],
564 "shared-volumes": [],
566 if "revision" in nsd
["_admin"]:
567 nsr_descriptor
["revision"] = nsd
["_admin"]["revision"]
569 ns_request
["nsr_id"] = nsr_id
570 if ns_request
and ns_request
.get("config-units"):
571 nsr_descriptor
["config-units"] = ns_request
["config-units"]
573 if nsd
.get("virtual-link-desc"):
574 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
575 # Fill each vld with vnfd-connection-point-ref data
576 # TODO: Change for multiple df support
577 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
578 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
579 for vnf_profile
in vnf_profiles
:
580 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
581 for cpd
in vlc
.get("constituent-cpd-id", ()):
582 all_vld_connection_point_data
[
583 vlc
.get("virtual-link-profile-id")
586 "member-vnf-index-ref": cpd
.get(
587 "constituent-base-element-id"
589 "vnfd-connection-point-ref": cpd
.get(
592 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
596 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
599 for vdu
in vnfd
.get("vdu", ()):
600 member_vnf_index
= vnf_profile
.get("id")
601 self
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr_descriptor
, member_vnf_index
)
602 self
._add
_shared
_volumes
_to
_nsr
(
603 vdu
, vnfd
, nsr_descriptor
, member_vnf_index
605 sw_image_id
= vdu
.get("sw-image-desc")
607 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
608 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
610 # also add alternative images to the list of images
611 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
612 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
613 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
615 # Add Affinity or Anti-affinity group information to NSR
616 vdu_profiles
= vnfd
.get("df", [[]])[0].get("vdu-profile", ())
617 affinity_group_prefix_name
= "{}-{}".format(
618 nsr_descriptor
["name"][:16], vnf_profile
.get("id")[:16]
621 for vdu_profile
in vdu_profiles
:
622 affinity_group_data
= {}
623 for affinity_group
in vdu_profile
.get(
624 "affinity-or-anti-affinity-group", ()
626 affinity_group_data
= (
627 self
._get
_affinity
_or
_anti
_affinity
_group
_data
_from
_vnfd
(
628 vnfd
, affinity_group
["id"]
631 affinity_group_data
["member-vnf-index"] = vnf_profile
.get("id")
632 self
._add
_affinity
_or
_anti
_affinity
_group
_to
_nsr
(
635 affinity_group_prefix_name
,
639 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
642 vld
["name"] = vld
["id"]
643 nsr_descriptor
["vld"] = nsr_vld
644 return nsr_descriptor
646 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
647 self
, vnfd
, affinity_group_id
650 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
652 affinity_group
= utils
.find_in_list(
653 vnfd
.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
654 lambda ag
: ag
["id"] == affinity_group_id
,
656 affinity_group_data
= {}
658 if affinity_group
.get("id"):
659 affinity_group_data
["ag-id"] = affinity_group
["id"]
660 if affinity_group
.get("type"):
661 affinity_group_data
["type"] = affinity_group
["type"]
662 if affinity_group
.get("scope"):
663 affinity_group_data
["scope"] = affinity_group
["scope"]
664 return affinity_group_data
666 def _add_affinity_or_anti_affinity_group_to_nsr(
667 self
, nsr_descriptor
, affinity_group_data
, affinity_group_prefix_name
670 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
672 affinity_group
= next(
675 for f
in nsr_descriptor
["affinity-or-anti-affinity-group"]
676 if all(f
.get(k
) == affinity_group_data
[k
] for k
in affinity_group_data
)
680 if not affinity_group
:
681 affinity_group_data
["id"] = str(
682 len(nsr_descriptor
["affinity-or-anti-affinity-group"])
684 affinity_group_data
["name"] = "{}-{}".format(
685 affinity_group_prefix_name
, affinity_group_data
["ag-id"][:32]
687 nsr_descriptor
["affinity-or-anti-affinity-group"].append(
691 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
692 sw_image_desc
= utils
.find_in_list(
693 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
696 if sw_image_desc
.get("image"):
697 image_data
["image"] = sw_image_desc
["image"]
698 if sw_image_desc
.get("checksum"):
699 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
700 if sw_image_desc
.get("vim-type"):
701 image_data
["vim-type"] = sw_image_desc
["vim-type"]
704 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
706 Adds image to nsr checking first it is not already added
711 for f
in nsr_descriptor
["image"]
712 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
717 image_data
["id"] = str(len(nsr_descriptor
["image"]))
718 nsr_descriptor
["image"].append(image_data
)
720 def _create_vnfr_descriptor_from_vnfd(
731 vnfr_id
= str(uuid4())
732 nsr_id
= nsr_descriptor
["id"]
734 additional_params
, vnf_params
= self
._format
_additional
_params
(
735 ns_request
, vnf_index
, descriptor
=vnfd
741 "nsr-id-ref": nsr_id
,
742 "member-vnf-index-ref": vnf_index
,
743 "additionalParamsForVnf": additional_params
,
745 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
747 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
748 "vim-account-id": None,
751 "connection-point": [],
752 "ip-address": None, # mgmt-interface filled by LCM
755 # Revision backwards compatility. Only specify the revision in the record if
756 # the original VNFD has a revision.
757 if "revision" in vnfd
:
758 vnfr_descriptor
["revision"] = vnfd
["revision"]
760 vnf_k8s_namespace
= ns_k8s_namespace
762 if vnf_params
.get("k8s-namespace"):
763 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
764 if vnf_params
.get("config-units"):
765 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
768 if vnfd
.get("int-virtual-link-desc"):
769 vnfr_descriptor
["vld"] = []
770 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
771 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
773 for cp
in vnfd
.get("ext-cpd", ()):
775 "name": cp
.get("id"),
776 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
777 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
779 # "ip-address", "mac-address" # filled by LCM
780 # vim-id # TODO it would be nice having a vim port id
782 vnfr_descriptor
["connection-point"].append(vnf_cp
)
784 # Create k8s-cluster information
785 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
786 if vnfd
.get("k8s-cluster"):
787 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
788 all_k8s_cluster_nets_cpds
= {}
789 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
790 if cpd
.get("k8s-cluster-net"):
791 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
794 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
795 if net
.get("id") in all_k8s_cluster_nets_cpds
:
796 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
801 for kdu
in get_iterable(vnfd
.get("kdu")):
802 additional_params
, kdu_params
= self
._format
_additional
_params
(
803 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
805 kdu_k8s_namespace
= vnf_k8s_namespace
806 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
807 if kdu_params
and kdu_params
.get("k8s-namespace"):
808 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
810 kdu_deployment_name
= ""
811 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
812 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
815 "additionalParams": additional_params
,
816 "k8s-namespace": kdu_k8s_namespace
,
817 "kdu-deployment-name": kdu_deployment_name
,
818 "kdu-name": kdu
["name"],
819 # TODO "name": "" Name of the VDU in the VIM
820 "ip-address": None, # mgmt-interface filled by LCM
823 if kdu_params
and kdu_params
.get("config-units"):
824 kdur
["config-units"] = kdu_params
["config-units"]
825 if kdu
.get("helm-version"):
826 kdur
["helm-version"] = kdu
["helm-version"]
827 for k8s_type
in ("helm-chart", "juju-bundle"):
828 if kdu
.get(k8s_type
):
829 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
830 if not vnfr_descriptor
.get("kdur"):
831 vnfr_descriptor
["kdur"] = []
832 vnfr_descriptor
["kdur"].append(kdur
)
834 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
836 for vdu
in vnfd
.get("vdu", ()):
839 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
840 "operate-vnf-op-config"
842 vdu_config
= utils
.find_in_list(
843 configs
, lambda config
: config
["id"] == vdu
["id"]
849 vdu_instantiation_level
= utils
.find_in_list(
850 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
851 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
854 vdu_instantiation_level
= None
857 external_connection_ee
= utils
.filter_in_list(
858 vdu_config
.get("execution-environment-list", []),
859 lambda ee
: "external-connection-point-ref" in ee
,
861 for ee
in external_connection_ee
:
862 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
864 additional_params
, vdu_params
= self
._format
_additional
_params
(
865 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
869 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
870 vnfd
.get("virtual-storage-desc", []),
871 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"],
874 vdu_virtual_storage_descriptors
= []
876 "vdu-id-ref": vdu
["id"],
877 # TODO "name": "" Name of the VDU in the VIM
878 "ip-address": None, # mgmt-interface filled by LCM
879 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
880 "internal-connection-point": [],
882 "additionalParams": additional_params
,
883 "vdu-name": vdu
["name"],
884 "virtual-storages": vdu_virtual_storage_descriptors
,
886 if vdu_params
and vdu_params
.get("config-units"):
887 vdur
["config-units"] = vdu_params
["config-units"]
888 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
889 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
892 if vdu
.get("pdu-type"):
893 vdur
["pdu-type"] = vdu
["pdu-type"]
894 vdur
["name"] = vdu
["pdu-type"]
895 # TODO volumes: name, volume-id
896 for icp
in vdu
.get("int-cpd", ()):
899 "connection-point-id": icp
["id"],
900 "name": icp
.get("id"),
903 vdur
["internal-connection-point"].append(vdu_icp
)
905 for iface
in icp
.get("virtual-network-interface-requirement", ()):
906 # Name, mac-address and interface position is taken from VNFD
907 # and included into VNFR. By this way RO can process this information
908 # while creating the VDU.
909 iface_fields
= ("name", "mac-address", "position", "ip-address")
911 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
914 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
915 if "port-security-enabled" in icp
:
916 vdu_iface
["port-security-enabled"] = icp
[
917 "port-security-enabled"
920 if "port-security-disable-strategy" in icp
:
921 vdu_iface
["port-security-disable-strategy"] = icp
[
922 "port-security-disable-strategy"
925 for ext_cp
in vnfd
.get("ext-cpd", ()):
926 if not ext_cp
.get("int-cpd"):
928 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
930 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
931 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
935 if "port-security-enabled" in ext_cp
:
936 vdu_iface
["port-security-enabled"] = ext_cp
[
937 "port-security-enabled"
940 if "port-security-disable-strategy" in ext_cp
:
941 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
942 "port-security-disable-strategy"
949 and vdu_iface
.get("external-connection-point-ref")
952 vdu_iface
["mgmt-vnf"] = True
953 vdu_iface
["mgmt-interface"] = True
955 for ecp
in vdu_mgmt_cp
:
956 if vdu_iface
.get("external-connection-point-ref") == ecp
:
957 vdu_iface
["mgmt-interface"] = True
959 if iface
.get("virtual-interface"):
960 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
962 # look for network where this interface is connected
963 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
965 # TODO: Change for multiple df support
966 for df
in get_iterable(nsd
.get("df")):
967 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
968 for vlc_index
, vlc
in enumerate(
970 vnf_profile
.get("virtual-link-connectivity")
973 for cpd
in get_iterable(
974 vlc
.get("constituent-cpd-id")
977 cpd
.get("constituent-cpd-id")
979 ) and vnf_profile
.get("id") == vnf_index
:
980 vdu_iface
["ns-vld-id"] = vlc
.get(
981 "virtual-link-profile-id"
983 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
984 if vdu_iface
.get("type") in (
988 nsr_descriptor
["vld"][vlc_index
][
992 elif vdu_iface
.get("internal-connection-point-ref"):
993 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
994 # TODO: store fixed IP address in the record (if it exists in the ICP)
995 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
996 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
997 ivld_index
= utils
.find_index_in_list(
998 vnfd
.get("int-virtual-link-desc", ()),
999 lambda ivld
: ivld
["id"]
1000 == icp
.get("int-virtual-link-desc"),
1002 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
1004 vdur
["interfaces"].append(vdu_iface
)
1006 if vdu
.get("sw-image-desc"):
1007 sw_image
= utils
.find_in_list(
1008 vnfd
.get("sw-image-desc", ()),
1009 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
1011 nsr_sw_image_data
= utils
.find_in_list(
1012 nsr_descriptor
["image"],
1013 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
1015 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
1017 if vdu
.get("alternative-sw-image-desc"):
1019 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
1020 sw_image
= utils
.find_in_list(
1021 vnfd
.get("sw-image-desc", ()),
1022 lambda image
: image
["id"] == alt_image_id
,
1024 nsr_sw_image_data
= utils
.find_in_list(
1025 nsr_descriptor
["image"],
1027 nsr_image
.get("image") == sw_image
.get("image")
1030 alt_image_ids
.append(nsr_sw_image_data
["id"])
1031 vdur
["alt-image-ids"] = alt_image_ids
1033 revision
= revision
if revision
is not None else 1
1034 flavor_data_name
= (
1035 vdu
["id"][:56] + "-" + vnf_index
+ "-" + str(revision
) + "-flv"
1037 nsr_flavor_desc
= utils
.find_in_list(
1038 nsr_descriptor
["flavor"],
1039 lambda flavor
: flavor
["name"] == flavor_data_name
,
1043 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
1045 # Adding Shared Volume information to vdur
1046 if vdur
.get("virtual-storages"):
1048 for vsd
in vdur
["virtual-storages"]:
1049 if vsd
.get("vdu-storage-requirements"):
1051 vsd
["vdu-storage-requirements"][0].get("key")
1053 and vsd
["vdu-storage-requirements"][0].get("value")
1056 nsr_sv
.append(vsd
["id"])
1058 vdur
["shared-volumes-id"] = nsr_sv
1060 # Adding Affinity groups information to vdur
1062 vdu_profile_affinity_group
= utils
.find_in_list(
1063 vnfd
.get("df")[0]["vdu-profile"],
1064 lambda a_vdu
: a_vdu
["id"] == vdu
["id"],
1067 vdu_profile_affinity_group
= None
1069 if vdu_profile_affinity_group
:
1070 affinity_group_ids
= []
1071 for affinity_group
in vdu_profile_affinity_group
.get(
1072 "affinity-or-anti-affinity-group", ()
1074 vdu_affinity_group
= utils
.find_in_list(
1075 vdu_profile_affinity_group
.get(
1076 "affinity-or-anti-affinity-group", ()
1078 lambda ag_fp
: ag_fp
["id"] == affinity_group
["id"],
1080 nsr_affinity_group
= utils
.find_in_list(
1081 nsr_descriptor
["affinity-or-anti-affinity-group"],
1083 nsr_ag
.get("ag-id") == vdu_affinity_group
.get("id")
1084 and nsr_ag
.get("member-vnf-index")
1085 == vnfr_descriptor
.get("member-vnf-index-ref")
1088 # Update Affinity Group VIM name if VDU instantiation parameter is present
1089 if vnf_params
and vnf_params
.get("affinity-or-anti-affinity-group"):
1090 vnf_params_affinity_group
= utils
.find_in_list(
1091 vnf_params
["affinity-or-anti-affinity-group"],
1093 vnfp_ag
.get("id") == vdu_affinity_group
.get("id")
1096 if vnf_params_affinity_group
.get("vim-affinity-group-id"):
1098 "vim-affinity-group-id"
1099 ] = vnf_params_affinity_group
["vim-affinity-group-id"]
1100 affinity_group_ids
.append(nsr_affinity_group
["id"])
1101 vdur
["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1103 if vdu_instantiation_level
:
1104 count
= vdu_instantiation_level
.get("number-of-instances")
1108 for index
in range(0, count
):
1109 vdur
= deepcopy(vdur
)
1110 for iface
in vdur
["interfaces"]:
1111 if iface
.get("ip-address") and index
!= 0:
1112 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
1113 if iface
.get("mac-address") and index
!= 0:
1114 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
1116 vdur
["_id"] = str(uuid4())
1117 vdur
["id"] = vdur
["_id"]
1118 vdur
["count-index"] = index
1119 vnfr_descriptor
["vdur"].append(vdur
)
1120 return vnfr_descriptor
1122 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
1124 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1125 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1126 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1127 :param ns_instance_content: ns instance content
1128 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1131 time_now
, time_delta
= (
1133 time() - ns_instance_content
["_admin"]["modified"],
1136 isinstance(filter_q
, dict) and filter_q
.get("vcaStatusRefresh") == "true"
1138 threshold_reached
= time_delta
> 120
1139 if force_refresh
or threshold_reached
:
1140 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
1141 ns_instance_content
["_admin"]["modified"] = time_now
1142 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
1143 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
1145 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
1147 nslcmop_desc
["_admin"].pop("nsState")
1148 self
.msg
.write("ns", operation
, nslcmop_desc
)
1151 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1153 Get complete information on an ns instance.
1154 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1155 :param _id: string, ns instance id
1156 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1157 :param api_req: True if this call is serving an external API request. False if serving internal request.
1158 :return: dictionary, raise exception if not found.
1160 ns_instance_content
= super().show(session
, _id
, api_req
)
1161 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1162 return ns_instance_content
1164 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1165 raise EngineException(
1166 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1170 class VnfrTopic(BaseTopic
):
1174 def __init__(self
, db
, fs
, msg
, auth
):
1175 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1177 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1178 raise EngineException(
1179 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1182 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1183 raise EngineException(
1184 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1187 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1188 # Not used because vnfrs are created and deleted by NsrTopic class directly
1189 raise EngineException(
1190 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1194 class NsLcmOpTopic(BaseTopic
):
1197 operation_schema
= { # mapping between operation and jsonschema to validate
1198 "instantiate": ns_instantiate
,
1199 "action": ns_action
,
1200 "update": ns_update
,
1203 "terminate": ns_terminate
,
1204 "migrate": ns_migrate
,
1205 "verticalscale": ns_verticalscale
,
1206 "cancel": nslcmop_cancel
,
1209 def __init__(self
, db
, fs
, msg
, auth
):
1210 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1211 self
.nsrtopic
= NsrTopic(db
, fs
, msg
, auth
)
1213 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1215 Check that user has enter right parameters for the operation
1216 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1217 :param operation: it can be: instantiate, terminate, action, update, heal
1218 :param indata: descriptor with the parameters of the operation
1221 if operation
== "action":
1222 self
._check
_action
_ns
_operation
(indata
, nsr
)
1223 elif operation
== "scale":
1224 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1225 elif operation
== "update":
1226 self
._check
_update
_ns
_operation
(indata
, nsr
)
1227 elif operation
== "heal":
1228 self
._check
_heal
_ns
_operation
(indata
, nsr
)
1229 elif operation
== "instantiate":
1230 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1232 def _check_action_ns_operation(self
, indata
, nsr
):
1234 # check vnf_member_index
1235 if indata
.get("vnf_member_index"):
1236 indata
["member_vnf_index"] = indata
.pop(
1238 ) # for backward compatibility
1239 if indata
.get("member_vnf_index"):
1240 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1241 indata
["member_vnf_index"], nsr
["_id"]
1244 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1245 "operate-vnf-op-config"
1250 if indata
.get("vdu_id"):
1251 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1252 descriptor_configuration
= utils
.find_in_list(
1253 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1255 elif indata
.get("kdu_name"):
1256 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1257 descriptor_configuration
= utils
.find_in_list(
1258 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1261 descriptor_configuration
= utils
.find_in_list(
1262 configs
, lambda config
: config
["id"] == vnfd
["id"]
1264 if descriptor_configuration
is not None:
1265 descriptor_configuration
= descriptor_configuration
.get(
1269 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1273 # For k8s allows default primitives without validating the parameters
1274 if indata
.get("kdu_name") and indata
["primitive"] in (
1281 # TODO should be checked that rollback only can contains revsision_numbe????
1282 if not indata
.get("member_vnf_index"):
1283 raise EngineException(
1284 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1289 # if not, check primitive
1290 for config_primitive
in get_iterable(descriptor_configuration
):
1291 if indata
["primitive"] == config_primitive
["name"]:
1292 # check needed primitive_params are provided
1293 if indata
.get("primitive_params"):
1294 in_primitive_params_copy
= copy(indata
["primitive_params"])
1296 in_primitive_params_copy
= {}
1297 for paramd
in get_iterable(config_primitive
.get("parameter")):
1298 if paramd
["name"] in in_primitive_params_copy
:
1299 del in_primitive_params_copy
[paramd
["name"]]
1300 elif not paramd
.get("default-value"):
1301 raise EngineException(
1302 "Needed parameter {} not provided for primitive '{}'".format(
1303 paramd
["name"], indata
["primitive"]
1306 # check no extra primitive params are provided
1307 if in_primitive_params_copy
:
1308 raise EngineException(
1309 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1310 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1315 raise EngineException(
1316 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1321 def _check_update_ns_operation(self
, indata
, nsr
) -> None:
1322 """Validates the ns-update request according to updateType
1324 If updateType is CHANGE_VNFPKG:
1325 - it checks the vnfInstanceId, whether it's available under ns instance
1326 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1327 Otherwise exception will be raised.
1328 If updateType is REMOVE_VNF:
1329 - it checks if the vnfInstanceId is available in the ns instance
1330 - Otherwise exception will be raised.
1333 indata: includes updateType such as CHANGE_VNFPKG,
1334 nsr: network service record
1338 a meaningful error if given update parameters are not proper such as
1339 "Error in validating ns-update request: <ID> does not match
1340 with the vnfd-id of vnfinstance
1341 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1345 if indata
["updateType"] == "CHANGE_VNFPKG":
1346 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1347 vnf_instance_id
= indata
["changeVnfPackageData"]["vnfInstanceId"]
1348 ns_instance_id
= indata
["nsInstanceId"]
1349 vnfd_id_2update
= indata
["changeVnfPackageData"]["vnfdId"]
1351 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1352 raise EngineException(
1353 f
"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1354 f
"belong to NS {ns_instance_id}",
1355 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1358 # Getting vnfrs through the ns_instance_id
1359 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": ns_instance_id
})
1360 constituent_vnfd_id
= next(
1364 if vnfr
["id"] == vnf_instance_id
1369 # Check the given vnfd-id belongs to given vnf instance
1370 if constituent_vnfd_id
and (vnfd_id_2update
!= constituent_vnfd_id
):
1371 raise EngineException(
1372 f
"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1373 f
"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1374 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1377 # Validating the ns update timeout
1379 indata
.get("timeout_ns_update")
1380 and indata
["timeout_ns_update"] < 300
1382 raise EngineException(
1383 "Error in validating ns-update request: {} second is not enough "
1384 "to upgrade the VNF instance: {}".format(
1385 indata
["timeout_ns_update"], vnf_instance_id
1387 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1389 elif indata
["updateType"] == "REMOVE_VNF":
1390 vnf_instance_id
= indata
["removeVnfInstanceId"]
1391 ns_instance_id
= indata
["nsInstanceId"]
1392 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1393 raise EngineException(
1394 "Invalid VNF Instance Id. '{}' is not "
1395 "present in the NS '{}'".format(vnf_instance_id
, ns_instance_id
)
1406 "Ns update request could not be processed with error: {}.".format(e
)
1409 def _check_scale_ns_operation(self
, indata
, nsr
):
1410 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1411 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1413 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1415 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1416 == scaling_aspect
["id"]
1420 raise EngineException(
1421 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1422 "present at vnfd:scaling-aspect".format(
1423 indata
["scaleVnfData"]["scaleByStepData"][
1424 "scaling-group-descriptor"
1429 def _check_heal_ns_operation(self
, indata
, nsr
):
1432 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1433 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1437 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1438 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1439 for in_vnf
in get_iterable(indata
.get("vnf")):
1440 member_vnf_index
= in_vnf
["member-vnf-index"]
1441 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1442 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1444 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1445 member_vnf_index
, nsr
["_id"]
1447 vnf_member_index_to_vnfd
[
1449 ] = vnfd
# add to cache, avoiding a later look for
1450 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1451 if in_vnf
.get("vimAccountId"):
1452 self
._check
_valid
_vim
_account
(
1453 in_vnf
["vimAccountId"], vim_accounts
, session
1456 for in_vld
in get_iterable(indata
.get("vld")):
1457 self
._check
_valid
_wim
_account
(
1458 in_vld
.get("wimAccountId"), wim_accounts
, session
1460 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1461 if in_vld
["name"] == vldd
["id"]:
1464 raise EngineException(
1465 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1470 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1471 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1472 vnfr
= self
.db
.get_one(
1474 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1475 fail_on_empty
=False,
1478 raise EngineException(
1479 "Invalid parameter member_vnf_index='{}' is not one of the "
1480 "nsd:constituent-vnfd".format(member_vnf_index
)
1483 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1484 if "revision" in vnfr
:
1485 vnfd_revision
= vnfr
["vnfd-id"] + ":" + str(vnfr
["revision"])
1486 vnfd
= self
.db
.get_one(
1487 "vnfds_revisions", {"_id": vnfd_revision
}, fail_on_empty
=False
1490 vnfd
= self
.db
.get_one(
1491 "vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False
1495 raise EngineException(
1496 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1502 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1503 for vdud
in get_iterable(vnfd
.get("vdu")):
1504 if vdud
["id"] == vdu_id
:
1507 raise EngineException(
1508 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1513 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1514 for kdud
in get_iterable(vnfd
.get("kdu")):
1515 if kdud
["name"] == kdu_name
:
1518 raise EngineException(
1519 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1524 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1525 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1526 for vdu
in get_iterable(vnfd
.get("vdu")):
1527 if in_vdu
["id"] == vdu
["id"]:
1528 for volume
in get_iterable(in_vdu
.get("volume")):
1529 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1530 if volumed
== volume
["name"]:
1533 raise EngineException(
1534 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1535 "volume:name='{}' is not present at "
1536 "vnfd:vdu:virtual-storage-desc list".format(
1537 in_vnf
["member-vnf-index"],
1543 vdu_if_names
= set()
1544 for cpd
in get_iterable(vdu
.get("int-cpd")):
1545 for iface
in get_iterable(
1546 cpd
.get("virtual-network-interface-requirement")
1548 vdu_if_names
.add(iface
.get("name"))
1550 for in_iface
in get_iterable(in_vdu
.get("interface")):
1551 if in_iface
["name"] in vdu_if_names
:
1554 raise EngineException(
1555 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1556 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1557 in_vnf
["member-vnf-index"],
1565 raise EngineException(
1566 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1567 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1571 ivld
.get("id"): set()
1572 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1574 for vdu
in vnfd
.get("vdu", {}):
1575 for cpd
in vdu
.get("int-cpd", {}):
1576 if cpd
.get("int-virtual-link-desc"):
1577 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1579 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1580 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1581 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1582 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1585 raise EngineException(
1586 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1587 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1588 "vnfd:internal-vld:name/id:internal-connection-point".format(
1589 in_vnf
["member-vnf-index"],
1595 raise EngineException(
1596 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1597 " is not present at vnfd '{}'".format(
1598 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1602 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1603 if vim_account
in vim_accounts
:
1606 db_filter
= self
._get
_project
_filter
(session
)
1607 db_filter
["_id"] = vim_account
1608 self
.db
.get_one("vim_accounts", db_filter
)
1610 raise EngineException(
1611 "Invalid vimAccountId='{}' not present for the project".format(
1615 vim_accounts
.append(vim_account
)
1617 def _get_vim_account(self
, vim_id
: str, session
):
1619 db_filter
= self
._get
_project
_filter
(session
)
1620 db_filter
["_id"] = vim_id
1621 return self
.db
.get_one("vim_accounts", db_filter
)
1623 raise EngineException(
1624 "Invalid vimAccountId='{}' not present for the project".format(vim_id
)
1627 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1628 if not isinstance(wim_account
, str):
1630 if wim_account
in wim_accounts
:
1633 db_filter
= self
._get
_project
_filter
(session
)
1634 db_filter
["_id"] = wim_account
1635 self
.db
.get_one("wim_accounts", db_filter
)
1637 raise EngineException(
1638 "Invalid wimAccountId='{}' not present for the project".format(
1642 wim_accounts
.append(wim_account
)
1645 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1648 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1649 (ip_address, ...) information.
1650 Modifies PDU _admin.usageState to 'IN_USE'
1651 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1652 :param rollback: list with the database modifications to rollback if needed
1653 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1654 :param vim_account: vim_account where this vnfr should be deployed
1655 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1656 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1657 of the changed vnfr is needed
1659 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1660 "vim-network-name": used at VIM
1661 "name": interface name
1662 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1663 "ns-vld-id": NSD vld where this interface is connected.
1664 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1667 ifaces_forcing_vim_network
= []
1668 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1669 if not vdur
.get("pdu-type"):
1671 pdu_type
= vdur
.get("pdu-type")
1672 pdu_filter
= self
._get
_project
_filter
(session
)
1673 pdu_filter
["vim_accounts"] = vim_account
1674 pdu_filter
["type"] = pdu_type
1675 pdu_filter
["_admin.operationalState"] = "ENABLED"
1676 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1677 # TODO feature 1417: "shared": True,
1679 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1680 for pdu
in available_pdus
:
1681 # step 1 check if this pdu contains needed interfaces:
1682 match_interfaces
= True
1683 for vdur_interface
in vdur
["interfaces"]:
1684 for pdu_interface
in pdu
["interfaces"]:
1685 if pdu_interface
["name"] == vdur_interface
["name"]:
1686 # TODO feature 1417: match per mgmt type
1688 else: # no interface found for name
1689 match_interfaces
= False
1691 if match_interfaces
:
1694 raise EngineException(
1695 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1699 vnfr
["member-vnf-index-ref"],
1704 # step 2. Update pdu
1706 "_admin.usageState": pdu
["_admin"]["usageState"],
1707 "_admin.usage.vnfr_id": None,
1708 "_admin.usage.nsr_id": None,
1709 "_admin.usage.vdur": None,
1713 {"_id": pdu
["_id"]},
1715 "_admin.usageState": "IN_USE",
1717 "vnfr_id": vnfr
["_id"],
1718 "nsr_id": vnfr
["nsr-id-ref"],
1719 "vdur": vdur
["vdu-id-ref"],
1728 "content": rollback_pdu
,
1732 # step 3. Fill vnfr info by filling vdur
1733 vdu_text
= "vdur.{}".format(vdur_index
)
1734 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1735 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1736 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1737 for pdu_interface
in pdu
["interfaces"]:
1738 if pdu_interface
["name"] == vdur_interface
["name"]:
1739 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1740 for k
, v
in pdu_interface
.items():
1744 ): # TODO: switch-xxxxx must be inserted
1745 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1746 vnfr_update_rollback
[
1747 iface_text
+ ".{}".format(k
)
1748 ] = vdur_interface
.get(v
)
1749 if pdu_interface
.get("ip-address"):
1750 if vdur_interface
.get(
1752 ) or vdur_interface
.get("mgmt-vnf"):
1753 vnfr_update_rollback
[
1754 vdu_text
+ ".ip-address"
1755 ] = vdur
.get("ip-address")
1756 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1759 if vdur_interface
.get("mgmt-vnf"):
1760 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1763 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1764 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1767 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1770 ifaces_forcing_vim_network
.append(
1772 "name": vdur_interface
.get("vnf-vld-id")
1773 or vdur_interface
.get("ns-vld-id"),
1774 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1775 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1778 if pdu_interface
.get("vim-network-id"):
1779 ifaces_forcing_vim_network
[-1][
1781 ] = pdu_interface
["vim-network-id"]
1782 if pdu_interface
.get("vim-network-name"):
1783 ifaces_forcing_vim_network
[-1][
1785 ] = pdu_interface
["vim-network-name"]
1788 return ifaces_forcing_vim_network
1790 def _look_for_k8scluster(
1791 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1794 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1795 Fills vnfr.kdur with the selected k8scluster
1797 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1798 :param rollback: list with the database modifications to rollback if needed
1799 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1800 :param vim_account: vim_account where this vnfr should be deployed
1801 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1802 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1803 of the changed vnfr is needed
1805 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1806 "vim-network-name": used at VIM
1807 "name": interface name
1808 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1809 "ns-vld-id": NSD vld where this interface is connected.
1810 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1813 ifaces_forcing_vim_network
= []
1814 if not vnfr
.get("kdur"):
1815 return ifaces_forcing_vim_network
1817 kdu_filter
= self
._get
_project
_filter
(session
)
1818 kdu_filter
["vim_account"] = vim_account
1819 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1820 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1822 k8s_requirements
= {} # just for logging
1823 for k8scluster
in available_k8sclusters
:
1824 if not vnfr
.get("k8s-cluster"):
1827 if vnfr
["k8s-cluster"].get("cni"):
1828 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1829 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1830 k8scluster
.get("cni", ())
1833 # restrict by version
1834 if vnfr
["k8s-cluster"].get("version"):
1835 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1836 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1838 # restrict by number of networks
1839 if vnfr
["k8s-cluster"].get("nets"):
1840 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1841 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1842 vnfr
["k8s-cluster"]["nets"]
1847 raise EngineException(
1848 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1849 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1853 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1854 # step 3. Fill vnfr info by filling kdur
1855 kdu_text
= "kdur.{}.".format(kdur_index
)
1856 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1857 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1859 # step 4. Check VIM networks that forces the selected k8s_cluster
1860 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1861 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1862 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1863 # get a network from k8s_cluster nets. If name matches use this, if not use other
1864 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1865 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1866 k8scluster_net_list
.remove(kdur_net
["id"])
1868 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1869 k8scluster_net_list
.pop(0)
1870 vnfr_update_rollback
[
1871 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1873 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1875 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1877 ifaces_forcing_vim_network
.append(
1879 "name": kdur_net
.get("vnf-vld-id")
1880 or kdur_net
.get("ns-vld-id"),
1881 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1882 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1883 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1886 # TODO check that this forcing is not incompatible with other forcing
1887 return ifaces_forcing_vim_network
1889 def _update_vnfrs_from_nsd(self
, nsr
):
1890 step
= "Getting vnf_profiles from nsd" # first step must be defined outside try
1895 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
1896 vld_fixed_ip_connection_point_data
= {}
1898 step
= "Getting ip-address info from vnf_profile if it exists"
1899 for vnfp
in vnf_profiles
:
1900 # Checking ip-address info from nsd.vnf_profile and storing
1901 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
1902 for cpd
in vlc
.get("constituent-cpd-id", ()):
1903 if cpd
.get("ip-address"):
1904 step
= "Storing ip-address info"
1905 vld_fixed_ip_connection_point_data
.update(
1907 vlc
.get("virtual-link-profile-id")
1909 + cpd
.get("constituent-base-element-id"): {
1910 "vnfd-connection-point-ref": cpd
.get(
1911 "constituent-cpd-id"
1913 "ip-address": cpd
.get("ip-address"),
1918 # Inserting ip address to vnfr
1919 if len(vld_fixed_ip_connection_point_data
) > 0:
1920 step
= "Getting vnfrs"
1921 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1922 for item
in vld_fixed_ip_connection_point_data
.keys():
1923 step
= "Filtering vnfrs"
1926 lambda vnfr
: vnfr
["member-vnf-index-ref"]
1927 == item
.split(".")[1],
1934 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1935 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1936 step
= "Looking for matched interface"
1938 iface
.get("external-connection-point-ref")
1939 == vld_fixed_ip_connection_point_data
[item
].get(
1940 "vnfd-connection-point-ref"
1942 and iface
.get("ns-vld-id") == item
.split(".")[0]
1944 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1945 vdur_index
, iface_index
1947 step
= "Storing info in order to update vnfr"
1949 vnfr_update_text
+ ".ip-address"
1950 ] = increment_ip_mac(
1951 vld_fixed_ip_connection_point_data
[item
].get(
1954 vdur
.get("count-index", 0),
1956 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1958 step
= "updating vnfr at database"
1959 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1967 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
1969 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1972 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1976 vnfr_update_rollback
= {}
1977 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1978 # update vim-account-id
1980 vim_account
= indata
["vimAccountId"]
1981 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1982 # check instantiate parameters
1983 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1984 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1986 if vnf_inst_params
.get("vimAccountId"):
1987 vim_account
= vnf_inst_params
.get("vimAccountId")
1988 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1990 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1991 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1992 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1993 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1995 for iface_inst_param
in get_iterable(
1996 vdu_inst_param
.get("interface")
1998 iface_index
, _
= next(
2000 for i
in enumerate(vdur
["interfaces"])
2001 if i
[1]["name"] == iface_inst_param
["name"]
2003 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2004 vdur_index
, iface_index
2006 if iface_inst_param
.get("ip-address"):
2008 vnfr_update_text
+ ".ip-address"
2009 ] = increment_ip_mac(
2010 iface_inst_param
.get("ip-address"),
2011 vdur
.get("count-index", 0),
2013 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2014 if iface_inst_param
.get("mac-address"):
2016 vnfr_update_text
+ ".mac-address"
2017 ] = increment_ip_mac(
2018 iface_inst_param
.get("mac-address"),
2019 vdur
.get("count-index", 0),
2021 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2022 if iface_inst_param
.get("floating-ip-required"):
2024 vnfr_update_text
+ ".floating-ip-required"
2026 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2027 # TODO update vld with the ip-profile
2028 for ivld_inst_param
in get_iterable(
2029 vnf_inst_params
.get("internal-vld")
2031 for icp_inst_param
in get_iterable(
2032 ivld_inst_param
.get("internal-connection-point")
2035 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2036 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2038 iface
.get("internal-connection-point-ref")
2039 == icp_inst_param
["id-ref"]
2041 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2042 vdur_index
, iface_index
2044 if icp_inst_param
.get("ip-address"):
2046 vnfr_update_text
+ ".ip-address"
2047 ] = increment_ip_mac(
2048 icp_inst_param
.get("ip-address"),
2049 vdur
.get("count-index", 0),
2052 vnfr_update_text
+ ".fixed-ip"
2054 if icp_inst_param
.get("mac-address"):
2056 vnfr_update_text
+ ".mac-address"
2057 ] = increment_ip_mac(
2058 icp_inst_param
.get("mac-address"),
2059 vdur
.get("count-index", 0),
2062 vnfr_update_text
+ ".fixed-mac"
2065 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2066 for vld_inst_param
in get_iterable(indata
.get("vld")):
2067 for vnfcp_inst_param
in get_iterable(
2068 vld_inst_param
.get("vnfd-connection-point-ref")
2070 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
2073 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2074 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2076 iface
.get("external-connection-point-ref")
2077 == vnfcp_inst_param
["vnfd-connection-point-ref"]
2079 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2080 vdur_index
, iface_index
2082 if vnfcp_inst_param
.get("ip-address"):
2084 vnfr_update_text
+ ".ip-address"
2085 ] = increment_ip_mac(
2086 vnfcp_inst_param
.get("ip-address"),
2087 vdur
.get("count-index", 0),
2089 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2090 if vnfcp_inst_param
.get("mac-address"):
2092 vnfr_update_text
+ ".mac-address"
2093 ] = increment_ip_mac(
2094 vnfcp_inst_param
.get("mac-address"),
2095 vdur
.get("count-index", 0),
2097 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2100 vnfr_update
["vim-account-id"] = vim_account
2101 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
2104 vnfr_update
["vca-id"] = vca_id
2105 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
2108 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
2109 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2113 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
2114 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2116 # update database vnfr
2117 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2123 "content": vnfr_update_rollback
,
2127 # Update indada in case pdu forces to use a concrete vim-network-name
2128 # TODO check if user has already insert a vim-network-name and raises an error
2129 if not ifaces_forcing_vim_network
:
2131 for iface_info
in ifaces_forcing_vim_network
:
2132 if iface_info
.get("ns-vld-id"):
2133 if "vld" not in indata
:
2135 indata
["vld"].append(
2137 key
: iface_info
[key
]
2138 for key
in ("name", "vim-network-name", "vim-network-id")
2139 if iface_info
.get(key
)
2143 elif iface_info
.get("vnf-vld-id"):
2144 if "vnf" not in indata
:
2146 indata
["vnf"].append(
2148 "member-vnf-index": member_vnf_index
,
2151 key
: iface_info
[key
]
2157 if iface_info
.get(key
)
2164 def _create_nslcmop(nsr_id
, operation
, params
):
2166 Creates a ns-lcm-opp content to be stored at database.
2167 :param nsr_id: internal id of the instance
2168 :param operation: instantiate, terminate, scale, action, update ...
2169 :param params: user parameters for the operation
2170 :return: dictionary following SOL005 format
2177 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2178 "queuePosition": None,
2180 "errorMessage": None,
2181 "detailedStatus": None,
2182 "statusEnteredTime": now
,
2183 "nsInstanceId": nsr_id
,
2184 "lcmOperationType": operation
,
2186 "isAutomaticInvocation": False,
2187 "operationParams": params
,
2188 "isCancelPending": False,
2190 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2191 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2196 def _get_enabled_vims(self
, session
):
2198 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2199 :param session: current session with user information
2201 db_filter
= self
._get
_project
_filter
(session
)
2202 db_filter
["_admin.operationalState"] = "ENABLED"
2203 vims
= self
.db
.get_list("vim_accounts", db_filter
)
2206 vimAccounts
.append(vim
["_id"])
2219 Performs a new operation over a ns
2220 :param rollback: list to append created items at database in case a rollback must to be done
2221 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2222 :param indata: descriptor with the parameters of the operation. It must contains among others
2223 nsInstanceId: _id of the nsr to perform the operation
2224 operation: it can be: instantiate, terminate, action, update TODO: heal
2225 :param kwargs: used to override the indata descriptor
2226 :param headers: http request headers
2227 :return: id of the nslcmops
2230 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
2232 db_filter
= self
._get
_project
_filter
(session
)
2233 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2234 nsis
= self
.db
.get_one(
2235 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
2238 raise EngineException(
2239 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2242 http_code
=HTTPStatus
.CONFLICT
,
2246 # Override descriptor with query string kwargs
2247 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2248 operation
= indata
["lcmOperationType"]
2249 nsInstanceId
= indata
["nsInstanceId"]
2251 validate_input(indata
, self
.operation_schema
[operation
])
2252 # get ns from nsr_id
2253 _filter
= BaseTopic
._get
_project
_filter
(session
)
2254 _filter
["_id"] = nsInstanceId
2255 nsr
= self
.db
.get_one("nsrs", _filter
)
2258 if operation
== "terminate" and slice_object
is False:
2259 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
2261 not nsr
["_admin"].get("nsState")
2262 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
2264 if operation
== "terminate" and indata
.get("autoremove"):
2265 # NSR must be deleted
2269 ) # a none in this case is used to indicate not instantiated. It can be removed
2270 if operation
!= "instantiate":
2271 raise EngineException(
2272 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2273 nsInstanceId
, operation
2275 HTTPStatus
.CONFLICT
,
2278 if operation
== "instantiate" and not session
["force"]:
2279 raise EngineException(
2280 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2281 nsInstanceId
, operation
2283 HTTPStatus
.CONFLICT
,
2285 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
2286 if indata
.get("primitive_params"):
2287 indata
["primitive_params"] = json
.dumps(indata
["primitive_params"])
2288 elif indata
.get("additionalParamsForVnf"):
2289 indata
["additionalParamsForVnf"] = json
.dumps(
2290 indata
["additionalParamsForVnf"]
2293 if operation
== "instantiate":
2294 self
._update
_vnfrs
_from
_nsd
(nsr
)
2295 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
2296 if (operation
== "update") and (indata
["updateType"] == "CHANGE_VNFPKG"):
2298 vnfd_id
= indata
["changeVnfPackageData"]["vnfdId"]
2299 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2300 nsd
= self
.db
.get_one("nsds", {"_id": nsr
["nsd-id"]})
2301 ns_request
= nsr
["instantiate_params"]
2302 vnfr
= self
.db
.get_one(
2303 "vnfrs", {"_id": indata
["changeVnfPackageData"]["vnfInstanceId"]}
2305 latest_vnfd_revision
= vnfd
["_admin"].get("revision", 1)
2306 vnfr_vnfd_revision
= vnfr
.get("revision", 1)
2307 if latest_vnfd_revision
!= vnfr_vnfd_revision
:
2308 old_vnfd_id
= vnfd_id
+ ":" + str(vnfr_vnfd_revision
)
2309 old_db_vnfd
= self
.db
.get_one(
2310 "vnfds_revisions", {"_id": old_vnfd_id
}
2312 old_sw_version
= old_db_vnfd
.get("software-version", "1.0")
2313 new_sw_version
= vnfd
.get("software-version", "1.0")
2314 if new_sw_version
!= old_sw_version
:
2315 vnf_index
= vnfr
["member-vnf-index-ref"]
2316 self
.logger
.info("nsr {}".format(nsr
))
2317 for vdu
in vnfd
["vdu"]:
2318 self
.nsrtopic
._add
_shared
_volumes
_to
_nsr
(
2319 vdu
, vnfd
, nsr
, vnf_index
, latest_vnfd_revision
2321 self
.nsrtopic
._add
_flavor
_to
_nsr
(
2322 vdu
, vnfd
, nsr
, vnf_index
, latest_vnfd_revision
2324 sw_image_id
= vdu
.get("sw-image-desc")
2326 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(
2329 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2330 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
2331 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(
2334 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2335 nsr_update
["image"] = nsr
["image"]
2336 nsr_update
["flavor"] = nsr
["flavor"]
2337 nsr_update
["shared-volumes"] = nsr
["shared-volumes"]
2338 self
.db
.set_one("nsrs", {"_id": nsr
["_id"]}, nsr_update
)
2339 ns_k8s_namespace
= self
.nsrtopic
._get
_ns
_k
8s
_namespace
(
2340 nsd
, ns_request
, session
2343 self
.nsrtopic
._create
_vnfr
_descriptor
_from
_vnfd
(
2351 latest_vnfd_revision
,
2354 indata
["newVdur"] = vnfr_descriptor
["vdur"]
2355 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
2356 _id
= nslcmop_desc
["_id"]
2358 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2360 if indata
.get("placement-engine"):
2361 # Save valid vim accounts in lcm operation descriptor
2362 nslcmop_desc
["operationParams"][
2364 ] = self
._get
_enabled
_vims
(session
)
2365 self
.db
.create("nslcmops", nslcmop_desc
)
2366 rollback
.append({"topic": "nslcmops", "_id": _id
})
2367 if not slice_object
:
2368 self
.msg
.write("ns", operation
, nslcmop_desc
)
2370 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2371 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2372 # except DbException as e:
2373 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2375 def cancel(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2376 validate_input(indata
, self
.operation_schema
["cancel"])
2377 # Override descriptor with query string kwargs
2378 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2379 nsLcmOpOccId
= indata
["nsLcmOpOccId"]
2380 cancelMode
= indata
["cancelMode"]
2381 # get nslcmop from nsLcmOpOccId
2382 _filter
= BaseTopic
._get
_project
_filter
(session
)
2383 _filter
["_id"] = nsLcmOpOccId
2384 nslcmop
= self
.db
.get_one("nslcmops", _filter
)
2385 # Fail is this is not an ongoing nslcmop
2386 if nslcmop
.get("operationState") not in [
2391 raise EngineException(
2392 "Operation is not in STARTING, PROCESSING or ROLLING_BACK state",
2393 http_code
=HTTPStatus
.CONFLICT
,
2395 nsInstanceId
= nslcmop
["nsInstanceId"]
2397 "isCancelPending": True,
2398 "cancelMode": cancelMode
,
2401 "nslcmops", q_filter
=_filter
, update_dict
=update_dict
, fail_on_empty
=False
2404 "_id": nsLcmOpOccId
,
2405 "nsInstanceId": nsInstanceId
,
2406 "cancelMode": cancelMode
,
2408 self
.msg
.write("nslcmops", "cancel", data
)
2410 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2411 raise EngineException(
2412 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2415 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2416 raise EngineException(
2417 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2421 class NsiTopic(BaseTopic
):
2424 quota_name
= "slice_instances"
2426 def __init__(self
, db
, fs
, msg
, auth
):
2427 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2428 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2431 def _format_ns_request(ns_request
):
2432 formated_request
= copy(ns_request
)
2433 # TODO: Add request params
2434 return formated_request
2437 def _format_addional_params(slice_request
):
2439 Get and format user additional params for NS or VNF
2440 :param slice_request: User instantiation additional parameters
2441 :return: a formatted copy of additional params or None if not supplied
2443 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2444 if additional_params
:
2445 for k
, v
in additional_params
.items():
2446 if not isinstance(k
, str):
2447 raise EngineException(
2448 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2452 if "." in k
or "$" in k
:
2453 raise EngineException(
2454 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2458 if isinstance(v
, (dict, tuple, list)):
2459 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2460 return additional_params
2462 def check_conflict_on_del(self
, session
, _id
, db_content
):
2464 Check that NSI is not instantiated
2465 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2466 :param _id: nsi internal id
2467 :param db_content: The database content of the _id
2468 :return: None or raises EngineException with the conflict
2470 if session
["force"]:
2473 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2474 raise EngineException(
2475 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2476 "Launch 'terminate' operation first; or force deletion".format(_id
),
2477 http_code
=HTTPStatus
.CONFLICT
,
2480 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2482 Deletes associated nsilcmops from database. Deletes associated filesystem.
2483 Set usageState of nst
2484 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2485 :param _id: server internal id
2486 :param db_content: The database content of the descriptor
2487 :param not_send_msg: To not send message (False) or store content (list) instead
2488 :return: None if ok or raises EngineException with the problem
2491 # Deleting the nsrs belonging to nsir
2493 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2494 nsr_id
= nsrs_detailed_item
["nsrId"]
2495 if nsrs_detailed_item
.get("shared"):
2497 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2498 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2499 "_id.ne": nsir
["_id"],
2501 nsi
= self
.db
.get_one(
2502 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2504 if nsi
: # last one using nsr
2507 self
.nsrTopic
.delete(
2508 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2510 except (DbException
, EngineException
) as e
:
2511 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2516 # delete related nsilcmops database entries
2517 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2519 # Check and set used NST usage state
2520 nsir_admin
= nsir
.get("_admin")
2521 if nsir_admin
and nsir_admin
.get("nst-id"):
2522 # check if used by another NSI
2523 nsis_list
= self
.db
.get_one(
2525 {"nst-id": nsir_admin
["nst-id"]},
2526 fail_on_empty
=False,
2532 {"_id": nsir_admin
["nst-id"]},
2533 {"_admin.usageState": "NOT_IN_USE"},
2536 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2538 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2539 :param rollback: list to append the created items at database in case a rollback must be done
2540 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2541 :param indata: params to be used for the nsir
2542 :param kwargs: used to override the indata descriptor
2543 :param headers: http request headers
2544 :return: the _id of nsi descriptor created at database
2547 step
= "checking quotas" # first step must be defined outside try
2549 self
.check_quota(session
)
2552 slice_request
= self
._remove
_envelop
(indata
)
2553 # Override descriptor with query string kwargs
2554 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2555 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2558 step
= "getting nstd id='{}' from database".format(
2559 slice_request
.get("nstId")
2561 _filter
= self
._get
_project
_filter
(session
)
2562 _filter
["_id"] = slice_request
["nstId"]
2563 nstd
= self
.db
.get_one("nsts", _filter
)
2564 # check NST is not disabled
2565 step
= "checking NST operationalState"
2566 if nstd
["_admin"]["operationalState"] == "DISABLED":
2567 raise EngineException(
2568 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2569 "instance".format(slice_request
["nstId"]),
2570 http_code
=HTTPStatus
.CONFLICT
,
2574 # check NSD is not disabled
2575 step
= "checking operationalState"
2576 if nstd
["_admin"]["operationalState"] == "DISABLED":
2577 raise EngineException(
2578 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2579 "a network slice".format(slice_request
["nstId"]),
2580 http_code
=HTTPStatus
.CONFLICT
,
2583 nstd
.pop("_admin", None)
2584 nstd_id
= nstd
.pop("_id", None)
2585 nsi_id
= str(uuid4())
2586 step
= "filling nsi_descriptor with input data"
2591 "name": slice_request
["nsiName"],
2592 "description": slice_request
.get("nsiDescription", ""),
2593 "datacenter": slice_request
["vimAccountId"],
2594 "nst-ref": nstd
["id"],
2595 "instantiation_parameters": slice_request
,
2596 "network-slice-template": nstd
,
2600 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2603 step
= "creating nsi at database"
2605 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2607 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2608 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2609 nsi_descriptor
["_admin"]["deployed"] = {}
2610 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2611 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2613 # Creating netslice-vld for the RO.
2614 step
= "creating netslice-vld at database"
2616 # Building the vlds list to be deployed
2617 # From netslice descriptors, creating the initial list
2620 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2621 # Getting template Instantiation parameters from NST
2622 nsi_vld
= deepcopy(netslice_vlds
)
2623 nsi_vld
["shared-nsrs-list"] = []
2624 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2625 nsi_vlds
.append(nsi_vld
)
2627 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2628 # Creating netslice-subnet_record.
2632 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2633 for member_ns
in nstd
["netslice-subnet"]:
2634 nsd_id
= member_ns
["nsd-ref"]
2635 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2636 member_ns
["nsd-ref"], member_ns
["id"]
2638 if nsd_id
not in needed_nsds
:
2640 _filter
["id"] = nsd_id
2641 nsd
= self
.db
.get_one(
2642 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2646 needed_nsds
[nsd_id
] = nsd
2648 nsd
= needed_nsds
[nsd_id
]
2649 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2650 services
.append(member_ns
)
2652 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2653 member_ns
["nsd-ref"], member_ns
["id"]
2656 # creates Network Services records (NSRs)
2657 step
= "creating nsrs at database using NsrTopic.new()"
2658 ns_params
= slice_request
.get("netslice-subnet")
2660 nsi_netslice_subnet
= []
2661 for service
in services
:
2662 # Check if the netslice-subnet is shared and if it is share if the nss exists
2665 # Is the nss shared and instantiated?
2666 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2667 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2670 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2671 nsi
= self
.db
.get_one(
2672 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2674 if nsi
and service
.get("is-shared-nss"):
2675 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2676 for nsrs_detailed_item
in nsrs_detailed_list
:
2677 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2678 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2679 _id_nsr
= nsrs_detailed_item
["nsrId"]
2681 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2682 if netslice_subnet
["nss-id"] == service
["id"]:
2683 indata_ns
= netslice_subnet
2687 if service
.get("instantiation-parameters"):
2688 indata_ns
= deepcopy(service
["instantiation-parameters"])
2689 # del service["instantiation-parameters"]
2691 indata_ns
["nsdId"] = service
["_id"]
2692 indata_ns
["nsName"] = (
2693 slice_request
.get("nsiName") + "." + service
["id"]
2695 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2696 indata_ns
["nsDescription"] = service
["description"]
2697 if slice_request
.get("ssh_keys"):
2698 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2701 for ns_param
in ns_params
:
2702 if ns_param
.get("id") == service
["id"]:
2703 copy_ns_param
= deepcopy(ns_param
)
2704 del copy_ns_param
["id"]
2705 indata_ns
.update(copy_ns_param
)
2708 # Creates Nsr objects
2709 _id_nsr
, _
= self
.nsrTopic
.new(
2710 rollback
, session
, indata_ns
, kwargs
, headers
2714 "shared": service
.get("is-shared-nss"),
2715 "nsd-id": service
["nsd-ref"],
2716 "nss-id": service
["id"],
2717 "nslcmop_instantiate": None,
2719 indata_ns
["nss-id"] = service
["id"]
2720 nsrs_list
.append(nsrs_item
)
2721 nsi_netslice_subnet
.append(indata_ns
)
2722 nsr_ref
= {"nsr-ref": _id_nsr
}
2723 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2725 # Adding the nsrs list to the nsi
2726 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2727 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2729 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2732 # Creating the entry in the database
2733 self
.db
.create("nsis", nsi_descriptor
)
2734 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2736 except ValidationError
as e
:
2737 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2738 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2739 self
.logger
.exception(
2740 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2742 raise EngineException("Error {}: {}".format(step
, e
))
2744 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2745 raise EngineException(
2746 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2750 class NsiLcmOpTopic(BaseTopic
):
2753 operation_schema
= { # mapping between operation and jsonschema to validate
2754 "instantiate": nsi_instantiate
,
2758 def __init__(self
, db
, fs
, msg
, auth
):
2759 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2760 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2762 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2764 Check that user has enter right parameters for the operation
2765 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2766 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2767 :param indata: descriptor with the parameters of the operation
2771 nstd
= nsir
["network-slice-template"]
2773 def check_valid_netslice_subnet_id(nstId
):
2774 # TODO change to vnfR (??)
2775 for netslice_subnet
in nstd
["netslice-subnet"]:
2776 if nstId
== netslice_subnet
["id"]:
2777 nsd_id
= netslice_subnet
["nsd-ref"]
2778 if nsd_id
not in nsds
:
2779 _filter
= self
._get
_project
_filter
(session
)
2780 _filter
["id"] = nsd_id
2781 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2784 raise EngineException(
2785 "Invalid parameter nstId='{}' is not one of the "
2786 "nst:netslice-subnet".format(nstId
)
2789 if operation
== "instantiate":
2790 # check the existance of netslice-subnet items
2791 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2792 check_valid_netslice_subnet_id(in_nst
["id"])
2794 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2800 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2801 "statusEnteredTime": now
,
2802 "netsliceInstanceId": netsliceInstanceId
,
2803 "lcmOperationType": operation
,
2805 "isAutomaticInvocation": False,
2806 "operationParams": params
,
2807 "isCancelPending": False,
2809 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2810 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2811 + netsliceInstanceId
,
2816 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2817 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2818 if nst_sb_item
.get("is-shared-nss"):
2819 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2820 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2821 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2822 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2823 "nss-connection-point-ref"
2826 admin_subnet_item
["nss-id"]
2827 == admin_vld_nss_cp_ref_item
["nss-ref"]
2830 not nsr_item
["nsrId"]
2831 in admin_vld_item
["shared-nsrs-list"]
2833 admin_vld_item
["shared-nsrs-list"].append(
2837 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2840 {"_id": nsir
["_id"]},
2841 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2844 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2846 Performs a new operation over a ns
2847 :param rollback: list to append created items at database in case a rollback must to be done
2848 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2849 :param indata: descriptor with the parameters of the operation. It must contains among others
2850 netsliceInstanceId: _id of the nsir to perform the operation
2851 operation: it can be: instantiate, terminate, action, TODO: update, heal
2852 :param kwargs: used to override the indata descriptor
2853 :param headers: http request headers
2854 :return: id of the nslcmops
2857 # Override descriptor with query string kwargs
2858 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2859 operation
= indata
["lcmOperationType"]
2860 netsliceInstanceId
= indata
["netsliceInstanceId"]
2861 validate_input(indata
, self
.operation_schema
[operation
])
2863 # get nsi from netsliceInstanceId
2864 _filter
= self
._get
_project
_filter
(session
)
2865 _filter
["_id"] = netsliceInstanceId
2866 nsir
= self
.db
.get_one("nsis", _filter
)
2867 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2872 not nsir
["_admin"].get("nsiState")
2873 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2875 if operation
== "terminate" and indata
.get("autoremove"):
2876 # NSIR must be deleted
2880 ) # a none in this case is used to indicate not instantiated. It can be removed
2881 if operation
!= "instantiate":
2882 raise EngineException(
2883 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2884 netsliceInstanceId
, operation
2886 HTTPStatus
.CONFLICT
,
2889 if operation
== "instantiate" and not session
["force"]:
2890 raise EngineException(
2891 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2892 netsliceInstanceId
, operation
2894 HTTPStatus
.CONFLICT
,
2897 # Creating all the NS_operation (nslcmop)
2898 # Get service list from db
2899 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2901 # nslcmops_item = None
2902 for index
, nsr_item
in enumerate(nsrs_list
):
2903 nsr_id
= nsr_item
["nsrId"]
2904 if nsr_item
.get("shared"):
2905 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2906 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2908 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2910 _filter
["_id.ne"] = netsliceInstanceId
2911 nsi
= self
.db
.get_one(
2912 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2914 if operation
== "terminate":
2916 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2920 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2923 ): # other nsi is using this nsr and it needs this nsr instantiated
2924 continue # do not create nsilcmop
2926 # looks the first nsi fulfilling the conditions but not being the current NSIR
2928 nsi_nsr_item
= next(
2930 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2931 if n
["nsrId"] == nsr_id
2933 and n
["nslcmop_instantiate"]
2935 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2936 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2938 "_admin.nsrs-detailed-list.{}".format(
2942 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2943 # continue to not create nslcmop since nsrs is shared and nsrs was created
2946 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2951 "lcmOperationType": operation
,
2952 "nsInstanceId": nsr_id
,
2953 # Including netslice_id in the ns instantiate Operation
2954 "netsliceInstanceId": netsliceInstanceId
,
2956 if operation
== "instantiate":
2957 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2958 indata_ns
.update(service
["instantiate_params"])
2960 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2961 # message via kafka bus
2962 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2963 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2965 nslcmops
.append(nslcmop
)
2966 if operation
== "instantiate":
2968 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2972 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2973 except (DbException
, EngineException
) as e
:
2974 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2977 + "skipping NS={} because not found".format(nsr_id
)
2984 indata
["nslcmops_ids"] = nslcmops
2985 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2987 nsilcmop_desc
= self
._create
_nsilcmop
(
2988 session
, netsliceInstanceId
, operation
, indata
2991 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2993 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2994 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2995 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2997 except ValidationError
as e
:
2998 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
3000 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
3001 raise EngineException(
3002 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
3005 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
3006 raise EngineException(
3007 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR