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 (
33 from osm_nbi
.base_topic
import (
40 from yaml
import safe_dump
41 from osm_common
.dbbase
import DbException
42 from osm_common
.msgbase
import MsgException
43 from osm_common
.fsbase
import FsException
44 from osm_nbi
import utils
47 ) # For checking that additional parameter names are valid Jinja2 identifiers
49 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
52 class NsrTopic(BaseTopic
):
55 quota_name
= "ns_instances"
56 schema_new
= ns_instantiate
58 def __init__(self
, db
, fs
, msg
, auth
):
59 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
61 def _check_descriptor_dependencies(self
, session
, descriptor
):
63 Check that the dependent descriptors exist on a new descriptor or edition
64 :param session: client session information
65 :param descriptor: descriptor to be inserted or edit
66 :return: None or raises exception
68 if not descriptor
.get("nsdId"):
70 nsd_id
= descriptor
["nsdId"]
71 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
72 raise EngineException(
73 "Descriptor error at nsdId='{}' references a non exist nsd".format(
76 http_code
=HTTPStatus
.CONFLICT
,
80 def format_on_new(content
, project_id
=None, make_public
=False):
81 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
82 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
85 def check_conflict_on_del(self
, session
, _id
, db_content
):
87 Check that NSR is not instantiated
88 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
89 :param _id: nsr internal id
90 :param db_content: The database content of the nsr
91 :return: None or raises EngineException with the conflict
96 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
97 raise EngineException(
98 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
99 "Launch 'terminate' operation first; or force deletion".format(_id
),
100 http_code
=HTTPStatus
.CONFLICT
,
103 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
105 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
106 Set usageState of pdu, vnfd, nsd
107 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
108 :param _id: server internal id
109 :param db_content: The database content of the descriptor
110 :param not_send_msg: To not send message (False) or store content (list) instead
111 :return: None if ok or raises EngineException with the problem
113 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
114 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
115 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
117 # set all used pdus as free
120 {"_admin.usage.nsr_id": _id
},
121 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
126 used_nsd_id
= nsr
.get("nsd-id")
128 # check if used by another NSR
129 nsrs_list
= self
.db
.get_one(
130 "nsrs", {"nsd-id": used_nsd_id
}, fail_on_empty
=False, fail_on_more
=False
134 "nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"}
137 # Set VNFD usageState
138 used_vnfd_id_list
= nsr
.get("vnfd-id")
139 if used_vnfd_id_list
:
140 for used_vnfd_id
in used_vnfd_id_list
:
141 # check if used by another NSR
142 nsrs_list
= self
.db
.get_one(
144 {"vnfd-id": used_vnfd_id
},
151 {"_id": used_vnfd_id
},
152 {"_admin.usageState": "NOT_IN_USE"},
155 # delete extra ro_nsrs used for internal RO module
156 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
159 def _format_ns_request(ns_request
):
160 formated_request
= copy(ns_request
)
161 formated_request
.pop("additionalParamsForNs", None)
162 formated_request
.pop("additionalParamsForVnf", None)
163 return formated_request
166 def _format_additional_params(
167 ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None
170 Get and format user additional params for NS or VNF
171 :param ns_request: User instantiation additional parameters
172 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
173 :param descriptor: If not None it check that needed parameters of descriptor are supplied
174 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
176 additional_params
= None
178 if not member_vnf_index
:
179 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
180 where_
= "additionalParamsForNs"
181 elif ns_request
.get("additionalParamsForVnf"):
182 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
188 for x
in ns_request
["additionalParamsForVnf"]
189 if x
["member-vnf-index"] == member_vnf_index
194 if not vdu_id
and not kdu_name
:
196 additional_params
= copy(item
.get("additionalParams")) or {}
197 if vdu_id
and item
.get("additionalParamsForVdu"):
201 for x
in item
["additionalParamsForVdu"]
202 if x
["vdu_id"] == vdu_id
206 other_params
= item_vdu
207 if item_vdu
and item_vdu
.get("additionalParams"):
208 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
209 additional_params
= item_vdu
["additionalParams"]
211 additional_params
= {}
212 if item
.get("additionalParamsForKdu"):
216 for x
in item
["additionalParamsForKdu"]
217 if x
["kdu_name"] == kdu_name
221 other_params
= item_kdu
222 if item_kdu
and item_kdu
.get("additionalParams"):
223 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(
226 additional_params
= item_kdu
["additionalParams"]
228 if additional_params
:
229 for k
, v
in additional_params
.items():
230 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
231 if not kdu_name
and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k
):
232 raise EngineException(
233 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
234 "and underscores, and cannot start with a digit".format(
238 # END Check that additional parameter names are valid Jinja2 identifiers
239 if not isinstance(k
, str):
240 raise EngineException(
241 "Invalid param at {}:{}. Only string keys are allowed".format(
246 raise EngineException(
247 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
251 if isinstance(v
, (dict, tuple, list)):
252 additional_params
[k
] = "!!yaml " + safe_dump(v
)
254 additional_params
= json
.dumps(additional_params
)
257 for df
in descriptor
.get("df", []):
258 # check that enough parameters are supplied for the initial-config-primitive
259 # TODO: check for cloud-init
261 initial_primitives
= []
263 "lcm-operations-configuration" in df
264 and "operate-vnf-op-config"
265 in df
["lcm-operations-configuration"]
267 for config
in df
["lcm-operations-configuration"][
268 "operate-vnf-op-config"
270 for primitive
in get_iterable(
271 config
.get("initial-config-primitive")
273 initial_primitives
.append(primitive
)
275 initial_primitives
= deep_get(
276 descriptor
, ("ns-configuration", "initial-config-primitive")
279 for initial_primitive
in get_iterable(initial_primitives
):
280 for param
in get_iterable(initial_primitive
.get("parameter")):
281 if param
["value"].startswith("<") and param
["value"].endswith(
284 if param
["value"] in (
291 not additional_params
292 or param
["value"][1:-1] not in additional_params
294 raise EngineException(
295 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
296 "initial-config-primitive[name={}] not supplied".format(
299 initial_primitive
["name"],
303 return additional_params
or None, other_params
or None
305 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
307 Creates a new nsr into database. It also creates needed vnfrs
308 :param rollback: list to append the created items at database in case a rollback must be done
309 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
310 :param indata: params to be used for the nsr
311 :param kwargs: used to override the indata descriptor
312 :param headers: http request headers
313 :return: the _id of nsr descriptor created at database. Or an exception of type
314 EngineException, ValidationError, DbException, FsException, MsgException.
315 Note: Exceptions are not captured on purpose. They should be captured at called
318 step
= "checking quotas"
319 self
.check_quota(session
)
321 step
= "validating input parameters"
322 ns_request
= self
._remove
_envelop
(indata
)
323 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
324 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
326 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
327 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
328 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
330 step
= "checking nsdOperationalState"
331 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
333 step
= "filling nsr from input data"
334 nsr_id
= str(uuid4())
335 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(
336 nsd
, ns_request
, nsr_id
, session
341 # TODO: Change for multiple df support
342 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
343 for vnfp
in vnf_profiles
:
344 vnfd_id
= vnfp
.get("vnfd-id")
345 vnf_index
= vnfp
.get("id")
347 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
351 if vnfd_id
not in needed_vnfds
:
352 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
353 if "revision" in vnfd
["_admin"]:
354 vnfd
["revision"] = vnfd
["_admin"]["revision"]
356 needed_vnfds
[vnfd_id
] = vnfd
357 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
359 vnfd
= needed_vnfds
[vnfd_id
]
361 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
364 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(
374 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
377 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
378 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
380 step
= "creating nsr at database"
381 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
383 step
= "creating nsr temporal folder"
384 self
.fs
.mkdir(nsr_id
)
394 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
396 def _get_nsd_from_db(self
, nsd_id
, session
):
397 _filter
= self
._get
_project
_filter
(session
)
398 _filter
["_id"] = nsd_id
399 return self
.db
.get_one("nsds", _filter
)
401 def _get_vnfd_from_db(self
, vnfd_id
, session
):
402 _filter
= self
._get
_project
_filter
(session
)
403 _filter
["id"] = vnfd_id
404 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
407 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
409 nsr_descriptor
, session
["project_id"], make_public
=session
["public"]
411 self
.db
.create("nsrs", nsr_descriptor
)
412 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
414 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
416 vnfr_descriptor
, session
["project_id"], make_public
=session
["public"]
418 self
.db
.create("vnfrs", vnfr_descriptor
)
419 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
421 def _check_nsd_operational_state(self
, nsd
, ns_request
):
422 if nsd
["_admin"]["operationalState"] == "DISABLED":
423 raise EngineException(
424 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
425 "a network service".format(ns_request
["nsdId"]),
426 http_code
=HTTPStatus
.CONFLICT
,
429 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
430 additional_params
, _
= self
._format
_additional
_params
(
431 ns_request
, descriptor
=nsd
433 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
434 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
435 if ns_request
and ns_request
.get("k8s-namespace"):
436 ns_k8s_namespace
= ns_request
["k8s-namespace"]
437 if additional_params
and additional_params
.get("k8s-namespace"):
438 ns_k8s_namespace
= additional_params
["k8s-namespace"]
440 return ns_k8s_namespace
442 def _add_flavor_to_nsr(self
, vdu
, vnfd
, nsr_descriptor
):
445 # Find this vdu compute and storage descriptors
446 vdu_virtual_compute
= {}
447 vdu_virtual_storage
= {}
448 for vcd
in vnfd
.get("virtual-compute-desc", ()):
449 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
450 vdu_virtual_compute
= vcd
451 for vsd
in vnfd
.get("virtual-storage-desc", ()):
452 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
453 vdu_virtual_storage
= vsd
454 # Get this vdu vcpus, memory and storage info for flavor_data
455 if vdu_virtual_compute
.get("virtual-cpu", {}).get(
458 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"][
461 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
462 flavor_data
["memory-mb"] = (
463 float(vdu_virtual_compute
["virtual-memory"]["size"])
466 if vdu_virtual_storage
.get("size-of-storage"):
467 flavor_data
["storage-gb"] = vdu_virtual_storage
[
470 # Get this vdu EPA info for guest_epa
471 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
472 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"][
475 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
476 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
477 if vcpu_pinning
.get("thread-policy"):
478 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
[
481 if vcpu_pinning
.get("policy"):
484 if vcpu_pinning
["policy"] == "dynamic"
487 guest_epa
["cpu-pinning-policy"] = cpu_policy
488 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
489 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"][
492 if vdu_virtual_compute
.get("virtual-memory", {}).get(
495 guest_epa
["mempage-size"] = vdu_virtual_compute
[
498 if vdu_virtual_compute
.get("virtual-memory", {}).get(
501 guest_epa
["numa-node-policy"] = vdu_virtual_compute
[
503 ]["numa-node-policy"]
504 if vdu_virtual_storage
.get("disk-io-quota"):
505 guest_epa
["disk-io-quota"] = vdu_virtual_storage
[
510 flavor_data
["guest-epa"] = guest_epa
512 flavor_data
["name"] = vdu
["id"][:56] + "-flv"
513 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
514 nsr_descriptor
["flavor"].append(flavor_data
)
516 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
518 additional_params
, _
= self
._format
_additional
_params
(
519 ns_request
, descriptor
=nsd
523 "name": ns_request
["nsName"],
524 "name-ref": ns_request
["nsName"],
525 "short-name": ns_request
["nsName"],
526 "admin-status": "ENABLED",
527 "nsState": "NOT_INSTANTIATED",
528 "currentOperation": "IDLE",
529 "currentOperationID": None,
530 "errorDescription": None,
532 "deploymentStatus": None,
533 "configurationStatus": None,
535 "nsd": {k
: v
for k
, v
in nsd
.items()},
536 "datacenter": ns_request
["vimAccountId"],
537 "resource-orchestrator": "osmopenmano",
538 "description": ns_request
.get("nsDescription", ""),
539 "constituent-vnfr-ref": [],
540 "operational-status": "init", # typedef ns-operational-
541 "config-status": "init", # typedef config-states
542 "detailed-status": "scheduled",
543 "orchestration-progress": {},
545 "nsd-name-ref": nsd
["name"],
546 "operational-events": [], # "id", "timestamp", "description", "event",
547 "nsd-ref": nsd
["id"],
548 "nsd-id": nsd
["_id"],
550 "instantiate_params": self
._format
_ns
_request
(ns_request
),
551 "additionalParamsForNs": additional_params
,
552 "ns-instance-config-ref": nsr_id
,
555 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
558 "affinity-or-anti-affinity-group": [],
560 if "revision" in nsd
["_admin"]:
561 nsr_descriptor
["revision"] = nsd
["_admin"]["revision"]
563 ns_request
["nsr_id"] = nsr_id
564 if ns_request
and ns_request
.get("config-units"):
565 nsr_descriptor
["config-units"] = ns_request
["config-units"]
567 if nsd
.get("virtual-link-desc"):
568 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
569 # Fill each vld with vnfd-connection-point-ref data
570 # TODO: Change for multiple df support
571 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
572 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
573 for vnf_profile
in vnf_profiles
:
574 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
575 for cpd
in vlc
.get("constituent-cpd-id", ()):
576 all_vld_connection_point_data
[
577 vlc
.get("virtual-link-profile-id")
580 "member-vnf-index-ref": cpd
.get(
581 "constituent-base-element-id"
583 "vnfd-connection-point-ref": cpd
.get(
586 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
590 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
593 for vdu
in vnfd
.get("vdu", ()):
594 self
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr_descriptor
)
595 sw_image_id
= vdu
.get("sw-image-desc")
597 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
598 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
600 # also add alternative images to the list of images
601 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
602 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
603 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
605 # Add Affinity or Anti-affinity group information to NSR
606 vdu_profiles
= vnfd
.get("df", [[]])[0].get("vdu-profile", ())
607 affinity_group_prefix_name
= "{}-{}".format(
608 nsr_descriptor
["name"][:16], vnf_profile
.get("id")[:16]
611 for vdu_profile
in vdu_profiles
:
612 affinity_group_data
= {}
613 for affinity_group
in vdu_profile
.get(
614 "affinity-or-anti-affinity-group", ()
616 affinity_group_data
= (
617 self
._get
_affinity
_or
_anti
_affinity
_group
_data
_from
_vnfd
(
618 vnfd
, affinity_group
["id"]
621 affinity_group_data
["member-vnf-index"] = vnf_profile
.get("id")
622 self
._add
_affinity
_or
_anti
_affinity
_group
_to
_nsr
(
625 affinity_group_prefix_name
,
629 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
632 vld
["name"] = vld
["id"]
633 nsr_descriptor
["vld"] = nsr_vld
635 return nsr_descriptor
637 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
638 self
, vnfd
, affinity_group_id
641 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
643 affinity_group
= utils
.find_in_list(
644 vnfd
.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
645 lambda ag
: ag
["id"] == affinity_group_id
,
647 affinity_group_data
= {}
649 if affinity_group
.get("id"):
650 affinity_group_data
["ag-id"] = affinity_group
["id"]
651 if affinity_group
.get("type"):
652 affinity_group_data
["type"] = affinity_group
["type"]
653 if affinity_group
.get("scope"):
654 affinity_group_data
["scope"] = affinity_group
["scope"]
655 return affinity_group_data
657 def _add_affinity_or_anti_affinity_group_to_nsr(
658 self
, nsr_descriptor
, affinity_group_data
, affinity_group_prefix_name
661 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
663 affinity_group
= next(
666 for f
in nsr_descriptor
["affinity-or-anti-affinity-group"]
667 if all(f
.get(k
) == affinity_group_data
[k
] for k
in affinity_group_data
)
671 if not affinity_group
:
672 affinity_group_data
["id"] = str(
673 len(nsr_descriptor
["affinity-or-anti-affinity-group"])
675 affinity_group_data
["name"] = "{}-{}".format(
676 affinity_group_prefix_name
, affinity_group_data
["ag-id"][:32]
678 nsr_descriptor
["affinity-or-anti-affinity-group"].append(
682 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
683 sw_image_desc
= utils
.find_in_list(
684 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
687 if sw_image_desc
.get("image"):
688 image_data
["image"] = sw_image_desc
["image"]
689 if sw_image_desc
.get("checksum"):
690 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
691 if sw_image_desc
.get("vim-type"):
692 image_data
["vim-type"] = sw_image_desc
["vim-type"]
695 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
697 Adds image to nsr checking first it is not already added
702 for f
in nsr_descriptor
["image"]
703 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
708 image_data
["id"] = str(len(nsr_descriptor
["image"]))
709 nsr_descriptor
["image"].append(image_data
)
711 def _create_vnfr_descriptor_from_vnfd(
721 vnfr_id
= str(uuid4())
722 nsr_id
= nsr_descriptor
["id"]
724 additional_params
, vnf_params
= self
._format
_additional
_params
(
725 ns_request
, vnf_index
, descriptor
=vnfd
731 "nsr-id-ref": nsr_id
,
732 "member-vnf-index-ref": vnf_index
,
733 "additionalParamsForVnf": additional_params
,
735 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
737 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
738 "vim-account-id": None,
741 "connection-point": [],
742 "ip-address": None, # mgmt-interface filled by LCM
745 # Revision backwards compatility. Only specify the revision in the record if
746 # the original VNFD has a revision.
747 if "revision" in vnfd
:
748 vnfr_descriptor
["revision"] = vnfd
["revision"]
751 vnf_k8s_namespace
= ns_k8s_namespace
753 if vnf_params
.get("k8s-namespace"):
754 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
755 if vnf_params
.get("config-units"):
756 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
759 if vnfd
.get("int-virtual-link-desc"):
760 vnfr_descriptor
["vld"] = []
761 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
762 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
764 for cp
in vnfd
.get("ext-cpd", ()):
766 "name": cp
.get("id"),
767 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
768 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
770 # "ip-address", "mac-address" # filled by LCM
771 # vim-id # TODO it would be nice having a vim port id
773 vnfr_descriptor
["connection-point"].append(vnf_cp
)
775 # Create k8s-cluster information
776 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
777 if vnfd
.get("k8s-cluster"):
778 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
779 all_k8s_cluster_nets_cpds
= {}
780 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
781 if cpd
.get("k8s-cluster-net"):
782 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
785 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
786 if net
.get("id") in all_k8s_cluster_nets_cpds
:
787 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
792 for kdu
in get_iterable(vnfd
.get("kdu")):
793 additional_params
, kdu_params
= self
._format
_additional
_params
(
794 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
796 kdu_k8s_namespace
= vnf_k8s_namespace
797 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
798 if kdu_params
and kdu_params
.get("k8s-namespace"):
799 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
801 kdu_deployment_name
= ""
802 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
803 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
806 "additionalParams": additional_params
,
807 "k8s-namespace": kdu_k8s_namespace
,
808 "kdu-deployment-name": kdu_deployment_name
,
809 "kdu-name": kdu
["name"],
810 # TODO "name": "" Name of the VDU in the VIM
811 "ip-address": None, # mgmt-interface filled by LCM
814 if kdu_params
and kdu_params
.get("config-units"):
815 kdur
["config-units"] = kdu_params
["config-units"]
816 if kdu
.get("helm-version"):
817 kdur
["helm-version"] = kdu
["helm-version"]
818 for k8s_type
in ("helm-chart", "juju-bundle"):
819 if kdu
.get(k8s_type
):
820 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
821 if not vnfr_descriptor
.get("kdur"):
822 vnfr_descriptor
["kdur"] = []
823 vnfr_descriptor
["kdur"].append(kdur
)
825 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
827 for vdu
in vnfd
.get("vdu", ()):
830 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
831 "operate-vnf-op-config"
833 vdu_config
= utils
.find_in_list(
834 configs
, lambda config
: config
["id"] == vdu
["id"]
840 vdu_instantiation_level
= utils
.find_in_list(
841 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
842 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
845 vdu_instantiation_level
= None
848 external_connection_ee
= utils
.filter_in_list(
849 vdu_config
.get("execution-environment-list", []),
850 lambda ee
: "external-connection-point-ref" in ee
,
852 for ee
in external_connection_ee
:
853 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
855 additional_params
, vdu_params
= self
._format
_additional
_params
(
856 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
860 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
861 vnfd
.get("virtual-storage-desc", []),
862 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"]
865 vdu_virtual_storage_descriptors
= []
867 "vdu-id-ref": vdu
["id"],
868 # TODO "name": "" Name of the VDU in the VIM
869 "ip-address": None, # mgmt-interface filled by LCM
870 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
871 "internal-connection-point": [],
873 "additionalParams": additional_params
,
874 "vdu-name": vdu
["name"],
875 "virtual-storages": vdu_virtual_storage_descriptors
877 if vdu_params
and vdu_params
.get("config-units"):
878 vdur
["config-units"] = vdu_params
["config-units"]
879 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
880 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
883 if vdu
.get("pdu-type"):
884 vdur
["pdu-type"] = vdu
["pdu-type"]
885 vdur
["name"] = vdu
["pdu-type"]
886 # TODO volumes: name, volume-id
887 for icp
in vdu
.get("int-cpd", ()):
890 "connection-point-id": icp
["id"],
891 "name": icp
.get("id"),
894 vdur
["internal-connection-point"].append(vdu_icp
)
896 for iface
in icp
.get("virtual-network-interface-requirement", ()):
897 iface_fields
= ("name", "mac-address")
899 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
902 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
903 if "port-security-enabled" in icp
:
904 vdu_iface
["port-security-enabled"] = icp
[
905 "port-security-enabled"
908 if "port-security-disable-strategy" in icp
:
909 vdu_iface
["port-security-disable-strategy"] = icp
[
910 "port-security-disable-strategy"
913 for ext_cp
in vnfd
.get("ext-cpd", ()):
914 if not ext_cp
.get("int-cpd"):
916 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
918 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
919 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
923 if "port-security-enabled" in ext_cp
:
924 vdu_iface
["port-security-enabled"] = ext_cp
[
925 "port-security-enabled"
928 if "port-security-disable-strategy" in ext_cp
:
929 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
930 "port-security-disable-strategy"
937 and vdu_iface
.get("external-connection-point-ref")
940 vdu_iface
["mgmt-vnf"] = True
941 vdu_iface
["mgmt-interface"] = True
943 for ecp
in vdu_mgmt_cp
:
944 if vdu_iface
.get("external-connection-point-ref") == ecp
:
945 vdu_iface
["mgmt-interface"] = True
947 if iface
.get("virtual-interface"):
948 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
950 # look for network where this interface is connected
951 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
953 # TODO: Change for multiple df support
954 for df
in get_iterable(nsd
.get("df")):
955 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
956 for vlc_index
, vlc
in enumerate(
958 vnf_profile
.get("virtual-link-connectivity")
961 for cpd
in get_iterable(
962 vlc
.get("constituent-cpd-id")
965 cpd
.get("constituent-cpd-id")
968 vdu_iface
["ns-vld-id"] = vlc
.get(
969 "virtual-link-profile-id"
971 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
972 if vdu_iface
.get("type") in (
976 nsr_descriptor
["vld"][vlc_index
][
980 elif vdu_iface
.get("internal-connection-point-ref"):
981 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
982 # TODO: store fixed IP address in the record (if it exists in the ICP)
983 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
984 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
985 ivld_index
= utils
.find_index_in_list(
986 vnfd
.get("int-virtual-link-desc", ()),
987 lambda ivld
: ivld
["id"]
988 == icp
.get("int-virtual-link-desc"),
990 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
992 vdur
["interfaces"].append(vdu_iface
)
994 if vdu
.get("sw-image-desc"):
995 sw_image
= utils
.find_in_list(
996 vnfd
.get("sw-image-desc", ()),
997 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
999 nsr_sw_image_data
= utils
.find_in_list(
1000 nsr_descriptor
["image"],
1001 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
1003 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
1005 if vdu
.get("alternative-sw-image-desc"):
1007 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
1008 sw_image
= utils
.find_in_list(
1009 vnfd
.get("sw-image-desc", ()),
1010 lambda image
: image
["id"] == alt_image_id
,
1012 nsr_sw_image_data
= utils
.find_in_list(
1013 nsr_descriptor
["image"],
1015 nsr_image
.get("image") == sw_image
.get("image")
1018 alt_image_ids
.append(nsr_sw_image_data
["id"])
1019 vdur
["alt-image-ids"] = alt_image_ids
1021 flavor_data_name
= vdu
["id"][:56] + "-flv"
1022 nsr_flavor_desc
= utils
.find_in_list(
1023 nsr_descriptor
["flavor"],
1024 lambda flavor
: flavor
["name"] == flavor_data_name
,
1028 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
1030 # Adding Affinity groups information to vdur
1032 vdu_profile_affinity_group
= utils
.find_in_list(
1033 vnfd
.get("df")[0]["vdu-profile"],
1034 lambda a_vdu
: a_vdu
["id"] == vdu
["id"],
1037 vdu_profile_affinity_group
= None
1039 if vdu_profile_affinity_group
:
1040 affinity_group_ids
= []
1041 for affinity_group
in vdu_profile_affinity_group
.get(
1042 "affinity-or-anti-affinity-group", ()
1044 vdu_affinity_group
= utils
.find_in_list(
1045 vdu_profile_affinity_group
.get(
1046 "affinity-or-anti-affinity-group", ()
1048 lambda ag_fp
: ag_fp
["id"] == affinity_group
["id"],
1050 nsr_affinity_group
= utils
.find_in_list(
1051 nsr_descriptor
["affinity-or-anti-affinity-group"],
1053 nsr_ag
.get("ag-id") == vdu_affinity_group
.get("id")
1054 and nsr_ag
.get("member-vnf-index")
1055 == vnfr_descriptor
.get("member-vnf-index-ref")
1058 # Update Affinity Group VIM name if VDU instantiation parameter is present
1059 if vnf_params
and vnf_params
.get("affinity-or-anti-affinity-group"):
1060 vnf_params_affinity_group
= utils
.find_in_list(
1061 vnf_params
["affinity-or-anti-affinity-group"],
1063 vnfp_ag
.get("id") == vdu_affinity_group
.get("id")
1066 if vnf_params_affinity_group
.get("vim-affinity-group-id"):
1068 "vim-affinity-group-id"
1069 ] = vnf_params_affinity_group
["vim-affinity-group-id"]
1070 affinity_group_ids
.append(nsr_affinity_group
["id"])
1071 vdur
["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1073 if vdu_instantiation_level
:
1074 count
= vdu_instantiation_level
.get("number-of-instances")
1078 for index
in range(0, count
):
1079 vdur
= deepcopy(vdur
)
1080 for iface
in vdur
["interfaces"]:
1081 if iface
.get("ip-address") and index
!= 0:
1082 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
1083 if iface
.get("mac-address") and index
!= 0:
1084 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
1086 vdur
["_id"] = str(uuid4())
1087 vdur
["id"] = vdur
["_id"]
1088 vdur
["count-index"] = index
1089 vnfr_descriptor
["vdur"].append(vdur
)
1091 return vnfr_descriptor
1093 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
1095 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1096 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1097 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1098 :param ns_instance_content: ns instance content
1099 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1102 time_now
, time_delta
= time(), time() - ns_instance_content
["_admin"]["modified"]
1103 force_refresh
= isinstance(filter_q
, dict) and filter_q
.get('vcaStatusRefresh') == 'true'
1104 threshold_reached
= time_delta
> 120
1105 if force_refresh
or threshold_reached
:
1106 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
1107 ns_instance_content
["_admin"]["modified"] = time_now
1108 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
1109 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
1110 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1111 nslcmop_desc
["_admin"].pop("nsState")
1112 self
.msg
.write("ns", operation
, nslcmop_desc
)
1115 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1117 Get complete information on an ns instance.
1118 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1119 :param _id: string, ns instance id
1120 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1121 :param api_req: True if this call is serving an external API request. False if serving internal request.
1122 :return: dictionary, raise exception if not found.
1124 ns_instance_content
= super().show(session
, _id
, api_req
)
1125 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1126 return ns_instance_content
1128 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1129 raise EngineException(
1130 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1134 class VnfrTopic(BaseTopic
):
1138 def __init__(self
, db
, fs
, msg
, auth
):
1139 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1141 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1142 raise EngineException(
1143 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1146 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1147 raise EngineException(
1148 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1151 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1152 # Not used because vnfrs are created and deleted by NsrTopic class directly
1153 raise EngineException(
1154 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1158 class NsLcmOpTopic(BaseTopic
):
1161 operation_schema
= { # mapping between operation and jsonschema to validate
1162 "instantiate": ns_instantiate
,
1163 "action": ns_action
,
1164 "update": ns_update
,
1166 "terminate": ns_terminate
,
1167 "migrate": ns_migrate
,
1170 def __init__(self
, db
, fs
, msg
, auth
):
1171 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1172 self
.nsrtopic
= NsrTopic(db
, fs
, msg
, auth
)
1174 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1176 Check that user has enter right parameters for the operation
1177 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1178 :param operation: it can be: instantiate, terminate, action, update. TODO: heal
1179 :param indata: descriptor with the parameters of the operation
1182 if operation
== "action":
1183 self
._check
_action
_ns
_operation
(indata
, nsr
)
1184 elif operation
== "scale":
1185 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1186 elif operation
== "update":
1187 self
._check
_update
_ns
_operation
(indata
, nsr
)
1188 elif operation
== "instantiate":
1189 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1191 def _check_action_ns_operation(self
, indata
, nsr
):
1193 # check vnf_member_index
1194 if indata
.get("vnf_member_index"):
1195 indata
["member_vnf_index"] = indata
.pop(
1197 ) # for backward compatibility
1198 if indata
.get("member_vnf_index"):
1199 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1200 indata
["member_vnf_index"], nsr
["_id"]
1203 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1204 "operate-vnf-op-config"
1209 if indata
.get("vdu_id"):
1210 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1211 descriptor_configuration
= utils
.find_in_list(
1212 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1214 elif indata
.get("kdu_name"):
1215 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1216 descriptor_configuration
= utils
.find_in_list(
1217 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1220 descriptor_configuration
= utils
.find_in_list(
1221 configs
, lambda config
: config
["id"] == vnfd
["id"]
1223 if descriptor_configuration
is not None:
1224 descriptor_configuration
= descriptor_configuration
.get(
1228 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1232 # For k8s allows default primitives without validating the parameters
1233 if indata
.get("kdu_name") and indata
["primitive"] in (
1240 # TODO should be checked that rollback only can contains revsision_numbe????
1241 if not indata
.get("member_vnf_index"):
1242 raise EngineException(
1243 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1248 # if not, check primitive
1249 for config_primitive
in get_iterable(descriptor_configuration
):
1250 if indata
["primitive"] == config_primitive
["name"]:
1251 # check needed primitive_params are provided
1252 if indata
.get("primitive_params"):
1253 in_primitive_params_copy
= copy(indata
["primitive_params"])
1255 in_primitive_params_copy
= {}
1256 for paramd
in get_iterable(config_primitive
.get("parameter")):
1257 if paramd
["name"] in in_primitive_params_copy
:
1258 del in_primitive_params_copy
[paramd
["name"]]
1259 elif not paramd
.get("default-value"):
1260 raise EngineException(
1261 "Needed parameter {} not provided for primitive '{}'".format(
1262 paramd
["name"], indata
["primitive"]
1265 # check no extra primitive params are provided
1266 if in_primitive_params_copy
:
1267 raise EngineException(
1268 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1269 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1274 raise EngineException(
1275 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1280 def _check_update_ns_operation(self
, indata
, nsr
) -> None:
1281 """Validates the ns-update request according to updateType
1283 If updateType is CHANGE_VNFPKG:
1284 - it checks the vnfInstanceId, whether it's available under ns instance
1285 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1286 Otherwise exception will be raised.
1287 If updateType is REMOVE_VNF:
1288 - it checks if the vnfInstanceId is available in the ns instance
1289 - Otherwise exception will be raised.
1292 indata: includes updateType such as CHANGE_VNFPKG,
1293 nsr: network service record
1297 a meaningful error if given update parameters are not proper such as
1298 "Error in validating ns-update request: <ID> does not match
1299 with the vnfd-id of vnfinstance
1300 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1304 if indata
["updateType"] == "CHANGE_VNFPKG":
1305 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1306 vnf_instance_id
= indata
["changeVnfPackageData"]["vnfInstanceId"]
1307 ns_instance_id
= indata
["nsInstanceId"]
1308 vnfd_id_2update
= indata
["changeVnfPackageData"]["vnfdId"]
1310 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1312 raise EngineException(
1313 f
"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1314 f
"belong to NS {ns_instance_id}",
1315 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1318 # Getting vnfrs through the ns_instance_id
1319 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": ns_instance_id
})
1320 constituent_vnfd_id
= next(
1324 if vnfr
["id"] == vnf_instance_id
1329 # Check the given vnfd-id belongs to given vnf instance
1330 if constituent_vnfd_id
and (vnfd_id_2update
!= constituent_vnfd_id
):
1332 raise EngineException(
1333 f
"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1334 f
"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1335 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1338 # Validating the ns update timeout
1340 indata
.get("timeout_ns_update")
1341 and indata
["timeout_ns_update"] < 300
1343 raise EngineException(
1344 "Error in validating ns-update request: {} second is not enough "
1345 "to upgrade the VNF instance: {}".format(
1346 indata
["timeout_ns_update"], vnf_instance_id
1348 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1350 elif indata
["updateType"] == "REMOVE_VNF":
1351 vnf_instance_id
= indata
["removeVnfInstanceId"]
1352 ns_instance_id
= indata
["nsInstanceId"]
1353 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1354 raise EngineException(
1355 "Invalid VNF Instance Id. '{}' is not "
1356 "present in the NS '{}'".format(vnf_instance_id
, ns_instance_id
)
1367 "Ns update request could not be processed with error: {}.".format(e
)
1370 def _check_scale_ns_operation(self
, indata
, nsr
):
1371 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1372 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1374 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1376 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1377 == scaling_aspect
["id"]
1381 raise EngineException(
1382 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1383 "present at vnfd:scaling-aspect".format(
1384 indata
["scaleVnfData"]["scaleByStepData"][
1385 "scaling-group-descriptor"
1390 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1391 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1395 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1396 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1397 for in_vnf
in get_iterable(indata
.get("vnf")):
1398 member_vnf_index
= in_vnf
["member-vnf-index"]
1399 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1400 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1402 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1403 member_vnf_index
, nsr
["_id"]
1405 vnf_member_index_to_vnfd
[
1407 ] = vnfd
# add to cache, avoiding a later look for
1408 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1409 if in_vnf
.get("vimAccountId"):
1410 self
._check
_valid
_vim
_account
(
1411 in_vnf
["vimAccountId"], vim_accounts
, session
1414 for in_vld
in get_iterable(indata
.get("vld")):
1415 self
._check
_valid
_wim
_account
(
1416 in_vld
.get("wimAccountId"), wim_accounts
, session
1418 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1419 if in_vld
["name"] == vldd
["id"]:
1422 raise EngineException(
1423 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1428 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1429 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1430 vnfr
= self
.db
.get_one(
1432 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1433 fail_on_empty
=False,
1436 raise EngineException(
1437 "Invalid parameter member_vnf_index='{}' is not one of the "
1438 "nsd:constituent-vnfd".format(member_vnf_index
)
1441 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1442 if "revision" in vnfr
:
1443 vnfd_revision
= vnfr
["vnfd-id"] + ":" + str(vnfr
["revision"])
1444 vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": vnfd_revision
}, fail_on_empty
=False)
1446 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
1449 raise EngineException(
1450 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1456 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1457 for vdud
in get_iterable(vnfd
.get("vdu")):
1458 if vdud
["id"] == vdu_id
:
1461 raise EngineException(
1462 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1467 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1468 for kdud
in get_iterable(vnfd
.get("kdu")):
1469 if kdud
["name"] == kdu_name
:
1472 raise EngineException(
1473 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1478 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1479 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1480 for vdu
in get_iterable(vnfd
.get("vdu")):
1481 if in_vdu
["id"] == vdu
["id"]:
1482 for volume
in get_iterable(in_vdu
.get("volume")):
1483 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1484 if volumed
["id"] == volume
["name"]:
1487 raise EngineException(
1488 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1489 "volume:name='{}' is not present at "
1490 "vnfd:vdu:virtual-storage-desc list".format(
1491 in_vnf
["member-vnf-index"],
1497 vdu_if_names
= set()
1498 for cpd
in get_iterable(vdu
.get("int-cpd")):
1499 for iface
in get_iterable(
1500 cpd
.get("virtual-network-interface-requirement")
1502 vdu_if_names
.add(iface
.get("name"))
1504 for in_iface
in get_iterable(in_vdu
["interface"]):
1505 if in_iface
["name"] in vdu_if_names
:
1508 raise EngineException(
1509 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1510 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1511 in_vnf
["member-vnf-index"],
1519 raise EngineException(
1520 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1521 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1525 ivld
.get("id"): set()
1526 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1528 for vdu
in get_iterable(vnfd
.get("vdu")):
1529 for cpd
in get_iterable(vnfd
.get("int-cpd")):
1530 if cpd
.get("int-virtual-link-desc"):
1531 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1533 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1534 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1535 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1536 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1539 raise EngineException(
1540 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1541 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1542 "vnfd:internal-vld:name/id:internal-connection-point".format(
1543 in_vnf
["member-vnf-index"],
1549 raise EngineException(
1550 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1551 " is not present at vnfd '{}'".format(
1552 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1556 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1557 if vim_account
in vim_accounts
:
1560 db_filter
= self
._get
_project
_filter
(session
)
1561 db_filter
["_id"] = vim_account
1562 self
.db
.get_one("vim_accounts", db_filter
)
1564 raise EngineException(
1565 "Invalid vimAccountId='{}' not present for the project".format(
1569 vim_accounts
.append(vim_account
)
1571 def _get_vim_account(self
, vim_id
: str, session
):
1573 db_filter
= self
._get
_project
_filter
(session
)
1574 db_filter
["_id"] = vim_id
1575 return self
.db
.get_one("vim_accounts", db_filter
)
1577 raise EngineException(
1578 "Invalid vimAccountId='{}' not present for the project".format(
1583 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1584 if not isinstance(wim_account
, str):
1586 if wim_account
in wim_accounts
:
1589 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
1590 db_filter
["_id"] = wim_account
1591 self
.db
.get_one("wim_accounts", db_filter
)
1593 raise EngineException(
1594 "Invalid wimAccountId='{}' not present for the project".format(
1598 wim_accounts
.append(wim_account
)
1601 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1604 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1605 (ip_address, ...) information.
1606 Modifies PDU _admin.usageState to 'IN_USE'
1607 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1608 :param rollback: list with the database modifications to rollback if needed
1609 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1610 :param vim_account: vim_account where this vnfr should be deployed
1611 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1612 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1613 of the changed vnfr is needed
1615 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1616 "vim-network-name": used at VIM
1617 "name": interface name
1618 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1619 "ns-vld-id": NSD vld where this interface is connected.
1620 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1623 ifaces_forcing_vim_network
= []
1624 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1625 if not vdur
.get("pdu-type"):
1627 pdu_type
= vdur
.get("pdu-type")
1628 pdu_filter
= self
._get
_project
_filter
(session
)
1629 pdu_filter
["vim_accounts"] = vim_account
1630 pdu_filter
["type"] = pdu_type
1631 pdu_filter
["_admin.operationalState"] = "ENABLED"
1632 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1633 # TODO feature 1417: "shared": True,
1635 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1636 for pdu
in available_pdus
:
1637 # step 1 check if this pdu contains needed interfaces:
1638 match_interfaces
= True
1639 for vdur_interface
in vdur
["interfaces"]:
1640 for pdu_interface
in pdu
["interfaces"]:
1641 if pdu_interface
["name"] == vdur_interface
["name"]:
1642 # TODO feature 1417: match per mgmt type
1644 else: # no interface found for name
1645 match_interfaces
= False
1647 if match_interfaces
:
1650 raise EngineException(
1651 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1655 vnfr
["member-vnf-index-ref"],
1660 # step 2. Update pdu
1662 "_admin.usageState": pdu
["_admin"]["usageState"],
1663 "_admin.usage.vnfr_id": None,
1664 "_admin.usage.nsr_id": None,
1665 "_admin.usage.vdur": None,
1669 {"_id": pdu
["_id"]},
1671 "_admin.usageState": "IN_USE",
1673 "vnfr_id": vnfr
["_id"],
1674 "nsr_id": vnfr
["nsr-id-ref"],
1675 "vdur": vdur
["vdu-id-ref"],
1684 "content": rollback_pdu
,
1688 # step 3. Fill vnfr info by filling vdur
1689 vdu_text
= "vdur.{}".format(vdur_index
)
1690 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1691 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1692 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1693 for pdu_interface
in pdu
["interfaces"]:
1694 if pdu_interface
["name"] == vdur_interface
["name"]:
1695 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1696 for k
, v
in pdu_interface
.items():
1700 ): # TODO: switch-xxxxx must be inserted
1701 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1702 vnfr_update_rollback
[
1703 iface_text
+ ".{}".format(k
)
1704 ] = vdur_interface
.get(v
)
1705 if pdu_interface
.get("ip-address"):
1706 if vdur_interface
.get(
1708 ) or vdur_interface
.get("mgmt-vnf"):
1709 vnfr_update_rollback
[
1710 vdu_text
+ ".ip-address"
1711 ] = vdur
.get("ip-address")
1712 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1715 if vdur_interface
.get("mgmt-vnf"):
1716 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1719 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1720 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1723 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1726 ifaces_forcing_vim_network
.append(
1728 "name": vdur_interface
.get("vnf-vld-id")
1729 or vdur_interface
.get("ns-vld-id"),
1730 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1731 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1734 if pdu_interface
.get("vim-network-id"):
1735 ifaces_forcing_vim_network
[-1][
1737 ] = pdu_interface
["vim-network-id"]
1738 if pdu_interface
.get("vim-network-name"):
1739 ifaces_forcing_vim_network
[-1][
1741 ] = pdu_interface
["vim-network-name"]
1744 return ifaces_forcing_vim_network
1746 def _look_for_k8scluster(
1747 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1750 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1751 Fills vnfr.kdur with the selected k8scluster
1753 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1754 :param rollback: list with the database modifications to rollback if needed
1755 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1756 :param vim_account: vim_account where this vnfr should be deployed
1757 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1758 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1759 of the changed vnfr is needed
1761 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1762 "vim-network-name": used at VIM
1763 "name": interface name
1764 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1765 "ns-vld-id": NSD vld where this interface is connected.
1766 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1769 ifaces_forcing_vim_network
= []
1770 if not vnfr
.get("kdur"):
1771 return ifaces_forcing_vim_network
1773 kdu_filter
= self
._get
_project
_filter
(session
)
1774 kdu_filter
["vim_account"] = vim_account
1775 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1776 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1778 k8s_requirements
= {} # just for logging
1779 for k8scluster
in available_k8sclusters
:
1780 if not vnfr
.get("k8s-cluster"):
1783 if vnfr
["k8s-cluster"].get("cni"):
1784 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1785 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1786 k8scluster
.get("cni", ())
1789 # restrict by version
1790 if vnfr
["k8s-cluster"].get("version"):
1791 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1792 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1794 # restrict by number of networks
1795 if vnfr
["k8s-cluster"].get("nets"):
1796 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1797 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1798 vnfr
["k8s-cluster"]["nets"]
1803 raise EngineException(
1804 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1805 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1809 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1810 # step 3. Fill vnfr info by filling kdur
1811 kdu_text
= "kdur.{}.".format(kdur_index
)
1812 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1813 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1815 # step 4. Check VIM networks that forces the selected k8s_cluster
1816 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1817 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1818 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1819 # get a network from k8s_cluster nets. If name matches use this, if not use other
1820 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1821 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1822 k8scluster_net_list
.remove(kdur_net
["id"])
1824 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1825 k8scluster_net_list
.pop(0)
1826 vnfr_update_rollback
[
1827 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1829 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1831 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1833 ifaces_forcing_vim_network
.append(
1835 "name": kdur_net
.get("vnf-vld-id")
1836 or kdur_net
.get("ns-vld-id"),
1837 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1838 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1839 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1842 # TODO check that this forcing is not incompatible with other forcing
1843 return ifaces_forcing_vim_network
1845 def _update_vnfrs_from_nsd(self
, nsr
):
1850 step
= "Getting vnf_profiles from nsd"
1851 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
1852 vld_fixed_ip_connection_point_data
= {}
1854 step
= "Getting ip-address info from vnf_profile if it exists"
1855 for vnfp
in vnf_profiles
:
1856 # Checking ip-address info from nsd.vnf_profile and storing
1857 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
1858 for cpd
in vlc
.get("constituent-cpd-id", ()):
1859 if cpd
.get("ip-address"):
1860 step
= "Storing ip-address info"
1861 vld_fixed_ip_connection_point_data
.update({vlc
.get("virtual-link-profile-id") + '.' + cpd
.get("constituent-base-element-id"): {
1862 "vnfd-connection-point-ref": cpd
.get(
1863 "constituent-cpd-id"),
1864 "ip-address": cpd
.get(
1867 # Inserting ip address to vnfr
1868 if len(vld_fixed_ip_connection_point_data
) > 0:
1869 step
= "Getting vnfrs"
1870 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1871 for item
in vld_fixed_ip_connection_point_data
.keys():
1872 step
= "Filtering vnfrs"
1873 vnfr
= next(filter(lambda vnfr
: vnfr
["member-vnf-index-ref"] == item
.split('.')[1], vnfrs
), None)
1876 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1877 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1878 step
= "Looking for matched interface"
1880 iface
.get("external-connection-point-ref")
1881 == vld_fixed_ip_connection_point_data
[item
].get("vnfd-connection-point-ref") and
1882 iface
.get("ns-vld-id") == item
.split('.')[0]
1885 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1886 vdur_index
, iface_index
1888 step
= "Storing info in order to update vnfr"
1890 vnfr_update_text
+ ".ip-address"
1891 ] = increment_ip_mac(
1892 vld_fixed_ip_connection_point_data
[item
].get("ip-address"),
1893 vdur
.get("count-index", 0), )
1894 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1896 step
= "updating vnfr at database"
1897 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1905 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
1907 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1910 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1914 vnfr_update_rollback
= {}
1915 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1916 # update vim-account-id
1918 vim_account
= indata
["vimAccountId"]
1919 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1920 # check instantiate parameters
1921 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1922 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1924 if vnf_inst_params
.get("vimAccountId"):
1925 vim_account
= vnf_inst_params
.get("vimAccountId")
1926 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1928 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1929 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1930 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1931 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1933 for iface_inst_param
in get_iterable(
1934 vdu_inst_param
.get("interface")
1936 iface_index
, _
= next(
1938 for i
in enumerate(vdur
["interfaces"])
1939 if i
[1]["name"] == iface_inst_param
["name"]
1941 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1942 vdur_index
, iface_index
1944 if iface_inst_param
.get("ip-address"):
1946 vnfr_update_text
+ ".ip-address"
1947 ] = increment_ip_mac(
1948 iface_inst_param
.get("ip-address"),
1949 vdur
.get("count-index", 0),
1951 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1952 if iface_inst_param
.get("mac-address"):
1954 vnfr_update_text
+ ".mac-address"
1955 ] = increment_ip_mac(
1956 iface_inst_param
.get("mac-address"),
1957 vdur
.get("count-index", 0),
1959 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1960 if iface_inst_param
.get("floating-ip-required"):
1962 vnfr_update_text
+ ".floating-ip-required"
1964 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1965 # TODO update vld with the ip-profile
1966 for ivld_inst_param
in get_iterable(
1967 vnf_inst_params
.get("internal-vld")
1969 for icp_inst_param
in get_iterable(
1970 ivld_inst_param
.get("internal-connection-point")
1973 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1974 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1976 iface
.get("internal-connection-point-ref")
1977 == icp_inst_param
["id-ref"]
1979 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1980 vdur_index
, iface_index
1982 if icp_inst_param
.get("ip-address"):
1984 vnfr_update_text
+ ".ip-address"
1985 ] = increment_ip_mac(
1986 icp_inst_param
.get("ip-address"),
1987 vdur
.get("count-index", 0),
1990 vnfr_update_text
+ ".fixed-ip"
1992 if icp_inst_param
.get("mac-address"):
1994 vnfr_update_text
+ ".mac-address"
1995 ] = increment_ip_mac(
1996 icp_inst_param
.get("mac-address"),
1997 vdur
.get("count-index", 0),
2000 vnfr_update_text
+ ".fixed-mac"
2003 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2004 for vld_inst_param
in get_iterable(indata
.get("vld")):
2005 for vnfcp_inst_param
in get_iterable(
2006 vld_inst_param
.get("vnfd-connection-point-ref")
2008 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
2011 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2012 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2014 iface
.get("external-connection-point-ref")
2015 == vnfcp_inst_param
["vnfd-connection-point-ref"]
2017 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2018 vdur_index
, iface_index
2020 if vnfcp_inst_param
.get("ip-address"):
2022 vnfr_update_text
+ ".ip-address"
2023 ] = increment_ip_mac(
2024 vnfcp_inst_param
.get("ip-address"),
2025 vdur
.get("count-index", 0),
2027 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2028 if vnfcp_inst_param
.get("mac-address"):
2030 vnfr_update_text
+ ".mac-address"
2031 ] = increment_ip_mac(
2032 vnfcp_inst_param
.get("mac-address"),
2033 vdur
.get("count-index", 0),
2035 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2038 vnfr_update
["vim-account-id"] = vim_account
2039 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
2042 vnfr_update
["vca-id"] = vca_id
2043 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
2046 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
2047 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2051 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
2052 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2054 # update database vnfr
2055 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2061 "content": vnfr_update_rollback
,
2065 # Update indada in case pdu forces to use a concrete vim-network-name
2066 # TODO check if user has already insert a vim-network-name and raises an error
2067 if not ifaces_forcing_vim_network
:
2069 for iface_info
in ifaces_forcing_vim_network
:
2070 if iface_info
.get("ns-vld-id"):
2071 if "vld" not in indata
:
2073 indata
["vld"].append(
2075 key
: iface_info
[key
]
2076 for key
in ("name", "vim-network-name", "vim-network-id")
2077 if iface_info
.get(key
)
2081 elif iface_info
.get("vnf-vld-id"):
2082 if "vnf" not in indata
:
2084 indata
["vnf"].append(
2086 "member-vnf-index": member_vnf_index
,
2089 key
: iface_info
[key
]
2095 if iface_info
.get(key
)
2102 def _create_nslcmop(nsr_id
, operation
, params
):
2104 Creates a ns-lcm-opp content to be stored at database.
2105 :param nsr_id: internal id of the instance
2106 :param operation: instantiate, terminate, scale, action, update ...
2107 :param params: user parameters for the operation
2108 :return: dictionary following SOL005 format
2115 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2116 "queuePosition": None,
2118 "errorMessage": None,
2119 "detailedStatus": None,
2120 "statusEnteredTime": now
,
2121 "nsInstanceId": nsr_id
,
2122 "lcmOperationType": operation
,
2124 "isAutomaticInvocation": False,
2125 "operationParams": params
,
2126 "isCancelPending": False,
2128 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2129 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2134 def _get_enabled_vims(self
, session
):
2136 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2137 :param session: current session with user information
2139 db_filter
= self
._get
_project
_filter
(session
)
2140 db_filter
["_admin.operationalState"] = "ENABLED"
2141 vims
= self
.db
.get_list("vim_accounts", db_filter
)
2144 vimAccounts
.append(vim
["_id"])
2157 Performs a new operation over a ns
2158 :param rollback: list to append created items at database in case a rollback must to be done
2159 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2160 :param indata: descriptor with the parameters of the operation. It must contains among others
2161 nsInstanceId: _id of the nsr to perform the operation
2162 operation: it can be: instantiate, terminate, action, update TODO: heal
2163 :param kwargs: used to override the indata descriptor
2164 :param headers: http request headers
2165 :return: id of the nslcmops
2168 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
2170 db_filter
= self
._get
_project
_filter
(session
)
2171 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2172 nsis
= self
.db
.get_one(
2173 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
2176 raise EngineException(
2177 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2180 http_code
=HTTPStatus
.CONFLICT
,
2184 # Override descriptor with query string kwargs
2185 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2186 operation
= indata
["lcmOperationType"]
2187 nsInstanceId
= indata
["nsInstanceId"]
2189 validate_input(indata
, self
.operation_schema
[operation
])
2190 # get ns from nsr_id
2191 _filter
= BaseTopic
._get
_project
_filter
(session
)
2192 _filter
["_id"] = nsInstanceId
2193 nsr
= self
.db
.get_one("nsrs", _filter
)
2196 if operation
== "terminate" and slice_object
is False:
2197 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
2199 not nsr
["_admin"].get("nsState")
2200 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
2202 if operation
== "terminate" and indata
.get("autoremove"):
2203 # NSR must be deleted
2207 ) # a none in this case is used to indicate not instantiated. It can be removed
2208 if operation
!= "instantiate":
2209 raise EngineException(
2210 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2211 nsInstanceId
, operation
2213 HTTPStatus
.CONFLICT
,
2216 if operation
== "instantiate" and not session
["force"]:
2217 raise EngineException(
2218 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2219 nsInstanceId
, operation
2221 HTTPStatus
.CONFLICT
,
2223 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
2224 if (indata
.get("primitive_params")):
2225 indata
["primitive_params"] = json
.dumps(indata
["primitive_params"])
2226 elif (indata
.get("additionalParamsForVnf")):
2227 indata
["additionalParamsForVnf"] = json
.dumps(indata
["additionalParamsForVnf"])
2229 if operation
== "instantiate":
2230 self
._update
_vnfrs
_from
_nsd
(nsr
)
2231 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
2232 if (operation
== "update") and (indata
["updateType"] == "CHANGE_VNFPKG"):
2234 vnfd_id
= indata
["changeVnfPackageData"]["vnfdId"]
2235 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2236 nsd
= self
.db
.get_one("nsds", {"_id": nsr
["nsd-id"]})
2237 ns_request
= nsr
["instantiate_params"]
2238 vnfr
= self
.db
.get_one("vnfrs", {"_id": indata
["changeVnfPackageData"]["vnfInstanceId"]})
2239 latest_vnfd_revision
= vnfd
["_admin"].get("revision", 1)
2240 vnfr_vnfd_revision
= vnfr
.get("revision", 1)
2241 if latest_vnfd_revision
!= vnfr_vnfd_revision
:
2242 old_vnfd_id
= vnfd_id
+ ":" + str(vnfr_vnfd_revision
)
2243 old_db_vnfd
= self
.db
.get_one("vnfds_revisions", {"_id": old_vnfd_id
})
2244 old_sw_version
= old_db_vnfd
.get("software-version", "1.0")
2245 new_sw_version
= vnfd
.get("software-version", "1.0")
2246 if new_sw_version
!= old_sw_version
:
2247 vnf_index
= vnfr
["member-vnf-index-ref"]
2248 self
.logger
.info("nsr {}".format(nsr
))
2249 for vdu
in vnfd
["vdu"]:
2250 self
.nsrtopic
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr
)
2251 sw_image_id
= vdu
.get("sw-image-desc")
2253 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
2254 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2255 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
2256 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
2257 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2258 nsr_update
["image"] = nsr
["image"]
2259 nsr_update
["flavor"] = nsr
["flavor"]
2260 self
.db
.set_one("nsrs", {"_id": nsr
["_id"]}, nsr_update
)
2261 ns_k8s_namespace
= self
.nsrtopic
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
2262 vnfr_descriptor
= self
.nsrtopic
._create
_vnfr
_descriptor
_from
_vnfd
(
2271 indata
["newVdur"] = vnfr_descriptor
["vdur"]
2272 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
2273 _id
= nslcmop_desc
["_id"]
2275 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2277 if indata
.get("placement-engine"):
2278 # Save valid vim accounts in lcm operation descriptor
2279 nslcmop_desc
["operationParams"][
2281 ] = self
._get
_enabled
_vims
(session
)
2282 self
.db
.create("nslcmops", nslcmop_desc
)
2283 rollback
.append({"topic": "nslcmops", "_id": _id
})
2284 if not slice_object
:
2285 self
.msg
.write("ns", operation
, nslcmop_desc
)
2287 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2288 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2289 # except DbException as e:
2290 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2292 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2293 raise EngineException(
2294 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2297 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2298 raise EngineException(
2299 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2303 class NsiTopic(BaseTopic
):
2306 quota_name
= "slice_instances"
2308 def __init__(self
, db
, fs
, msg
, auth
):
2309 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2310 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2313 def _format_ns_request(ns_request
):
2314 formated_request
= copy(ns_request
)
2315 # TODO: Add request params
2316 return formated_request
2319 def _format_addional_params(slice_request
):
2321 Get and format user additional params for NS or VNF
2322 :param slice_request: User instantiation additional parameters
2323 :return: a formatted copy of additional params or None if not supplied
2325 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2326 if additional_params
:
2327 for k
, v
in additional_params
.items():
2328 if not isinstance(k
, str):
2329 raise EngineException(
2330 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2334 if "." in k
or "$" in k
:
2335 raise EngineException(
2336 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2340 if isinstance(v
, (dict, tuple, list)):
2341 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2342 return additional_params
2344 def _check_descriptor_dependencies(self
, session
, descriptor
):
2346 Check that the dependent descriptors exist on a new descriptor or edition
2347 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2348 :param descriptor: descriptor to be inserted or edit
2349 :return: None or raises exception
2351 if not descriptor
.get("nst-ref"):
2353 nstd_id
= descriptor
["nst-ref"]
2354 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
2355 raise EngineException(
2356 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2359 http_code
=HTTPStatus
.CONFLICT
,
2362 def check_conflict_on_del(self
, session
, _id
, db_content
):
2364 Check that NSI is not instantiated
2365 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2366 :param _id: nsi internal id
2367 :param db_content: The database content of the _id
2368 :return: None or raises EngineException with the conflict
2370 if session
["force"]:
2373 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2374 raise EngineException(
2375 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2376 "Launch 'terminate' operation first; or force deletion".format(_id
),
2377 http_code
=HTTPStatus
.CONFLICT
,
2380 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2382 Deletes associated nsilcmops from database. Deletes associated filesystem.
2383 Set usageState of nst
2384 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2385 :param _id: server internal id
2386 :param db_content: The database content of the descriptor
2387 :param not_send_msg: To not send message (False) or store content (list) instead
2388 :return: None if ok or raises EngineException with the problem
2391 # Deleting the nsrs belonging to nsir
2393 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2394 nsr_id
= nsrs_detailed_item
["nsrId"]
2395 if nsrs_detailed_item
.get("shared"):
2397 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2398 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2399 "_id.ne": nsir
["_id"],
2401 nsi
= self
.db
.get_one(
2402 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2404 if nsi
: # last one using nsr
2407 self
.nsrTopic
.delete(
2408 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2410 except (DbException
, EngineException
) as e
:
2411 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2416 # delete related nsilcmops database entries
2417 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2419 # Check and set used NST usage state
2420 nsir_admin
= nsir
.get("_admin")
2421 if nsir_admin
and nsir_admin
.get("nst-id"):
2422 # check if used by another NSI
2423 nsis_list
= self
.db
.get_one(
2425 {"nst-id": nsir_admin
["nst-id"]},
2426 fail_on_empty
=False,
2432 {"_id": nsir_admin
["nst-id"]},
2433 {"_admin.usageState": "NOT_IN_USE"},
2436 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2438 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2439 :param rollback: list to append the created items at database in case a rollback must be done
2440 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2441 :param indata: params to be used for the nsir
2442 :param kwargs: used to override the indata descriptor
2443 :param headers: http request headers
2444 :return: the _id of nsi descriptor created at database
2448 step
= "checking quotas"
2449 self
.check_quota(session
)
2452 slice_request
= self
._remove
_envelop
(indata
)
2453 # Override descriptor with query string kwargs
2454 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2455 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2458 step
= "getting nstd id='{}' from database".format(
2459 slice_request
.get("nstId")
2461 _filter
= self
._get
_project
_filter
(session
)
2462 _filter
["_id"] = slice_request
["nstId"]
2463 nstd
= self
.db
.get_one("nsts", _filter
)
2464 # check NST is not disabled
2465 step
= "checking NST operationalState"
2466 if nstd
["_admin"]["operationalState"] == "DISABLED":
2467 raise EngineException(
2468 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2469 "instance".format(slice_request
["nstId"]),
2470 http_code
=HTTPStatus
.CONFLICT
,
2474 # check NSD is not disabled
2475 step
= "checking operationalState"
2476 if nstd
["_admin"]["operationalState"] == "DISABLED":
2477 raise EngineException(
2478 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2479 "a network slice".format(slice_request
["nstId"]),
2480 http_code
=HTTPStatus
.CONFLICT
,
2483 nstd
.pop("_admin", None)
2484 nstd_id
= nstd
.pop("_id", None)
2485 nsi_id
= str(uuid4())
2486 step
= "filling nsi_descriptor with input data"
2491 "name": slice_request
["nsiName"],
2492 "description": slice_request
.get("nsiDescription", ""),
2493 "datacenter": slice_request
["vimAccountId"],
2494 "nst-ref": nstd
["id"],
2495 "instantiation_parameters": slice_request
,
2496 "network-slice-template": nstd
,
2500 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2503 step
= "creating nsi at database"
2505 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2507 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2508 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2509 nsi_descriptor
["_admin"]["deployed"] = {}
2510 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2511 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2513 # Creating netslice-vld for the RO.
2514 step
= "creating netslice-vld at database"
2516 # Building the vlds list to be deployed
2517 # From netslice descriptors, creating the initial list
2520 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2521 # Getting template Instantiation parameters from NST
2522 nsi_vld
= deepcopy(netslice_vlds
)
2523 nsi_vld
["shared-nsrs-list"] = []
2524 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2525 nsi_vlds
.append(nsi_vld
)
2527 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2528 # Creating netslice-subnet_record.
2532 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2533 for member_ns
in nstd
["netslice-subnet"]:
2534 nsd_id
= member_ns
["nsd-ref"]
2535 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2536 member_ns
["nsd-ref"], member_ns
["id"]
2538 if nsd_id
not in needed_nsds
:
2540 _filter
["id"] = nsd_id
2541 nsd
= self
.db
.get_one(
2542 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2546 needed_nsds
[nsd_id
] = nsd
2548 nsd
= needed_nsds
[nsd_id
]
2549 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2550 services
.append(member_ns
)
2552 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2553 member_ns
["nsd-ref"], member_ns
["id"]
2556 # creates Network Services records (NSRs)
2557 step
= "creating nsrs at database using NsrTopic.new()"
2558 ns_params
= slice_request
.get("netslice-subnet")
2560 nsi_netslice_subnet
= []
2561 for service
in services
:
2562 # Check if the netslice-subnet is shared and if it is share if the nss exists
2565 # Is the nss shared and instantiated?
2566 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2567 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2570 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2571 nsi
= self
.db
.get_one(
2572 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2574 if nsi
and service
.get("is-shared-nss"):
2575 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2576 for nsrs_detailed_item
in nsrs_detailed_list
:
2577 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2578 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2579 _id_nsr
= nsrs_detailed_item
["nsrId"]
2581 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2582 if netslice_subnet
["nss-id"] == service
["id"]:
2583 indata_ns
= netslice_subnet
2587 if service
.get("instantiation-parameters"):
2588 indata_ns
= deepcopy(service
["instantiation-parameters"])
2589 # del service["instantiation-parameters"]
2591 indata_ns
["nsdId"] = service
["_id"]
2592 indata_ns
["nsName"] = (
2593 slice_request
.get("nsiName") + "." + service
["id"]
2595 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2596 indata_ns
["nsDescription"] = service
["description"]
2597 if slice_request
.get("ssh_keys"):
2598 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2601 for ns_param
in ns_params
:
2602 if ns_param
.get("id") == service
["id"]:
2603 copy_ns_param
= deepcopy(ns_param
)
2604 del copy_ns_param
["id"]
2605 indata_ns
.update(copy_ns_param
)
2608 # Creates Nsr objects
2609 _id_nsr
, _
= self
.nsrTopic
.new(
2610 rollback
, session
, indata_ns
, kwargs
, headers
2614 "shared": service
.get("is-shared-nss"),
2615 "nsd-id": service
["nsd-ref"],
2616 "nss-id": service
["id"],
2617 "nslcmop_instantiate": None,
2619 indata_ns
["nss-id"] = service
["id"]
2620 nsrs_list
.append(nsrs_item
)
2621 nsi_netslice_subnet
.append(indata_ns
)
2622 nsr_ref
= {"nsr-ref": _id_nsr
}
2623 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2625 # Adding the nsrs list to the nsi
2626 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2627 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2629 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2632 # Creating the entry in the database
2633 self
.db
.create("nsis", nsi_descriptor
)
2634 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2636 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2637 self
.logger
.exception(
2638 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2640 raise EngineException("Error {}: {}".format(step
, e
))
2641 except ValidationError
as e
:
2642 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2644 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2645 raise EngineException(
2646 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2650 class NsiLcmOpTopic(BaseTopic
):
2653 operation_schema
= { # mapping between operation and jsonschema to validate
2654 "instantiate": nsi_instantiate
,
2658 def __init__(self
, db
, fs
, msg
, auth
):
2659 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2660 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2662 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2664 Check that user has enter right parameters for the operation
2665 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2666 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2667 :param indata: descriptor with the parameters of the operation
2671 nstd
= nsir
["network-slice-template"]
2673 def check_valid_netslice_subnet_id(nstId
):
2674 # TODO change to vnfR (??)
2675 for netslice_subnet
in nstd
["netslice-subnet"]:
2676 if nstId
== netslice_subnet
["id"]:
2677 nsd_id
= netslice_subnet
["nsd-ref"]
2678 if nsd_id
not in nsds
:
2679 _filter
= self
._get
_project
_filter
(session
)
2680 _filter
["id"] = nsd_id
2681 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2684 raise EngineException(
2685 "Invalid parameter nstId='{}' is not one of the "
2686 "nst:netslice-subnet".format(nstId
)
2689 if operation
== "instantiate":
2690 # check the existance of netslice-subnet items
2691 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2692 check_valid_netslice_subnet_id(in_nst
["id"])
2694 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2700 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2701 "statusEnteredTime": now
,
2702 "netsliceInstanceId": netsliceInstanceId
,
2703 "lcmOperationType": operation
,
2705 "isAutomaticInvocation": False,
2706 "operationParams": params
,
2707 "isCancelPending": False,
2709 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2710 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2711 + netsliceInstanceId
,
2716 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2717 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2718 if nst_sb_item
.get("is-shared-nss"):
2719 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2720 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2721 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2722 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2723 "nss-connection-point-ref"
2726 admin_subnet_item
["nss-id"]
2727 == admin_vld_nss_cp_ref_item
["nss-ref"]
2730 not nsr_item
["nsrId"]
2731 in admin_vld_item
["shared-nsrs-list"]
2733 admin_vld_item
["shared-nsrs-list"].append(
2737 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2740 {"_id": nsir
["_id"]},
2741 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2744 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2746 Performs a new operation over a ns
2747 :param rollback: list to append created items at database in case a rollback must to be done
2748 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2749 :param indata: descriptor with the parameters of the operation. It must contains among others
2750 netsliceInstanceId: _id of the nsir to perform the operation
2751 operation: it can be: instantiate, terminate, action, TODO: update, heal
2752 :param kwargs: used to override the indata descriptor
2753 :param headers: http request headers
2754 :return: id of the nslcmops
2757 # Override descriptor with query string kwargs
2758 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2759 operation
= indata
["lcmOperationType"]
2760 netsliceInstanceId
= indata
["netsliceInstanceId"]
2761 validate_input(indata
, self
.operation_schema
[operation
])
2763 # get nsi from netsliceInstanceId
2764 _filter
= self
._get
_project
_filter
(session
)
2765 _filter
["_id"] = netsliceInstanceId
2766 nsir
= self
.db
.get_one("nsis", _filter
)
2767 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2772 not nsir
["_admin"].get("nsiState")
2773 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2775 if operation
== "terminate" and indata
.get("autoremove"):
2776 # NSIR must be deleted
2780 ) # a none in this case is used to indicate not instantiated. It can be removed
2781 if operation
!= "instantiate":
2782 raise EngineException(
2783 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2784 netsliceInstanceId
, operation
2786 HTTPStatus
.CONFLICT
,
2789 if operation
== "instantiate" and not session
["force"]:
2790 raise EngineException(
2791 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2792 netsliceInstanceId
, operation
2794 HTTPStatus
.CONFLICT
,
2797 # Creating all the NS_operation (nslcmop)
2798 # Get service list from db
2799 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2801 # nslcmops_item = None
2802 for index
, nsr_item
in enumerate(nsrs_list
):
2803 nsr_id
= nsr_item
["nsrId"]
2804 if nsr_item
.get("shared"):
2805 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2806 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2808 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2810 _filter
["_id.ne"] = netsliceInstanceId
2811 nsi
= self
.db
.get_one(
2812 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2814 if operation
== "terminate":
2816 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2820 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2823 ): # other nsi is using this nsr and it needs this nsr instantiated
2824 continue # do not create nsilcmop
2826 # looks the first nsi fulfilling the conditions but not being the current NSIR
2828 nsi_nsr_item
= next(
2830 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2831 if n
["nsrId"] == nsr_id
2833 and n
["nslcmop_instantiate"]
2835 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2836 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2838 "_admin.nsrs-detailed-list.{}".format(
2842 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2843 # continue to not create nslcmop since nsrs is shared and nsrs was created
2846 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2851 "lcmOperationType": operation
,
2852 "nsInstanceId": nsr_id
,
2853 # Including netslice_id in the ns instantiate Operation
2854 "netsliceInstanceId": netsliceInstanceId
,
2856 if operation
== "instantiate":
2857 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2858 indata_ns
.update(service
["instantiate_params"])
2860 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2861 # message via kafka bus
2862 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2863 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2865 nslcmops
.append(nslcmop
)
2866 if operation
== "instantiate":
2868 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2872 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2873 except (DbException
, EngineException
) as e
:
2874 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2877 + "skipping NS={} because not found".format(nsr_id
)
2884 indata
["nslcmops_ids"] = nslcmops
2885 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2887 nsilcmop_desc
= self
._create
_nsilcmop
(
2888 session
, netsliceInstanceId
, operation
, indata
2891 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2893 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2894 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2895 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2897 except ValidationError
as e
:
2898 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2900 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2901 raise EngineException(
2902 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2905 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2906 raise EngineException(
2907 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR