1 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
18 from uuid
import uuid4
19 from http
import HTTPStatus
21 from copy
import copy
, deepcopy
22 from osm_nbi
.validation
import (
35 from osm_nbi
.base_topic
import (
41 update_descriptor_usage_state
,
43 from yaml
import safe_dump
44 from osm_common
.dbbase
import DbException
45 from osm_common
.msgbase
import MsgException
46 from osm_common
.fsbase
import FsException
47 from osm_nbi
import utils
50 ) # For checking that additional parameter names are valid Jinja2 identifiers
52 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
55 class NsrTopic(BaseTopic
):
58 quota_name
= "ns_instances"
59 schema_new
= ns_instantiate
61 def __init__(self
, db
, fs
, msg
, auth
):
62 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
64 def _check_descriptor_dependencies(self
, session
, descriptor
):
66 Check that the dependent descriptors exist on a new descriptor or edition
67 :param session: client session information
68 :param descriptor: descriptor to be inserted or edit
69 :return: None or raises exception
71 if not descriptor
.get("nsdId"):
73 nsd_id
= descriptor
["nsdId"]
74 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
75 raise EngineException(
76 "Descriptor error at nsdId='{}' references a non exist nsd".format(
79 http_code
=HTTPStatus
.CONFLICT
,
83 def format_on_new(content
, project_id
=None, make_public
=False):
84 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
85 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
88 def check_conflict_on_del(self
, session
, _id
, db_content
):
90 Check that NSR is not instantiated
91 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
92 :param _id: nsr internal id
93 :param db_content: The database content of the nsr
94 :return: None or raises EngineException with the conflict
99 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
100 raise EngineException(
101 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
102 "Launch 'terminate' operation first; or force deletion".format(_id
),
103 http_code
=HTTPStatus
.CONFLICT
,
106 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
108 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
109 Set usageState of pdu, vnfd, nsd
110 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
111 :param _id: server internal id
112 :param db_content: The database content of the descriptor
113 :param not_send_msg: To not send message (False) or store content (list) instead
114 :return: None if ok or raises EngineException with the problem
116 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
117 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
118 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
120 # set all used pdus as free
123 {"_admin.usage.nsr_id": _id
},
124 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
129 used_nsd_id
= nsr
.get("nsd-id")
131 # check if used by another NSR
132 nsrs_list
= self
.db
.get_one(
133 "nsrs", {"nsd-id": used_nsd_id
}, fail_on_empty
=False, fail_on_more
=False
137 "nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"}
140 # Set VNFD usageState
141 used_vnfd_id_list
= nsr
.get("vnfd-id")
142 if used_vnfd_id_list
:
143 for used_vnfd_id
in used_vnfd_id_list
:
144 # check if used by another NSR
145 nsrs_list
= self
.db
.get_one(
147 {"vnfd-id": used_vnfd_id
},
154 {"_id": used_vnfd_id
},
155 {"_admin.usageState": "NOT_IN_USE"},
158 # delete extra ro_nsrs used for internal RO module
159 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
162 def _format_ns_request(ns_request
):
163 formated_request
= copy(ns_request
)
164 formated_request
.pop("additionalParamsForNs", None)
165 formated_request
.pop("additionalParamsForVnf", None)
166 return formated_request
169 def _format_additional_params(
170 ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None
173 Get and format user additional params for NS or VNF.
174 The vdu_id and kdu_name params are mutually exclusive! If none of them are given, then the method will
175 exclusively search for the VNF/NS LCM additional params.
177 :param ns_request: User instantiation additional parameters
178 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
179 :vdu_id: VDU's ID against which we want to format the additional params
180 :kdu_name: KDU's name against which we want to format the additional params
181 :param descriptor: If not None it check that needed parameters of descriptor are supplied
182 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
184 additional_params
= None
186 if not member_vnf_index
:
187 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
188 where_
= "additionalParamsForNs"
189 elif ns_request
.get("additionalParamsForVnf"):
190 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
196 for x
in ns_request
["additionalParamsForVnf"]
197 if x
["member-vnf-index"] == member_vnf_index
202 if not vdu_id
and not kdu_name
:
204 additional_params
= copy(item
.get("additionalParams")) or {}
205 if vdu_id
and item
.get("additionalParamsForVdu"):
209 for x
in item
["additionalParamsForVdu"]
210 if x
["vdu_id"] == vdu_id
214 other_params
= item_vdu
215 if item_vdu
and item_vdu
.get("additionalParams"):
216 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
217 additional_params
= item_vdu
["additionalParams"]
219 additional_params
= {}
220 if item
.get("additionalParamsForKdu"):
224 for x
in item
["additionalParamsForKdu"]
225 if x
["kdu_name"] == kdu_name
229 other_params
= item_kdu
230 if item_kdu
and item_kdu
.get("additionalParams"):
231 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(
234 additional_params
= item_kdu
["additionalParams"]
236 if additional_params
:
237 for k
, v
in additional_params
.items():
238 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
239 if not kdu_name
and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k
):
240 raise EngineException(
241 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
242 "and underscores, and cannot start with a digit".format(
246 # END Check that additional parameter names are valid Jinja2 identifiers
247 if not isinstance(k
, str):
248 raise EngineException(
249 "Invalid param at {}:{}. Only string keys are allowed".format(
254 raise EngineException(
255 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
259 if isinstance(v
, (dict, tuple, list)):
260 additional_params
[k
] = "!!yaml " + safe_dump(v
)
262 additional_params
= json
.dumps(additional_params
)
264 # Select the VDU ID, KDU name or NS/VNF ID, depending on the method's call intent
265 selector
= vdu_id
if vdu_id
else kdu_name
if kdu_name
else descriptor
.get("id")
268 for df
in descriptor
.get("df", []):
269 # check that enough parameters are supplied for the initial-config-primitive
270 # TODO: check for cloud-init
272 initial_primitives
= []
274 "lcm-operations-configuration" in df
275 and "operate-vnf-op-config"
276 in df
["lcm-operations-configuration"]
278 for config
in df
["lcm-operations-configuration"][
279 "operate-vnf-op-config"
281 # Verify the target object (VNF|NS|VDU|KDU) where we need to populate
282 # the params with the additional ones given by the user
283 if config
.get("id") == selector
:
284 for primitive
in get_iterable(
285 config
.get("initial-config-primitive")
287 initial_primitives
.append(primitive
)
289 initial_primitives
= deep_get(
290 descriptor
, ("ns-configuration", "initial-config-primitive")
293 for initial_primitive
in get_iterable(initial_primitives
):
294 for param
in get_iterable(initial_primitive
.get("parameter")):
295 if param
["value"].startswith("<") and param
["value"].endswith(
298 if param
["value"] in (
305 not additional_params
306 or param
["value"][1:-1] not in additional_params
308 raise EngineException(
309 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
310 "initial-config-primitive[name={}] not supplied".format(
313 initial_primitive
["name"],
317 return additional_params
or None, other_params
or None
319 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
321 Creates a new nsr into database. It also creates needed vnfrs
322 :param rollback: list to append the created items at database in case a rollback must be done
323 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
324 :param indata: params to be used for the nsr
325 :param kwargs: used to override the indata descriptor
326 :param headers: http request headers
327 :return: the _id of nsr descriptor created at database. Or an exception of type
328 EngineException, ValidationError, DbException, FsException, MsgException.
329 Note: Exceptions are not captured on purpose. They should be captured at called
332 step
= "checking quotas"
333 self
.check_quota(session
)
335 step
= "validating input parameters"
336 ns_request
= self
._remove
_envelop
(indata
)
337 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
338 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
340 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
341 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
342 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
344 step
= "checking nsdOperationalState"
345 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
347 step
= "filling nsr from input data"
348 nsr_id
= str(uuid4())
349 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(
350 nsd
, ns_request
, nsr_id
, session
355 # TODO: Change for multiple df support
356 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
357 for vnfp
in vnf_profiles
:
358 vnfd_id
= vnfp
.get("vnfd-id")
359 vnf_index
= vnfp
.get("id")
361 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
365 if vnfd_id
not in needed_vnfds
:
366 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
367 if "revision" in vnfd
["_admin"]:
368 vnfd
["revision"] = vnfd
["_admin"]["revision"]
370 needed_vnfds
[vnfd_id
] = vnfd
371 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
373 vnfd
= needed_vnfds
[vnfd_id
]
375 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
378 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(
388 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
391 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
392 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
393 step
= "Updating VNFD usageState"
394 update_descriptor_usage_state(vnfd
, "vnfds", self
.db
)
396 step
= "creating nsr at database"
397 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
398 step
= "Updating NSD usageState"
399 update_descriptor_usage_state(nsd
, "nsds", self
.db
)
401 step
= "creating nsr temporal folder"
402 self
.fs
.mkdir(nsr_id
)
412 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
414 def _get_nsd_from_db(self
, nsd_id
, session
):
415 _filter
= self
._get
_project
_filter
(session
)
416 _filter
["_id"] = nsd_id
417 return self
.db
.get_one("nsds", _filter
)
419 def _get_vnfd_from_db(self
, vnfd_id
, session
):
420 _filter
= self
._get
_project
_filter
(session
)
421 _filter
["id"] = vnfd_id
422 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
425 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
427 nsr_descriptor
, session
["project_id"], make_public
=session
["public"]
429 self
.db
.create("nsrs", nsr_descriptor
)
430 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
432 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
434 vnfr_descriptor
, session
["project_id"], make_public
=session
["public"]
436 self
.db
.create("vnfrs", vnfr_descriptor
)
437 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
439 def _check_nsd_operational_state(self
, nsd
, ns_request
):
440 if nsd
["_admin"]["operationalState"] == "DISABLED":
441 raise EngineException(
442 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
443 "a network service".format(ns_request
["nsdId"]),
444 http_code
=HTTPStatus
.CONFLICT
,
447 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
448 additional_params
, _
= self
._format
_additional
_params
(
449 ns_request
, descriptor
=nsd
451 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
452 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
453 if ns_request
and ns_request
.get("k8s-namespace"):
454 ns_k8s_namespace
= ns_request
["k8s-namespace"]
455 if additional_params
and additional_params
.get("k8s-namespace"):
456 ns_k8s_namespace
= additional_params
["k8s-namespace"]
458 return ns_k8s_namespace
460 def _add_flavor_to_nsr(
461 self
, vdu
, vnfd
, nsr_descriptor
, member_vnf_index
, revision
=None
465 # Find this vdu compute and storage descriptors
466 vdu_virtual_compute
= {}
467 vdu_virtual_storage
= {}
468 for vcd
in vnfd
.get("virtual-compute-desc", ()):
469 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
470 vdu_virtual_compute
= vcd
471 for vsd
in vnfd
.get("virtual-storage-desc", ()):
472 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
473 vdu_virtual_storage
= vsd
474 # Get this vdu vcpus, memory and storage info for flavor_data
475 if vdu_virtual_compute
.get("virtual-cpu", {}).get("num-virtual-cpu"):
476 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"][
479 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
480 flavor_data
["memory-mb"] = (
481 float(vdu_virtual_compute
["virtual-memory"]["size"]) * 1024.0
483 if vdu_virtual_storage
.get("size-of-storage"):
484 flavor_data
["storage-gb"] = vdu_virtual_storage
["size-of-storage"]
485 # Get this vdu EPA info for guest_epa
486 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
487 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"]["cpu-quota"]
488 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
489 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
490 if vcpu_pinning
.get("thread-policy"):
491 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
["thread-policy"]
492 if vcpu_pinning
.get("policy"):
494 "SHARED" if vcpu_pinning
["policy"] == "dynamic" else "DEDICATED"
496 guest_epa
["cpu-pinning-policy"] = cpu_policy
497 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
498 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"]["mem-quota"]
499 if vdu_virtual_compute
.get("virtual-memory", {}).get("mempage-size"):
500 guest_epa
["mempage-size"] = vdu_virtual_compute
["virtual-memory"][
503 if vdu_virtual_compute
.get("virtual-memory", {}).get("numa-node-policy"):
504 guest_epa
["numa-node-policy"] = vdu_virtual_compute
["virtual-memory"][
507 if vdu_virtual_storage
.get("disk-io-quota"):
508 guest_epa
["disk-io-quota"] = vdu_virtual_storage
["disk-io-quota"]
511 flavor_data
["guest-epa"] = guest_epa
513 revision
= revision
if revision
is not None else 1
514 flavor_data
["name"] = (
515 vdu
["id"][:56] + "-" + member_vnf_index
+ "-" + str(revision
) + "-flv"
517 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
518 nsr_descriptor
["flavor"].append(flavor_data
)
520 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
522 additional_params
, _
= self
._format
_additional
_params
(
523 ns_request
, descriptor
=nsd
527 "name": ns_request
["nsName"],
528 "name-ref": ns_request
["nsName"],
529 "short-name": ns_request
["nsName"],
530 "admin-status": "ENABLED",
531 "nsState": "NOT_INSTANTIATED",
532 "currentOperation": "IDLE",
533 "currentOperationID": None,
534 "errorDescription": None,
536 "deploymentStatus": None,
537 "configurationStatus": None,
539 "nsd": {k
: v
for k
, v
in nsd
.items()},
540 "vimdatacenter": ns_request
.get("vimAccountId"),
541 "paasdatacenter": ns_request
.get("paasAccountId"),
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": [],
565 if "revision" in nsd
["_admin"]:
566 nsr_descriptor
["revision"] = nsd
["_admin"]["revision"]
568 ns_request
["nsr_id"] = nsr_id
569 if ns_request
and ns_request
.get("config-units"):
570 nsr_descriptor
["config-units"] = ns_request
["config-units"]
572 if nsd
.get("virtual-link-desc"):
573 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
574 # Fill each vld with vnfd-connection-point-ref data
575 # TODO: Change for multiple df support
576 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
577 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
578 for vnf_profile
in vnf_profiles
:
579 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
580 for cpd
in vlc
.get("constituent-cpd-id", ()):
581 all_vld_connection_point_data
[
582 vlc
.get("virtual-link-profile-id")
585 "member-vnf-index-ref": cpd
.get(
586 "constituent-base-element-id"
588 "vnfd-connection-point-ref": cpd
.get(
591 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
595 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
598 for vdu
in vnfd
.get("vdu", ()):
599 member_vnf_index
= vnf_profile
.get("id")
600 self
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr_descriptor
, member_vnf_index
)
601 sw_image_id
= vdu
.get("sw-image-desc")
603 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
604 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
606 # also add alternative images to the list of images
607 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
608 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
609 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
611 # Add Affinity or Anti-affinity group information to NSR
612 vdu_profiles
= vnfd
.get("df", [[]])[0].get("vdu-profile", ())
613 affinity_group_prefix_name
= "{}-{}".format(
614 nsr_descriptor
["name"][:16], vnf_profile
.get("id")[:16]
617 for vdu_profile
in vdu_profiles
:
618 affinity_group_data
= {}
619 for affinity_group
in vdu_profile
.get(
620 "affinity-or-anti-affinity-group", ()
622 affinity_group_data
= (
623 self
._get
_affinity
_or
_anti
_affinity
_group
_data
_from
_vnfd
(
624 vnfd
, affinity_group
["id"]
627 affinity_group_data
["member-vnf-index"] = vnf_profile
.get("id")
628 self
._add
_affinity
_or
_anti
_affinity
_group
_to
_nsr
(
631 affinity_group_prefix_name
,
635 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
638 vld
["name"] = vld
["id"]
639 nsr_descriptor
["vld"] = nsr_vld
641 return nsr_descriptor
643 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
644 self
, vnfd
, affinity_group_id
647 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
649 affinity_group
= utils
.find_in_list(
650 vnfd
.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
651 lambda ag
: ag
["id"] == affinity_group_id
,
653 affinity_group_data
= {}
655 if affinity_group
.get("id"):
656 affinity_group_data
["ag-id"] = affinity_group
["id"]
657 if affinity_group
.get("type"):
658 affinity_group_data
["type"] = affinity_group
["type"]
659 if affinity_group
.get("scope"):
660 affinity_group_data
["scope"] = affinity_group
["scope"]
661 return affinity_group_data
663 def _add_affinity_or_anti_affinity_group_to_nsr(
664 self
, nsr_descriptor
, affinity_group_data
, affinity_group_prefix_name
667 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
669 affinity_group
= next(
672 for f
in nsr_descriptor
["affinity-or-anti-affinity-group"]
673 if all(f
.get(k
) == affinity_group_data
[k
] for k
in affinity_group_data
)
677 if not affinity_group
:
678 affinity_group_data
["id"] = str(
679 len(nsr_descriptor
["affinity-or-anti-affinity-group"])
681 affinity_group_data
["name"] = "{}-{}".format(
682 affinity_group_prefix_name
, affinity_group_data
["ag-id"][:32]
684 nsr_descriptor
["affinity-or-anti-affinity-group"].append(
688 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
689 sw_image_desc
= utils
.find_in_list(
690 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
693 if sw_image_desc
.get("image"):
694 image_data
["image"] = sw_image_desc
["image"]
695 if sw_image_desc
.get("checksum"):
696 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
697 if sw_image_desc
.get("vim-type"):
698 image_data
["vim-type"] = sw_image_desc
["vim-type"]
701 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
703 Adds image to nsr checking first it is not already added
708 for f
in nsr_descriptor
["image"]
709 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
714 image_data
["id"] = str(len(nsr_descriptor
["image"]))
715 nsr_descriptor
["image"].append(image_data
)
717 def _create_vnfr_descriptor_from_vnfd(
728 vnfr_id
= str(uuid4())
729 nsr_id
= nsr_descriptor
["id"]
731 additional_params
, vnf_params
= self
._format
_additional
_params
(
732 ns_request
, vnf_index
, descriptor
=vnfd
738 "nsr-id-ref": nsr_id
,
739 "member-vnf-index-ref": vnf_index
,
740 "additionalParamsForVnf": additional_params
,
742 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
744 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
745 "vim-account-id": None,
746 "paas-account-id": None,
749 "connection-point": [],
750 "ip-address": None, # mgmt-interface filled by LCM
753 # Revision backwards compatility. Only specify the revision in the record if
754 # the original VNFD has a revision.
755 if "revision" in vnfd
:
756 vnfr_descriptor
["revision"] = vnfd
["revision"]
758 vnf_k8s_namespace
= ns_k8s_namespace
760 if vnf_params
.get("k8s-namespace"):
761 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
762 if vnf_params
.get("config-units"):
763 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
766 if vnfd
.get("int-virtual-link-desc"):
767 vnfr_descriptor
["vld"] = []
768 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
769 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
771 for cp
in vnfd
.get("ext-cpd", ()):
773 "name": cp
.get("id"),
774 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
775 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
777 # "ip-address", "mac-address" # filled by LCM
778 # vim-id # TODO it would be nice having a vim port id
780 vnfr_descriptor
["connection-point"].append(vnf_cp
)
782 # Create k8s-cluster information
783 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
784 if vnfd
.get("k8s-cluster"):
785 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
786 all_k8s_cluster_nets_cpds
= {}
787 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
788 if cpd
.get("k8s-cluster-net"):
789 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
792 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
793 if net
.get("id") in all_k8s_cluster_nets_cpds
:
794 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
799 for kdu
in get_iterable(vnfd
.get("kdu")):
800 additional_params
, kdu_params
= self
._format
_additional
_params
(
801 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
803 kdu_k8s_namespace
= vnf_k8s_namespace
804 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
805 if kdu_params
and kdu_params
.get("k8s-namespace"):
806 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
808 kdu_deployment_name
= ""
809 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
810 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
813 "additionalParams": additional_params
,
814 "k8s-namespace": kdu_k8s_namespace
,
815 "kdu-deployment-name": kdu_deployment_name
,
816 "kdu-name": kdu
["name"],
817 # TODO "name": "" Name of the VDU in the VIM
818 "ip-address": None, # mgmt-interface filled by LCM
821 if kdu_params
and kdu_params
.get("config-units"):
822 kdur
["config-units"] = kdu_params
["config-units"]
823 if kdu
.get("helm-version"):
824 kdur
["helm-version"] = kdu
["helm-version"]
825 for k8s_type
in ("helm-chart", "juju-bundle"):
826 if kdu
.get(k8s_type
):
827 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
828 if not vnfr_descriptor
.get("kdur"):
829 vnfr_descriptor
["kdur"] = []
830 vnfr_descriptor
["kdur"].append(kdur
)
832 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
834 for vdu
in vnfd
.get("vdu", ()):
837 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
838 "operate-vnf-op-config"
840 vdu_config
= utils
.find_in_list(
841 configs
, lambda config
: config
["id"] == vdu
["id"]
847 vdu_instantiation_level
= utils
.find_in_list(
848 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
849 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
852 vdu_instantiation_level
= None
855 external_connection_ee
= utils
.filter_in_list(
856 vdu_config
.get("execution-environment-list", []),
857 lambda ee
: "external-connection-point-ref" in ee
,
859 for ee
in external_connection_ee
:
860 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
862 additional_params
, vdu_params
= self
._format
_additional
_params
(
863 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
867 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
868 vnfd
.get("virtual-storage-desc", []),
869 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"],
872 vdu_virtual_storage_descriptors
= []
874 "vdu-id-ref": vdu
["id"],
875 # TODO "name": "" Name of the VDU in the VIM
876 "ip-address": None, # mgmt-interface filled by LCM
877 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
878 "internal-connection-point": [],
880 "additionalParams": additional_params
,
881 "vdu-name": vdu
["name"],
882 "virtual-storages": vdu_virtual_storage_descriptors
,
884 if vdu_params
and vdu_params
.get("config-units"):
885 vdur
["config-units"] = vdu_params
["config-units"]
886 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
887 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
890 if vdu
.get("pdu-type"):
891 vdur
["pdu-type"] = vdu
["pdu-type"]
892 vdur
["name"] = vdu
["pdu-type"]
893 # TODO volumes: name, volume-id
894 for icp
in vdu
.get("int-cpd", ()):
897 "connection-point-id": icp
["id"],
898 "name": icp
.get("id"),
901 vdur
["internal-connection-point"].append(vdu_icp
)
903 for iface
in icp
.get("virtual-network-interface-requirement", ()):
904 # Name, mac-address and interface position is taken from VNFD
905 # and included into VNFR. By this way RO can process this information
906 # while creating the VDU.
907 iface_fields
= ("name", "mac-address", "position")
909 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
912 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
913 if "port-security-enabled" in icp
:
914 vdu_iface
["port-security-enabled"] = icp
[
915 "port-security-enabled"
918 if "port-security-disable-strategy" in icp
:
919 vdu_iface
["port-security-disable-strategy"] = icp
[
920 "port-security-disable-strategy"
923 for ext_cp
in vnfd
.get("ext-cpd", ()):
924 if not ext_cp
.get("int-cpd"):
926 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
928 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
929 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
933 if "port-security-enabled" in ext_cp
:
934 vdu_iface
["port-security-enabled"] = ext_cp
[
935 "port-security-enabled"
938 if "port-security-disable-strategy" in ext_cp
:
939 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
940 "port-security-disable-strategy"
947 and vdu_iface
.get("external-connection-point-ref")
950 vdu_iface
["mgmt-vnf"] = True
951 vdu_iface
["mgmt-interface"] = True
953 for ecp
in vdu_mgmt_cp
:
954 if vdu_iface
.get("external-connection-point-ref") == ecp
:
955 vdu_iface
["mgmt-interface"] = True
957 if iface
.get("virtual-interface"):
958 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
960 # look for network where this interface is connected
961 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
963 # TODO: Change for multiple df support
964 for df
in get_iterable(nsd
.get("df")):
965 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
966 for vlc_index
, vlc
in enumerate(
968 vnf_profile
.get("virtual-link-connectivity")
971 for cpd
in get_iterable(
972 vlc
.get("constituent-cpd-id")
975 cpd
.get("constituent-cpd-id")
978 vdu_iface
["ns-vld-id"] = vlc
.get(
979 "virtual-link-profile-id"
981 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
982 if vdu_iface
.get("type") in (
986 nsr_descriptor
["vld"][vlc_index
][
990 elif vdu_iface
.get("internal-connection-point-ref"):
991 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
992 # TODO: store fixed IP address in the record (if it exists in the ICP)
993 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
994 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
995 ivld_index
= utils
.find_index_in_list(
996 vnfd
.get("int-virtual-link-desc", ()),
997 lambda ivld
: ivld
["id"]
998 == icp
.get("int-virtual-link-desc"),
1000 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
1002 vdur
["interfaces"].append(vdu_iface
)
1004 if vdu
.get("sw-image-desc"):
1005 sw_image
= utils
.find_in_list(
1006 vnfd
.get("sw-image-desc", ()),
1007 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
1009 nsr_sw_image_data
= utils
.find_in_list(
1010 nsr_descriptor
["image"],
1011 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
1013 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
1015 if vdu
.get("alternative-sw-image-desc"):
1017 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
1018 sw_image
= utils
.find_in_list(
1019 vnfd
.get("sw-image-desc", ()),
1020 lambda image
: image
["id"] == alt_image_id
,
1022 nsr_sw_image_data
= utils
.find_in_list(
1023 nsr_descriptor
["image"],
1025 nsr_image
.get("image") == sw_image
.get("image")
1028 alt_image_ids
.append(nsr_sw_image_data
["id"])
1029 vdur
["alt-image-ids"] = alt_image_ids
1031 revision
= revision
if revision
is not None else 1
1032 flavor_data_name
= (
1033 vdu
["id"][:56] + "-" + vnf_index
+ "-" + str(revision
) + "-flv"
1035 nsr_flavor_desc
= utils
.find_in_list(
1036 nsr_descriptor
["flavor"],
1037 lambda flavor
: flavor
["name"] == flavor_data_name
,
1041 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
1043 # Adding Affinity groups information to vdur
1045 vdu_profile_affinity_group
= utils
.find_in_list(
1046 vnfd
.get("df")[0]["vdu-profile"],
1047 lambda a_vdu
: a_vdu
["id"] == vdu
["id"],
1050 vdu_profile_affinity_group
= None
1052 if vdu_profile_affinity_group
:
1053 affinity_group_ids
= []
1054 for affinity_group
in vdu_profile_affinity_group
.get(
1055 "affinity-or-anti-affinity-group", ()
1057 vdu_affinity_group
= utils
.find_in_list(
1058 vdu_profile_affinity_group
.get(
1059 "affinity-or-anti-affinity-group", ()
1061 lambda ag_fp
: ag_fp
["id"] == affinity_group
["id"],
1063 nsr_affinity_group
= utils
.find_in_list(
1064 nsr_descriptor
["affinity-or-anti-affinity-group"],
1066 nsr_ag
.get("ag-id") == vdu_affinity_group
.get("id")
1067 and nsr_ag
.get("member-vnf-index")
1068 == vnfr_descriptor
.get("member-vnf-index-ref")
1071 # Update Affinity Group VIM name if VDU instantiation parameter is present
1072 if vnf_params
and vnf_params
.get("affinity-or-anti-affinity-group"):
1073 vnf_params_affinity_group
= utils
.find_in_list(
1074 vnf_params
["affinity-or-anti-affinity-group"],
1076 vnfp_ag
.get("id") == vdu_affinity_group
.get("id")
1079 if vnf_params_affinity_group
.get("vim-affinity-group-id"):
1081 "vim-affinity-group-id"
1082 ] = vnf_params_affinity_group
["vim-affinity-group-id"]
1083 affinity_group_ids
.append(nsr_affinity_group
["id"])
1084 vdur
["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1086 if vdu_instantiation_level
:
1087 count
= vdu_instantiation_level
.get("number-of-instances")
1091 for index
in range(0, count
):
1092 vdur
= deepcopy(vdur
)
1093 for iface
in vdur
["interfaces"]:
1094 if iface
.get("ip-address") and index
!= 0:
1095 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
1096 if iface
.get("mac-address") and index
!= 0:
1097 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
1099 vdur
["_id"] = str(uuid4())
1100 vdur
["id"] = vdur
["_id"]
1101 vdur
["count-index"] = index
1102 vnfr_descriptor
["vdur"].append(vdur
)
1104 return vnfr_descriptor
1106 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
1108 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1109 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1110 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1111 :param ns_instance_content: ns instance content
1112 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1115 time_now
, time_delta
= (
1117 time() - ns_instance_content
["_admin"]["modified"],
1120 isinstance(filter_q
, dict) and filter_q
.get("vcaStatusRefresh") == "true"
1122 threshold_reached
= time_delta
> 120
1123 if force_refresh
or threshold_reached
:
1124 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
1125 ns_instance_content
["_admin"]["modified"] = time_now
1126 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
1127 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
1129 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
1131 nslcmop_desc
["_admin"].pop("nsState")
1132 self
.msg
.write("ns", operation
, nslcmop_desc
)
1135 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1137 Get complete information on an ns instance.
1138 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1139 :param _id: string, ns instance id
1140 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1141 :param api_req: True if this call is serving an external API request. False if serving internal request.
1142 :return: dictionary, raise exception if not found.
1144 ns_instance_content
= super().show(session
, _id
, api_req
)
1145 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1146 return ns_instance_content
1148 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1149 raise EngineException(
1150 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1154 class VnfrTopic(BaseTopic
):
1158 def __init__(self
, db
, fs
, msg
, auth
):
1159 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1161 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1162 raise EngineException(
1163 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1166 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1167 raise EngineException(
1168 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1171 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1172 # Not used because vnfrs are created and deleted by NsrTopic class directly
1173 raise EngineException(
1174 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1178 class NsLcmOpTopic(BaseTopic
):
1181 operation_schema
= { # mapping between operation and jsonschema to validate
1182 "instantiate": ns_instantiate
,
1183 "action": ns_action
,
1184 "update": ns_update
,
1187 "terminate": ns_terminate
,
1188 "migrate": ns_migrate
,
1189 "verticalscale": ns_verticalscale
,
1192 def __init__(self
, db
, fs
, msg
, auth
):
1193 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1194 self
.nsrtopic
= NsrTopic(db
, fs
, msg
, auth
)
1196 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1198 Check that user has enter right parameters for the operation
1199 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1200 :param operation: it can be: instantiate, terminate, action, update, heal
1201 :param indata: descriptor with the parameters of the operation
1204 if operation
== "action":
1205 self
._check
_action
_ns
_operation
(indata
, nsr
)
1206 elif operation
== "scale":
1207 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1208 elif operation
== "update":
1209 self
._check
_update
_ns
_operation
(indata
, nsr
)
1210 elif operation
== "heal":
1211 self
._check
_heal
_ns
_operation
(indata
, nsr
)
1212 elif operation
== "instantiate":
1213 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1215 def _check_action_ns_operation(self
, indata
, nsr
):
1217 # check vnf_member_index
1218 if indata
.get("vnf_member_index"):
1219 indata
["member_vnf_index"] = indata
.pop(
1221 ) # for backward compatibility
1222 if indata
.get("member_vnf_index"):
1223 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1224 indata
["member_vnf_index"], nsr
["_id"]
1227 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1228 "operate-vnf-op-config"
1233 if indata
.get("vdu_id"):
1234 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1235 descriptor_configuration
= utils
.find_in_list(
1236 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1238 elif indata
.get("kdu_name"):
1239 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1240 descriptor_configuration
= utils
.find_in_list(
1241 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1244 descriptor_configuration
= utils
.find_in_list(
1245 configs
, lambda config
: config
["id"] == vnfd
["id"]
1247 if descriptor_configuration
is not None:
1248 descriptor_configuration
= descriptor_configuration
.get(
1252 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1256 # For k8s allows default primitives without validating the parameters
1257 if indata
.get("kdu_name") and indata
["primitive"] in (
1264 # TODO should be checked that rollback only can contains revsision_numbe????
1265 if not indata
.get("member_vnf_index"):
1266 raise EngineException(
1267 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1272 # if not, check primitive
1273 for config_primitive
in get_iterable(descriptor_configuration
):
1274 if indata
["primitive"] == config_primitive
["name"]:
1275 # check needed primitive_params are provided
1276 if indata
.get("primitive_params"):
1277 in_primitive_params_copy
= copy(indata
["primitive_params"])
1279 in_primitive_params_copy
= {}
1280 for paramd
in get_iterable(config_primitive
.get("parameter")):
1281 if paramd
["name"] in in_primitive_params_copy
:
1282 del in_primitive_params_copy
[paramd
["name"]]
1283 elif not paramd
.get("default-value"):
1284 raise EngineException(
1285 "Needed parameter {} not provided for primitive '{}'".format(
1286 paramd
["name"], indata
["primitive"]
1289 # check no extra primitive params are provided
1290 if in_primitive_params_copy
:
1291 raise EngineException(
1292 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1293 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1298 raise EngineException(
1299 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1304 def _check_update_ns_operation(self
, indata
, nsr
) -> None:
1305 """Validates the ns-update request according to updateType
1307 If updateType is CHANGE_VNFPKG:
1308 - it checks the vnfInstanceId, whether it's available under ns instance
1309 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1310 Otherwise exception will be raised.
1311 If updateType is REMOVE_VNF:
1312 - it checks if the vnfInstanceId is available in the ns instance
1313 - Otherwise exception will be raised.
1316 indata: includes updateType such as CHANGE_VNFPKG,
1317 nsr: network service record
1321 a meaningful error if given update parameters are not proper such as
1322 "Error in validating ns-update request: <ID> does not match
1323 with the vnfd-id of vnfinstance
1324 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1328 if indata
["updateType"] == "CHANGE_VNFPKG":
1329 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1330 vnf_instance_id
= indata
["changeVnfPackageData"]["vnfInstanceId"]
1331 ns_instance_id
= indata
["nsInstanceId"]
1332 vnfd_id_2update
= indata
["changeVnfPackageData"]["vnfdId"]
1334 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1336 raise EngineException(
1337 f
"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1338 f
"belong to NS {ns_instance_id}",
1339 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1342 # Getting vnfrs through the ns_instance_id
1343 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": ns_instance_id
})
1344 constituent_vnfd_id
= next(
1348 if vnfr
["id"] == vnf_instance_id
1353 # Check the given vnfd-id belongs to given vnf instance
1354 if constituent_vnfd_id
and (vnfd_id_2update
!= constituent_vnfd_id
):
1356 raise EngineException(
1357 f
"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1358 f
"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1359 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1362 # Validating the ns update timeout
1364 indata
.get("timeout_ns_update")
1365 and indata
["timeout_ns_update"] < 300
1367 raise EngineException(
1368 "Error in validating ns-update request: {} second is not enough "
1369 "to upgrade the VNF instance: {}".format(
1370 indata
["timeout_ns_update"], vnf_instance_id
1372 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1374 elif indata
["updateType"] == "REMOVE_VNF":
1375 vnf_instance_id
= indata
["removeVnfInstanceId"]
1376 ns_instance_id
= indata
["nsInstanceId"]
1377 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1378 raise EngineException(
1379 "Invalid VNF Instance Id. '{}' is not "
1380 "present in the NS '{}'".format(vnf_instance_id
, ns_instance_id
)
1391 "Ns update request could not be processed with error: {}.".format(e
)
1394 def _check_scale_ns_operation(self
, indata
, nsr
):
1395 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1396 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1398 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1400 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1401 == scaling_aspect
["id"]
1405 raise EngineException(
1406 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1407 "present at vnfd:scaling-aspect".format(
1408 indata
["scaleVnfData"]["scaleByStepData"][
1409 "scaling-group-descriptor"
1414 def _check_heal_ns_operation(self
, indata
, nsr
):
1417 def _validate_vnf_in_indata(
1420 vim_accounts
: dict = None,
1421 paas_accounts
: dict = None,
1423 session
: dict = None,
1425 """Validate the VNF parameters in indata.
1428 indata (dict): Input data dictionary
1429 vim_accounts (dict): VIM accounts dictionary
1430 paas_accounts (dict) PaaS accounts dictionary
1431 nsr (dict): Network service record dictionary
1432 session (dict): Dictionary contains "username", "admin", "force", "public",
1433 "project_id", "set_project"
1435 # Map between vnf_member_index to vnf descriptor.
1436 vnf_member_index_to_vnfd
= {}
1438 for in_vnf
in get_iterable(indata
.get("vnf")):
1439 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
]
1445 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1446 member_vnf_index
, nsr
["_id"]
1448 vnf_member_index_to_vnfd
[
1450 ] = vnfd
# add to cache, avoiding a later look for
1452 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1454 if in_vnf
.get("vimAccountId"):
1455 self
._check
_valid
_vim
_account
(
1456 in_vnf
["vimAccountId"], vim_accounts
, session
1459 elif in_vnf
.get("paasAccountId"):
1460 self
._check
_valid
_paas
_account
(
1461 in_vnf
["paasAccountId"], paas_accounts
, session
1464 def _validate_vld_in_indata(
1467 session
: dict = None,
1469 wim_accounts
: dict = None,
1471 """Validate the Virtual Link Descriptor parameters in indata.
1474 indata (dict): Input data dictionary
1475 session (dict): Dictionary contains "username", "admin", "force", "public",
1476 "project_id", "set_project"
1477 nsd (dict): Network service descriptor dictionary
1478 wim_accounts (dict): WIM accounts dictionary
1483 for in_vld
in get_iterable(indata
.get("vld")):
1484 self
._check
_valid
_wim
_account
(
1485 in_vld
.get("wimAccountId"), wim_accounts
, session
1487 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1488 if in_vld
["name"] == vldd
["id"]:
1491 raise EngineException(
1492 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1497 def _check_instantiate_ns_operation(
1498 self
, indata
: dict, nsr
: dict, session
: dict
1500 """Validate the parameters for NS instantiate operation
1503 indata (dict): Input data dictionary
1504 nsr (dict): Network service record dictionary
1505 session (dict): Dictionary contains "username", "admin", "force", "public", "project_id", "set_project"
1507 vim_accounts
, wim_accounts
, paas_accounts
= [], [], []
1509 self
._check
_valid
_vim
_account
(indata
.get("vimAccountId"), vim_accounts
, session
)
1510 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1511 self
._check
_valid
_paas
_account
(indata
.get("paasAccountId"), paas_accounts
, session
)
1513 self
._validate
_vnf
_in
_indata
(
1515 vim_accounts
=vim_accounts
,
1516 paas_accounts
=paas_accounts
,
1520 self
._validate
_vld
_in
_indata
(
1521 indata
, session
=session
, nsd
=nsd
, wim_accounts
=wim_accounts
1524 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1525 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1526 vnfr
= self
.db
.get_one(
1528 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1529 fail_on_empty
=False,
1532 raise EngineException(
1533 "Invalid parameter member_vnf_index='{}' is not one of the "
1534 "nsd:constituent-vnfd".format(member_vnf_index
)
1537 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1538 if "revision" in vnfr
:
1539 vnfd_revision
= vnfr
["vnfd-id"] + ":" + str(vnfr
["revision"])
1540 vnfd
= self
.db
.get_one(
1541 "vnfds_revisions", {"_id": vnfd_revision
}, fail_on_empty
=False
1544 vnfd
= self
.db
.get_one(
1545 "vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False
1549 raise EngineException(
1550 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1556 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1557 for vdud
in get_iterable(vnfd
.get("vdu")):
1558 if vdud
["id"] == vdu_id
:
1561 raise EngineException(
1562 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1567 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1568 for kdud
in get_iterable(vnfd
.get("kdu")):
1569 if kdud
["name"] == kdu_name
:
1572 raise EngineException(
1573 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1578 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1579 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1580 for vdu
in get_iterable(vnfd
.get("vdu")):
1581 if in_vdu
["id"] == vdu
["id"]:
1582 for volume
in get_iterable(in_vdu
.get("volume")):
1583 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1584 if volumed
== volume
["name"]:
1587 raise EngineException(
1588 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1589 "volume:name='{}' is not present at "
1590 "vnfd:vdu:virtual-storage-desc list".format(
1591 in_vnf
["member-vnf-index"],
1597 vdu_if_names
= set()
1598 for cpd
in get_iterable(vdu
.get("int-cpd")):
1599 for iface
in get_iterable(
1600 cpd
.get("virtual-network-interface-requirement")
1602 vdu_if_names
.add(iface
.get("name"))
1604 for in_iface
in get_iterable(in_vdu
.get("interface")):
1605 if in_iface
["name"] in vdu_if_names
:
1608 raise EngineException(
1609 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1610 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1611 in_vnf
["member-vnf-index"],
1619 raise EngineException(
1620 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1621 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1625 ivld
.get("id"): set()
1626 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1628 for vdu
in get_iterable(vnfd
.get("vdu")):
1629 for cpd
in get_iterable(vnfd
.get("int-cpd")):
1630 if cpd
.get("int-virtual-link-desc"):
1631 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1633 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1634 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1635 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1636 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1639 raise EngineException(
1640 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1641 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1642 "vnfd:internal-vld:name/id:internal-connection-point".format(
1643 in_vnf
["member-vnf-index"],
1649 raise EngineException(
1650 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1651 " is not present at vnfd '{}'".format(
1652 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1656 def _check_valid_vim_account(
1657 self
, vim_account
: str, vim_accounts
: list, session
: dict
1659 """Validate the given VIM account whether present in the project or not,
1660 add the given vim_account to vim_accounts list.
1663 vim_account (str): VIM Account to be used
1664 vim_accounts (list): List of VIM accounts
1665 session (dict): Contains "username", "admin", "force", "public", "project_id", "set_project"
1671 if vim_account
and vim_account
not in vim_accounts
:
1672 db_filter
= self
._get
_project
_filter
(session
)
1673 db_filter
["_id"] = vim_account
1674 self
.db
.get_one("vim_accounts", db_filter
)
1675 vim_accounts
.append(vim_account
)
1677 raise EngineException(
1678 "Invalid vimAccountId='{}' not present for the project".format(
1683 def _check_valid_paas_account(
1684 self
, paas_account
: str, paas_accounts
: list, session
: dict
1686 """Validate the given PaaS account whether present in the project or not,
1687 add the given paas_account to paas_accounts list and return.
1690 paas_account (str): PaaS Account to be used
1691 paas_accounts (list): List of PaaS accounts
1692 session (dict): Contains "username", "admin", "force", "public", "project_id", "set_project"
1698 if paas_account
and paas_account
not in paas_accounts
:
1699 db_filter
= self
._get
_project
_filter
(session
)
1700 db_filter
["_id"] = paas_account
1701 self
.db
.get_one("paas", db_filter
)
1702 paas_accounts
.append(paas_account
)
1704 raise EngineException(
1705 "Invalid paasAccountId='{}' not present for the project".format(
1710 def _get_vim_account(self
, vim_id
: str, session
):
1712 db_filter
= self
._get
_project
_filter
(session
)
1713 db_filter
["_id"] = vim_id
1714 return self
.db
.get_one("vim_accounts", db_filter
)
1716 raise EngineException(
1717 "Invalid vimAccountId='{}' not present for the project".format(vim_id
)
1720 def _check_valid_wim_account(
1721 self
, wim_account
: str, wim_accounts
: list, session
: dict
1723 """Validate the given WIM account whether present in the project or not,
1724 add the given wim_account to wim_accounts list and return.
1727 wim_account (str): WIM Account to be used
1728 wim_accounts (list): List of WIM accounts
1729 session (dict): Contains "username", "admin", "force", "public", "project_id", "set_project"
1735 if isinstance(wim_account
, str) and wim_account
not in wim_accounts
:
1736 db_filter
= self
._get
_project
_filter
(session
)
1737 db_filter
["_id"] = wim_account
1738 self
.db
.get_one("wim_accounts", db_filter
)
1739 wim_accounts
.append(wim_account
)
1741 raise EngineException(
1742 "Invalid wimAccountId='{}' not present for the project".format(
1748 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1751 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1752 (ip_address, ...) information.
1753 Modifies PDU _admin.usageState to 'IN_USE'
1754 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1755 :param rollback: list with the database modifications to rollback if needed
1756 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1757 :param vim_account: vim_account where this vnfr should be deployed
1758 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1759 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1760 of the changed vnfr is needed
1762 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1763 "vim-network-name": used at VIM
1764 "name": interface name
1765 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1766 "ns-vld-id": NSD vld where this interface is connected.
1767 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1769 ifaces_forcing_vim_network
= []
1771 return ifaces_forcing_vim_network
1772 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1773 if not vdur
.get("pdu-type"):
1775 pdu_type
= vdur
.get("pdu-type")
1776 pdu_filter
= self
._get
_project
_filter
(session
)
1777 pdu_filter
["vim_accounts"] = vim_account
1778 pdu_filter
["type"] = pdu_type
1779 pdu_filter
["_admin.operationalState"] = "ENABLED"
1780 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1781 # TODO feature 1417: "shared": True,
1783 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1784 for pdu
in available_pdus
:
1785 # step 1 check if this pdu contains needed interfaces:
1786 match_interfaces
= True
1787 for vdur_interface
in vdur
["interfaces"]:
1788 for pdu_interface
in pdu
["interfaces"]:
1789 if pdu_interface
["name"] == vdur_interface
["name"]:
1790 # TODO feature 1417: match per mgmt type
1792 else: # no interface found for name
1793 match_interfaces
= False
1795 if match_interfaces
:
1798 raise EngineException(
1799 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1803 vnfr
["member-vnf-index-ref"],
1808 # step 2. Update pdu
1810 "_admin.usageState": pdu
["_admin"]["usageState"],
1811 "_admin.usage.vnfr_id": None,
1812 "_admin.usage.nsr_id": None,
1813 "_admin.usage.vdur": None,
1817 {"_id": pdu
["_id"]},
1819 "_admin.usageState": "IN_USE",
1821 "vnfr_id": vnfr
["_id"],
1822 "nsr_id": vnfr
["nsr-id-ref"],
1823 "vdur": vdur
["vdu-id-ref"],
1832 "content": rollback_pdu
,
1836 # step 3. Fill vnfr info by filling vdur
1837 vdu_text
= "vdur.{}".format(vdur_index
)
1838 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1839 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1840 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1841 for pdu_interface
in pdu
["interfaces"]:
1842 if pdu_interface
["name"] == vdur_interface
["name"]:
1843 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1844 for k
, v
in pdu_interface
.items():
1848 ): # TODO: switch-xxxxx must be inserted
1849 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1850 vnfr_update_rollback
[
1851 iface_text
+ ".{}".format(k
)
1852 ] = vdur_interface
.get(v
)
1853 if pdu_interface
.get("ip-address"):
1854 if vdur_interface
.get(
1856 ) or vdur_interface
.get("mgmt-vnf"):
1857 vnfr_update_rollback
[
1858 vdu_text
+ ".ip-address"
1859 ] = vdur
.get("ip-address")
1860 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1863 if vdur_interface
.get("mgmt-vnf"):
1864 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1867 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1868 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1871 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1874 ifaces_forcing_vim_network
.append(
1876 "name": vdur_interface
.get("vnf-vld-id")
1877 or vdur_interface
.get("ns-vld-id"),
1878 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1879 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1882 if pdu_interface
.get("vim-network-id"):
1883 ifaces_forcing_vim_network
[-1][
1885 ] = pdu_interface
["vim-network-id"]
1886 if pdu_interface
.get("vim-network-name"):
1887 ifaces_forcing_vim_network
[-1][
1889 ] = pdu_interface
["vim-network-name"]
1892 return ifaces_forcing_vim_network
1894 def _look_for_k8scluster(
1895 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1898 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1899 Fills vnfr.kdur with the selected k8scluster
1901 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1902 :param rollback: list with the database modifications to rollback if needed
1903 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1904 :param vim_account: vim_account where this vnfr should be deployed
1905 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1906 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1907 of the changed vnfr is needed
1909 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1910 "vim-network-name": used at VIM
1911 "name": interface name
1912 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1913 "ns-vld-id": NSD vld where this interface is connected.
1914 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1916 ifaces_forcing_vim_network
= []
1919 return ifaces_forcing_vim_network
1921 if not vnfr
.get("kdur"):
1922 return ifaces_forcing_vim_network
1924 kdu_filter
= self
._get
_project
_filter
(session
)
1925 kdu_filter
["vim_account"] = vim_account
1926 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1927 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1929 k8s_requirements
= {} # just for logging
1930 for k8scluster
in available_k8sclusters
:
1931 if not vnfr
.get("k8s-cluster"):
1934 if vnfr
["k8s-cluster"].get("cni"):
1935 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1936 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1937 k8scluster
.get("cni", ())
1940 # restrict by version
1941 if vnfr
["k8s-cluster"].get("version"):
1942 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1943 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1945 # restrict by number of networks
1946 if vnfr
["k8s-cluster"].get("nets"):
1947 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1948 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1949 vnfr
["k8s-cluster"]["nets"]
1954 raise EngineException(
1955 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1956 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1960 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1961 # step 3. Fill vnfr info by filling kdur
1962 kdu_text
= "kdur.{}.".format(kdur_index
)
1963 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1964 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1966 # step 4. Check VIM networks that forces the selected k8s_cluster
1967 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1968 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1969 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1970 # get a network from k8s_cluster nets. If name matches use this, if not use other
1971 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1972 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1973 k8scluster_net_list
.remove(kdur_net
["id"])
1975 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1976 k8scluster_net_list
.pop(0)
1977 vnfr_update_rollback
[
1978 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1980 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1982 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1984 ifaces_forcing_vim_network
.append(
1986 "name": kdur_net
.get("vnf-vld-id")
1987 or kdur_net
.get("ns-vld-id"),
1988 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1989 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1990 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1993 # TODO check that this forcing is not incompatible with other forcing
1994 return ifaces_forcing_vim_network
1996 def _update_vnfrs_from_nsd(self
, nsr
):
2001 step
= "Getting vnf_profiles from nsd"
2002 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
2003 vld_fixed_ip_connection_point_data
= {}
2005 step
= "Getting ip-address info from vnf_profile if it exists"
2006 for vnfp
in vnf_profiles
:
2007 # Checking ip-address info from nsd.vnf_profile and storing
2008 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
2009 for cpd
in vlc
.get("constituent-cpd-id", ()):
2010 if cpd
.get("ip-address"):
2011 step
= "Storing ip-address info"
2012 vld_fixed_ip_connection_point_data
.update(
2014 vlc
.get("virtual-link-profile-id")
2016 + cpd
.get("constituent-base-element-id"): {
2017 "vnfd-connection-point-ref": cpd
.get(
2018 "constituent-cpd-id"
2020 "ip-address": cpd
.get("ip-address"),
2025 # Inserting ip address to vnfr
2026 if len(vld_fixed_ip_connection_point_data
) > 0:
2027 step
= "Getting vnfrs"
2028 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2029 for item
in vld_fixed_ip_connection_point_data
.keys():
2030 step
= "Filtering vnfrs"
2033 lambda vnfr
: vnfr
["member-vnf-index-ref"]
2034 == item
.split(".")[1],
2041 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2042 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2043 step
= "Looking for matched interface"
2045 iface
.get("external-connection-point-ref")
2046 == vld_fixed_ip_connection_point_data
[item
].get(
2047 "vnfd-connection-point-ref"
2049 and iface
.get("ns-vld-id") == item
.split(".")[0]
2051 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2052 vdur_index
, iface_index
2054 step
= "Storing info in order to update vnfr"
2056 vnfr_update_text
+ ".ip-address"
2057 ] = increment_ip_mac(
2058 vld_fixed_ip_connection_point_data
[item
].get(
2061 vdur
.get("count-index", 0),
2063 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2065 step
= "updating vnfr at database"
2066 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2074 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
2077 def _get_vld_icp_from_instantiation_params(
2078 vnf_inst_params
: dict, vnfr
: dict, vnfr_update
: dict
2080 """Get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2082 vnf_inst_params (dict): VNF instantiation parameters dictionary
2083 vnfr (dict): VNF record dictionary
2084 vnfr_update (dict): VNF record update dictionary
2087 vnfr_update (dict): VNF record update dictionary
2089 for ivld_inst_param
in get_iterable(vnf_inst_params
.get("internal-vld")):
2090 for icp_inst_param
in get_iterable(
2091 ivld_inst_param
.get("internal-connection-point")
2094 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2095 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2097 iface
.get("internal-connection-point-ref")
2098 == icp_inst_param
["id-ref"]
2100 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2101 vdur_index
, iface_index
2103 if icp_inst_param
.get("ip-address"):
2105 vnfr_update_text
+ ".ip-address"
2106 ] = increment_ip_mac(
2107 icp_inst_param
.get("ip-address"),
2108 vdur
.get("count-index", 0),
2110 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2111 if icp_inst_param
.get("mac-address"):
2113 vnfr_update_text
+ ".mac-address"
2114 ] = increment_ip_mac(
2115 icp_inst_param
.get("mac-address"),
2116 vdur
.get("count-index", 0),
2118 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2123 def _get_vdu_interfaces_from_instantiation_params(
2124 vnfr_update
: dict, vnf_inst_params
: dict, vnfr
: dict
2126 """Get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
2128 vnfr_update (dict): VNF record update dictionary
2129 vnf_inst_params (dict): VNF instantiation parameters dictionary
2130 vnfr (dict): VNF record dictionary
2133 vnfr_update (dict): VNF record update dictionary
2135 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
2136 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2137 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
2139 for iface_inst_param
in get_iterable(vdu_inst_param
.get("interface")):
2140 iface_index
, _
= next(
2142 for i
in enumerate(vdur
["interfaces"])
2143 if i
[1]["name"] == iface_inst_param
["name"]
2145 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2146 vdur_index
, iface_index
2148 if iface_inst_param
.get("ip-address"):
2150 vnfr_update_text
+ ".ip-address"
2151 ] = increment_ip_mac(
2152 iface_inst_param
.get("ip-address"),
2153 vdur
.get("count-index", 0),
2155 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2156 if iface_inst_param
.get("mac-address"):
2158 vnfr_update_text
+ ".mac-address"
2159 ] = increment_ip_mac(
2160 iface_inst_param
.get("mac-address"),
2161 vdur
.get("count-index", 0),
2163 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2164 if iface_inst_param
.get("floating-ip-required"):
2165 vnfr_update
[vnfr_update_text
+ ".floating-ip-required"] = True
2169 def _get_ip_address_from_instantiation_params(
2170 indata
: dict, member_vnf_index
: str, vnfr
: dict, vnfr_update
: dict
2172 """Get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2174 indata (dict): Input data dictionary
2175 member_vnf_index (str): VNF index as an identifier
2176 vnfr (dict): VNF record dictionary
2177 vnfr_update (dict): VNF record update dictionary to keep the updates
2180 vnfr_update (dict): VNF record update dictionary to keep the updates
2182 for vld_inst_param
in get_iterable(indata
.get("vld")):
2183 for vnfcp_inst_param
in get_iterable(
2184 vld_inst_param
.get("vnfd-connection-point-ref")
2186 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
2189 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2190 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2192 iface
.get("external-connection-point-ref")
2193 == vnfcp_inst_param
["vnfd-connection-point-ref"]
2195 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2196 vdur_index
, iface_index
2198 if vnfcp_inst_param
.get("ip-address"):
2200 vnfr_update_text
+ ".ip-address"
2201 ] = increment_ip_mac(
2202 vnfcp_inst_param
.get("ip-address"),
2203 vdur
.get("count-index", 0),
2205 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2206 if vnfcp_inst_param
.get("mac-address"):
2208 vnfr_update_text
+ ".mac-address"
2209 ] = increment_ip_mac(
2210 vnfcp_inst_param
.get("mac-address"),
2211 vdur
.get("count-index", 0),
2213 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2218 def _update_indata_to_use_concrete_vim_network(
2219 ifaces_forcing_vim_network
: list, indata
: dict, member_vnf_index
: str
2221 """Update indata in case pdu forces to use a concrete vim-network-name
2223 ifaces_forcing_vim_network (list): List of interfaces that are connected to an existing VIM network.
2224 indata (dict): Input data dictionary
2225 member_vnf_index (str): VNF index as an identifier
2227 indata (dict): Input data dictionary
2229 for iface_info
in ifaces_forcing_vim_network
:
2230 if iface_info
.get("ns-vld-id"):
2231 if "vld" not in indata
:
2233 indata
["vld"].append(
2235 key
: iface_info
[key
]
2236 for key
in ("name", "vim-network-name", "vim-network-id")
2237 if iface_info
.get(key
)
2241 elif iface_info
.get("vnf-vld-id"):
2242 if "vnf" not in indata
:
2244 indata
["vnf"].append(
2246 "member-vnf-index": member_vnf_index
,
2249 key
: iface_info
[key
]
2255 if iface_info
.get(key
)
2263 self
, session
: dict, rollback
: list, nsr
: dict, indata
: dict
2265 """Update VNF record using indata.
2267 session (dict): Contains "username", "admin", "force", "public", "project_id", "set_project"
2268 rollback (list): List with the database modifications to rollback if needed
2269 nsr (dict): NS record to get the related VNF record.
2270 indata (dict): Input data dictionary
2280 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2284 vnfr_update_rollback
= {}
2285 member_vnf_index
= vnfr
["member-vnf-index-ref"]
2287 # Update vim-account-id
2288 vim_account
= indata
.get("vimAccountId")
2289 paas_account
= indata
.get("paasAccountId")
2292 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
2294 # Check instantiate parameters
2295 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
2296 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
2298 if vnf_inst_params
.get("vimAccountId"):
2299 vim_account
= vnf_inst_params
["vimAccountId"]
2300 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
2301 elif vnf_inst_params
.get("paasAccountId"):
2302 paas_account
= vnf_inst_params
["paasAccountId"]
2304 # Get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
2306 NsLcmOpTopic
._get
_vdu
_interfaces
_from
_instantiation
_params
(
2307 vnfr_update
, vnf_inst_params
, vnfr
2311 # Get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
2312 # TODO update vld with the ip-profile
2313 vnfr_update
= NsLcmOpTopic
._get
_vld
_icp
_from
_instantiation
_params
(
2314 vnf_inst_params
, vnfr
, vnfr_update
2317 # Get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2318 vnfr_update
= NsLcmOpTopic
._get
_ip
_address
_from
_instantiation
_params
(
2319 indata
, member_vnf_index
, vnfr
, vnfr_update
2323 vnfr_update
["vim-account-id"] = vim_account
2324 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
2326 vnfr_update
["paas-account-id"] = paas_account
2327 vnfr_update_rollback
["paas-account-id"] = vnfr
.get("paas-account-id")
2330 vnfr_update
["vca-id"] = vca_id
2331 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
2334 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
2335 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2339 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
2340 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2343 # Update vnfr in database
2344 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2350 "content": vnfr_update_rollback
,
2354 # Update indata in case pdu forces to use a concrete vim-network-name
2355 # TODO check if user has already insert a vim-network-name and raises an error
2356 if not ifaces_forcing_vim_network
:
2358 indata
= NsLcmOpTopic
._update
_indata
_to
_use
_concrete
_vim
_network
(
2359 ifaces_forcing_vim_network
, indata
, member_vnf_index
2363 def _create_nslcmop(nsr_id
, operation
, params
):
2365 Creates a ns-lcm-opp content to be stored at database.
2366 :param nsr_id: internal id of the instance
2367 :param operation: instantiate, terminate, scale, action, update ...
2368 :param params: user parameters for the operation
2369 :return: dictionary following SOL005 format
2376 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2377 "queuePosition": None,
2379 "errorMessage": None,
2380 "detailedStatus": None,
2381 "statusEnteredTime": now
,
2382 "nsInstanceId": nsr_id
,
2383 "lcmOperationType": operation
,
2385 "isAutomaticInvocation": False,
2386 "operationParams": params
,
2387 "isCancelPending": False,
2389 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2390 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2395 def _get_enabled_vims(self
, session
):
2397 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2398 :param session: current session with user information
2400 db_filter
= self
._get
_project
_filter
(session
)
2401 db_filter
["_admin.operationalState"] = "ENABLED"
2402 vims
= self
.db
.get_list("vim_accounts", db_filter
)
2405 vimAccounts
.append(vim
["_id"])
2418 Performs a new operation over a ns
2419 :param rollback: list to append created items at database in case a rollback must to be done
2420 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2421 :param indata: descriptor with the parameters of the operation. It must contains among others
2422 nsInstanceId: _id of the nsr to perform the operation
2423 operation: it can be: instantiate, terminate, action, update TODO: heal
2424 :param kwargs: used to override the indata descriptor
2425 :param headers: http request headers
2426 :return: id of the nslcmops
2429 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
2431 db_filter
= self
._get
_project
_filter
(session
)
2432 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2433 nsis
= self
.db
.get_one(
2434 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
2437 raise EngineException(
2438 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2441 http_code
=HTTPStatus
.CONFLICT
,
2445 # Override descriptor with query string kwargs
2446 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2447 operation
= indata
["lcmOperationType"]
2448 nsInstanceId
= indata
["nsInstanceId"]
2450 validate_input(indata
, self
.operation_schema
[operation
])
2451 # get ns from nsr_id
2452 _filter
= BaseTopic
._get
_project
_filter
(session
)
2453 _filter
["_id"] = nsInstanceId
2454 nsr
= self
.db
.get_one("nsrs", _filter
)
2457 if operation
== "terminate" and slice_object
is False:
2458 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
2460 not nsr
["_admin"].get("nsState")
2461 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
2463 if operation
== "terminate" and indata
.get("autoremove"):
2464 # NSR must be deleted
2468 ) # a none in this case is used to indicate not instantiated. It can be removed
2469 if operation
!= "instantiate":
2470 raise EngineException(
2471 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2472 nsInstanceId
, operation
2474 HTTPStatus
.CONFLICT
,
2477 if operation
== "instantiate" and not session
["force"]:
2478 raise EngineException(
2479 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2480 nsInstanceId
, operation
2482 HTTPStatus
.CONFLICT
,
2484 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
2485 if indata
.get("primitive_params"):
2486 indata
["primitive_params"] = json
.dumps(indata
["primitive_params"])
2487 elif indata
.get("additionalParamsForVnf"):
2488 indata
["additionalParamsForVnf"] = json
.dumps(
2489 indata
["additionalParamsForVnf"]
2492 if operation
== "instantiate":
2493 self
._update
_vnfrs
_from
_nsd
(nsr
)
2494 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
2495 if (operation
== "update") and (indata
["updateType"] == "CHANGE_VNFPKG"):
2497 vnfd_id
= indata
["changeVnfPackageData"]["vnfdId"]
2498 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2499 nsd
= self
.db
.get_one("nsds", {"_id": nsr
["nsd-id"]})
2500 ns_request
= nsr
["instantiate_params"]
2501 vnfr
= self
.db
.get_one(
2502 "vnfrs", {"_id": indata
["changeVnfPackageData"]["vnfInstanceId"]}
2504 latest_vnfd_revision
= vnfd
["_admin"].get("revision", 1)
2505 vnfr_vnfd_revision
= vnfr
.get("revision", 1)
2506 if latest_vnfd_revision
!= vnfr_vnfd_revision
:
2507 old_vnfd_id
= vnfd_id
+ ":" + str(vnfr_vnfd_revision
)
2508 old_db_vnfd
= self
.db
.get_one(
2509 "vnfds_revisions", {"_id": old_vnfd_id
}
2511 old_sw_version
= old_db_vnfd
.get("software-version", "1.0")
2512 new_sw_version
= vnfd
.get("software-version", "1.0")
2513 if new_sw_version
!= old_sw_version
:
2514 vnf_index
= vnfr
["member-vnf-index-ref"]
2515 self
.logger
.info("nsr {}".format(nsr
))
2516 for vdu
in vnfd
["vdu"]:
2517 self
.nsrtopic
._add
_flavor
_to
_nsr
(
2518 vdu
, vnfd
, nsr
, vnf_index
, latest_vnfd_revision
2520 sw_image_id
= vdu
.get("sw-image-desc")
2522 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(
2525 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2526 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
2527 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(
2530 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2531 nsr_update
["image"] = nsr
["image"]
2532 nsr_update
["flavor"] = nsr
["flavor"]
2533 self
.db
.set_one("nsrs", {"_id": nsr
["_id"]}, nsr_update
)
2534 ns_k8s_namespace
= self
.nsrtopic
._get
_ns
_k
8s
_namespace
(
2535 nsd
, ns_request
, session
2538 self
.nsrtopic
._create
_vnfr
_descriptor
_from
_vnfd
(
2546 latest_vnfd_revision
,
2549 indata
["newVdur"] = vnfr_descriptor
["vdur"]
2550 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
2551 _id
= nslcmop_desc
["_id"]
2553 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2555 if indata
.get("placement-engine"):
2556 # Save valid vim accounts in lcm operation descriptor
2557 nslcmop_desc
["operationParams"][
2559 ] = self
._get
_enabled
_vims
(session
)
2560 self
.db
.create("nslcmops", nslcmop_desc
)
2561 rollback
.append({"topic": "nslcmops", "_id": _id
})
2562 if not slice_object
:
2563 self
.msg
.write("ns", operation
, nslcmop_desc
)
2565 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2566 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2567 # except DbException as e:
2568 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2570 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2571 raise EngineException(
2572 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2575 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2576 raise EngineException(
2577 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2581 class NsiTopic(BaseTopic
):
2584 quota_name
= "slice_instances"
2586 def __init__(self
, db
, fs
, msg
, auth
):
2587 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2588 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2591 def _format_ns_request(ns_request
):
2592 formated_request
= copy(ns_request
)
2593 # TODO: Add request params
2594 return formated_request
2597 def _format_addional_params(slice_request
):
2599 Get and format user additional params for NS or VNF
2600 :param slice_request: User instantiation additional parameters
2601 :return: a formatted copy of additional params or None if not supplied
2603 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2604 if additional_params
:
2605 for k
, v
in additional_params
.items():
2606 if not isinstance(k
, str):
2607 raise EngineException(
2608 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2612 if "." in k
or "$" in k
:
2613 raise EngineException(
2614 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2618 if isinstance(v
, (dict, tuple, list)):
2619 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2620 return additional_params
2622 def _check_descriptor_dependencies(self
, session
, descriptor
):
2624 Check that the dependent descriptors exist on a new descriptor or edition
2625 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2626 :param descriptor: descriptor to be inserted or edit
2627 :return: None or raises exception
2629 if not descriptor
.get("nst-ref"):
2631 nstd_id
= descriptor
["nst-ref"]
2632 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
2633 raise EngineException(
2634 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2637 http_code
=HTTPStatus
.CONFLICT
,
2640 def check_conflict_on_del(self
, session
, _id
, db_content
):
2642 Check that NSI is not instantiated
2643 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2644 :param _id: nsi internal id
2645 :param db_content: The database content of the _id
2646 :return: None or raises EngineException with the conflict
2648 if session
["force"]:
2651 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2652 raise EngineException(
2653 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2654 "Launch 'terminate' operation first; or force deletion".format(_id
),
2655 http_code
=HTTPStatus
.CONFLICT
,
2658 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2660 Deletes associated nsilcmops from database. Deletes associated filesystem.
2661 Set usageState of nst
2662 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2663 :param _id: server internal id
2664 :param db_content: The database content of the descriptor
2665 :param not_send_msg: To not send message (False) or store content (list) instead
2666 :return: None if ok or raises EngineException with the problem
2669 # Deleting the nsrs belonging to nsir
2671 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2672 nsr_id
= nsrs_detailed_item
["nsrId"]
2673 if nsrs_detailed_item
.get("shared"):
2675 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2676 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2677 "_id.ne": nsir
["_id"],
2679 nsi
= self
.db
.get_one(
2680 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2682 if nsi
: # last one using nsr
2685 self
.nsrTopic
.delete(
2686 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2688 except (DbException
, EngineException
) as e
:
2689 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2694 # delete related nsilcmops database entries
2695 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2697 # Check and set used NST usage state
2698 nsir_admin
= nsir
.get("_admin")
2699 if nsir_admin
and nsir_admin
.get("nst-id"):
2700 # check if used by another NSI
2701 nsis_list
= self
.db
.get_one(
2703 {"nst-id": nsir_admin
["nst-id"]},
2704 fail_on_empty
=False,
2710 {"_id": nsir_admin
["nst-id"]},
2711 {"_admin.usageState": "NOT_IN_USE"},
2714 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2716 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2717 :param rollback: list to append the created items at database in case a rollback must be done
2718 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2719 :param indata: params to be used for the nsir
2720 :param kwargs: used to override the indata descriptor
2721 :param headers: http request headers
2722 :return: the _id of nsi descriptor created at database
2726 step
= "checking quotas"
2727 self
.check_quota(session
)
2730 slice_request
= self
._remove
_envelop
(indata
)
2731 # Override descriptor with query string kwargs
2732 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2733 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2736 step
= "getting nstd id='{}' from database".format(
2737 slice_request
.get("nstId")
2739 _filter
= self
._get
_project
_filter
(session
)
2740 _filter
["_id"] = slice_request
["nstId"]
2741 nstd
= self
.db
.get_one("nsts", _filter
)
2742 # check NST is not disabled
2743 step
= "checking NST operationalState"
2744 if nstd
["_admin"]["operationalState"] == "DISABLED":
2745 raise EngineException(
2746 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2747 "instance".format(slice_request
["nstId"]),
2748 http_code
=HTTPStatus
.CONFLICT
,
2752 # check NSD is not disabled
2753 step
= "checking operationalState"
2754 if nstd
["_admin"]["operationalState"] == "DISABLED":
2755 raise EngineException(
2756 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2757 "a network slice".format(slice_request
["nstId"]),
2758 http_code
=HTTPStatus
.CONFLICT
,
2761 nstd
.pop("_admin", None)
2762 nstd_id
= nstd
.pop("_id", None)
2763 nsi_id
= str(uuid4())
2764 step
= "filling nsi_descriptor with input data"
2769 "name": slice_request
["nsiName"],
2770 "description": slice_request
.get("nsiDescription", ""),
2771 "datacenter": slice_request
["vimAccountId"],
2772 "nst-ref": nstd
["id"],
2773 "instantiation_parameters": slice_request
,
2774 "network-slice-template": nstd
,
2778 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2781 step
= "creating nsi at database"
2783 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2785 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2786 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2787 nsi_descriptor
["_admin"]["deployed"] = {}
2788 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2789 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2791 # Creating netslice-vld for the RO.
2792 step
= "creating netslice-vld at database"
2794 # Building the vlds list to be deployed
2795 # From netslice descriptors, creating the initial list
2798 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2799 # Getting template Instantiation parameters from NST
2800 nsi_vld
= deepcopy(netslice_vlds
)
2801 nsi_vld
["shared-nsrs-list"] = []
2802 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2803 nsi_vlds
.append(nsi_vld
)
2805 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2806 # Creating netslice-subnet_record.
2810 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2811 for member_ns
in nstd
["netslice-subnet"]:
2812 nsd_id
= member_ns
["nsd-ref"]
2813 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2814 member_ns
["nsd-ref"], member_ns
["id"]
2816 if nsd_id
not in needed_nsds
:
2818 _filter
["id"] = nsd_id
2819 nsd
= self
.db
.get_one(
2820 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2824 needed_nsds
[nsd_id
] = nsd
2826 nsd
= needed_nsds
[nsd_id
]
2827 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2828 services
.append(member_ns
)
2830 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2831 member_ns
["nsd-ref"], member_ns
["id"]
2834 # creates Network Services records (NSRs)
2835 step
= "creating nsrs at database using NsrTopic.new()"
2836 ns_params
= slice_request
.get("netslice-subnet")
2838 nsi_netslice_subnet
= []
2839 for service
in services
:
2840 # Check if the netslice-subnet is shared and if it is share if the nss exists
2843 # Is the nss shared and instantiated?
2844 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2845 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2848 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2849 nsi
= self
.db
.get_one(
2850 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2852 if nsi
and service
.get("is-shared-nss"):
2853 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2854 for nsrs_detailed_item
in nsrs_detailed_list
:
2855 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2856 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2857 _id_nsr
= nsrs_detailed_item
["nsrId"]
2859 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2860 if netslice_subnet
["nss-id"] == service
["id"]:
2861 indata_ns
= netslice_subnet
2865 if service
.get("instantiation-parameters"):
2866 indata_ns
= deepcopy(service
["instantiation-parameters"])
2867 # del service["instantiation-parameters"]
2869 indata_ns
["nsdId"] = service
["_id"]
2870 indata_ns
["nsName"] = (
2871 slice_request
.get("nsiName") + "." + service
["id"]
2873 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2874 indata_ns
["nsDescription"] = service
["description"]
2875 if slice_request
.get("ssh_keys"):
2876 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2879 for ns_param
in ns_params
:
2880 if ns_param
.get("id") == service
["id"]:
2881 copy_ns_param
= deepcopy(ns_param
)
2882 del copy_ns_param
["id"]
2883 indata_ns
.update(copy_ns_param
)
2886 # Creates Nsr objects
2887 _id_nsr
, _
= self
.nsrTopic
.new(
2888 rollback
, session
, indata_ns
, kwargs
, headers
2892 "shared": service
.get("is-shared-nss"),
2893 "nsd-id": service
["nsd-ref"],
2894 "nss-id": service
["id"],
2895 "nslcmop_instantiate": None,
2897 indata_ns
["nss-id"] = service
["id"]
2898 nsrs_list
.append(nsrs_item
)
2899 nsi_netslice_subnet
.append(indata_ns
)
2900 nsr_ref
= {"nsr-ref": _id_nsr
}
2901 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2903 # Adding the nsrs list to the nsi
2904 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2905 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2907 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2910 # Creating the entry in the database
2911 self
.db
.create("nsis", nsi_descriptor
)
2912 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2914 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2915 self
.logger
.exception(
2916 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2918 raise EngineException("Error {}: {}".format(step
, e
))
2919 except ValidationError
as e
:
2920 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2922 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2923 raise EngineException(
2924 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2928 class NsiLcmOpTopic(BaseTopic
):
2931 operation_schema
= { # mapping between operation and jsonschema to validate
2932 "instantiate": nsi_instantiate
,
2936 def __init__(self
, db
, fs
, msg
, auth
):
2937 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2938 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2940 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2942 Check that user has enter right parameters for the operation
2943 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2944 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2945 :param indata: descriptor with the parameters of the operation
2949 nstd
= nsir
["network-slice-template"]
2951 def check_valid_netslice_subnet_id(nstId
):
2952 # TODO change to vnfR (??)
2953 for netslice_subnet
in nstd
["netslice-subnet"]:
2954 if nstId
== netslice_subnet
["id"]:
2955 nsd_id
= netslice_subnet
["nsd-ref"]
2956 if nsd_id
not in nsds
:
2957 _filter
= self
._get
_project
_filter
(session
)
2958 _filter
["id"] = nsd_id
2959 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2962 raise EngineException(
2963 "Invalid parameter nstId='{}' is not one of the "
2964 "nst:netslice-subnet".format(nstId
)
2967 if operation
== "instantiate":
2968 # check the existance of netslice-subnet items
2969 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2970 check_valid_netslice_subnet_id(in_nst
["id"])
2972 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2978 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2979 "statusEnteredTime": now
,
2980 "netsliceInstanceId": netsliceInstanceId
,
2981 "lcmOperationType": operation
,
2983 "isAutomaticInvocation": False,
2984 "operationParams": params
,
2985 "isCancelPending": False,
2987 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2988 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2989 + netsliceInstanceId
,
2994 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2995 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2996 if nst_sb_item
.get("is-shared-nss"):
2997 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2998 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2999 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
3000 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
3001 "nss-connection-point-ref"
3004 admin_subnet_item
["nss-id"]
3005 == admin_vld_nss_cp_ref_item
["nss-ref"]
3008 not nsr_item
["nsrId"]
3009 in admin_vld_item
["shared-nsrs-list"]
3011 admin_vld_item
["shared-nsrs-list"].append(
3015 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
3018 {"_id": nsir
["_id"]},
3019 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
3022 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
3024 Performs a new operation over a ns
3025 :param rollback: list to append created items at database in case a rollback must to be done
3026 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
3027 :param indata: descriptor with the parameters of the operation. It must contains among others
3028 netsliceInstanceId: _id of the nsir to perform the operation
3029 operation: it can be: instantiate, terminate, action, TODO: update, heal
3030 :param kwargs: used to override the indata descriptor
3031 :param headers: http request headers
3032 :return: id of the nslcmops
3035 # Override descriptor with query string kwargs
3036 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
3037 operation
= indata
["lcmOperationType"]
3038 netsliceInstanceId
= indata
["netsliceInstanceId"]
3039 validate_input(indata
, self
.operation_schema
[operation
])
3041 # get nsi from netsliceInstanceId
3042 _filter
= self
._get
_project
_filter
(session
)
3043 _filter
["_id"] = netsliceInstanceId
3044 nsir
= self
.db
.get_one("nsis", _filter
)
3045 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
3050 not nsir
["_admin"].get("nsiState")
3051 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
3053 if operation
== "terminate" and indata
.get("autoremove"):
3054 # NSIR must be deleted
3058 ) # a none in this case is used to indicate not instantiated. It can be removed
3059 if operation
!= "instantiate":
3060 raise EngineException(
3061 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
3062 netsliceInstanceId
, operation
3064 HTTPStatus
.CONFLICT
,
3067 if operation
== "instantiate" and not session
["force"]:
3068 raise EngineException(
3069 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
3070 netsliceInstanceId
, operation
3072 HTTPStatus
.CONFLICT
,
3075 # Creating all the NS_operation (nslcmop)
3076 # Get service list from db
3077 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
3079 # nslcmops_item = None
3080 for index
, nsr_item
in enumerate(nsrs_list
):
3081 nsr_id
= nsr_item
["nsrId"]
3082 if nsr_item
.get("shared"):
3083 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
3084 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
3086 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
3088 _filter
["_id.ne"] = netsliceInstanceId
3089 nsi
= self
.db
.get_one(
3090 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
3092 if operation
== "terminate":
3094 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3098 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
3101 ): # other nsi is using this nsr and it needs this nsr instantiated
3102 continue # do not create nsilcmop
3104 # looks the first nsi fulfilling the conditions but not being the current NSIR
3106 nsi_nsr_item
= next(
3108 for n
in nsi
["_admin"]["nsrs-detailed-list"]
3109 if n
["nsrId"] == nsr_id
3111 and n
["nslcmop_instantiate"]
3113 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
3114 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
3116 "_admin.nsrs-detailed-list.{}".format(
3120 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
3121 # continue to not create nslcmop since nsrs is shared and nsrs was created
3124 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
3129 "lcmOperationType": operation
,
3130 "nsInstanceId": nsr_id
,
3131 # Including netslice_id in the ns instantiate Operation
3132 "netsliceInstanceId": netsliceInstanceId
,
3134 if operation
== "instantiate":
3135 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3136 indata_ns
.update(service
["instantiate_params"])
3138 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
3139 # message via kafka bus
3140 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
3141 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
3143 nslcmops
.append(nslcmop
)
3144 if operation
== "instantiate":
3146 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
3150 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
3151 except (DbException
, EngineException
) as e
:
3152 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
3155 + "skipping NS={} because not found".format(nsr_id
)
3162 indata
["nslcmops_ids"] = nslcmops
3163 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
3165 nsilcmop_desc
= self
._create
_nsilcmop
(
3166 session
, netsliceInstanceId
, operation
, indata
3169 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
3171 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
3172 rollback
.append({"topic": "nsilcmops", "_id": _id
})
3173 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
3175 except ValidationError
as e
:
3176 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
3178 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
3179 raise EngineException(
3180 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
3183 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
3184 raise EngineException(
3185 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR