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
)
65 def format_on_new(content
, project_id
=None, make_public
=False):
66 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
67 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
70 def check_conflict_on_del(self
, session
, _id
, db_content
):
72 Check that NSR is not instantiated
73 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
74 :param _id: nsr internal id
75 :param db_content: The database content of the nsr
76 :return: None or raises EngineException with the conflict
81 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
82 raise EngineException(
83 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
84 "Launch 'terminate' operation first; or force deletion".format(_id
),
85 http_code
=HTTPStatus
.CONFLICT
,
88 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
90 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
91 Set usageState of pdu, vnfd, nsd
92 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
93 :param _id: server internal id
94 :param db_content: The database content of the descriptor
95 :param not_send_msg: To not send message (False) or store content (list) instead
96 :return: None if ok or raises EngineException with the problem
98 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
99 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
100 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
102 # set all used pdus as free
105 {"_admin.usage.nsr_id": _id
},
106 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
111 used_nsd_id
= nsr
.get("nsd-id")
113 # check if used by another NSR
114 nsrs_list
= self
.db
.get_one(
115 "nsrs", {"nsd-id": used_nsd_id
}, fail_on_empty
=False, fail_on_more
=False
119 "nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"}
122 # Set VNFD usageState
123 used_vnfd_id_list
= nsr
.get("vnfd-id")
124 if used_vnfd_id_list
:
125 for used_vnfd_id
in used_vnfd_id_list
:
126 # check if used by another NSR
127 nsrs_list
= self
.db
.get_one(
129 {"vnfd-id": used_vnfd_id
},
136 {"_id": used_vnfd_id
},
137 {"_admin.usageState": "NOT_IN_USE"},
140 # delete extra ro_nsrs used for internal RO module
141 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
144 def _format_ns_request(ns_request
):
145 formated_request
= copy(ns_request
)
146 formated_request
.pop("additionalParamsForNs", None)
147 formated_request
.pop("additionalParamsForVnf", None)
148 return formated_request
151 def _format_additional_params(
152 ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None
155 Get and format user additional params for NS or VNF.
156 The vdu_id and kdu_name params are mutually exclusive! If none of them are given, then the method will
157 exclusively search for the VNF/NS LCM additional params.
159 :param ns_request: User instantiation additional parameters
160 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
161 :vdu_id: VDU's ID against which we want to format the additional params
162 :kdu_name: KDU's name against which we want to format the additional params
163 :param descriptor: If not None it check that needed parameters of descriptor are supplied
164 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
166 additional_params
= None
168 if not member_vnf_index
:
169 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
170 where_
= "additionalParamsForNs"
171 elif ns_request
.get("additionalParamsForVnf"):
172 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
178 for x
in ns_request
["additionalParamsForVnf"]
179 if x
["member-vnf-index"] == member_vnf_index
184 if not vdu_id
and not kdu_name
:
186 additional_params
= copy(item
.get("additionalParams")) or {}
187 if vdu_id
and item
.get("additionalParamsForVdu"):
191 for x
in item
["additionalParamsForVdu"]
192 if x
["vdu_id"] == vdu_id
196 other_params
= item_vdu
197 if item_vdu
and item_vdu
.get("additionalParams"):
198 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
199 additional_params
= item_vdu
["additionalParams"]
201 additional_params
= {}
202 if item
.get("additionalParamsForKdu"):
206 for x
in item
["additionalParamsForKdu"]
207 if x
["kdu_name"] == kdu_name
211 other_params
= item_kdu
212 if item_kdu
and item_kdu
.get("additionalParams"):
213 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(
216 additional_params
= item_kdu
["additionalParams"]
218 if additional_params
:
219 for k
, v
in additional_params
.items():
220 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
221 if not kdu_name
and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k
):
222 raise EngineException(
223 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
224 "and underscores, and cannot start with a digit".format(
228 # END Check that additional parameter names are valid Jinja2 identifiers
229 if not isinstance(k
, str):
230 raise EngineException(
231 "Invalid param at {}:{}. Only string keys are allowed".format(
236 raise EngineException(
237 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
241 if isinstance(v
, (dict, tuple, list)):
242 additional_params
[k
] = "!!yaml " + safe_dump(v
)
244 additional_params
= json
.dumps(additional_params
)
246 # Select the VDU ID, KDU name or NS/VNF ID, depending on the method's call intent
247 selector
= vdu_id
if vdu_id
else kdu_name
if kdu_name
else descriptor
.get("id")
250 for df
in descriptor
.get("df", []):
251 # check that enough parameters are supplied for the initial-config-primitive
252 # TODO: check for cloud-init
254 initial_primitives
= []
256 "lcm-operations-configuration" in df
257 and "operate-vnf-op-config"
258 in df
["lcm-operations-configuration"]
260 for config
in df
["lcm-operations-configuration"][
261 "operate-vnf-op-config"
263 # Verify the target object (VNF|NS|VDU|KDU) where we need to populate
264 # the params with the additional ones given by the user
265 if config
.get("id") == selector
:
266 for primitive
in get_iterable(
267 config
.get("initial-config-primitive")
269 initial_primitives
.append(primitive
)
271 initial_primitives
= deep_get(
272 descriptor
, ("ns-configuration", "initial-config-primitive")
275 for initial_primitive
in get_iterable(initial_primitives
):
276 for param
in get_iterable(initial_primitive
.get("parameter")):
277 if param
["value"].startswith("<") and param
["value"].endswith(
280 if param
["value"] in (
288 not additional_params
289 or param
["value"][1:-1] not in additional_params
291 raise EngineException(
292 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
293 "initial-config-primitive[name={}] not supplied".format(
296 initial_primitive
["name"],
300 return additional_params
or None, other_params
or None
302 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
304 Creates a new nsr into database. It also creates needed vnfrs
305 :param rollback: list to append the created items at database in case a rollback must be done
306 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
307 :param indata: params to be used for the nsr
308 :param kwargs: used to override the indata descriptor
309 :param headers: http request headers
310 :return: the _id of nsr descriptor created at database. Or an exception of type
311 EngineException, ValidationError, DbException, FsException, MsgException.
312 Note: Exceptions are not captured on purpose. They should be captured at called
314 step
= "checking quotas" # first step must be defined outside try
316 self
.check_quota(session
)
318 step
= "validating input parameters"
319 ns_request
= self
._remove
_envelop
(indata
)
320 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
321 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
323 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
324 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
325 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
327 step
= "checking nsdOperationalState"
328 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
330 step
= "filling nsr from input data"
331 nsr_id
= str(uuid4())
332 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(
333 nsd
, ns_request
, nsr_id
, session
338 # TODO: Change for multiple df support
339 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
340 for vnfp
in vnf_profiles
:
341 vnfd_id
= vnfp
.get("vnfd-id")
342 vnf_index
= vnfp
.get("id")
344 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
348 if vnfd_id
not in needed_vnfds
:
349 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
350 if "revision" in vnfd
["_admin"]:
351 vnfd
["revision"] = vnfd
["_admin"]["revision"]
353 needed_vnfds
[vnfd_id
] = vnfd
354 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
356 vnfd
= needed_vnfds
[vnfd_id
]
358 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
361 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(
371 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
374 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
375 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
376 step
= "Updating VNFD usageState"
377 update_descriptor_usage_state(vnfd
, "vnfds", self
.db
)
379 step
= "creating nsr at database"
380 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
381 step
= "Updating NSD usageState"
382 update_descriptor_usage_state(nsd
, "nsds", self
.db
)
384 step
= "creating nsr temporal folder"
385 self
.fs
.mkdir(nsr_id
)
395 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
397 def _get_nsd_from_db(self
, nsd_id
, session
):
398 _filter
= self
._get
_project
_filter
(session
)
399 _filter
["_id"] = nsd_id
400 return self
.db
.get_one("nsds", _filter
)
402 def _get_vnfd_from_db(self
, vnfd_id
, session
):
403 _filter
= self
._get
_project
_filter
(session
)
404 _filter
["id"] = vnfd_id
405 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
408 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
410 nsr_descriptor
, session
["project_id"], make_public
=session
["public"]
412 self
.db
.create("nsrs", nsr_descriptor
)
413 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
415 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
417 vnfr_descriptor
, session
["project_id"], make_public
=session
["public"]
419 self
.db
.create("vnfrs", vnfr_descriptor
)
420 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
422 def _check_nsd_operational_state(self
, nsd
, ns_request
):
423 if nsd
["_admin"]["operationalState"] == "DISABLED":
424 raise EngineException(
425 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
426 "a network service".format(ns_request
["nsdId"]),
427 http_code
=HTTPStatus
.CONFLICT
,
430 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
431 additional_params
, _
= self
._format
_additional
_params
(
432 ns_request
, descriptor
=nsd
434 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
435 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
436 if ns_request
and ns_request
.get("k8s-namespace"):
437 ns_k8s_namespace
= ns_request
["k8s-namespace"]
438 if additional_params
and additional_params
.get("k8s-namespace"):
439 ns_k8s_namespace
= additional_params
["k8s-namespace"]
441 return ns_k8s_namespace
443 def _add_flavor_to_nsr(
444 self
, vdu
, vnfd
, nsr_descriptor
, member_vnf_index
, revision
=None
448 # Find this vdu compute and storage descriptors
449 vdu_virtual_compute
= {}
450 vdu_virtual_storage
= {}
451 for vcd
in vnfd
.get("virtual-compute-desc", ()):
452 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
453 vdu_virtual_compute
= vcd
454 for vsd
in vnfd
.get("virtual-storage-desc", ()):
455 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
456 vdu_virtual_storage
= vsd
457 # Get this vdu vcpus, memory and storage info for flavor_data
458 if vdu_virtual_compute
.get("virtual-cpu", {}).get("num-virtual-cpu"):
459 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"][
462 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
463 flavor_data
["memory-mb"] = (
464 float(vdu_virtual_compute
["virtual-memory"]["size"]) * 1024.0
466 if vdu_virtual_storage
.get("size-of-storage"):
467 flavor_data
["storage-gb"] = vdu_virtual_storage
["size-of-storage"]
468 # Get this vdu EPA info for guest_epa
469 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
470 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"]["cpu-quota"]
471 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
472 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
473 if vcpu_pinning
.get("thread-policy"):
474 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
["thread-policy"]
475 if vcpu_pinning
.get("policy"):
477 "SHARED" if vcpu_pinning
["policy"] == "dynamic" else "DEDICATED"
479 guest_epa
["cpu-pinning-policy"] = cpu_policy
480 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
481 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"]["mem-quota"]
482 if vdu_virtual_compute
.get("virtual-memory", {}).get("mempage-size"):
483 guest_epa
["mempage-size"] = vdu_virtual_compute
["virtual-memory"][
486 if vdu_virtual_compute
.get("virtual-memory", {}).get("numa-node-policy"):
487 guest_epa
["numa-node-policy"] = vdu_virtual_compute
["virtual-memory"][
490 if vdu_virtual_storage
.get("disk-io-quota"):
491 guest_epa
["disk-io-quota"] = vdu_virtual_storage
["disk-io-quota"]
494 flavor_data
["guest-epa"] = guest_epa
496 revision
= revision
if revision
is not None else 1
497 flavor_data
["name"] = (
498 vdu
["id"][:56] + "-" + member_vnf_index
+ "-" + str(revision
) + "-flv"
500 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
501 nsr_descriptor
["flavor"].append(flavor_data
)
503 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
505 additional_params
, _
= self
._format
_additional
_params
(
506 ns_request
, descriptor
=nsd
510 "name": ns_request
["nsName"],
511 "name-ref": ns_request
["nsName"],
512 "short-name": ns_request
["nsName"],
513 "admin-status": "ENABLED",
514 "nsState": "NOT_INSTANTIATED",
515 "currentOperation": "IDLE",
516 "currentOperationID": None,
517 "errorDescription": None,
519 "deploymentStatus": None,
520 "configurationStatus": None,
522 "nsd": {k
: v
for k
, v
in nsd
.items()},
523 "datacenter": ns_request
["vimAccountId"],
524 "resource-orchestrator": "osmopenmano",
525 "description": ns_request
.get("nsDescription", ""),
526 "constituent-vnfr-ref": [],
527 "operational-status": "init", # typedef ns-operational-
528 "config-status": "init", # typedef config-states
529 "detailed-status": "scheduled",
530 "orchestration-progress": {},
532 "nsd-name-ref": nsd
["name"],
533 "operational-events": [], # "id", "timestamp", "description", "event",
534 "nsd-ref": nsd
["id"],
535 "nsd-id": nsd
["_id"],
537 "instantiate_params": self
._format
_ns
_request
(ns_request
),
538 "additionalParamsForNs": additional_params
,
539 "ns-instance-config-ref": nsr_id
,
542 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
545 "affinity-or-anti-affinity-group": [],
547 if "revision" in nsd
["_admin"]:
548 nsr_descriptor
["revision"] = nsd
["_admin"]["revision"]
550 ns_request
["nsr_id"] = nsr_id
551 if ns_request
and ns_request
.get("config-units"):
552 nsr_descriptor
["config-units"] = ns_request
["config-units"]
554 if nsd
.get("virtual-link-desc"):
555 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
556 # Fill each vld with vnfd-connection-point-ref data
557 # TODO: Change for multiple df support
558 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
559 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
560 for vnf_profile
in vnf_profiles
:
561 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
562 for cpd
in vlc
.get("constituent-cpd-id", ()):
563 all_vld_connection_point_data
[
564 vlc
.get("virtual-link-profile-id")
567 "member-vnf-index-ref": cpd
.get(
568 "constituent-base-element-id"
570 "vnfd-connection-point-ref": cpd
.get(
573 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
577 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
580 for vdu
in vnfd
.get("vdu", ()):
581 member_vnf_index
= vnf_profile
.get("id")
582 self
._add
_flavor
_to
_nsr
(vdu
, vnfd
, nsr_descriptor
, member_vnf_index
)
583 sw_image_id
= vdu
.get("sw-image-desc")
585 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
586 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
588 # also add alternative images to the list of images
589 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
590 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
591 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
593 # Add Affinity or Anti-affinity group information to NSR
594 vdu_profiles
= vnfd
.get("df", [[]])[0].get("vdu-profile", ())
595 affinity_group_prefix_name
= "{}-{}".format(
596 nsr_descriptor
["name"][:16], vnf_profile
.get("id")[:16]
599 for vdu_profile
in vdu_profiles
:
600 affinity_group_data
= {}
601 for affinity_group
in vdu_profile
.get(
602 "affinity-or-anti-affinity-group", ()
604 affinity_group_data
= (
605 self
._get
_affinity
_or
_anti
_affinity
_group
_data
_from
_vnfd
(
606 vnfd
, affinity_group
["id"]
609 affinity_group_data
["member-vnf-index"] = vnf_profile
.get("id")
610 self
._add
_affinity
_or
_anti
_affinity
_group
_to
_nsr
(
613 affinity_group_prefix_name
,
617 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
620 vld
["name"] = vld
["id"]
621 nsr_descriptor
["vld"] = nsr_vld
623 return nsr_descriptor
625 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
626 self
, vnfd
, affinity_group_id
629 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
631 affinity_group
= utils
.find_in_list(
632 vnfd
.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
633 lambda ag
: ag
["id"] == affinity_group_id
,
635 affinity_group_data
= {}
637 if affinity_group
.get("id"):
638 affinity_group_data
["ag-id"] = affinity_group
["id"]
639 if affinity_group
.get("type"):
640 affinity_group_data
["type"] = affinity_group
["type"]
641 if affinity_group
.get("scope"):
642 affinity_group_data
["scope"] = affinity_group
["scope"]
643 return affinity_group_data
645 def _add_affinity_or_anti_affinity_group_to_nsr(
646 self
, nsr_descriptor
, affinity_group_data
, affinity_group_prefix_name
649 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
651 affinity_group
= next(
654 for f
in nsr_descriptor
["affinity-or-anti-affinity-group"]
655 if all(f
.get(k
) == affinity_group_data
[k
] for k
in affinity_group_data
)
659 if not affinity_group
:
660 affinity_group_data
["id"] = str(
661 len(nsr_descriptor
["affinity-or-anti-affinity-group"])
663 affinity_group_data
["name"] = "{}-{}".format(
664 affinity_group_prefix_name
, affinity_group_data
["ag-id"][:32]
666 nsr_descriptor
["affinity-or-anti-affinity-group"].append(
670 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
671 sw_image_desc
= utils
.find_in_list(
672 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
675 if sw_image_desc
.get("image"):
676 image_data
["image"] = sw_image_desc
["image"]
677 if sw_image_desc
.get("checksum"):
678 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
679 if sw_image_desc
.get("vim-type"):
680 image_data
["vim-type"] = sw_image_desc
["vim-type"]
683 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
685 Adds image to nsr checking first it is not already added
690 for f
in nsr_descriptor
["image"]
691 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
696 image_data
["id"] = str(len(nsr_descriptor
["image"]))
697 nsr_descriptor
["image"].append(image_data
)
699 def _create_vnfr_descriptor_from_vnfd(
710 vnfr_id
= str(uuid4())
711 nsr_id
= nsr_descriptor
["id"]
713 additional_params
, vnf_params
= self
._format
_additional
_params
(
714 ns_request
, vnf_index
, descriptor
=vnfd
720 "nsr-id-ref": nsr_id
,
721 "member-vnf-index-ref": vnf_index
,
722 "additionalParamsForVnf": additional_params
,
724 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
726 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
727 "vim-account-id": None,
730 "connection-point": [],
731 "ip-address": None, # mgmt-interface filled by LCM
734 # Revision backwards compatility. Only specify the revision in the record if
735 # the original VNFD has a revision.
736 if "revision" in vnfd
:
737 vnfr_descriptor
["revision"] = vnfd
["revision"]
739 vnf_k8s_namespace
= ns_k8s_namespace
741 if vnf_params
.get("k8s-namespace"):
742 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
743 if vnf_params
.get("config-units"):
744 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
747 if vnfd
.get("int-virtual-link-desc"):
748 vnfr_descriptor
["vld"] = []
749 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
750 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
752 for cp
in vnfd
.get("ext-cpd", ()):
754 "name": cp
.get("id"),
755 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
756 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
758 # "ip-address", "mac-address" # filled by LCM
759 # vim-id # TODO it would be nice having a vim port id
761 vnfr_descriptor
["connection-point"].append(vnf_cp
)
763 # Create k8s-cluster information
764 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
765 if vnfd
.get("k8s-cluster"):
766 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
767 all_k8s_cluster_nets_cpds
= {}
768 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
769 if cpd
.get("k8s-cluster-net"):
770 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
773 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
774 if net
.get("id") in all_k8s_cluster_nets_cpds
:
775 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
780 for kdu
in get_iterable(vnfd
.get("kdu")):
781 additional_params
, kdu_params
= self
._format
_additional
_params
(
782 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
784 kdu_k8s_namespace
= vnf_k8s_namespace
785 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
786 if kdu_params
and kdu_params
.get("k8s-namespace"):
787 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
789 kdu_deployment_name
= ""
790 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
791 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
794 "additionalParams": additional_params
,
795 "k8s-namespace": kdu_k8s_namespace
,
796 "kdu-deployment-name": kdu_deployment_name
,
797 "kdu-name": kdu
["name"],
798 # TODO "name": "" Name of the VDU in the VIM
799 "ip-address": None, # mgmt-interface filled by LCM
802 if kdu_params
and kdu_params
.get("config-units"):
803 kdur
["config-units"] = kdu_params
["config-units"]
804 if kdu
.get("helm-version"):
805 kdur
["helm-version"] = kdu
["helm-version"]
806 for k8s_type
in ("helm-chart", "juju-bundle"):
807 if kdu
.get(k8s_type
):
808 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
809 if not vnfr_descriptor
.get("kdur"):
810 vnfr_descriptor
["kdur"] = []
811 vnfr_descriptor
["kdur"].append(kdur
)
813 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
815 for vdu
in vnfd
.get("vdu", ()):
818 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
819 "operate-vnf-op-config"
821 vdu_config
= utils
.find_in_list(
822 configs
, lambda config
: config
["id"] == vdu
["id"]
828 vdu_instantiation_level
= utils
.find_in_list(
829 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
830 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
833 vdu_instantiation_level
= None
836 external_connection_ee
= utils
.filter_in_list(
837 vdu_config
.get("execution-environment-list", []),
838 lambda ee
: "external-connection-point-ref" in ee
,
840 for ee
in external_connection_ee
:
841 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
843 additional_params
, vdu_params
= self
._format
_additional
_params
(
844 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
848 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
849 vnfd
.get("virtual-storage-desc", []),
850 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"],
853 vdu_virtual_storage_descriptors
= []
855 "vdu-id-ref": vdu
["id"],
856 # TODO "name": "" Name of the VDU in the VIM
857 "ip-address": None, # mgmt-interface filled by LCM
858 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
859 "internal-connection-point": [],
861 "additionalParams": additional_params
,
862 "vdu-name": vdu
["name"],
863 "virtual-storages": vdu_virtual_storage_descriptors
,
865 if vdu_params
and vdu_params
.get("config-units"):
866 vdur
["config-units"] = vdu_params
["config-units"]
867 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
868 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
871 if vdu
.get("pdu-type"):
872 vdur
["pdu-type"] = vdu
["pdu-type"]
873 vdur
["name"] = vdu
["pdu-type"]
874 # TODO volumes: name, volume-id
875 for icp
in vdu
.get("int-cpd", ()):
878 "connection-point-id": icp
["id"],
879 "name": icp
.get("id"),
882 vdur
["internal-connection-point"].append(vdu_icp
)
884 for iface
in icp
.get("virtual-network-interface-requirement", ()):
885 # Name, mac-address and interface position is taken from VNFD
886 # and included into VNFR. By this way RO can process this information
887 # while creating the VDU.
888 iface_fields
= ("name", "mac-address", "position")
890 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
893 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
894 if "port-security-enabled" in icp
:
895 vdu_iface
["port-security-enabled"] = icp
[
896 "port-security-enabled"
899 if "port-security-disable-strategy" in icp
:
900 vdu_iface
["port-security-disable-strategy"] = icp
[
901 "port-security-disable-strategy"
904 for ext_cp
in vnfd
.get("ext-cpd", ()):
905 if not ext_cp
.get("int-cpd"):
907 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
909 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
910 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
914 if "port-security-enabled" in ext_cp
:
915 vdu_iface
["port-security-enabled"] = ext_cp
[
916 "port-security-enabled"
919 if "port-security-disable-strategy" in ext_cp
:
920 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
921 "port-security-disable-strategy"
928 and vdu_iface
.get("external-connection-point-ref")
931 vdu_iface
["mgmt-vnf"] = True
932 vdu_iface
["mgmt-interface"] = True
934 for ecp
in vdu_mgmt_cp
:
935 if vdu_iface
.get("external-connection-point-ref") == ecp
:
936 vdu_iface
["mgmt-interface"] = True
938 if iface
.get("virtual-interface"):
939 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
941 # look for network where this interface is connected
942 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
944 # TODO: Change for multiple df support
945 for df
in get_iterable(nsd
.get("df")):
946 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
947 for vlc_index
, vlc
in enumerate(
949 vnf_profile
.get("virtual-link-connectivity")
952 for cpd
in get_iterable(
953 vlc
.get("constituent-cpd-id")
956 cpd
.get("constituent-cpd-id")
959 vdu_iface
["ns-vld-id"] = vlc
.get(
960 "virtual-link-profile-id"
962 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
963 if vdu_iface
.get("type") in (
967 nsr_descriptor
["vld"][vlc_index
][
971 elif vdu_iface
.get("internal-connection-point-ref"):
972 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
973 # TODO: store fixed IP address in the record (if it exists in the ICP)
974 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
975 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
976 ivld_index
= utils
.find_index_in_list(
977 vnfd
.get("int-virtual-link-desc", ()),
978 lambda ivld
: ivld
["id"]
979 == icp
.get("int-virtual-link-desc"),
981 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
983 vdur
["interfaces"].append(vdu_iface
)
985 if vdu
.get("sw-image-desc"):
986 sw_image
= utils
.find_in_list(
987 vnfd
.get("sw-image-desc", ()),
988 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
990 nsr_sw_image_data
= utils
.find_in_list(
991 nsr_descriptor
["image"],
992 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
994 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
996 if vdu
.get("alternative-sw-image-desc"):
998 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
999 sw_image
= utils
.find_in_list(
1000 vnfd
.get("sw-image-desc", ()),
1001 lambda image
: image
["id"] == alt_image_id
,
1003 nsr_sw_image_data
= utils
.find_in_list(
1004 nsr_descriptor
["image"],
1006 nsr_image
.get("image") == sw_image
.get("image")
1009 alt_image_ids
.append(nsr_sw_image_data
["id"])
1010 vdur
["alt-image-ids"] = alt_image_ids
1012 revision
= revision
if revision
is not None else 1
1013 flavor_data_name
= (
1014 vdu
["id"][:56] + "-" + vnf_index
+ "-" + str(revision
) + "-flv"
1016 nsr_flavor_desc
= utils
.find_in_list(
1017 nsr_descriptor
["flavor"],
1018 lambda flavor
: flavor
["name"] == flavor_data_name
,
1022 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
1024 # Adding Affinity groups information to vdur
1026 vdu_profile_affinity_group
= utils
.find_in_list(
1027 vnfd
.get("df")[0]["vdu-profile"],
1028 lambda a_vdu
: a_vdu
["id"] == vdu
["id"],
1031 vdu_profile_affinity_group
= None
1033 if vdu_profile_affinity_group
:
1034 affinity_group_ids
= []
1035 for affinity_group
in vdu_profile_affinity_group
.get(
1036 "affinity-or-anti-affinity-group", ()
1038 vdu_affinity_group
= utils
.find_in_list(
1039 vdu_profile_affinity_group
.get(
1040 "affinity-or-anti-affinity-group", ()
1042 lambda ag_fp
: ag_fp
["id"] == affinity_group
["id"],
1044 nsr_affinity_group
= utils
.find_in_list(
1045 nsr_descriptor
["affinity-or-anti-affinity-group"],
1047 nsr_ag
.get("ag-id") == vdu_affinity_group
.get("id")
1048 and nsr_ag
.get("member-vnf-index")
1049 == vnfr_descriptor
.get("member-vnf-index-ref")
1052 # Update Affinity Group VIM name if VDU instantiation parameter is present
1053 if vnf_params
and vnf_params
.get("affinity-or-anti-affinity-group"):
1054 vnf_params_affinity_group
= utils
.find_in_list(
1055 vnf_params
["affinity-or-anti-affinity-group"],
1057 vnfp_ag
.get("id") == vdu_affinity_group
.get("id")
1060 if vnf_params_affinity_group
.get("vim-affinity-group-id"):
1062 "vim-affinity-group-id"
1063 ] = vnf_params_affinity_group
["vim-affinity-group-id"]
1064 affinity_group_ids
.append(nsr_affinity_group
["id"])
1065 vdur
["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1067 if vdu_instantiation_level
:
1068 count
= vdu_instantiation_level
.get("number-of-instances")
1072 for index
in range(0, count
):
1073 vdur
= deepcopy(vdur
)
1074 for iface
in vdur
["interfaces"]:
1075 if iface
.get("ip-address") and index
!= 0:
1076 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
1077 if iface
.get("mac-address") and index
!= 0:
1078 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
1080 vdur
["_id"] = str(uuid4())
1081 vdur
["id"] = vdur
["_id"]
1082 vdur
["count-index"] = index
1083 vnfr_descriptor
["vdur"].append(vdur
)
1085 return vnfr_descriptor
1087 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
1089 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1090 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1091 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1092 :param ns_instance_content: ns instance content
1093 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1096 time_now
, time_delta
= (
1098 time() - ns_instance_content
["_admin"]["modified"],
1101 isinstance(filter_q
, dict) and filter_q
.get("vcaStatusRefresh") == "true"
1103 threshold_reached
= time_delta
> 120
1104 if force_refresh
or threshold_reached
:
1105 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
1106 ns_instance_content
["_admin"]["modified"] = time_now
1107 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
1108 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
1110 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
1112 nslcmop_desc
["_admin"].pop("nsState")
1113 self
.msg
.write("ns", operation
, nslcmop_desc
)
1116 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1118 Get complete information on an ns instance.
1119 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1120 :param _id: string, ns instance id
1121 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1122 :param api_req: True if this call is serving an external API request. False if serving internal request.
1123 :return: dictionary, raise exception if not found.
1125 ns_instance_content
= super().show(session
, _id
, api_req
)
1126 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1127 return ns_instance_content
1129 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1130 raise EngineException(
1131 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1135 class VnfrTopic(BaseTopic
):
1139 def __init__(self
, db
, fs
, msg
, auth
):
1140 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1142 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1143 raise EngineException(
1144 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1147 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1148 raise EngineException(
1149 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1152 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1153 # Not used because vnfrs are created and deleted by NsrTopic class directly
1154 raise EngineException(
1155 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1159 class NsLcmOpTopic(BaseTopic
):
1162 operation_schema
= { # mapping between operation and jsonschema to validate
1163 "instantiate": ns_instantiate
,
1164 "action": ns_action
,
1165 "update": ns_update
,
1168 "terminate": ns_terminate
,
1169 "migrate": ns_migrate
,
1170 "verticalscale": ns_verticalscale
,
1173 def __init__(self
, db
, fs
, msg
, auth
):
1174 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1175 self
.nsrtopic
= NsrTopic(db
, fs
, msg
, auth
)
1177 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1179 Check that user has enter right parameters for the operation
1180 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1181 :param operation: it can be: instantiate, terminate, action, update, heal
1182 :param indata: descriptor with the parameters of the operation
1185 if operation
== "action":
1186 self
._check
_action
_ns
_operation
(indata
, nsr
)
1187 elif operation
== "scale":
1188 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1189 elif operation
== "update":
1190 self
._check
_update
_ns
_operation
(indata
, nsr
)
1191 elif operation
== "heal":
1192 self
._check
_heal
_ns
_operation
(indata
, nsr
)
1193 elif operation
== "instantiate":
1194 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1196 def _check_action_ns_operation(self
, indata
, nsr
):
1198 # check vnf_member_index
1199 if indata
.get("vnf_member_index"):
1200 indata
["member_vnf_index"] = indata
.pop(
1202 ) # for backward compatibility
1203 if indata
.get("member_vnf_index"):
1204 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1205 indata
["member_vnf_index"], nsr
["_id"]
1208 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1209 "operate-vnf-op-config"
1214 if indata
.get("vdu_id"):
1215 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1216 descriptor_configuration
= utils
.find_in_list(
1217 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1219 elif indata
.get("kdu_name"):
1220 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1221 descriptor_configuration
= utils
.find_in_list(
1222 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1225 descriptor_configuration
= utils
.find_in_list(
1226 configs
, lambda config
: config
["id"] == vnfd
["id"]
1228 if descriptor_configuration
is not None:
1229 descriptor_configuration
= descriptor_configuration
.get(
1233 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1237 # For k8s allows default primitives without validating the parameters
1238 if indata
.get("kdu_name") and indata
["primitive"] in (
1245 # TODO should be checked that rollback only can contains revsision_numbe????
1246 if not indata
.get("member_vnf_index"):
1247 raise EngineException(
1248 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1253 # if not, check primitive
1254 for config_primitive
in get_iterable(descriptor_configuration
):
1255 if indata
["primitive"] == config_primitive
["name"]:
1256 # check needed primitive_params are provided
1257 if indata
.get("primitive_params"):
1258 in_primitive_params_copy
= copy(indata
["primitive_params"])
1260 in_primitive_params_copy
= {}
1261 for paramd
in get_iterable(config_primitive
.get("parameter")):
1262 if paramd
["name"] in in_primitive_params_copy
:
1263 del in_primitive_params_copy
[paramd
["name"]]
1264 elif not paramd
.get("default-value"):
1265 raise EngineException(
1266 "Needed parameter {} not provided for primitive '{}'".format(
1267 paramd
["name"], indata
["primitive"]
1270 # check no extra primitive params are provided
1271 if in_primitive_params_copy
:
1272 raise EngineException(
1273 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1274 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1279 raise EngineException(
1280 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1285 def _check_update_ns_operation(self
, indata
, nsr
) -> None:
1286 """Validates the ns-update request according to updateType
1288 If updateType is CHANGE_VNFPKG:
1289 - it checks the vnfInstanceId, whether it's available under ns instance
1290 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1291 Otherwise exception will be raised.
1292 If updateType is REMOVE_VNF:
1293 - it checks if the vnfInstanceId is available in the ns instance
1294 - Otherwise exception will be raised.
1297 indata: includes updateType such as CHANGE_VNFPKG,
1298 nsr: network service record
1302 a meaningful error if given update parameters are not proper such as
1303 "Error in validating ns-update request: <ID> does not match
1304 with the vnfd-id of vnfinstance
1305 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1309 if indata
["updateType"] == "CHANGE_VNFPKG":
1310 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1311 vnf_instance_id
= indata
["changeVnfPackageData"]["vnfInstanceId"]
1312 ns_instance_id
= indata
["nsInstanceId"]
1313 vnfd_id_2update
= indata
["changeVnfPackageData"]["vnfdId"]
1315 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1316 raise EngineException(
1317 f
"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1318 f
"belong to NS {ns_instance_id}",
1319 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1322 # Getting vnfrs through the ns_instance_id
1323 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": ns_instance_id
})
1324 constituent_vnfd_id
= next(
1328 if vnfr
["id"] == vnf_instance_id
1333 # Check the given vnfd-id belongs to given vnf instance
1334 if constituent_vnfd_id
and (vnfd_id_2update
!= constituent_vnfd_id
):
1335 raise EngineException(
1336 f
"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1337 f
"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1338 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1341 # Validating the ns update timeout
1343 indata
.get("timeout_ns_update")
1344 and indata
["timeout_ns_update"] < 300
1346 raise EngineException(
1347 "Error in validating ns-update request: {} second is not enough "
1348 "to upgrade the VNF instance: {}".format(
1349 indata
["timeout_ns_update"], vnf_instance_id
1351 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
1353 elif indata
["updateType"] == "REMOVE_VNF":
1354 vnf_instance_id
= indata
["removeVnfInstanceId"]
1355 ns_instance_id
= indata
["nsInstanceId"]
1356 if vnf_instance_id
not in nsr
["constituent-vnfr-ref"]:
1357 raise EngineException(
1358 "Invalid VNF Instance Id. '{}' is not "
1359 "present in the NS '{}'".format(vnf_instance_id
, ns_instance_id
)
1370 "Ns update request could not be processed with error: {}.".format(e
)
1373 def _check_scale_ns_operation(self
, indata
, nsr
):
1374 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1375 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1377 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1379 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1380 == scaling_aspect
["id"]
1384 raise EngineException(
1385 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1386 "present at vnfd:scaling-aspect".format(
1387 indata
["scaleVnfData"]["scaleByStepData"][
1388 "scaling-group-descriptor"
1393 def _check_heal_ns_operation(self
, indata
, nsr
):
1396 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1397 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1401 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1402 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1403 for in_vnf
in get_iterable(indata
.get("vnf")):
1404 member_vnf_index
= in_vnf
["member-vnf-index"]
1405 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1406 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1408 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1409 member_vnf_index
, nsr
["_id"]
1411 vnf_member_index_to_vnfd
[
1413 ] = vnfd
# add to cache, avoiding a later look for
1414 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1415 if in_vnf
.get("vimAccountId"):
1416 self
._check
_valid
_vim
_account
(
1417 in_vnf
["vimAccountId"], vim_accounts
, session
1420 for in_vld
in get_iterable(indata
.get("vld")):
1421 self
._check
_valid
_wim
_account
(
1422 in_vld
.get("wimAccountId"), wim_accounts
, session
1424 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1425 if in_vld
["name"] == vldd
["id"]:
1428 raise EngineException(
1429 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1434 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1435 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1436 vnfr
= self
.db
.get_one(
1438 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1439 fail_on_empty
=False,
1442 raise EngineException(
1443 "Invalid parameter member_vnf_index='{}' is not one of the "
1444 "nsd:constituent-vnfd".format(member_vnf_index
)
1447 # Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1448 if "revision" in vnfr
:
1449 vnfd_revision
= vnfr
["vnfd-id"] + ":" + str(vnfr
["revision"])
1450 vnfd
= self
.db
.get_one(
1451 "vnfds_revisions", {"_id": vnfd_revision
}, fail_on_empty
=False
1454 vnfd
= self
.db
.get_one(
1455 "vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False
1459 raise EngineException(
1460 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1466 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1467 for vdud
in get_iterable(vnfd
.get("vdu")):
1468 if vdud
["id"] == vdu_id
:
1471 raise EngineException(
1472 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1477 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1478 for kdud
in get_iterable(vnfd
.get("kdu")):
1479 if kdud
["name"] == kdu_name
:
1482 raise EngineException(
1483 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1488 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1489 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1490 for vdu
in get_iterable(vnfd
.get("vdu")):
1491 if in_vdu
["id"] == vdu
["id"]:
1492 for volume
in get_iterable(in_vdu
.get("volume")):
1493 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1494 if volumed
== volume
["name"]:
1497 raise EngineException(
1498 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1499 "volume:name='{}' is not present at "
1500 "vnfd:vdu:virtual-storage-desc list".format(
1501 in_vnf
["member-vnf-index"],
1507 vdu_if_names
= set()
1508 for cpd
in get_iterable(vdu
.get("int-cpd")):
1509 for iface
in get_iterable(
1510 cpd
.get("virtual-network-interface-requirement")
1512 vdu_if_names
.add(iface
.get("name"))
1514 for in_iface
in get_iterable(in_vdu
.get("interface")):
1515 if in_iface
["name"] in vdu_if_names
:
1518 raise EngineException(
1519 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1520 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1521 in_vnf
["member-vnf-index"],
1529 raise EngineException(
1530 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1531 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1535 ivld
.get("id"): set()
1536 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1538 for vdu
in get_iterable(vnfd
.get("vdu")):
1539 for cpd
in get_iterable(vnfd
.get("int-cpd")):
1540 if cpd
.get("int-virtual-link-desc"):
1541 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1543 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1544 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1545 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1546 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1549 raise EngineException(
1550 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1551 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1552 "vnfd:internal-vld:name/id:internal-connection-point".format(
1553 in_vnf
["member-vnf-index"],
1559 raise EngineException(
1560 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1561 " is not present at vnfd '{}'".format(
1562 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1566 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1567 if vim_account
in vim_accounts
:
1570 db_filter
= self
._get
_project
_filter
(session
)
1571 db_filter
["_id"] = vim_account
1572 self
.db
.get_one("vim_accounts", db_filter
)
1574 raise EngineException(
1575 "Invalid vimAccountId='{}' not present for the project".format(
1579 vim_accounts
.append(vim_account
)
1581 def _get_vim_account(self
, vim_id
: str, session
):
1583 db_filter
= self
._get
_project
_filter
(session
)
1584 db_filter
["_id"] = vim_id
1585 return self
.db
.get_one("vim_accounts", db_filter
)
1587 raise EngineException(
1588 "Invalid vimAccountId='{}' not present for the project".format(vim_id
)
1591 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1592 if not isinstance(wim_account
, str):
1594 if wim_account
in wim_accounts
:
1597 db_filter
= self
._get
_project
_filter
(session
)
1598 db_filter
["_id"] = wim_account
1599 self
.db
.get_one("wim_accounts", db_filter
)
1601 raise EngineException(
1602 "Invalid wimAccountId='{}' not present for the project".format(
1606 wim_accounts
.append(wim_account
)
1609 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1612 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1613 (ip_address, ...) information.
1614 Modifies PDU _admin.usageState to 'IN_USE'
1615 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1616 :param rollback: list with the database modifications to rollback if needed
1617 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1618 :param vim_account: vim_account where this vnfr should be deployed
1619 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1620 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1621 of the changed vnfr is needed
1623 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1624 "vim-network-name": used at VIM
1625 "name": interface name
1626 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1627 "ns-vld-id": NSD vld where this interface is connected.
1628 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1631 ifaces_forcing_vim_network
= []
1632 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1633 if not vdur
.get("pdu-type"):
1635 pdu_type
= vdur
.get("pdu-type")
1636 pdu_filter
= self
._get
_project
_filter
(session
)
1637 pdu_filter
["vim_accounts"] = vim_account
1638 pdu_filter
["type"] = pdu_type
1639 pdu_filter
["_admin.operationalState"] = "ENABLED"
1640 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1641 # TODO feature 1417: "shared": True,
1643 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1644 for pdu
in available_pdus
:
1645 # step 1 check if this pdu contains needed interfaces:
1646 match_interfaces
= True
1647 for vdur_interface
in vdur
["interfaces"]:
1648 for pdu_interface
in pdu
["interfaces"]:
1649 if pdu_interface
["name"] == vdur_interface
["name"]:
1650 # TODO feature 1417: match per mgmt type
1652 else: # no interface found for name
1653 match_interfaces
= False
1655 if match_interfaces
:
1658 raise EngineException(
1659 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1663 vnfr
["member-vnf-index-ref"],
1668 # step 2. Update pdu
1670 "_admin.usageState": pdu
["_admin"]["usageState"],
1671 "_admin.usage.vnfr_id": None,
1672 "_admin.usage.nsr_id": None,
1673 "_admin.usage.vdur": None,
1677 {"_id": pdu
["_id"]},
1679 "_admin.usageState": "IN_USE",
1681 "vnfr_id": vnfr
["_id"],
1682 "nsr_id": vnfr
["nsr-id-ref"],
1683 "vdur": vdur
["vdu-id-ref"],
1692 "content": rollback_pdu
,
1696 # step 3. Fill vnfr info by filling vdur
1697 vdu_text
= "vdur.{}".format(vdur_index
)
1698 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1699 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1700 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1701 for pdu_interface
in pdu
["interfaces"]:
1702 if pdu_interface
["name"] == vdur_interface
["name"]:
1703 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1704 for k
, v
in pdu_interface
.items():
1708 ): # TODO: switch-xxxxx must be inserted
1709 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1710 vnfr_update_rollback
[
1711 iface_text
+ ".{}".format(k
)
1712 ] = vdur_interface
.get(v
)
1713 if pdu_interface
.get("ip-address"):
1714 if vdur_interface
.get(
1716 ) or vdur_interface
.get("mgmt-vnf"):
1717 vnfr_update_rollback
[
1718 vdu_text
+ ".ip-address"
1719 ] = vdur
.get("ip-address")
1720 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1723 if vdur_interface
.get("mgmt-vnf"):
1724 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1727 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1728 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1731 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1734 ifaces_forcing_vim_network
.append(
1736 "name": vdur_interface
.get("vnf-vld-id")
1737 or vdur_interface
.get("ns-vld-id"),
1738 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1739 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1742 if pdu_interface
.get("vim-network-id"):
1743 ifaces_forcing_vim_network
[-1][
1745 ] = pdu_interface
["vim-network-id"]
1746 if pdu_interface
.get("vim-network-name"):
1747 ifaces_forcing_vim_network
[-1][
1749 ] = pdu_interface
["vim-network-name"]
1752 return ifaces_forcing_vim_network
1754 def _look_for_k8scluster(
1755 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1758 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1759 Fills vnfr.kdur with the selected k8scluster
1761 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1762 :param rollback: list with the database modifications to rollback if needed
1763 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1764 :param vim_account: vim_account where this vnfr should be deployed
1765 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1766 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1767 of the changed vnfr is needed
1769 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1770 "vim-network-name": used at VIM
1771 "name": interface name
1772 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1773 "ns-vld-id": NSD vld where this interface is connected.
1774 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1777 ifaces_forcing_vim_network
= []
1778 if not vnfr
.get("kdur"):
1779 return ifaces_forcing_vim_network
1781 kdu_filter
= self
._get
_project
_filter
(session
)
1782 kdu_filter
["vim_account"] = vim_account
1783 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1784 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1786 k8s_requirements
= {} # just for logging
1787 for k8scluster
in available_k8sclusters
:
1788 if not vnfr
.get("k8s-cluster"):
1791 if vnfr
["k8s-cluster"].get("cni"):
1792 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1793 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1794 k8scluster
.get("cni", ())
1797 # restrict by version
1798 if vnfr
["k8s-cluster"].get("version"):
1799 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1800 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1802 # restrict by number of networks
1803 if vnfr
["k8s-cluster"].get("nets"):
1804 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1805 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1806 vnfr
["k8s-cluster"]["nets"]
1811 raise EngineException(
1812 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1813 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1817 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1818 # step 3. Fill vnfr info by filling kdur
1819 kdu_text
= "kdur.{}.".format(kdur_index
)
1820 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1821 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1823 # step 4. Check VIM networks that forces the selected k8s_cluster
1824 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1825 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1826 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1827 # get a network from k8s_cluster nets. If name matches use this, if not use other
1828 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1829 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1830 k8scluster_net_list
.remove(kdur_net
["id"])
1832 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1833 k8scluster_net_list
.pop(0)
1834 vnfr_update_rollback
[
1835 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1837 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1839 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1841 ifaces_forcing_vim_network
.append(
1843 "name": kdur_net
.get("vnf-vld-id")
1844 or kdur_net
.get("ns-vld-id"),
1845 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1846 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1847 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1850 # TODO check that this forcing is not incompatible with other forcing
1851 return ifaces_forcing_vim_network
1853 def _update_vnfrs_from_nsd(self
, nsr
):
1854 step
= "Getting vnf_profiles from nsd" # first step must be defined outside try
1859 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
1860 vld_fixed_ip_connection_point_data
= {}
1862 step
= "Getting ip-address info from vnf_profile if it exists"
1863 for vnfp
in vnf_profiles
:
1864 # Checking ip-address info from nsd.vnf_profile and storing
1865 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
1866 for cpd
in vlc
.get("constituent-cpd-id", ()):
1867 if cpd
.get("ip-address"):
1868 step
= "Storing ip-address info"
1869 vld_fixed_ip_connection_point_data
.update(
1871 vlc
.get("virtual-link-profile-id")
1873 + cpd
.get("constituent-base-element-id"): {
1874 "vnfd-connection-point-ref": cpd
.get(
1875 "constituent-cpd-id"
1877 "ip-address": cpd
.get("ip-address"),
1882 # Inserting ip address to vnfr
1883 if len(vld_fixed_ip_connection_point_data
) > 0:
1884 step
= "Getting vnfrs"
1885 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1886 for item
in vld_fixed_ip_connection_point_data
.keys():
1887 step
= "Filtering vnfrs"
1890 lambda vnfr
: vnfr
["member-vnf-index-ref"]
1891 == item
.split(".")[1],
1898 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1899 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1900 step
= "Looking for matched interface"
1902 iface
.get("external-connection-point-ref")
1903 == vld_fixed_ip_connection_point_data
[item
].get(
1904 "vnfd-connection-point-ref"
1906 and iface
.get("ns-vld-id") == item
.split(".")[0]
1908 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1909 vdur_index
, iface_index
1911 step
= "Storing info in order to update vnfr"
1913 vnfr_update_text
+ ".ip-address"
1914 ] = increment_ip_mac(
1915 vld_fixed_ip_connection_point_data
[item
].get(
1918 vdur
.get("count-index", 0),
1920 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1922 step
= "updating vnfr at database"
1923 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1931 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
1933 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1936 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1940 vnfr_update_rollback
= {}
1941 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1942 # update vim-account-id
1944 vim_account
= indata
["vimAccountId"]
1945 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1946 # check instantiate parameters
1947 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1948 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1950 if vnf_inst_params
.get("vimAccountId"):
1951 vim_account
= vnf_inst_params
.get("vimAccountId")
1952 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1954 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1955 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1956 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1957 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1959 for iface_inst_param
in get_iterable(
1960 vdu_inst_param
.get("interface")
1962 iface_index
, _
= next(
1964 for i
in enumerate(vdur
["interfaces"])
1965 if i
[1]["name"] == iface_inst_param
["name"]
1967 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1968 vdur_index
, iface_index
1970 if iface_inst_param
.get("ip-address"):
1972 vnfr_update_text
+ ".ip-address"
1973 ] = increment_ip_mac(
1974 iface_inst_param
.get("ip-address"),
1975 vdur
.get("count-index", 0),
1977 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1978 if iface_inst_param
.get("mac-address"):
1980 vnfr_update_text
+ ".mac-address"
1981 ] = increment_ip_mac(
1982 iface_inst_param
.get("mac-address"),
1983 vdur
.get("count-index", 0),
1985 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1986 if iface_inst_param
.get("floating-ip-required"):
1988 vnfr_update_text
+ ".floating-ip-required"
1990 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1991 # TODO update vld with the ip-profile
1992 for ivld_inst_param
in get_iterable(
1993 vnf_inst_params
.get("internal-vld")
1995 for icp_inst_param
in get_iterable(
1996 ivld_inst_param
.get("internal-connection-point")
1999 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2000 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2002 iface
.get("internal-connection-point-ref")
2003 == icp_inst_param
["id-ref"]
2005 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2006 vdur_index
, iface_index
2008 if icp_inst_param
.get("ip-address"):
2010 vnfr_update_text
+ ".ip-address"
2011 ] = increment_ip_mac(
2012 icp_inst_param
.get("ip-address"),
2013 vdur
.get("count-index", 0),
2016 vnfr_update_text
+ ".fixed-ip"
2018 if icp_inst_param
.get("mac-address"):
2020 vnfr_update_text
+ ".mac-address"
2021 ] = increment_ip_mac(
2022 icp_inst_param
.get("mac-address"),
2023 vdur
.get("count-index", 0),
2026 vnfr_update_text
+ ".fixed-mac"
2029 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2030 for vld_inst_param
in get_iterable(indata
.get("vld")):
2031 for vnfcp_inst_param
in get_iterable(
2032 vld_inst_param
.get("vnfd-connection-point-ref")
2034 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
2037 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
2038 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
2040 iface
.get("external-connection-point-ref")
2041 == vnfcp_inst_param
["vnfd-connection-point-ref"]
2043 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
2044 vdur_index
, iface_index
2046 if vnfcp_inst_param
.get("ip-address"):
2048 vnfr_update_text
+ ".ip-address"
2049 ] = increment_ip_mac(
2050 vnfcp_inst_param
.get("ip-address"),
2051 vdur
.get("count-index", 0),
2053 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
2054 if vnfcp_inst_param
.get("mac-address"):
2056 vnfr_update_text
+ ".mac-address"
2057 ] = increment_ip_mac(
2058 vnfcp_inst_param
.get("mac-address"),
2059 vdur
.get("count-index", 0),
2061 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
2064 vnfr_update
["vim-account-id"] = vim_account
2065 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
2068 vnfr_update
["vca-id"] = vca_id
2069 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
2072 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
2073 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2077 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
2078 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
2080 # update database vnfr
2081 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
2087 "content": vnfr_update_rollback
,
2091 # Update indada in case pdu forces to use a concrete vim-network-name
2092 # TODO check if user has already insert a vim-network-name and raises an error
2093 if not ifaces_forcing_vim_network
:
2095 for iface_info
in ifaces_forcing_vim_network
:
2096 if iface_info
.get("ns-vld-id"):
2097 if "vld" not in indata
:
2099 indata
["vld"].append(
2101 key
: iface_info
[key
]
2102 for key
in ("name", "vim-network-name", "vim-network-id")
2103 if iface_info
.get(key
)
2107 elif iface_info
.get("vnf-vld-id"):
2108 if "vnf" not in indata
:
2110 indata
["vnf"].append(
2112 "member-vnf-index": member_vnf_index
,
2115 key
: iface_info
[key
]
2121 if iface_info
.get(key
)
2128 def _create_nslcmop(nsr_id
, operation
, params
):
2130 Creates a ns-lcm-opp content to be stored at database.
2131 :param nsr_id: internal id of the instance
2132 :param operation: instantiate, terminate, scale, action, update ...
2133 :param params: user parameters for the operation
2134 :return: dictionary following SOL005 format
2141 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2142 "queuePosition": None,
2144 "errorMessage": None,
2145 "detailedStatus": None,
2146 "statusEnteredTime": now
,
2147 "nsInstanceId": nsr_id
,
2148 "lcmOperationType": operation
,
2150 "isAutomaticInvocation": False,
2151 "operationParams": params
,
2152 "isCancelPending": False,
2154 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2155 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2160 def _get_enabled_vims(self
, session
):
2162 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2163 :param session: current session with user information
2165 db_filter
= self
._get
_project
_filter
(session
)
2166 db_filter
["_admin.operationalState"] = "ENABLED"
2167 vims
= self
.db
.get_list("vim_accounts", db_filter
)
2170 vimAccounts
.append(vim
["_id"])
2183 Performs a new operation over a ns
2184 :param rollback: list to append created items at database in case a rollback must to be done
2185 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2186 :param indata: descriptor with the parameters of the operation. It must contains among others
2187 nsInstanceId: _id of the nsr to perform the operation
2188 operation: it can be: instantiate, terminate, action, update TODO: heal
2189 :param kwargs: used to override the indata descriptor
2190 :param headers: http request headers
2191 :return: id of the nslcmops
2194 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
2196 db_filter
= self
._get
_project
_filter
(session
)
2197 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2198 nsis
= self
.db
.get_one(
2199 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
2202 raise EngineException(
2203 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2206 http_code
=HTTPStatus
.CONFLICT
,
2210 # Override descriptor with query string kwargs
2211 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
2212 operation
= indata
["lcmOperationType"]
2213 nsInstanceId
= indata
["nsInstanceId"]
2215 validate_input(indata
, self
.operation_schema
[operation
])
2216 # get ns from nsr_id
2217 _filter
= BaseTopic
._get
_project
_filter
(session
)
2218 _filter
["_id"] = nsInstanceId
2219 nsr
= self
.db
.get_one("nsrs", _filter
)
2222 if operation
== "terminate" and slice_object
is False:
2223 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
2225 not nsr
["_admin"].get("nsState")
2226 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
2228 if operation
== "terminate" and indata
.get("autoremove"):
2229 # NSR must be deleted
2233 ) # a none in this case is used to indicate not instantiated. It can be removed
2234 if operation
!= "instantiate":
2235 raise EngineException(
2236 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2237 nsInstanceId
, operation
2239 HTTPStatus
.CONFLICT
,
2242 if operation
== "instantiate" and not session
["force"]:
2243 raise EngineException(
2244 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2245 nsInstanceId
, operation
2247 HTTPStatus
.CONFLICT
,
2249 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
2250 if indata
.get("primitive_params"):
2251 indata
["primitive_params"] = json
.dumps(indata
["primitive_params"])
2252 elif indata
.get("additionalParamsForVnf"):
2253 indata
["additionalParamsForVnf"] = json
.dumps(
2254 indata
["additionalParamsForVnf"]
2257 if operation
== "instantiate":
2258 self
._update
_vnfrs
_from
_nsd
(nsr
)
2259 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
2260 if (operation
== "update") and (indata
["updateType"] == "CHANGE_VNFPKG"):
2262 vnfd_id
= indata
["changeVnfPackageData"]["vnfdId"]
2263 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2264 nsd
= self
.db
.get_one("nsds", {"_id": nsr
["nsd-id"]})
2265 ns_request
= nsr
["instantiate_params"]
2266 vnfr
= self
.db
.get_one(
2267 "vnfrs", {"_id": indata
["changeVnfPackageData"]["vnfInstanceId"]}
2269 latest_vnfd_revision
= vnfd
["_admin"].get("revision", 1)
2270 vnfr_vnfd_revision
= vnfr
.get("revision", 1)
2271 if latest_vnfd_revision
!= vnfr_vnfd_revision
:
2272 old_vnfd_id
= vnfd_id
+ ":" + str(vnfr_vnfd_revision
)
2273 old_db_vnfd
= self
.db
.get_one(
2274 "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
(
2283 vdu
, vnfd
, nsr
, vnf_index
, latest_vnfd_revision
2285 sw_image_id
= vdu
.get("sw-image-desc")
2287 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(
2290 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2291 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
2292 image_data
= self
.nsrtopic
._get
_image
_data
_from
_vnfd
(
2295 self
.nsrtopic
._add
_image
_to
_nsr
(nsr
, image_data
)
2296 nsr_update
["image"] = nsr
["image"]
2297 nsr_update
["flavor"] = nsr
["flavor"]
2298 self
.db
.set_one("nsrs", {"_id": nsr
["_id"]}, nsr_update
)
2299 ns_k8s_namespace
= self
.nsrtopic
._get
_ns
_k
8s
_namespace
(
2300 nsd
, ns_request
, session
2303 self
.nsrtopic
._create
_vnfr
_descriptor
_from
_vnfd
(
2311 latest_vnfd_revision
,
2314 indata
["newVdur"] = vnfr_descriptor
["vdur"]
2315 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
2316 _id
= nslcmop_desc
["_id"]
2318 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2320 if indata
.get("placement-engine"):
2321 # Save valid vim accounts in lcm operation descriptor
2322 nslcmop_desc
["operationParams"][
2324 ] = self
._get
_enabled
_vims
(session
)
2325 self
.db
.create("nslcmops", nslcmop_desc
)
2326 rollback
.append({"topic": "nslcmops", "_id": _id
})
2327 if not slice_object
:
2328 self
.msg
.write("ns", operation
, nslcmop_desc
)
2330 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2331 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2332 # except DbException as e:
2333 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2335 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2336 raise EngineException(
2337 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2340 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2341 raise EngineException(
2342 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2346 class NsiTopic(BaseTopic
):
2349 quota_name
= "slice_instances"
2351 def __init__(self
, db
, fs
, msg
, auth
):
2352 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2353 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2356 def _format_ns_request(ns_request
):
2357 formated_request
= copy(ns_request
)
2358 # TODO: Add request params
2359 return formated_request
2362 def _format_addional_params(slice_request
):
2364 Get and format user additional params for NS or VNF
2365 :param slice_request: User instantiation additional parameters
2366 :return: a formatted copy of additional params or None if not supplied
2368 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2369 if additional_params
:
2370 for k
, v
in additional_params
.items():
2371 if not isinstance(k
, str):
2372 raise EngineException(
2373 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2377 if "." in k
or "$" in k
:
2378 raise EngineException(
2379 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2383 if isinstance(v
, (dict, tuple, list)):
2384 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2385 return additional_params
2387 def check_conflict_on_del(self
, session
, _id
, db_content
):
2389 Check that NSI is not instantiated
2390 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2391 :param _id: nsi internal id
2392 :param db_content: The database content of the _id
2393 :return: None or raises EngineException with the conflict
2395 if session
["force"]:
2398 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2399 raise EngineException(
2400 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2401 "Launch 'terminate' operation first; or force deletion".format(_id
),
2402 http_code
=HTTPStatus
.CONFLICT
,
2405 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2407 Deletes associated nsilcmops from database. Deletes associated filesystem.
2408 Set usageState of nst
2409 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2410 :param _id: server internal id
2411 :param db_content: The database content of the descriptor
2412 :param not_send_msg: To not send message (False) or store content (list) instead
2413 :return: None if ok or raises EngineException with the problem
2416 # Deleting the nsrs belonging to nsir
2418 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2419 nsr_id
= nsrs_detailed_item
["nsrId"]
2420 if nsrs_detailed_item
.get("shared"):
2422 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2423 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2424 "_id.ne": nsir
["_id"],
2426 nsi
= self
.db
.get_one(
2427 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2429 if nsi
: # last one using nsr
2432 self
.nsrTopic
.delete(
2433 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2435 except (DbException
, EngineException
) as e
:
2436 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2441 # delete related nsilcmops database entries
2442 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2444 # Check and set used NST usage state
2445 nsir_admin
= nsir
.get("_admin")
2446 if nsir_admin
and nsir_admin
.get("nst-id"):
2447 # check if used by another NSI
2448 nsis_list
= self
.db
.get_one(
2450 {"nst-id": nsir_admin
["nst-id"]},
2451 fail_on_empty
=False,
2457 {"_id": nsir_admin
["nst-id"]},
2458 {"_admin.usageState": "NOT_IN_USE"},
2461 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2463 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2464 :param rollback: list to append the created items at database in case a rollback must be done
2465 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2466 :param indata: params to be used for the nsir
2467 :param kwargs: used to override the indata descriptor
2468 :param headers: http request headers
2469 :return: the _id of nsi descriptor created at database
2472 step
= "checking quotas" # first step must be defined outside try
2474 self
.check_quota(session
)
2477 slice_request
= self
._remove
_envelop
(indata
)
2478 # Override descriptor with query string kwargs
2479 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2480 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2483 step
= "getting nstd id='{}' from database".format(
2484 slice_request
.get("nstId")
2486 _filter
= self
._get
_project
_filter
(session
)
2487 _filter
["_id"] = slice_request
["nstId"]
2488 nstd
= self
.db
.get_one("nsts", _filter
)
2489 # check NST is not disabled
2490 step
= "checking NST operationalState"
2491 if nstd
["_admin"]["operationalState"] == "DISABLED":
2492 raise EngineException(
2493 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2494 "instance".format(slice_request
["nstId"]),
2495 http_code
=HTTPStatus
.CONFLICT
,
2499 # check NSD is not disabled
2500 step
= "checking operationalState"
2501 if nstd
["_admin"]["operationalState"] == "DISABLED":
2502 raise EngineException(
2503 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2504 "a network slice".format(slice_request
["nstId"]),
2505 http_code
=HTTPStatus
.CONFLICT
,
2508 nstd
.pop("_admin", None)
2509 nstd_id
= nstd
.pop("_id", None)
2510 nsi_id
= str(uuid4())
2511 step
= "filling nsi_descriptor with input data"
2516 "name": slice_request
["nsiName"],
2517 "description": slice_request
.get("nsiDescription", ""),
2518 "datacenter": slice_request
["vimAccountId"],
2519 "nst-ref": nstd
["id"],
2520 "instantiation_parameters": slice_request
,
2521 "network-slice-template": nstd
,
2525 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2528 step
= "creating nsi at database"
2530 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2532 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2533 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2534 nsi_descriptor
["_admin"]["deployed"] = {}
2535 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2536 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2538 # Creating netslice-vld for the RO.
2539 step
= "creating netslice-vld at database"
2541 # Building the vlds list to be deployed
2542 # From netslice descriptors, creating the initial list
2545 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2546 # Getting template Instantiation parameters from NST
2547 nsi_vld
= deepcopy(netslice_vlds
)
2548 nsi_vld
["shared-nsrs-list"] = []
2549 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2550 nsi_vlds
.append(nsi_vld
)
2552 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2553 # Creating netslice-subnet_record.
2557 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2558 for member_ns
in nstd
["netslice-subnet"]:
2559 nsd_id
= member_ns
["nsd-ref"]
2560 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2561 member_ns
["nsd-ref"], member_ns
["id"]
2563 if nsd_id
not in needed_nsds
:
2565 _filter
["id"] = nsd_id
2566 nsd
= self
.db
.get_one(
2567 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2571 needed_nsds
[nsd_id
] = nsd
2573 nsd
= needed_nsds
[nsd_id
]
2574 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2575 services
.append(member_ns
)
2577 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2578 member_ns
["nsd-ref"], member_ns
["id"]
2581 # creates Network Services records (NSRs)
2582 step
= "creating nsrs at database using NsrTopic.new()"
2583 ns_params
= slice_request
.get("netslice-subnet")
2585 nsi_netslice_subnet
= []
2586 for service
in services
:
2587 # Check if the netslice-subnet is shared and if it is share if the nss exists
2590 # Is the nss shared and instantiated?
2591 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2592 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2595 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2596 nsi
= self
.db
.get_one(
2597 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2599 if nsi
and service
.get("is-shared-nss"):
2600 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2601 for nsrs_detailed_item
in nsrs_detailed_list
:
2602 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2603 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2604 _id_nsr
= nsrs_detailed_item
["nsrId"]
2606 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2607 if netslice_subnet
["nss-id"] == service
["id"]:
2608 indata_ns
= netslice_subnet
2612 if service
.get("instantiation-parameters"):
2613 indata_ns
= deepcopy(service
["instantiation-parameters"])
2614 # del service["instantiation-parameters"]
2616 indata_ns
["nsdId"] = service
["_id"]
2617 indata_ns
["nsName"] = (
2618 slice_request
.get("nsiName") + "." + service
["id"]
2620 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2621 indata_ns
["nsDescription"] = service
["description"]
2622 if slice_request
.get("ssh_keys"):
2623 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2626 for ns_param
in ns_params
:
2627 if ns_param
.get("id") == service
["id"]:
2628 copy_ns_param
= deepcopy(ns_param
)
2629 del copy_ns_param
["id"]
2630 indata_ns
.update(copy_ns_param
)
2633 # Creates Nsr objects
2634 _id_nsr
, _
= self
.nsrTopic
.new(
2635 rollback
, session
, indata_ns
, kwargs
, headers
2639 "shared": service
.get("is-shared-nss"),
2640 "nsd-id": service
["nsd-ref"],
2641 "nss-id": service
["id"],
2642 "nslcmop_instantiate": None,
2644 indata_ns
["nss-id"] = service
["id"]
2645 nsrs_list
.append(nsrs_item
)
2646 nsi_netslice_subnet
.append(indata_ns
)
2647 nsr_ref
= {"nsr-ref": _id_nsr
}
2648 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2650 # Adding the nsrs list to the nsi
2651 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2652 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2654 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2657 # Creating the entry in the database
2658 self
.db
.create("nsis", nsi_descriptor
)
2659 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2661 except ValidationError
as e
:
2662 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2663 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2664 self
.logger
.exception(
2665 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2667 raise EngineException("Error {}: {}".format(step
, e
))
2669 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2670 raise EngineException(
2671 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2675 class NsiLcmOpTopic(BaseTopic
):
2678 operation_schema
= { # mapping between operation and jsonschema to validate
2679 "instantiate": nsi_instantiate
,
2683 def __init__(self
, db
, fs
, msg
, auth
):
2684 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2685 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2687 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2689 Check that user has enter right parameters for the operation
2690 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2691 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2692 :param indata: descriptor with the parameters of the operation
2696 nstd
= nsir
["network-slice-template"]
2698 def check_valid_netslice_subnet_id(nstId
):
2699 # TODO change to vnfR (??)
2700 for netslice_subnet
in nstd
["netslice-subnet"]:
2701 if nstId
== netslice_subnet
["id"]:
2702 nsd_id
= netslice_subnet
["nsd-ref"]
2703 if nsd_id
not in nsds
:
2704 _filter
= self
._get
_project
_filter
(session
)
2705 _filter
["id"] = nsd_id
2706 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2709 raise EngineException(
2710 "Invalid parameter nstId='{}' is not one of the "
2711 "nst:netslice-subnet".format(nstId
)
2714 if operation
== "instantiate":
2715 # check the existance of netslice-subnet items
2716 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2717 check_valid_netslice_subnet_id(in_nst
["id"])
2719 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2725 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2726 "statusEnteredTime": now
,
2727 "netsliceInstanceId": netsliceInstanceId
,
2728 "lcmOperationType": operation
,
2730 "isAutomaticInvocation": False,
2731 "operationParams": params
,
2732 "isCancelPending": False,
2734 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2735 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2736 + netsliceInstanceId
,
2741 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2742 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2743 if nst_sb_item
.get("is-shared-nss"):
2744 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2745 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2746 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2747 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2748 "nss-connection-point-ref"
2751 admin_subnet_item
["nss-id"]
2752 == admin_vld_nss_cp_ref_item
["nss-ref"]
2755 not nsr_item
["nsrId"]
2756 in admin_vld_item
["shared-nsrs-list"]
2758 admin_vld_item
["shared-nsrs-list"].append(
2762 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2765 {"_id": nsir
["_id"]},
2766 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2769 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2771 Performs a new operation over a ns
2772 :param rollback: list to append created items at database in case a rollback must to be done
2773 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2774 :param indata: descriptor with the parameters of the operation. It must contains among others
2775 netsliceInstanceId: _id of the nsir to perform the operation
2776 operation: it can be: instantiate, terminate, action, TODO: update, heal
2777 :param kwargs: used to override the indata descriptor
2778 :param headers: http request headers
2779 :return: id of the nslcmops
2782 # Override descriptor with query string kwargs
2783 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2784 operation
= indata
["lcmOperationType"]
2785 netsliceInstanceId
= indata
["netsliceInstanceId"]
2786 validate_input(indata
, self
.operation_schema
[operation
])
2788 # get nsi from netsliceInstanceId
2789 _filter
= self
._get
_project
_filter
(session
)
2790 _filter
["_id"] = netsliceInstanceId
2791 nsir
= self
.db
.get_one("nsis", _filter
)
2792 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2797 not nsir
["_admin"].get("nsiState")
2798 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2800 if operation
== "terminate" and indata
.get("autoremove"):
2801 # NSIR must be deleted
2805 ) # a none in this case is used to indicate not instantiated. It can be removed
2806 if operation
!= "instantiate":
2807 raise EngineException(
2808 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2809 netsliceInstanceId
, operation
2811 HTTPStatus
.CONFLICT
,
2814 if operation
== "instantiate" and not session
["force"]:
2815 raise EngineException(
2816 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2817 netsliceInstanceId
, operation
2819 HTTPStatus
.CONFLICT
,
2822 # Creating all the NS_operation (nslcmop)
2823 # Get service list from db
2824 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2826 # nslcmops_item = None
2827 for index
, nsr_item
in enumerate(nsrs_list
):
2828 nsr_id
= nsr_item
["nsrId"]
2829 if nsr_item
.get("shared"):
2830 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2831 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2833 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2835 _filter
["_id.ne"] = netsliceInstanceId
2836 nsi
= self
.db
.get_one(
2837 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2839 if operation
== "terminate":
2841 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2845 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2848 ): # other nsi is using this nsr and it needs this nsr instantiated
2849 continue # do not create nsilcmop
2851 # looks the first nsi fulfilling the conditions but not being the current NSIR
2853 nsi_nsr_item
= next(
2855 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2856 if n
["nsrId"] == nsr_id
2858 and n
["nslcmop_instantiate"]
2860 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2861 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2863 "_admin.nsrs-detailed-list.{}".format(
2867 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2868 # continue to not create nslcmop since nsrs is shared and nsrs was created
2871 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2876 "lcmOperationType": operation
,
2877 "nsInstanceId": nsr_id
,
2878 # Including netslice_id in the ns instantiate Operation
2879 "netsliceInstanceId": netsliceInstanceId
,
2881 if operation
== "instantiate":
2882 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2883 indata_ns
.update(service
["instantiate_params"])
2885 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2886 # message via kafka bus
2887 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2888 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2890 nslcmops
.append(nslcmop
)
2891 if operation
== "instantiate":
2893 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2897 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2898 except (DbException
, EngineException
) as e
:
2899 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2902 + "skipping NS={} because not found".format(nsr_id
)
2909 indata
["nslcmops_ids"] = nslcmops
2910 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2912 nsilcmop_desc
= self
._create
_nsilcmop
(
2913 session
, netsliceInstanceId
, operation
, indata
2916 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2918 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2919 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2920 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2922 except ValidationError
as e
:
2923 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2925 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2926 raise EngineException(
2927 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2930 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2931 raise EngineException(
2932 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR