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(self
, vdu
, vnfd
, nsr_descriptor
, member_vnf_index
, revision
=None):
463 # Find this vdu compute and storage descriptors
464 vdu_virtual_compute
= {}
465 vdu_virtual_storage
= {}
466 for vcd
in vnfd
.get("virtual-compute-desc", ()):
467 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
468 vdu_virtual_compute
= vcd
469 for vsd
in vnfd
.get("virtual-storage-desc", ()):
470 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
471 vdu_virtual_storage
= vsd
472 # Get this vdu vcpus, memory and storage info for flavor_data
473 if vdu_virtual_compute
.get("virtual-cpu", {}).get(
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"])
484 if vdu_virtual_storage
.get("size-of-storage"):
485 flavor_data
["storage-gb"] = vdu_virtual_storage
[
488 # Get this vdu EPA info for guest_epa
489 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
490 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"][
493 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
494 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
495 if vcpu_pinning
.get("thread-policy"):
496 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
[
499 if vcpu_pinning
.get("policy"):
502 if vcpu_pinning
["policy"] == "dynamic"
505 guest_epa
["cpu-pinning-policy"] = cpu_policy
506 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
507 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"][
510 if vdu_virtual_compute
.get("virtual-memory", {}).get(
513 guest_epa
["mempage-size"] = vdu_virtual_compute
[
516 if vdu_virtual_compute
.get("virtual-memory", {}).get(
519 guest_epa
["numa-node-policy"] = vdu_virtual_compute
[
521 ]["numa-node-policy"]
522 if vdu_virtual_storage
.get("disk-io-quota"):
523 guest_epa
["disk-io-quota"] = vdu_virtual_storage
[
528 flavor_data
["guest-epa"] = guest_epa
530 revision
= revision
if revision
is not None else 1
531 flavor_data
["name"] = vdu
["id"][:56] + "-" + member_vnf_index
+ "-" + str(revision
) + "-flv"
532 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
533 nsr_descriptor
["flavor"].append(flavor_data
)
535 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
537 additional_params
, _
= self
._format
_additional
_params
(
538 ns_request
, descriptor
=nsd
542 "name": ns_request
["nsName"],
543 "name-ref": ns_request
["nsName"],
544 "short-name": ns_request
["nsName"],
545 "admin-status": "ENABLED",
546 "nsState": "NOT_INSTANTIATED",
547 "currentOperation": "IDLE",
548 "currentOperationID": None,
549 "errorDescription": None,
551 "deploymentStatus": None,
552 "configurationStatus": None,
554 "nsd": {k
: v
for k
, v
in nsd
.items()},
555 "datacenter": ns_request
["vimAccountId"],
556 "resource-orchestrator": "osmopenmano",
557 "description": ns_request
.get("nsDescription", ""),
558 "constituent-vnfr-ref": [],
559 "operational-status": "init", # typedef ns-operational-
560 "config-status": "init", # typedef config-states
561 "detailed-status": "scheduled",
562 "orchestration-progress": {},
564 "nsd-name-ref": nsd
["name"],
565 "operational-events": [], # "id", "timestamp", "description", "event",
566 "nsd-ref": nsd
["id"],
567 "nsd-id": nsd
["_id"],
569 "instantiate_params": self
._format
_ns
_request
(ns_request
),
570 "additionalParamsForNs": additional_params
,
571 "ns-instance-config-ref": nsr_id
,
574 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
577 "affinity-or-anti-affinity-group": [],
579 if "revision" in nsd
["_admin"]:
580 nsr_descriptor
["revision"] = nsd
["_admin"]["revision"]
582 ns_request
["nsr_id"] = nsr_id
583 if ns_request
and ns_request
.get("config-units"):
584 nsr_descriptor
["config-units"] = ns_request
["config-units"]
586 if nsd
.get("virtual-link-desc"):
587 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
588 # Fill each vld with vnfd-connection-point-ref data
589 # TODO: Change for multiple df support
590 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
591 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
592 for vnf_profile
in vnf_profiles
:
593 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
594 for cpd
in vlc
.get("constituent-cpd-id", ()):
595 all_vld_connection_point_data
[
596 vlc
.get("virtual-link-profile-id")
599 "member-vnf-index-ref": cpd
.get(
600 "constituent-base-element-id"
602 "vnfd-connection-point-ref": cpd
.get(
605 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
609 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
612 for vdu
in vnfd
.get("vdu", ()):
613 member_vnf_index
= vnf_profile
.get("id")
614 self
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr_descriptor
, member_vnf_index
)
615 sw_image_id
= vdu
.get("sw-image-desc")
617 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
618 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
620 # also add alternative images to the list of images
621 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
622 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
623 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
625 # Add Affinity or Anti-affinity group information to NSR
626 vdu_profiles
= vnfd
.get("df", [[]])[0].get("vdu-profile", ())
627 affinity_group_prefix_name
= "{}-{}".format(
628 nsr_descriptor
["name"][:16], vnf_profile
.get("id")[:16]
631 for vdu_profile
in vdu_profiles
:
632 affinity_group_data
= {}
633 for affinity_group
in vdu_profile
.get(
634 "affinity-or-anti-affinity-group", ()
636 affinity_group_data
= (
637 self
._get
_affinity
_or
_anti
_affinity
_group
_data
_from
_vnfd
(
638 vnfd
, affinity_group
["id"]
641 affinity_group_data
["member-vnf-index"] = vnf_profile
.get("id")
642 self
._add
_affinity
_or
_anti
_affinity
_group
_to
_nsr
(
645 affinity_group_prefix_name
,
649 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
652 vld
["name"] = vld
["id"]
653 nsr_descriptor
["vld"] = nsr_vld
655 return nsr_descriptor
657 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
658 self
, vnfd
, affinity_group_id
661 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
663 affinity_group
= utils
.find_in_list(
664 vnfd
.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
665 lambda ag
: ag
["id"] == affinity_group_id
,
667 affinity_group_data
= {}
669 if affinity_group
.get("id"):
670 affinity_group_data
["ag-id"] = affinity_group
["id"]
671 if affinity_group
.get("type"):
672 affinity_group_data
["type"] = affinity_group
["type"]
673 if affinity_group
.get("scope"):
674 affinity_group_data
["scope"] = affinity_group
["scope"]
675 return affinity_group_data
677 def _add_affinity_or_anti_affinity_group_to_nsr(
678 self
, nsr_descriptor
, affinity_group_data
, affinity_group_prefix_name
681 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
683 affinity_group
= next(
686 for f
in nsr_descriptor
["affinity-or-anti-affinity-group"]
687 if all(f
.get(k
) == affinity_group_data
[k
] for k
in affinity_group_data
)
691 if not affinity_group
:
692 affinity_group_data
["id"] = str(
693 len(nsr_descriptor
["affinity-or-anti-affinity-group"])
695 affinity_group_data
["name"] = "{}-{}".format(
696 affinity_group_prefix_name
, affinity_group_data
["ag-id"][:32]
698 nsr_descriptor
["affinity-or-anti-affinity-group"].append(
702 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
703 sw_image_desc
= utils
.find_in_list(
704 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
707 if sw_image_desc
.get("image"):
708 image_data
["image"] = sw_image_desc
["image"]
709 if sw_image_desc
.get("checksum"):
710 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
711 if sw_image_desc
.get("vim-type"):
712 image_data
["vim-type"] = sw_image_desc
["vim-type"]
715 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
717 Adds image to nsr checking first it is not already added
722 for f
in nsr_descriptor
["image"]
723 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
728 image_data
["id"] = str(len(nsr_descriptor
["image"]))
729 nsr_descriptor
["image"].append(image_data
)
731 def _create_vnfr_descriptor_from_vnfd(
742 vnfr_id
= str(uuid4())
743 nsr_id
= nsr_descriptor
["id"]
745 additional_params
, vnf_params
= self
._format
_additional
_params
(
746 ns_request
, vnf_index
, descriptor
=vnfd
752 "nsr-id-ref": nsr_id
,
753 "member-vnf-index-ref": vnf_index
,
754 "additionalParamsForVnf": additional_params
,
756 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
758 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
759 "vim-account-id": None,
762 "connection-point": [],
763 "ip-address": None, # mgmt-interface filled by LCM
766 # Revision backwards compatility. Only specify the revision in the record if
767 # the original VNFD has a revision.
768 if "revision" in vnfd
:
769 vnfr_descriptor
["revision"] = vnfd
["revision"]
772 vnf_k8s_namespace
= ns_k8s_namespace
774 if vnf_params
.get("k8s-namespace"):
775 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
776 if vnf_params
.get("config-units"):
777 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
780 if vnfd
.get("int-virtual-link-desc"):
781 vnfr_descriptor
["vld"] = []
782 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
783 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
785 for cp
in vnfd
.get("ext-cpd", ()):
787 "name": cp
.get("id"),
788 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
789 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
791 # "ip-address", "mac-address" # filled by LCM
792 # vim-id # TODO it would be nice having a vim port id
794 vnfr_descriptor
["connection-point"].append(vnf_cp
)
796 # Create k8s-cluster information
797 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
798 if vnfd
.get("k8s-cluster"):
799 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
800 all_k8s_cluster_nets_cpds
= {}
801 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
802 if cpd
.get("k8s-cluster-net"):
803 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
806 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
807 if net
.get("id") in all_k8s_cluster_nets_cpds
:
808 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
813 for kdu
in get_iterable(vnfd
.get("kdu")):
814 additional_params
, kdu_params
= self
._format
_additional
_params
(
815 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
817 kdu_k8s_namespace
= vnf_k8s_namespace
818 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
819 if kdu_params
and kdu_params
.get("k8s-namespace"):
820 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
822 kdu_deployment_name
= ""
823 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
824 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
827 "additionalParams": additional_params
,
828 "k8s-namespace": kdu_k8s_namespace
,
829 "kdu-deployment-name": kdu_deployment_name
,
830 "kdu-name": kdu
["name"],
831 # TODO "name": "" Name of the VDU in the VIM
832 "ip-address": None, # mgmt-interface filled by LCM
835 if kdu_params
and kdu_params
.get("config-units"):
836 kdur
["config-units"] = kdu_params
["config-units"]
837 if kdu
.get("helm-version"):
838 kdur
["helm-version"] = kdu
["helm-version"]
839 for k8s_type
in ("helm-chart", "juju-bundle"):
840 if kdu
.get(k8s_type
):
841 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
842 if not vnfr_descriptor
.get("kdur"):
843 vnfr_descriptor
["kdur"] = []
844 vnfr_descriptor
["kdur"].append(kdur
)
846 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
848 for vdu
in vnfd
.get("vdu", ()):
851 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
852 "operate-vnf-op-config"
854 vdu_config
= utils
.find_in_list(
855 configs
, lambda config
: config
["id"] == vdu
["id"]
861 vdu_instantiation_level
= utils
.find_in_list(
862 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
863 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
866 vdu_instantiation_level
= None
869 external_connection_ee
= utils
.filter_in_list(
870 vdu_config
.get("execution-environment-list", []),
871 lambda ee
: "external-connection-point-ref" in ee
,
873 for ee
in external_connection_ee
:
874 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
876 additional_params
, vdu_params
= self
._format
_additional
_params
(
877 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
881 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
882 vnfd
.get("virtual-storage-desc", []),
883 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"]
886 vdu_virtual_storage_descriptors
= []
888 "vdu-id-ref": vdu
["id"],
889 # TODO "name": "" Name of the VDU in the VIM
890 "ip-address": None, # mgmt-interface filled by LCM
891 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
892 "internal-connection-point": [],
894 "additionalParams": additional_params
,
895 "vdu-name": vdu
["name"],
896 "virtual-storages": vdu_virtual_storage_descriptors
898 if vdu_params
and vdu_params
.get("config-units"):
899 vdur
["config-units"] = vdu_params
["config-units"]
900 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
901 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
904 if vdu
.get("pdu-type"):
905 vdur
["pdu-type"] = vdu
["pdu-type"]
906 vdur
["name"] = vdu
["pdu-type"]
907 # TODO volumes: name, volume-id
908 for icp
in vdu
.get("int-cpd", ()):
911 "connection-point-id": icp
["id"],
912 "name": icp
.get("id"),
915 vdur
["internal-connection-point"].append(vdu_icp
)
917 for iface
in icp
.get("virtual-network-interface-requirement", ()):
918 # Name, mac-address and interface position is taken from VNFD
919 # and included into VNFR. By this way RO can process this information
920 # while creating the VDU.
921 iface_fields
= ("name", "mac-address", "position")
923 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
926 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
927 if "port-security-enabled" in icp
:
928 vdu_iface
["port-security-enabled"] = icp
[
929 "port-security-enabled"
932 if "port-security-disable-strategy" in icp
:
933 vdu_iface
["port-security-disable-strategy"] = icp
[
934 "port-security-disable-strategy"
937 for ext_cp
in vnfd
.get("ext-cpd", ()):
938 if not ext_cp
.get("int-cpd"):
940 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
942 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
943 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
947 if "port-security-enabled" in ext_cp
:
948 vdu_iface
["port-security-enabled"] = ext_cp
[
949 "port-security-enabled"
952 if "port-security-disable-strategy" in ext_cp
:
953 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
954 "port-security-disable-strategy"
961 and vdu_iface
.get("external-connection-point-ref")
964 vdu_iface
["mgmt-vnf"] = True
965 vdu_iface
["mgmt-interface"] = True
967 for ecp
in vdu_mgmt_cp
:
968 if vdu_iface
.get("external-connection-point-ref") == ecp
:
969 vdu_iface
["mgmt-interface"] = True
971 if iface
.get("virtual-interface"):
972 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
974 # look for network where this interface is connected
975 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
977 # TODO: Change for multiple df support
978 for df
in get_iterable(nsd
.get("df")):
979 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
980 for vlc_index
, vlc
in enumerate(
982 vnf_profile
.get("virtual-link-connectivity")
985 for cpd
in get_iterable(
986 vlc
.get("constituent-cpd-id")
989 cpd
.get("constituent-cpd-id")
992 vdu_iface
["ns-vld-id"] = vlc
.get(
993 "virtual-link-profile-id"
995 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
996 if vdu_iface
.get("type") in (
1000 nsr_descriptor
["vld"][vlc_index
][
1004 elif vdu_iface
.get("internal-connection-point-ref"):
1005 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
1006 # TODO: store fixed IP address in the record (if it exists in the ICP)
1007 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
1008 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1009 ivld_index
= utils
.find_index_in_list(
1010 vnfd
.get("int-virtual-link-desc", ()),
1011 lambda ivld
: ivld
["id"]
1012 == icp
.get("int-virtual-link-desc"),
1014 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
1016 vdur
["interfaces"].append(vdu_iface
)
1018 if vdu
.get("sw-image-desc"):
1019 sw_image
= utils
.find_in_list(
1020 vnfd
.get("sw-image-desc", ()),
1021 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
1023 nsr_sw_image_data
= utils
.find_in_list(
1024 nsr_descriptor
["image"],
1025 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
1027 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
1029 if vdu
.get("alternative-sw-image-desc"):
1031 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
1032 sw_image
= utils
.find_in_list(
1033 vnfd
.get("sw-image-desc", ()),
1034 lambda image
: image
["id"] == alt_image_id
,
1036 nsr_sw_image_data
= utils
.find_in_list(
1037 nsr_descriptor
["image"],
1039 nsr_image
.get("image") == sw_image
.get("image")
1042 alt_image_ids
.append(nsr_sw_image_data
["id"])
1043 vdur
["alt-image-ids"] = alt_image_ids
1045 revision
= revision
if revision
is not None else 1
1046 flavor_data_name
= vdu
["id"][:56] + "-" + vnf_index
+ "-" + str(revision
) + "-flv"
1047 nsr_flavor_desc
= utils
.find_in_list(
1048 nsr_descriptor
["flavor"],
1049 lambda flavor
: flavor
["name"] == flavor_data_name
,
1053 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
1055 # Adding Affinity groups information to vdur
1057 vdu_profile_affinity_group
= utils
.find_in_list(
1058 vnfd
.get("df")[0]["vdu-profile"],
1059 lambda a_vdu
: a_vdu
["id"] == vdu
["id"],
1062 vdu_profile_affinity_group
= None
1064 if vdu_profile_affinity_group
:
1065 affinity_group_ids
= []
1066 for affinity_group
in vdu_profile_affinity_group
.get(
1067 "affinity-or-anti-affinity-group", ()
1069 vdu_affinity_group
= utils
.find_in_list(
1070 vdu_profile_affinity_group
.get(
1071 "affinity-or-anti-affinity-group", ()
1073 lambda ag_fp
: ag_fp
["id"] == affinity_group
["id"],
1075 nsr_affinity_group
= utils
.find_in_list(
1076 nsr_descriptor
["affinity-or-anti-affinity-group"],
1078 nsr_ag
.get("ag-id") == vdu_affinity_group
.get("id")
1079 and nsr_ag
.get("member-vnf-index")
1080 == vnfr_descriptor
.get("member-vnf-index-ref")
1083 # Update Affinity Group VIM name if VDU instantiation parameter is present
1084 if vnf_params
and vnf_params
.get("affinity-or-anti-affinity-group"):
1085 vnf_params_affinity_group
= utils
.find_in_list(
1086 vnf_params
["affinity-or-anti-affinity-group"],
1088 vnfp_ag
.get("id") == vdu_affinity_group
.get("id")
1091 if vnf_params_affinity_group
.get("vim-affinity-group-id"):
1093 "vim-affinity-group-id"
1094 ] = vnf_params_affinity_group
["vim-affinity-group-id"]
1095 affinity_group_ids
.append(nsr_affinity_group
["id"])
1096 vdur
["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1098 if vdu_instantiation_level
:
1099 count
= vdu_instantiation_level
.get("number-of-instances")
1103 for index
in range(0, count
):
1104 vdur
= deepcopy(vdur
)
1105 for iface
in vdur
["interfaces"]:
1106 if iface
.get("ip-address") and index
!= 0:
1107 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
1108 if iface
.get("mac-address") and index
!= 0:
1109 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
1111 vdur
["_id"] = str(uuid4())
1112 vdur
["id"] = vdur
["_id"]
1113 vdur
["count-index"] = index
1114 vnfr_descriptor
["vdur"].append(vdur
)
1116 return vnfr_descriptor
1118 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
1120 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1121 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1122 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1123 :param ns_instance_content: ns instance content
1124 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1127 time_now
, time_delta
= time(), time() - ns_instance_content
["_admin"]["modified"]
1128 force_refresh
= isinstance(filter_q
, dict) and filter_q
.get('vcaStatusRefresh') == 'true'
1129 threshold_reached
= time_delta
> 120
1130 if force_refresh
or threshold_reached
:
1131 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
1132 ns_instance_content
["_admin"]["modified"] = time_now
1133 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
1134 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
1135 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1136 nslcmop_desc
["_admin"].pop("nsState")
1137 self
.msg
.write("ns", operation
, nslcmop_desc
)
1140 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1142 Get complete information on an ns instance.
1143 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1144 :param _id: string, ns instance id
1145 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1146 :param api_req: True if this call is serving an external API request. False if serving internal request.
1147 :return: dictionary, raise exception if not found.
1149 ns_instance_content
= super().show(session
, _id
, api_req
)
1150 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1151 return ns_instance_content
1153 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1154 raise EngineException(
1155 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1159 class VnfrTopic(BaseTopic
):
1163 def __init__(self
, db
, fs
, msg
, auth
):
1164 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1166 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1167 raise EngineException(
1168 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1171 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1172 raise EngineException(
1173 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1176 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1177 # Not used because vnfrs are created and deleted by NsrTopic class directly
1178 raise EngineException(
1179 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1183 class NsLcmOpTopic(BaseTopic
):
1186 operation_schema
= { # mapping between operation and jsonschema to validate
1187 "instantiate": ns_instantiate
,
1188 "action": ns_action
,
1189 "update": ns_update
,
1192 "terminate": ns_terminate
,
1193 "migrate": ns_migrate
,
1194 "verticalscale": ns_verticalscale
,
1197 def __init__(self
, db
, fs
, msg
, auth
):
1198 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1199 self
.nsrtopic
= NsrTopic(db
, fs
, msg
, auth
)
1201 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1203 Check that user has enter right parameters for the operation
1204 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1205 :param operation: it can be: instantiate, terminate, action, update, heal
1206 :param indata: descriptor with the parameters of the operation
1209 if operation
== "action":
1210 self
._check
_action
_ns
_operation
(indata
, nsr
)
1211 elif operation
== "scale":
1212 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1213 elif operation
== "update":
1214 self
._check
_update
_ns
_operation
(indata
, nsr
)
1215 elif operation
== "heal":
1216 self
._check
_heal
_ns
_operation
(indata
, nsr
)
1217 elif operation
== "instantiate":
1218 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1220 def _check_action_ns_operation(self
, indata
, nsr
):
1222 # check vnf_member_index
1223 if indata
.get("vnf_member_index"):
1224 indata
["member_vnf_index"] = indata
.pop(
1226 ) # for backward compatibility
1227 if indata
.get("member_vnf_index"):
1228 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1229 indata
["member_vnf_index"], nsr
["_id"]
1232 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1233 "operate-vnf-op-config"
1238 if indata
.get("vdu_id"):
1239 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1240 descriptor_configuration
= utils
.find_in_list(
1241 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1243 elif indata
.get("kdu_name"):
1244 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1245 descriptor_configuration
= utils
.find_in_list(
1246 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1249 descriptor_configuration
= utils
.find_in_list(
1250 configs
, lambda config
: config
["id"] == vnfd
["id"]
1252 if descriptor_configuration
is not None:
1253 descriptor_configuration
= descriptor_configuration
.get(
1257 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1261 # For k8s allows default primitives without validating the parameters
1262 if indata
.get("kdu_name") and indata
["primitive"] in (
1269 # TODO should be checked that rollback only can contains revsision_numbe????
1270 if not indata
.get("member_vnf_index"):
1271 raise EngineException(
1272 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1277 # if not, check primitive
1278 for config_primitive
in get_iterable(descriptor_configuration
):
1279 if indata
["primitive"] == config_primitive
["name"]:
1280 # check needed primitive_params are provided
1281 if indata
.get("primitive_params"):
1282 in_primitive_params_copy
= copy(indata
["primitive_params"])
1284 in_primitive_params_copy
= {}
1285 for paramd
in get_iterable(config_primitive
.get("parameter")):
1286 if paramd
["name"] in in_primitive_params_copy
:
1287 del in_primitive_params_copy
[paramd
["name"]]
1288 elif not paramd
.get("default-value"):
1289 raise EngineException(
1290 "Needed parameter {} not provided for primitive '{}'".format(
1291 paramd
["name"], indata
["primitive"]
1294 # check no extra primitive params are provided
1295 if in_primitive_params_copy
:
1296 raise EngineException(
1297 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1298 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1303 raise EngineException(
1304 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1309 def _check_update_ns_operation(self
, indata
, nsr
) -> None:
1310 """Validates the ns-update request according to updateType
1312 If updateType is CHANGE_VNFPKG:
1313 - it checks the vnfInstanceId, whether it's available under ns instance
1314 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1315 Otherwise exception will be raised.
1316 If updateType is REMOVE_VNF:
1317 - it checks if the vnfInstanceId is available in the ns instance
1318 - Otherwise exception will be raised.
1321 indata: includes updateType such as CHANGE_VNFPKG,
1322 nsr: network service record
1326 a meaningful error if given update parameters are not proper such as
1327 "Error in validating ns-update request: <ID> does not match
1328 with the vnfd-id of vnfinstance
1329 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1333 if indata
["updateType"] == "CHANGE_VNFPKG":
1334 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1335 vnf_instance_id
= indata
["changeVnfPackageData"]["vnfInstanceId"]
1336 ns_instance_id
= indata
["nsInstanceId"]
1337 vnfd_id_2update
= indata
["changeVnfPackageData"]["vnfdId"]
1339 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1341 raise EngineException(
1342 f
"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1343 f
"belong to NS {ns_instance_id}",
1344 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1347 # Getting vnfrs through the ns_instance_id
1348 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": ns_instance_id
})
1349 constituent_vnfd_id
= next(
1353 if vnfr
["id"] == vnf_instance_id
1358 # Check the given vnfd-id belongs to given vnf instance
1359 if constituent_vnfd_id
and (vnfd_id_2update
!= constituent_vnfd_id
):
1361 raise EngineException(
1362 f
"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1363 f
"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1364 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1367 # Validating the ns update timeout
1369 indata
.get("timeout_ns_update")
1370 and indata
["timeout_ns_update"] < 300
1372 raise EngineException(
1373 "Error in validating ns-update request: {} second is not enough "
1374 "to upgrade the VNF instance: {}".format(
1375 indata
["timeout_ns_update"], vnf_instance_id
1377 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1379 elif indata
["updateType"] == "REMOVE_VNF":
1380 vnf_instance_id
= indata
["removeVnfInstanceId"]
1381 ns_instance_id
= indata
["nsInstanceId"]
1382 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1383 raise EngineException(
1384 "Invalid VNF Instance Id. '{}' is not "
1385 "present in the NS '{}'".format(vnf_instance_id
, ns_instance_id
)
1396 "Ns update request could not be processed with error: {}.".format(e
)
1399 def _check_scale_ns_operation(self
, indata
, nsr
):
1400 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1401 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1403 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1405 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1406 == scaling_aspect
["id"]
1410 raise EngineException(
1411 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1412 "present at vnfd:scaling-aspect".format(
1413 indata
["scaleVnfData"]["scaleByStepData"][
1414 "scaling-group-descriptor"
1419 def _check_heal_ns_operation(self
, indata
, nsr
):
1422 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1423 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1427 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1428 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1429 for in_vnf
in get_iterable(indata
.get("vnf")):
1430 member_vnf_index
= in_vnf
["member-vnf-index"]
1431 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1432 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1434 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1435 member_vnf_index
, nsr
["_id"]
1437 vnf_member_index_to_vnfd
[
1439 ] = vnfd
# add to cache, avoiding a later look for
1440 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1441 if in_vnf
.get("vimAccountId"):
1442 self
._check
_valid
_vim
_account
(
1443 in_vnf
["vimAccountId"], vim_accounts
, session
1446 for in_vld
in get_iterable(indata
.get("vld")):
1447 self
._check
_valid
_wim
_account
(
1448 in_vld
.get("wimAccountId"), wim_accounts
, session
1450 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1451 if in_vld
["name"] == vldd
["id"]:
1454 raise EngineException(
1455 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1460 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1461 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1462 vnfr
= self
.db
.get_one(
1464 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1465 fail_on_empty
=False,
1468 raise EngineException(
1469 "Invalid parameter member_vnf_index='{}' is not one of the "
1470 "nsd:constituent-vnfd".format(member_vnf_index
)
1473 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1474 if "revision" in vnfr
:
1475 vnfd_revision
= vnfr
["vnfd-id"] + ":" + str(vnfr
["revision"])
1476 vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": vnfd_revision
}, fail_on_empty
=False)
1478 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
1481 raise EngineException(
1482 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1488 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1489 for vdud
in get_iterable(vnfd
.get("vdu")):
1490 if vdud
["id"] == vdu_id
:
1493 raise EngineException(
1494 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1499 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1500 for kdud
in get_iterable(vnfd
.get("kdu")):
1501 if kdud
["name"] == kdu_name
:
1504 raise EngineException(
1505 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1510 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1511 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1512 for vdu
in get_iterable(vnfd
.get("vdu")):
1513 if in_vdu
["id"] == vdu
["id"]:
1514 for volume
in get_iterable(in_vdu
.get("volume")):
1515 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1516 if volumed
== volume
["name"]:
1519 raise EngineException(
1520 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1521 "volume:name='{}' is not present at "
1522 "vnfd:vdu:virtual-storage-desc list".format(
1523 in_vnf
["member-vnf-index"],
1529 vdu_if_names
= set()
1530 for cpd
in get_iterable(vdu
.get("int-cpd")):
1531 for iface
in get_iterable(
1532 cpd
.get("virtual-network-interface-requirement")
1534 vdu_if_names
.add(iface
.get("name"))
1536 for in_iface
in get_iterable(in_vdu
.get("interface")):
1537 if in_iface
["name"] in vdu_if_names
:
1540 raise EngineException(
1541 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1542 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1543 in_vnf
["member-vnf-index"],
1551 raise EngineException(
1552 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1553 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1557 ivld
.get("id"): set()
1558 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1560 for vdu
in get_iterable(vnfd
.get("vdu")):
1561 for cpd
in get_iterable(vnfd
.get("int-cpd")):
1562 if cpd
.get("int-virtual-link-desc"):
1563 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1565 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1566 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1567 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1568 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1571 raise EngineException(
1572 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1573 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1574 "vnfd:internal-vld:name/id:internal-connection-point".format(
1575 in_vnf
["member-vnf-index"],
1581 raise EngineException(
1582 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1583 " is not present at vnfd '{}'".format(
1584 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1588 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1589 if vim_account
in vim_accounts
:
1592 db_filter
= self
._get
_project
_filter
(session
)
1593 db_filter
["_id"] = vim_account
1594 self
.db
.get_one("vim_accounts", db_filter
)
1596 raise EngineException(
1597 "Invalid vimAccountId='{}' not present for the project".format(
1601 vim_accounts
.append(vim_account
)
1603 def _get_vim_account(self
, vim_id
: str, session
):
1605 db_filter
= self
._get
_project
_filter
(session
)
1606 db_filter
["_id"] = vim_id
1607 return self
.db
.get_one("vim_accounts", db_filter
)
1609 raise EngineException(
1610 "Invalid vimAccountId='{}' not present for the project".format(
1615 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1616 if not isinstance(wim_account
, str):
1618 if wim_account
in wim_accounts
:
1621 db_filter
= self
._get
_project
_filter
(session
)
1622 db_filter
["_id"] = wim_account
1623 self
.db
.get_one("wim_accounts", db_filter
)
1625 raise EngineException(
1626 "Invalid wimAccountId='{}' not present for the project".format(
1630 wim_accounts
.append(wim_account
)
1633 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1636 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1637 (ip_address, ...) information.
1638 Modifies PDU _admin.usageState to 'IN_USE'
1639 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1640 :param rollback: list with the database modifications to rollback if needed
1641 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1642 :param vim_account: vim_account where this vnfr should be deployed
1643 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1644 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1645 of the changed vnfr is needed
1647 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1648 "vim-network-name": used at VIM
1649 "name": interface name
1650 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1651 "ns-vld-id": NSD vld where this interface is connected.
1652 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1655 ifaces_forcing_vim_network
= []
1656 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1657 if not vdur
.get("pdu-type"):
1659 pdu_type
= vdur
.get("pdu-type")
1660 pdu_filter
= self
._get
_project
_filter
(session
)
1661 pdu_filter
["vim_accounts"] = vim_account
1662 pdu_filter
["type"] = pdu_type
1663 pdu_filter
["_admin.operationalState"] = "ENABLED"
1664 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1665 # TODO feature 1417: "shared": True,
1667 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1668 for pdu
in available_pdus
:
1669 # step 1 check if this pdu contains needed interfaces:
1670 match_interfaces
= True
1671 for vdur_interface
in vdur
["interfaces"]:
1672 for pdu_interface
in pdu
["interfaces"]:
1673 if pdu_interface
["name"] == vdur_interface
["name"]:
1674 # TODO feature 1417: match per mgmt type
1676 else: # no interface found for name
1677 match_interfaces
= False
1679 if match_interfaces
:
1682 raise EngineException(
1683 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1687 vnfr
["member-vnf-index-ref"],
1692 # step 2. Update pdu
1694 "_admin.usageState": pdu
["_admin"]["usageState"],
1695 "_admin.usage.vnfr_id": None,
1696 "_admin.usage.nsr_id": None,
1697 "_admin.usage.vdur": None,
1701 {"_id": pdu
["_id"]},
1703 "_admin.usageState": "IN_USE",
1705 "vnfr_id": vnfr
["_id"],
1706 "nsr_id": vnfr
["nsr-id-ref"],
1707 "vdur": vdur
["vdu-id-ref"],
1716 "content": rollback_pdu
,
1720 # step 3. Fill vnfr info by filling vdur
1721 vdu_text
= "vdur.{}".format(vdur_index
)
1722 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1723 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1724 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1725 for pdu_interface
in pdu
["interfaces"]:
1726 if pdu_interface
["name"] == vdur_interface
["name"]:
1727 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1728 for k
, v
in pdu_interface
.items():
1732 ): # TODO: switch-xxxxx must be inserted
1733 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1734 vnfr_update_rollback
[
1735 iface_text
+ ".{}".format(k
)
1736 ] = vdur_interface
.get(v
)
1737 if pdu_interface
.get("ip-address"):
1738 if vdur_interface
.get(
1740 ) or vdur_interface
.get("mgmt-vnf"):
1741 vnfr_update_rollback
[
1742 vdu_text
+ ".ip-address"
1743 ] = vdur
.get("ip-address")
1744 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1747 if vdur_interface
.get("mgmt-vnf"):
1748 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1751 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1752 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1755 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1758 ifaces_forcing_vim_network
.append(
1760 "name": vdur_interface
.get("vnf-vld-id")
1761 or vdur_interface
.get("ns-vld-id"),
1762 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1763 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1766 if pdu_interface
.get("vim-network-id"):
1767 ifaces_forcing_vim_network
[-1][
1769 ] = pdu_interface
["vim-network-id"]
1770 if pdu_interface
.get("vim-network-name"):
1771 ifaces_forcing_vim_network
[-1][
1773 ] = pdu_interface
["vim-network-name"]
1776 return ifaces_forcing_vim_network
1778 def _look_for_k8scluster(
1779 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1782 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1783 Fills vnfr.kdur with the selected k8scluster
1785 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1786 :param rollback: list with the database modifications to rollback if needed
1787 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1788 :param vim_account: vim_account where this vnfr should be deployed
1789 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1790 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1791 of the changed vnfr is needed
1793 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1794 "vim-network-name": used at VIM
1795 "name": interface name
1796 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1797 "ns-vld-id": NSD vld where this interface is connected.
1798 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1801 ifaces_forcing_vim_network
= []
1802 if not vnfr
.get("kdur"):
1803 return ifaces_forcing_vim_network
1805 kdu_filter
= self
._get
_project
_filter
(session
)
1806 kdu_filter
["vim_account"] = vim_account
1807 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1808 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1810 k8s_requirements
= {} # just for logging
1811 for k8scluster
in available_k8sclusters
:
1812 if not vnfr
.get("k8s-cluster"):
1815 if vnfr
["k8s-cluster"].get("cni"):
1816 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1817 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1818 k8scluster
.get("cni", ())
1821 # restrict by version
1822 if vnfr
["k8s-cluster"].get("version"):
1823 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1824 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1826 # restrict by number of networks
1827 if vnfr
["k8s-cluster"].get("nets"):
1828 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1829 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1830 vnfr
["k8s-cluster"]["nets"]
1835 raise EngineException(
1836 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1837 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1841 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1842 # step 3. Fill vnfr info by filling kdur
1843 kdu_text
= "kdur.{}.".format(kdur_index
)
1844 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1845 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1847 # step 4. Check VIM networks that forces the selected k8s_cluster
1848 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1849 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1850 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1851 # get a network from k8s_cluster nets. If name matches use this, if not use other
1852 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1853 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1854 k8scluster_net_list
.remove(kdur_net
["id"])
1856 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1857 k8scluster_net_list
.pop(0)
1858 vnfr_update_rollback
[
1859 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1861 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1863 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1865 ifaces_forcing_vim_network
.append(
1867 "name": kdur_net
.get("vnf-vld-id")
1868 or kdur_net
.get("ns-vld-id"),
1869 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1870 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1871 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1874 # TODO check that this forcing is not incompatible with other forcing
1875 return ifaces_forcing_vim_network
1877 def _update_vnfrs_from_nsd(self
, nsr
):
1882 step
= "Getting vnf_profiles from nsd"
1883 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
1884 vld_fixed_ip_connection_point_data
= {}
1886 step
= "Getting ip-address info from vnf_profile if it exists"
1887 for vnfp
in vnf_profiles
:
1888 # Checking ip-address info from nsd.vnf_profile and storing
1889 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
1890 for cpd
in vlc
.get("constituent-cpd-id", ()):
1891 if cpd
.get("ip-address"):
1892 step
= "Storing ip-address info"
1893 vld_fixed_ip_connection_point_data
.update({vlc
.get("virtual-link-profile-id") + '.' + cpd
.get("constituent-base-element-id"): {
1894 "vnfd-connection-point-ref": cpd
.get(
1895 "constituent-cpd-id"),
1896 "ip-address": cpd
.get(
1899 # Inserting ip address to vnfr
1900 if len(vld_fixed_ip_connection_point_data
) > 0:
1901 step
= "Getting vnfrs"
1902 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1903 for item
in vld_fixed_ip_connection_point_data
.keys():
1904 step
= "Filtering vnfrs"
1905 vnfr
= next(filter(lambda vnfr
: vnfr
["member-vnf-index-ref"] == item
.split('.')[1], vnfrs
), None)
1908 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1909 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1910 step
= "Looking for matched interface"
1912 iface
.get("external-connection-point-ref")
1913 == vld_fixed_ip_connection_point_data
[item
].get("vnfd-connection-point-ref") and
1914 iface
.get("ns-vld-id") == item
.split('.')[0]
1917 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1918 vdur_index
, iface_index
1920 step
= "Storing info in order to update vnfr"
1922 vnfr_update_text
+ ".ip-address"
1923 ] = increment_ip_mac(
1924 vld_fixed_ip_connection_point_data
[item
].get("ip-address"),
1925 vdur
.get("count-index", 0), )
1926 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1928 step
= "updating vnfr at database"
1929 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1937 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
1939 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1942 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1946 vnfr_update_rollback
= {}
1947 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1948 # update vim-account-id
1950 vim_account
= indata
["vimAccountId"]
1951 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1952 # check instantiate parameters
1953 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1954 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1956 if vnf_inst_params
.get("vimAccountId"):
1957 vim_account
= vnf_inst_params
.get("vimAccountId")
1958 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1960 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1961 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1962 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1963 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1965 for iface_inst_param
in get_iterable(
1966 vdu_inst_param
.get("interface")
1968 iface_index
, _
= next(
1970 for i
in enumerate(vdur
["interfaces"])
1971 if i
[1]["name"] == iface_inst_param
["name"]
1973 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1974 vdur_index
, iface_index
1976 if iface_inst_param
.get("ip-address"):
1978 vnfr_update_text
+ ".ip-address"
1979 ] = increment_ip_mac(
1980 iface_inst_param
.get("ip-address"),
1981 vdur
.get("count-index", 0),
1983 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1984 if iface_inst_param
.get("mac-address"):
1986 vnfr_update_text
+ ".mac-address"
1987 ] = increment_ip_mac(
1988 iface_inst_param
.get("mac-address"),
1989 vdur
.get("count-index", 0),
1991 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1992 if iface_inst_param
.get("floating-ip-required"):
1994 vnfr_update_text
+ ".floating-ip-required"
1996 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1997 # TODO update vld with the ip-profile
1998 for ivld_inst_param
in get_iterable(
1999 vnf_inst_params
.get("internal-vld")
2001 for icp_inst_param
in get_iterable(
2002 ivld_inst_param
.get("internal-connection-point")
2005 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2006 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2008 iface
.get("internal-connection-point-ref")
2009 == icp_inst_param
["id-ref"]
2011 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2012 vdur_index
, iface_index
2014 if icp_inst_param
.get("ip-address"):
2016 vnfr_update_text
+ ".ip-address"
2017 ] = increment_ip_mac(
2018 icp_inst_param
.get("ip-address"),
2019 vdur
.get("count-index", 0),
2022 vnfr_update_text
+ ".fixed-ip"
2024 if icp_inst_param
.get("mac-address"):
2026 vnfr_update_text
+ ".mac-address"
2027 ] = increment_ip_mac(
2028 icp_inst_param
.get("mac-address"),
2029 vdur
.get("count-index", 0),
2032 vnfr_update_text
+ ".fixed-mac"
2035 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2036 for vld_inst_param
in get_iterable(indata
.get("vld")):
2037 for vnfcp_inst_param
in get_iterable(
2038 vld_inst_param
.get("vnfd-connection-point-ref")
2040 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
2043 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2044 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2046 iface
.get("external-connection-point-ref")
2047 == vnfcp_inst_param
["vnfd-connection-point-ref"]
2049 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2050 vdur_index
, iface_index
2052 if vnfcp_inst_param
.get("ip-address"):
2054 vnfr_update_text
+ ".ip-address"
2055 ] = increment_ip_mac(
2056 vnfcp_inst_param
.get("ip-address"),
2057 vdur
.get("count-index", 0),
2059 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2060 if vnfcp_inst_param
.get("mac-address"):
2062 vnfr_update_text
+ ".mac-address"
2063 ] = increment_ip_mac(
2064 vnfcp_inst_param
.get("mac-address"),
2065 vdur
.get("count-index", 0),
2067 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2070 vnfr_update
["vim-account-id"] = vim_account
2071 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
2074 vnfr_update
["vca-id"] = vca_id
2075 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
2078 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
2079 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2083 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
2084 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2086 # update database vnfr
2087 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2093 "content": vnfr_update_rollback
,
2097 # Update indada in case pdu forces to use a concrete vim-network-name
2098 # TODO check if user has already insert a vim-network-name and raises an error
2099 if not ifaces_forcing_vim_network
:
2101 for iface_info
in ifaces_forcing_vim_network
:
2102 if iface_info
.get("ns-vld-id"):
2103 if "vld" not in indata
:
2105 indata
["vld"].append(
2107 key
: iface_info
[key
]
2108 for key
in ("name", "vim-network-name", "vim-network-id")
2109 if iface_info
.get(key
)
2113 elif iface_info
.get("vnf-vld-id"):
2114 if "vnf" not in indata
:
2116 indata
["vnf"].append(
2118 "member-vnf-index": member_vnf_index
,
2121 key
: iface_info
[key
]
2127 if iface_info
.get(key
)
2134 def _create_nslcmop(nsr_id
, operation
, params
):
2136 Creates a ns-lcm-opp content to be stored at database.
2137 :param nsr_id: internal id of the instance
2138 :param operation: instantiate, terminate, scale, action, update ...
2139 :param params: user parameters for the operation
2140 :return: dictionary following SOL005 format
2147 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2148 "queuePosition": None,
2150 "errorMessage": None,
2151 "detailedStatus": None,
2152 "statusEnteredTime": now
,
2153 "nsInstanceId": nsr_id
,
2154 "lcmOperationType": operation
,
2156 "isAutomaticInvocation": False,
2157 "operationParams": params
,
2158 "isCancelPending": False,
2160 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2161 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2166 def _get_enabled_vims(self
, session
):
2168 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2169 :param session: current session with user information
2171 db_filter
= self
._get
_project
_filter
(session
)
2172 db_filter
["_admin.operationalState"] = "ENABLED"
2173 vims
= self
.db
.get_list("vim_accounts", db_filter
)
2176 vimAccounts
.append(vim
["_id"])
2189 Performs a new operation over a ns
2190 :param rollback: list to append created items at database in case a rollback must to be done
2191 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2192 :param indata: descriptor with the parameters of the operation. It must contains among others
2193 nsInstanceId: _id of the nsr to perform the operation
2194 operation: it can be: instantiate, terminate, action, update TODO: heal
2195 :param kwargs: used to override the indata descriptor
2196 :param headers: http request headers
2197 :return: id of the nslcmops
2200 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
2202 db_filter
= self
._get
_project
_filter
(session
)
2203 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2204 nsis
= self
.db
.get_one(
2205 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
2208 raise EngineException(
2209 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2212 http_code
=HTTPStatus
.CONFLICT
,
2216 # Override descriptor with query string kwargs
2217 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2218 operation
= indata
["lcmOperationType"]
2219 nsInstanceId
= indata
["nsInstanceId"]
2221 validate_input(indata
, self
.operation_schema
[operation
])
2222 # get ns from nsr_id
2223 _filter
= BaseTopic
._get
_project
_filter
(session
)
2224 _filter
["_id"] = nsInstanceId
2225 nsr
= self
.db
.get_one("nsrs", _filter
)
2228 if operation
== "terminate" and slice_object
is False:
2229 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
2231 not nsr
["_admin"].get("nsState")
2232 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
2234 if operation
== "terminate" and indata
.get("autoremove"):
2235 # NSR must be deleted
2239 ) # a none in this case is used to indicate not instantiated. It can be removed
2240 if operation
!= "instantiate":
2241 raise EngineException(
2242 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2243 nsInstanceId
, operation
2245 HTTPStatus
.CONFLICT
,
2248 if operation
== "instantiate" and not session
["force"]:
2249 raise EngineException(
2250 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2251 nsInstanceId
, operation
2253 HTTPStatus
.CONFLICT
,
2255 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
2256 if (indata
.get("primitive_params")):
2257 indata
["primitive_params"] = json
.dumps(indata
["primitive_params"])
2258 elif (indata
.get("additionalParamsForVnf")):
2259 indata
["additionalParamsForVnf"] = json
.dumps(indata
["additionalParamsForVnf"])
2261 if operation
== "instantiate":
2262 self
._update
_vnfrs
_from
_nsd
(nsr
)
2263 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
2264 if (operation
== "update") and (indata
["updateType"] == "CHANGE_VNFPKG"):
2266 vnfd_id
= indata
["changeVnfPackageData"]["vnfdId"]
2267 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2268 nsd
= self
.db
.get_one("nsds", {"_id": nsr
["nsd-id"]})
2269 ns_request
= nsr
["instantiate_params"]
2270 vnfr
= self
.db
.get_one("vnfrs", {"_id": indata
["changeVnfPackageData"]["vnfInstanceId"]})
2271 latest_vnfd_revision
= vnfd
["_admin"].get("revision", 1)
2272 vnfr_vnfd_revision
= vnfr
.get("revision", 1)
2273 if latest_vnfd_revision
!= vnfr_vnfd_revision
:
2274 old_vnfd_id
= vnfd_id
+ ":" + str(vnfr_vnfd_revision
)
2275 old_db_vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": old_vnfd_id
})
2276 old_sw_version
= old_db_vnfd
.get("software-version", "1.0")
2277 new_sw_version
= vnfd
.get("software-version", "1.0")
2278 if new_sw_version
!= old_sw_version
:
2279 vnf_index
= vnfr
["member-vnf-index-ref"]
2280 self
.logger
.info("nsr {}".format(nsr
))
2281 for vdu
in vnfd
["vdu"]:
2282 self
.nsrtopic
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr
, vnf_index
, latest_vnfd_revision
)
2283 sw_image_id
= vdu
.get("sw-image-desc")
2285 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
2286 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2287 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
2288 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
2289 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2290 nsr_update
["image"] = nsr
["image"]
2291 nsr_update
["flavor"] = nsr
["flavor"]
2292 self
.db
.set_one("nsrs", {"_id": nsr
["_id"]}, nsr_update
)
2293 ns_k8s_namespace
= self
.nsrtopic
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
2294 vnfr_descriptor
= self
.nsrtopic
._create
_vnfr
_descriptor
_from
_vnfd
(
2302 latest_vnfd_revision
,
2304 indata
["newVdur"] = vnfr_descriptor
["vdur"]
2305 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
2306 _id
= nslcmop_desc
["_id"]
2308 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2310 if indata
.get("placement-engine"):
2311 # Save valid vim accounts in lcm operation descriptor
2312 nslcmop_desc
["operationParams"][
2314 ] = self
._get
_enabled
_vims
(session
)
2315 self
.db
.create("nslcmops", nslcmop_desc
)
2316 rollback
.append({"topic": "nslcmops", "_id": _id
})
2317 if not slice_object
:
2318 self
.msg
.write("ns", operation
, nslcmop_desc
)
2320 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2321 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2322 # except DbException as e:
2323 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2325 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2326 raise EngineException(
2327 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2330 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2331 raise EngineException(
2332 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2336 class NsiTopic(BaseTopic
):
2339 quota_name
= "slice_instances"
2341 def __init__(self
, db
, fs
, msg
, auth
):
2342 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2343 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2346 def _format_ns_request(ns_request
):
2347 formated_request
= copy(ns_request
)
2348 # TODO: Add request params
2349 return formated_request
2352 def _format_addional_params(slice_request
):
2354 Get and format user additional params for NS or VNF
2355 :param slice_request: User instantiation additional parameters
2356 :return: a formatted copy of additional params or None if not supplied
2358 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2359 if additional_params
:
2360 for k
, v
in additional_params
.items():
2361 if not isinstance(k
, str):
2362 raise EngineException(
2363 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2367 if "." in k
or "$" in k
:
2368 raise EngineException(
2369 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2373 if isinstance(v
, (dict, tuple, list)):
2374 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2375 return additional_params
2377 def _check_descriptor_dependencies(self
, session
, descriptor
):
2379 Check that the dependent descriptors exist on a new descriptor or edition
2380 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2381 :param descriptor: descriptor to be inserted or edit
2382 :return: None or raises exception
2384 if not descriptor
.get("nst-ref"):
2386 nstd_id
= descriptor
["nst-ref"]
2387 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
2388 raise EngineException(
2389 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2392 http_code
=HTTPStatus
.CONFLICT
,
2395 def check_conflict_on_del(self
, session
, _id
, db_content
):
2397 Check that NSI is not instantiated
2398 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2399 :param _id: nsi internal id
2400 :param db_content: The database content of the _id
2401 :return: None or raises EngineException with the conflict
2403 if session
["force"]:
2406 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2407 raise EngineException(
2408 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2409 "Launch 'terminate' operation first; or force deletion".format(_id
),
2410 http_code
=HTTPStatus
.CONFLICT
,
2413 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2415 Deletes associated nsilcmops from database. Deletes associated filesystem.
2416 Set usageState of nst
2417 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2418 :param _id: server internal id
2419 :param db_content: The database content of the descriptor
2420 :param not_send_msg: To not send message (False) or store content (list) instead
2421 :return: None if ok or raises EngineException with the problem
2424 # Deleting the nsrs belonging to nsir
2426 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2427 nsr_id
= nsrs_detailed_item
["nsrId"]
2428 if nsrs_detailed_item
.get("shared"):
2430 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2431 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2432 "_id.ne": nsir
["_id"],
2434 nsi
= self
.db
.get_one(
2435 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2437 if nsi
: # last one using nsr
2440 self
.nsrTopic
.delete(
2441 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2443 except (DbException
, EngineException
) as e
:
2444 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2449 # delete related nsilcmops database entries
2450 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2452 # Check and set used NST usage state
2453 nsir_admin
= nsir
.get("_admin")
2454 if nsir_admin
and nsir_admin
.get("nst-id"):
2455 # check if used by another NSI
2456 nsis_list
= self
.db
.get_one(
2458 {"nst-id": nsir_admin
["nst-id"]},
2459 fail_on_empty
=False,
2465 {"_id": nsir_admin
["nst-id"]},
2466 {"_admin.usageState": "NOT_IN_USE"},
2469 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2471 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2472 :param rollback: list to append the created items at database in case a rollback must be done
2473 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2474 :param indata: params to be used for the nsir
2475 :param kwargs: used to override the indata descriptor
2476 :param headers: http request headers
2477 :return: the _id of nsi descriptor created at database
2481 step
= "checking quotas"
2482 self
.check_quota(session
)
2485 slice_request
= self
._remove
_envelop
(indata
)
2486 # Override descriptor with query string kwargs
2487 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2488 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2491 step
= "getting nstd id='{}' from database".format(
2492 slice_request
.get("nstId")
2494 _filter
= self
._get
_project
_filter
(session
)
2495 _filter
["_id"] = slice_request
["nstId"]
2496 nstd
= self
.db
.get_one("nsts", _filter
)
2497 # check NST is not disabled
2498 step
= "checking NST operationalState"
2499 if nstd
["_admin"]["operationalState"] == "DISABLED":
2500 raise EngineException(
2501 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2502 "instance".format(slice_request
["nstId"]),
2503 http_code
=HTTPStatus
.CONFLICT
,
2507 # check NSD is not disabled
2508 step
= "checking operationalState"
2509 if nstd
["_admin"]["operationalState"] == "DISABLED":
2510 raise EngineException(
2511 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2512 "a network slice".format(slice_request
["nstId"]),
2513 http_code
=HTTPStatus
.CONFLICT
,
2516 nstd
.pop("_admin", None)
2517 nstd_id
= nstd
.pop("_id", None)
2518 nsi_id
= str(uuid4())
2519 step
= "filling nsi_descriptor with input data"
2524 "name": slice_request
["nsiName"],
2525 "description": slice_request
.get("nsiDescription", ""),
2526 "datacenter": slice_request
["vimAccountId"],
2527 "nst-ref": nstd
["id"],
2528 "instantiation_parameters": slice_request
,
2529 "network-slice-template": nstd
,
2533 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2536 step
= "creating nsi at database"
2538 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2540 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2541 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2542 nsi_descriptor
["_admin"]["deployed"] = {}
2543 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2544 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2546 # Creating netslice-vld for the RO.
2547 step
= "creating netslice-vld at database"
2549 # Building the vlds list to be deployed
2550 # From netslice descriptors, creating the initial list
2553 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2554 # Getting template Instantiation parameters from NST
2555 nsi_vld
= deepcopy(netslice_vlds
)
2556 nsi_vld
["shared-nsrs-list"] = []
2557 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2558 nsi_vlds
.append(nsi_vld
)
2560 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2561 # Creating netslice-subnet_record.
2565 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2566 for member_ns
in nstd
["netslice-subnet"]:
2567 nsd_id
= member_ns
["nsd-ref"]
2568 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2569 member_ns
["nsd-ref"], member_ns
["id"]
2571 if nsd_id
not in needed_nsds
:
2573 _filter
["id"] = nsd_id
2574 nsd
= self
.db
.get_one(
2575 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2579 needed_nsds
[nsd_id
] = nsd
2581 nsd
= needed_nsds
[nsd_id
]
2582 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2583 services
.append(member_ns
)
2585 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2586 member_ns
["nsd-ref"], member_ns
["id"]
2589 # creates Network Services records (NSRs)
2590 step
= "creating nsrs at database using NsrTopic.new()"
2591 ns_params
= slice_request
.get("netslice-subnet")
2593 nsi_netslice_subnet
= []
2594 for service
in services
:
2595 # Check if the netslice-subnet is shared and if it is share if the nss exists
2598 # Is the nss shared and instantiated?
2599 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2600 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2603 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2604 nsi
= self
.db
.get_one(
2605 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2607 if nsi
and service
.get("is-shared-nss"):
2608 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2609 for nsrs_detailed_item
in nsrs_detailed_list
:
2610 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2611 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2612 _id_nsr
= nsrs_detailed_item
["nsrId"]
2614 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2615 if netslice_subnet
["nss-id"] == service
["id"]:
2616 indata_ns
= netslice_subnet
2620 if service
.get("instantiation-parameters"):
2621 indata_ns
= deepcopy(service
["instantiation-parameters"])
2622 # del service["instantiation-parameters"]
2624 indata_ns
["nsdId"] = service
["_id"]
2625 indata_ns
["nsName"] = (
2626 slice_request
.get("nsiName") + "." + service
["id"]
2628 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2629 indata_ns
["nsDescription"] = service
["description"]
2630 if slice_request
.get("ssh_keys"):
2631 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2634 for ns_param
in ns_params
:
2635 if ns_param
.get("id") == service
["id"]:
2636 copy_ns_param
= deepcopy(ns_param
)
2637 del copy_ns_param
["id"]
2638 indata_ns
.update(copy_ns_param
)
2641 # Creates Nsr objects
2642 _id_nsr
, _
= self
.nsrTopic
.new(
2643 rollback
, session
, indata_ns
, kwargs
, headers
2647 "shared": service
.get("is-shared-nss"),
2648 "nsd-id": service
["nsd-ref"],
2649 "nss-id": service
["id"],
2650 "nslcmop_instantiate": None,
2652 indata_ns
["nss-id"] = service
["id"]
2653 nsrs_list
.append(nsrs_item
)
2654 nsi_netslice_subnet
.append(indata_ns
)
2655 nsr_ref
= {"nsr-ref": _id_nsr
}
2656 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2658 # Adding the nsrs list to the nsi
2659 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2660 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2662 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2665 # Creating the entry in the database
2666 self
.db
.create("nsis", nsi_descriptor
)
2667 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2669 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2670 self
.logger
.exception(
2671 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2673 raise EngineException("Error {}: {}".format(step
, e
))
2674 except ValidationError
as e
:
2675 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2677 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2678 raise EngineException(
2679 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2683 class NsiLcmOpTopic(BaseTopic
):
2686 operation_schema
= { # mapping between operation and jsonschema to validate
2687 "instantiate": nsi_instantiate
,
2691 def __init__(self
, db
, fs
, msg
, auth
):
2692 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2693 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2695 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2697 Check that user has enter right parameters for the operation
2698 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2699 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2700 :param indata: descriptor with the parameters of the operation
2704 nstd
= nsir
["network-slice-template"]
2706 def check_valid_netslice_subnet_id(nstId
):
2707 # TODO change to vnfR (??)
2708 for netslice_subnet
in nstd
["netslice-subnet"]:
2709 if nstId
== netslice_subnet
["id"]:
2710 nsd_id
= netslice_subnet
["nsd-ref"]
2711 if nsd_id
not in nsds
:
2712 _filter
= self
._get
_project
_filter
(session
)
2713 _filter
["id"] = nsd_id
2714 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2717 raise EngineException(
2718 "Invalid parameter nstId='{}' is not one of the "
2719 "nst:netslice-subnet".format(nstId
)
2722 if operation
== "instantiate":
2723 # check the existance of netslice-subnet items
2724 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2725 check_valid_netslice_subnet_id(in_nst
["id"])
2727 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2733 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2734 "statusEnteredTime": now
,
2735 "netsliceInstanceId": netsliceInstanceId
,
2736 "lcmOperationType": operation
,
2738 "isAutomaticInvocation": False,
2739 "operationParams": params
,
2740 "isCancelPending": False,
2742 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2743 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2744 + netsliceInstanceId
,
2749 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2750 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2751 if nst_sb_item
.get("is-shared-nss"):
2752 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2753 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2754 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2755 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2756 "nss-connection-point-ref"
2759 admin_subnet_item
["nss-id"]
2760 == admin_vld_nss_cp_ref_item
["nss-ref"]
2763 not nsr_item
["nsrId"]
2764 in admin_vld_item
["shared-nsrs-list"]
2766 admin_vld_item
["shared-nsrs-list"].append(
2770 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2773 {"_id": nsir
["_id"]},
2774 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2777 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2779 Performs a new operation over a ns
2780 :param rollback: list to append created items at database in case a rollback must to be done
2781 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2782 :param indata: descriptor with the parameters of the operation. It must contains among others
2783 netsliceInstanceId: _id of the nsir to perform the operation
2784 operation: it can be: instantiate, terminate, action, TODO: update, heal
2785 :param kwargs: used to override the indata descriptor
2786 :param headers: http request headers
2787 :return: id of the nslcmops
2790 # Override descriptor with query string kwargs
2791 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2792 operation
= indata
["lcmOperationType"]
2793 netsliceInstanceId
= indata
["netsliceInstanceId"]
2794 validate_input(indata
, self
.operation_schema
[operation
])
2796 # get nsi from netsliceInstanceId
2797 _filter
= self
._get
_project
_filter
(session
)
2798 _filter
["_id"] = netsliceInstanceId
2799 nsir
= self
.db
.get_one("nsis", _filter
)
2800 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2805 not nsir
["_admin"].get("nsiState")
2806 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2808 if operation
== "terminate" and indata
.get("autoremove"):
2809 # NSIR must be deleted
2813 ) # a none in this case is used to indicate not instantiated. It can be removed
2814 if operation
!= "instantiate":
2815 raise EngineException(
2816 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2817 netsliceInstanceId
, operation
2819 HTTPStatus
.CONFLICT
,
2822 if operation
== "instantiate" and not session
["force"]:
2823 raise EngineException(
2824 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2825 netsliceInstanceId
, operation
2827 HTTPStatus
.CONFLICT
,
2830 # Creating all the NS_operation (nslcmop)
2831 # Get service list from db
2832 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2834 # nslcmops_item = None
2835 for index
, nsr_item
in enumerate(nsrs_list
):
2836 nsr_id
= nsr_item
["nsrId"]
2837 if nsr_item
.get("shared"):
2838 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2839 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2841 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2843 _filter
["_id.ne"] = netsliceInstanceId
2844 nsi
= self
.db
.get_one(
2845 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2847 if operation
== "terminate":
2849 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2853 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2856 ): # other nsi is using this nsr and it needs this nsr instantiated
2857 continue # do not create nsilcmop
2859 # looks the first nsi fulfilling the conditions but not being the current NSIR
2861 nsi_nsr_item
= next(
2863 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2864 if n
["nsrId"] == nsr_id
2866 and n
["nslcmop_instantiate"]
2868 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2869 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2871 "_admin.nsrs-detailed-list.{}".format(
2875 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2876 # continue to not create nslcmop since nsrs is shared and nsrs was created
2879 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2884 "lcmOperationType": operation
,
2885 "nsInstanceId": nsr_id
,
2886 # Including netslice_id in the ns instantiate Operation
2887 "netsliceInstanceId": netsliceInstanceId
,
2889 if operation
== "instantiate":
2890 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2891 indata_ns
.update(service
["instantiate_params"])
2893 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2894 # message via kafka bus
2895 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2896 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2898 nslcmops
.append(nslcmop
)
2899 if operation
== "instantiate":
2901 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2905 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2906 except (DbException
, EngineException
) as e
:
2907 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2910 + "skipping NS={} because not found".format(nsr_id
)
2917 indata
["nslcmops_ids"] = nslcmops
2918 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2920 nsilcmop_desc
= self
._create
_nsilcmop
(
2921 session
, netsliceInstanceId
, operation
, indata
2924 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2926 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2927 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2928 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2930 except ValidationError
as e
:
2931 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2933 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2934 raise EngineException(
2935 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2938 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2939 raise EngineException(
2940 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR