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.
17 from uuid
import uuid4
18 from http
import HTTPStatus
20 from copy
import copy
, deepcopy
21 from osm_nbi
.validation
import (
30 from osm_nbi
.base_topic
import (
37 from yaml
import safe_dump
38 from osm_common
.dbbase
import DbException
39 from osm_common
.msgbase
import MsgException
40 from osm_common
.fsbase
import FsException
41 from osm_nbi
import utils
44 ) # For checking that additional parameter names are valid Jinja2 identifiers
46 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
49 class NsrTopic(BaseTopic
):
52 quota_name
= "ns_instances"
53 schema_new
= ns_instantiate
55 def __init__(self
, db
, fs
, msg
, auth
):
56 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
58 def _check_descriptor_dependencies(self
, session
, descriptor
):
60 Check that the dependent descriptors exist on a new descriptor or edition
61 :param session: client session information
62 :param descriptor: descriptor to be inserted or edit
63 :return: None or raises exception
65 if not descriptor
.get("nsdId"):
67 nsd_id
= descriptor
["nsdId"]
68 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
69 raise EngineException(
70 "Descriptor error at nsdId='{}' references a non exist nsd".format(
73 http_code
=HTTPStatus
.CONFLICT
,
77 def format_on_new(content
, project_id
=None, make_public
=False):
78 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
79 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
82 def check_conflict_on_del(self
, session
, _id
, db_content
):
84 Check that NSR is not instantiated
85 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
86 :param _id: nsr internal id
87 :param db_content: The database content of the nsr
88 :return: None or raises EngineException with the conflict
93 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
94 raise EngineException(
95 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
96 "Launch 'terminate' operation first; or force deletion".format(_id
),
97 http_code
=HTTPStatus
.CONFLICT
,
100 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
102 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
103 Set usageState of pdu, vnfd, nsd
104 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
105 :param _id: server internal id
106 :param db_content: The database content of the descriptor
107 :param not_send_msg: To not send message (False) or store content (list) instead
108 :return: None if ok or raises EngineException with the problem
110 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
111 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
112 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
114 # set all used pdus as free
117 {"_admin.usage.nsr_id": _id
},
118 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
123 used_nsd_id
= nsr
.get("nsd-id")
125 # check if used by another NSR
126 nsrs_list
= self
.db
.get_one(
127 "nsrs", {"nsd-id": used_nsd_id
}, fail_on_empty
=False, fail_on_more
=False
131 "nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"}
134 # Set VNFD usageState
135 used_vnfd_id_list
= nsr
.get("vnfd-id")
136 if used_vnfd_id_list
:
137 for used_vnfd_id
in used_vnfd_id_list
:
138 # check if used by another NSR
139 nsrs_list
= self
.db
.get_one(
141 {"vnfd-id": used_vnfd_id
},
148 {"_id": used_vnfd_id
},
149 {"_admin.usageState": "NOT_IN_USE"},
152 # delete extra ro_nsrs used for internal RO module
153 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
156 def _format_ns_request(ns_request
):
157 formated_request
= copy(ns_request
)
158 formated_request
.pop("additionalParamsForNs", None)
159 formated_request
.pop("additionalParamsForVnf", None)
160 return formated_request
163 def _format_additional_params(
164 ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None
167 Get and format user additional params for NS or VNF
168 :param ns_request: User instantiation additional parameters
169 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
170 :param descriptor: If not None it check that needed parameters of descriptor are supplied
171 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
173 additional_params
= None
175 if not member_vnf_index
:
176 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
177 where_
= "additionalParamsForNs"
178 elif ns_request
.get("additionalParamsForVnf"):
179 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
185 for x
in ns_request
["additionalParamsForVnf"]
186 if x
["member-vnf-index"] == member_vnf_index
191 if not vdu_id
and not kdu_name
:
193 additional_params
= copy(item
.get("additionalParams")) or {}
194 if vdu_id
and item
.get("additionalParamsForVdu"):
198 for x
in item
["additionalParamsForVdu"]
199 if x
["vdu_id"] == vdu_id
203 other_params
= item_vdu
204 if item_vdu
and item_vdu
.get("additionalParams"):
205 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
206 additional_params
= item_vdu
["additionalParams"]
208 additional_params
= {}
209 if item
.get("additionalParamsForKdu"):
213 for x
in item
["additionalParamsForKdu"]
214 if x
["kdu_name"] == kdu_name
218 other_params
= item_kdu
219 if item_kdu
and item_kdu
.get("additionalParams"):
220 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(
223 additional_params
= item_kdu
["additionalParams"]
225 if additional_params
:
226 for k
, v
in additional_params
.items():
227 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
228 if not kdu_name
and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k
):
229 raise EngineException(
230 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
231 "and underscores, and cannot start with a digit".format(
235 # END Check that additional parameter names are valid Jinja2 identifiers
236 if not isinstance(k
, str):
237 raise EngineException(
238 "Invalid param at {}:{}. Only string keys are allowed".format(
242 if "." in k
or "$" in k
:
243 raise EngineException(
244 "Invalid param at {}:{}. Keys must not contain dots or $".format(
248 if isinstance(v
, (dict, tuple, list)):
249 additional_params
[k
] = "!!yaml " + safe_dump(v
)
252 for df
in descriptor
.get("df", []):
253 # check that enough parameters are supplied for the initial-config-primitive
254 # TODO: check for cloud-init
256 initial_primitives
= []
258 "lcm-operations-configuration" in df
259 and "operate-vnf-op-config"
260 in df
["lcm-operations-configuration"]
262 for config
in df
["lcm-operations-configuration"][
263 "operate-vnf-op-config"
265 for primitive
in get_iterable(
266 config
.get("initial-config-primitive")
268 initial_primitives
.append(primitive
)
270 initial_primitives
= deep_get(
271 descriptor
, ("ns-configuration", "initial-config-primitive")
274 for initial_primitive
in get_iterable(initial_primitives
):
275 for param
in get_iterable(initial_primitive
.get("parameter")):
276 if param
["value"].startswith("<") and param
["value"].endswith(
279 if param
["value"] in (
286 not additional_params
287 or param
["value"][1:-1] not in additional_params
289 raise EngineException(
290 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
291 "initial-config-primitive[name={}] not supplied".format(
294 initial_primitive
["name"],
298 return additional_params
or None, other_params
or None
300 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
302 Creates a new nsr into database. It also creates needed vnfrs
303 :param rollback: list to append the created items at database in case a rollback must be done
304 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
305 :param indata: params to be used for the nsr
306 :param kwargs: used to override the indata descriptor
307 :param headers: http request headers
308 :return: the _id of nsr descriptor created at database. Or an exception of type
309 EngineException, ValidationError, DbException, FsException, MsgException.
310 Note: Exceptions are not captured on purpose. They should be captured at called
313 step
= "checking quotas"
314 self
.check_quota(session
)
316 step
= "validating input parameters"
317 ns_request
= self
._remove
_envelop
(indata
)
318 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
319 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
321 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
322 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
323 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
325 step
= "checking nsdOperationalState"
326 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
328 step
= "filling nsr from input data"
329 nsr_id
= str(uuid4())
330 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(
331 nsd
, ns_request
, nsr_id
, session
336 # TODO: Change for multiple df support
337 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
338 for vnfp
in vnf_profiles
:
339 vnfd_id
= vnfp
.get("vnfd-id")
340 vnf_index
= vnfp
.get("id")
342 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
346 if vnfd_id
not in needed_vnfds
:
347 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
348 needed_vnfds
[vnfd_id
] = vnfd
349 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
351 vnfd
= needed_vnfds
[vnfd_id
]
353 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
356 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(
366 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
369 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
370 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
372 step
= "creating nsr at database"
373 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
375 step
= "creating nsr temporal folder"
376 self
.fs
.mkdir(nsr_id
)
386 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
388 def _get_nsd_from_db(self
, nsd_id
, session
):
389 _filter
= self
._get
_project
_filter
(session
)
390 _filter
["_id"] = nsd_id
391 return self
.db
.get_one("nsds", _filter
)
393 def _get_vnfd_from_db(self
, vnfd_id
, session
):
394 _filter
= self
._get
_project
_filter
(session
)
395 _filter
["id"] = vnfd_id
396 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
400 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
402 nsr_descriptor
, session
["project_id"], make_public
=session
["public"]
404 self
.db
.create("nsrs", nsr_descriptor
)
405 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
407 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
409 vnfr_descriptor
, session
["project_id"], make_public
=session
["public"]
411 self
.db
.create("vnfrs", vnfr_descriptor
)
412 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
414 def _check_nsd_operational_state(self
, nsd
, ns_request
):
415 if nsd
["_admin"]["operationalState"] == "DISABLED":
416 raise EngineException(
417 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
418 "a network service".format(ns_request
["nsdId"]),
419 http_code
=HTTPStatus
.CONFLICT
,
422 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
423 additional_params
, _
= self
._format
_additional
_params
(
424 ns_request
, descriptor
=nsd
426 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
427 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
428 if ns_request
and ns_request
.get("k8s-namespace"):
429 ns_k8s_namespace
= ns_request
["k8s-namespace"]
430 if additional_params
and additional_params
.get("k8s-namespace"):
431 ns_k8s_namespace
= additional_params
["k8s-namespace"]
433 return ns_k8s_namespace
435 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
437 additional_params
, _
= self
._format
_additional
_params
(
438 ns_request
, descriptor
=nsd
442 "name": ns_request
["nsName"],
443 "name-ref": ns_request
["nsName"],
444 "short-name": ns_request
["nsName"],
445 "admin-status": "ENABLED",
446 "nsState": "NOT_INSTANTIATED",
447 "currentOperation": "IDLE",
448 "currentOperationID": None,
449 "errorDescription": None,
451 "deploymentStatus": None,
452 "configurationStatus": None,
454 "nsd": {k
: v
for k
, v
in nsd
.items()},
455 "datacenter": ns_request
["vimAccountId"],
456 "resource-orchestrator": "osmopenmano",
457 "description": ns_request
.get("nsDescription", ""),
458 "constituent-vnfr-ref": [],
459 "operational-status": "init", # typedef ns-operational-
460 "config-status": "init", # typedef config-states
461 "detailed-status": "scheduled",
462 "orchestration-progress": {},
464 "nsd-name-ref": nsd
["name"],
465 "operational-events": [], # "id", "timestamp", "description", "event",
466 "nsd-ref": nsd
["id"],
467 "nsd-id": nsd
["_id"],
469 "instantiate_params": self
._format
_ns
_request
(ns_request
),
470 "additionalParamsForNs": additional_params
,
471 "ns-instance-config-ref": nsr_id
,
474 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
478 ns_request
["nsr_id"] = nsr_id
479 if ns_request
and ns_request
.get("config-units"):
480 nsr_descriptor
["config-units"] = ns_request
["config-units"]
482 if nsd
.get("virtual-link-desc"):
483 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
484 # Fill each vld with vnfd-connection-point-ref data
485 # TODO: Change for multiple df support
486 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
487 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
488 for vnf_profile
in vnf_profiles
:
489 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
490 for cpd
in vlc
.get("constituent-cpd-id", ()):
491 all_vld_connection_point_data
[
492 vlc
.get("virtual-link-profile-id")
495 "member-vnf-index-ref": cpd
.get(
496 "constituent-base-element-id"
498 "vnfd-connection-point-ref": cpd
.get(
501 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
505 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
507 for vdu
in vnfd
.get("vdu", ()):
510 # Find this vdu compute and storage descriptors
511 vdu_virtual_compute
= {}
512 vdu_virtual_storage
= {}
513 for vcd
in vnfd
.get("virtual-compute-desc", ()):
514 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
515 vdu_virtual_compute
= vcd
516 for vsd
in vnfd
.get("virtual-storage-desc", ()):
517 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
518 vdu_virtual_storage
= vsd
519 # Get this vdu vcpus, memory and storage info for flavor_data
520 if vdu_virtual_compute
.get("virtual-cpu", {}).get(
523 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"][
526 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
527 flavor_data
["memory-mb"] = (
528 float(vdu_virtual_compute
["virtual-memory"]["size"])
531 if vdu_virtual_storage
.get("size-of-storage"):
532 flavor_data
["storage-gb"] = vdu_virtual_storage
[
535 # Get this vdu EPA info for guest_epa
536 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
537 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"][
540 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
541 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
542 if vcpu_pinning
.get("thread-policy"):
543 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
[
546 if vcpu_pinning
.get("policy"):
549 if vcpu_pinning
["policy"] == "dynamic"
552 guest_epa
["cpu-pinning-policy"] = cpu_policy
553 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
554 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"][
557 if vdu_virtual_compute
.get("virtual-memory", {}).get(
560 guest_epa
["mempage-size"] = vdu_virtual_compute
[
563 if vdu_virtual_compute
.get("virtual-memory", {}).get(
566 guest_epa
["numa-node-policy"] = vdu_virtual_compute
[
568 ]["numa-node-policy"]
569 if vdu_virtual_storage
.get("disk-io-quota"):
570 guest_epa
["disk-io-quota"] = vdu_virtual_storage
[
575 flavor_data
["guest-epa"] = guest_epa
577 flavor_data
["name"] = vdu
["id"][:56] + "-flv"
578 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
579 nsr_descriptor
["flavor"].append(flavor_data
)
581 sw_image_id
= vdu
.get("sw-image-desc")
583 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
584 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
586 # also add alternative images to the list of images
587 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
588 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
589 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
592 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
595 vld
["name"] = vld
["id"]
596 nsr_descriptor
["vld"] = nsr_vld
598 return nsr_descriptor
600 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
601 sw_image_desc
= utils
.find_in_list(
602 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
605 if sw_image_desc
.get("image"):
606 image_data
["image"] = sw_image_desc
["image"]
607 if sw_image_desc
.get("checksum"):
608 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
609 if sw_image_desc
.get("vim-type"):
610 image_data
["vim-type"] = sw_image_desc
["vim-type"]
613 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
615 Adds image to nsr checking first it is not already added
620 for f
in nsr_descriptor
["image"]
621 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
626 image_data
["id"] = str(len(nsr_descriptor
["image"]))
627 nsr_descriptor
["image"].append(image_data
)
629 def _create_vnfr_descriptor_from_vnfd(
639 vnfr_id
= str(uuid4())
640 nsr_id
= nsr_descriptor
["id"]
642 additional_params
, vnf_params
= self
._format
_additional
_params
(
643 ns_request
, vnf_index
, descriptor
=vnfd
649 "nsr-id-ref": nsr_id
,
650 "member-vnf-index-ref": vnf_index
,
651 "additionalParamsForVnf": additional_params
,
653 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
655 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
656 "vim-account-id": None,
659 "connection-point": [],
660 "ip-address": None, # mgmt-interface filled by LCM
662 vnf_k8s_namespace
= ns_k8s_namespace
664 if vnf_params
.get("k8s-namespace"):
665 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
666 if vnf_params
.get("config-units"):
667 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
670 if vnfd
.get("int-virtual-link-desc"):
671 vnfr_descriptor
["vld"] = []
672 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
673 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
675 for cp
in vnfd
.get("ext-cpd", ()):
677 "name": cp
.get("id"),
678 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
679 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
681 # "ip-address", "mac-address" # filled by LCM
682 # vim-id # TODO it would be nice having a vim port id
684 vnfr_descriptor
["connection-point"].append(vnf_cp
)
686 # Create k8s-cluster information
687 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
688 if vnfd
.get("k8s-cluster"):
689 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
690 all_k8s_cluster_nets_cpds
= {}
691 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
692 if cpd
.get("k8s-cluster-net"):
693 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
696 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
697 if net
.get("id") in all_k8s_cluster_nets_cpds
:
698 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
703 for kdu
in get_iterable(vnfd
.get("kdu")):
704 additional_params
, kdu_params
= self
._format
_additional
_params
(
705 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
707 kdu_k8s_namespace
= vnf_k8s_namespace
708 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
709 if kdu_params
and kdu_params
.get("k8s-namespace"):
710 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
712 kdu_deployment_name
= ""
713 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
714 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
717 "additionalParams": additional_params
,
718 "k8s-namespace": kdu_k8s_namespace
,
719 "kdu-deployment-name": kdu_deployment_name
,
720 "kdu-name": kdu
["name"],
721 # TODO "name": "" Name of the VDU in the VIM
722 "ip-address": None, # mgmt-interface filled by LCM
725 if kdu_params
and kdu_params
.get("config-units"):
726 kdur
["config-units"] = kdu_params
["config-units"]
727 if kdu
.get("helm-version"):
728 kdur
["helm-version"] = kdu
["helm-version"]
729 for k8s_type
in ("helm-chart", "juju-bundle"):
730 if kdu
.get(k8s_type
):
731 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
732 if not vnfr_descriptor
.get("kdur"):
733 vnfr_descriptor
["kdur"] = []
734 vnfr_descriptor
["kdur"].append(kdur
)
736 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
738 for vdu
in vnfd
.get("vdu", ()):
741 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
742 "operate-vnf-op-config"
744 vdu_config
= utils
.find_in_list(
745 configs
, lambda config
: config
["id"] == vdu
["id"]
751 vdu_instantiation_level
= utils
.find_in_list(
752 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
753 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
756 vdu_instantiation_level
= None
759 external_connection_ee
= utils
.filter_in_list(
760 vdu_config
.get("execution-environment-list", []),
761 lambda ee
: "external-connection-point-ref" in ee
,
763 for ee
in external_connection_ee
:
764 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
766 additional_params
, vdu_params
= self
._format
_additional
_params
(
767 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
771 vdu_virtual_storage_descriptors
= utils
.filter_in_list(
772 vnfd
.get("virtual-storage-desc", []),
773 lambda stg_desc
: stg_desc
["id"] in vdu
["virtual-storage-desc"]
776 vdu_virtual_storage_descriptors
= []
778 "vdu-id-ref": vdu
["id"],
779 # TODO "name": "" Name of the VDU in the VIM
780 "ip-address": None, # mgmt-interface filled by LCM
781 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
782 "internal-connection-point": [],
784 "additionalParams": additional_params
,
785 "vdu-name": vdu
["name"],
786 "virtual-storages": vdu_virtual_storage_descriptors
788 if vdu_params
and vdu_params
.get("config-units"):
789 vdur
["config-units"] = vdu_params
["config-units"]
790 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
791 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
794 if vdu
.get("pdu-type"):
795 vdur
["pdu-type"] = vdu
["pdu-type"]
796 vdur
["name"] = vdu
["pdu-type"]
797 # TODO volumes: name, volume-id
798 for icp
in vdu
.get("int-cpd", ()):
801 "connection-point-id": icp
["id"],
802 "name": icp
.get("id"),
805 vdur
["internal-connection-point"].append(vdu_icp
)
807 for iface
in icp
.get("virtual-network-interface-requirement", ()):
808 iface_fields
= ("name", "mac-address")
810 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
813 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
814 if "port-security-enabled" in icp
:
815 vdu_iface
["port-security-enabled"] = icp
[
816 "port-security-enabled"
819 if "port-security-disable-strategy" in icp
:
820 vdu_iface
["port-security-disable-strategy"] = icp
[
821 "port-security-disable-strategy"
824 for ext_cp
in vnfd
.get("ext-cpd", ()):
825 if not ext_cp
.get("int-cpd"):
827 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
829 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
830 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
834 if "port-security-enabled" in ext_cp
:
835 vdu_iface
["port-security-enabled"] = ext_cp
[
836 "port-security-enabled"
839 if "port-security-disable-strategy" in ext_cp
:
840 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
841 "port-security-disable-strategy"
848 and vdu_iface
.get("external-connection-point-ref")
851 vdu_iface
["mgmt-vnf"] = True
852 vdu_iface
["mgmt-interface"] = True
854 for ecp
in vdu_mgmt_cp
:
855 if vdu_iface
.get("external-connection-point-ref") == ecp
:
856 vdu_iface
["mgmt-interface"] = True
858 if iface
.get("virtual-interface"):
859 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
861 # look for network where this interface is connected
862 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
864 # TODO: Change for multiple df support
865 for df
in get_iterable(nsd
.get("df")):
866 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
867 for vlc_index
, vlc
in enumerate(
869 vnf_profile
.get("virtual-link-connectivity")
872 for cpd
in get_iterable(
873 vlc
.get("constituent-cpd-id")
876 cpd
.get("constituent-cpd-id")
879 vdu_iface
["ns-vld-id"] = vlc
.get(
880 "virtual-link-profile-id"
882 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
883 if vdu_iface
.get("type") in (
887 nsr_descriptor
["vld"][vlc_index
][
891 elif vdu_iface
.get("internal-connection-point-ref"):
892 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
893 # TODO: store fixed IP address in the record (if it exists in the ICP)
894 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
895 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
896 ivld_index
= utils
.find_index_in_list(
897 vnfd
.get("int-virtual-link-desc", ()),
898 lambda ivld
: ivld
["id"]
899 == icp
.get("int-virtual-link-desc"),
901 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
903 vdur
["interfaces"].append(vdu_iface
)
905 if vdu
.get("sw-image-desc"):
906 sw_image
= utils
.find_in_list(
907 vnfd
.get("sw-image-desc", ()),
908 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
910 nsr_sw_image_data
= utils
.find_in_list(
911 nsr_descriptor
["image"],
912 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
914 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
916 if vdu
.get("alternative-sw-image-desc"):
918 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
919 sw_image
= utils
.find_in_list(
920 vnfd
.get("sw-image-desc", ()),
921 lambda image
: image
["id"] == alt_image_id
,
923 nsr_sw_image_data
= utils
.find_in_list(
924 nsr_descriptor
["image"],
926 nsr_image
.get("image") == sw_image
.get("image")
929 alt_image_ids
.append(nsr_sw_image_data
["id"])
930 vdur
["alt-image-ids"] = alt_image_ids
932 flavor_data_name
= vdu
["id"][:56] + "-flv"
933 nsr_flavor_desc
= utils
.find_in_list(
934 nsr_descriptor
["flavor"],
935 lambda flavor
: flavor
["name"] == flavor_data_name
,
939 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
941 if vdu_instantiation_level
:
942 count
= vdu_instantiation_level
.get("number-of-instances")
946 for index
in range(0, count
):
947 vdur
= deepcopy(vdur
)
948 for iface
in vdur
["interfaces"]:
949 if iface
.get("ip-address") and index
!= 0:
950 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
951 if iface
.get("mac-address") and index
!= 0:
952 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
954 vdur
["_id"] = str(uuid4())
955 vdur
["id"] = vdur
["_id"]
956 vdur
["count-index"] = index
957 vnfr_descriptor
["vdur"].append(vdur
)
959 return vnfr_descriptor
961 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
963 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
964 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
965 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
966 :param ns_instance_content: ns instance content
967 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
970 time_now
, time_delta
= time(), time() - ns_instance_content
["_admin"]["modified"]
971 force_refresh
= isinstance(filter_q
, dict) and filter_q
.get('vcaStatusRefresh') == 'true'
972 threshold_reached
= time_delta
> 120
973 if force_refresh
or threshold_reached
:
974 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
975 ns_instance_content
["_admin"]["modified"] = time_now
976 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
977 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
978 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
979 nslcmop_desc
["_admin"].pop("nsState")
980 self
.msg
.write("ns", operation
, nslcmop_desc
)
983 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
985 Get complete information on an ns instance.
986 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
987 :param _id: string, ns instance id
988 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
989 :param api_req: True if this call is serving an external API request. False if serving internal request.
990 :return: dictionary, raise exception if not found.
992 ns_instance_content
= super().show(session
, _id
, api_req
)
993 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
994 return ns_instance_content
996 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
997 raise EngineException(
998 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1002 class VnfrTopic(BaseTopic
):
1006 def __init__(self
, db
, fs
, msg
, auth
):
1007 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1009 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1010 raise EngineException(
1011 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1014 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1015 raise EngineException(
1016 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1019 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1020 # Not used because vnfrs are created and deleted by NsrTopic class directly
1021 raise EngineException(
1022 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1026 class NsLcmOpTopic(BaseTopic
):
1029 operation_schema
= { # mapping between operation and jsonschema to validate
1030 "instantiate": ns_instantiate
,
1031 "action": ns_action
,
1033 "terminate": ns_terminate
,
1036 def __init__(self
, db
, fs
, msg
, auth
):
1037 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1039 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1041 Check that user has enter right parameters for the operation
1042 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1043 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1044 :param indata: descriptor with the parameters of the operation
1047 if operation
== "action":
1048 self
._check
_action
_ns
_operation
(indata
, nsr
)
1049 elif operation
== "scale":
1050 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1051 elif operation
== "instantiate":
1052 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1054 def _check_action_ns_operation(self
, indata
, nsr
):
1056 # check vnf_member_index
1057 if indata
.get("vnf_member_index"):
1058 indata
["member_vnf_index"] = indata
.pop(
1060 ) # for backward compatibility
1061 if indata
.get("member_vnf_index"):
1062 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1063 indata
["member_vnf_index"], nsr
["_id"]
1066 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1067 "operate-vnf-op-config"
1072 if indata
.get("vdu_id"):
1073 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1074 descriptor_configuration
= utils
.find_in_list(
1075 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1077 elif indata
.get("kdu_name"):
1078 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1079 descriptor_configuration
= utils
.find_in_list(
1080 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1083 descriptor_configuration
= utils
.find_in_list(
1084 configs
, lambda config
: config
["id"] == vnfd
["id"]
1086 if descriptor_configuration
is not None:
1087 descriptor_configuration
= descriptor_configuration
.get(
1091 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1095 # For k8s allows default primitives without validating the parameters
1096 if indata
.get("kdu_name") and indata
["primitive"] in (
1103 # TODO should be checked that rollback only can contains revsision_numbe????
1104 if not indata
.get("member_vnf_index"):
1105 raise EngineException(
1106 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1111 # if not, check primitive
1112 for config_primitive
in get_iterable(descriptor_configuration
):
1113 if indata
["primitive"] == config_primitive
["name"]:
1114 # check needed primitive_params are provided
1115 if indata
.get("primitive_params"):
1116 in_primitive_params_copy
= copy(indata
["primitive_params"])
1118 in_primitive_params_copy
= {}
1119 for paramd
in get_iterable(config_primitive
.get("parameter")):
1120 if paramd
["name"] in in_primitive_params_copy
:
1121 del in_primitive_params_copy
[paramd
["name"]]
1122 elif not paramd
.get("default-value"):
1123 raise EngineException(
1124 "Needed parameter {} not provided for primitive '{}'".format(
1125 paramd
["name"], indata
["primitive"]
1128 # check no extra primitive params are provided
1129 if in_primitive_params_copy
:
1130 raise EngineException(
1131 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1132 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1137 raise EngineException(
1138 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1143 def _check_scale_ns_operation(self
, indata
, nsr
):
1144 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1145 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1147 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1149 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1150 == scaling_aspect
["id"]
1154 raise EngineException(
1155 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1156 "present at vnfd:scaling-aspect".format(
1157 indata
["scaleVnfData"]["scaleByStepData"][
1158 "scaling-group-descriptor"
1163 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1164 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1168 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1169 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1170 for in_vnf
in get_iterable(indata
.get("vnf")):
1171 member_vnf_index
= in_vnf
["member-vnf-index"]
1172 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1173 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1175 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1176 member_vnf_index
, nsr
["_id"]
1178 vnf_member_index_to_vnfd
[
1180 ] = vnfd
# add to cache, avoiding a later look for
1181 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1182 if in_vnf
.get("vimAccountId"):
1183 self
._check
_valid
_vim
_account
(
1184 in_vnf
["vimAccountId"], vim_accounts
, session
1187 for in_vld
in get_iterable(indata
.get("vld")):
1188 self
._check
_valid
_wim
_account
(
1189 in_vld
.get("wimAccountId"), wim_accounts
, session
1191 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1192 if in_vld
["name"] == vldd
["id"]:
1195 raise EngineException(
1196 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1201 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1202 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1203 vnfr
= self
.db
.get_one(
1205 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1206 fail_on_empty
=False,
1209 raise EngineException(
1210 "Invalid parameter member_vnf_index='{}' is not one of the "
1211 "nsd:constituent-vnfd".format(member_vnf_index
)
1213 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
1215 raise EngineException(
1216 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1222 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1223 for vdud
in get_iterable(vnfd
.get("vdu")):
1224 if vdud
["id"] == vdu_id
:
1227 raise EngineException(
1228 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1233 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1234 for kdud
in get_iterable(vnfd
.get("kdu")):
1235 if kdud
["name"] == kdu_name
:
1238 raise EngineException(
1239 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1244 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1245 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1246 for vdu
in get_iterable(vnfd
.get("vdu")):
1247 if in_vdu
["id"] == vdu
["id"]:
1248 for volume
in get_iterable(in_vdu
.get("volume")):
1249 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1250 if volumed
["id"] == volume
["name"]:
1253 raise EngineException(
1254 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1255 "volume:name='{}' is not present at "
1256 "vnfd:vdu:virtual-storage-desc list".format(
1257 in_vnf
["member-vnf-index"],
1263 vdu_if_names
= set()
1264 for cpd
in get_iterable(vdu
.get("int-cpd")):
1265 for iface
in get_iterable(
1266 cpd
.get("virtual-network-interface-requirement")
1268 vdu_if_names
.add(iface
.get("name"))
1270 for in_iface
in get_iterable(in_vdu
["interface"]):
1271 if in_iface
["name"] in vdu_if_names
:
1274 raise EngineException(
1275 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1276 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1277 in_vnf
["member-vnf-index"],
1285 raise EngineException(
1286 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1287 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1291 ivld
.get("id"): set()
1292 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1294 for vdu
in get_iterable(vnfd
.get("vdu")):
1295 for cpd
in get_iterable(vnfd
.get("int-cpd")):
1296 if cpd
.get("int-virtual-link-desc"):
1297 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1299 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1300 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1301 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1302 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1305 raise EngineException(
1306 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1307 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1308 "vnfd:internal-vld:name/id:internal-connection-point".format(
1309 in_vnf
["member-vnf-index"],
1315 raise EngineException(
1316 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1317 " is not present at vnfd '{}'".format(
1318 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1322 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1323 if vim_account
in vim_accounts
:
1326 db_filter
= self
._get
_project
_filter
(session
)
1327 db_filter
["_id"] = vim_account
1328 self
.db
.get_one("vim_accounts", db_filter
)
1330 raise EngineException(
1331 "Invalid vimAccountId='{}' not present for the project".format(
1335 vim_accounts
.append(vim_account
)
1337 def _get_vim_account(self
, vim_id
: str, session
):
1339 db_filter
= self
._get
_project
_filter
(session
)
1340 db_filter
["_id"] = vim_id
1341 return self
.db
.get_one("vim_accounts", db_filter
)
1343 raise EngineException(
1344 "Invalid vimAccountId='{}' not present for the project".format(
1349 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1350 if not isinstance(wim_account
, str):
1352 if wim_account
in wim_accounts
:
1355 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
1356 db_filter
["_id"] = wim_account
1357 self
.db
.get_one("wim_accounts", db_filter
)
1359 raise EngineException(
1360 "Invalid wimAccountId='{}' not present for the project".format(
1364 wim_accounts
.append(wim_account
)
1367 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1370 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1371 (ip_address, ...) information.
1372 Modifies PDU _admin.usageState to 'IN_USE'
1373 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1374 :param rollback: list with the database modifications to rollback if needed
1375 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1376 :param vim_account: vim_account where this vnfr should be deployed
1377 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1378 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1379 of the changed vnfr is needed
1381 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1382 "vim-network-name": used at VIM
1383 "name": interface name
1384 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1385 "ns-vld-id": NSD vld where this interface is connected.
1386 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1389 ifaces_forcing_vim_network
= []
1390 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1391 if not vdur
.get("pdu-type"):
1393 pdu_type
= vdur
.get("pdu-type")
1394 pdu_filter
= self
._get
_project
_filter
(session
)
1395 pdu_filter
["vim_accounts"] = vim_account
1396 pdu_filter
["type"] = pdu_type
1397 pdu_filter
["_admin.operationalState"] = "ENABLED"
1398 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1399 # TODO feature 1417: "shared": True,
1401 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1402 for pdu
in available_pdus
:
1403 # step 1 check if this pdu contains needed interfaces:
1404 match_interfaces
= True
1405 for vdur_interface
in vdur
["interfaces"]:
1406 for pdu_interface
in pdu
["interfaces"]:
1407 if pdu_interface
["name"] == vdur_interface
["name"]:
1408 # TODO feature 1417: match per mgmt type
1410 else: # no interface found for name
1411 match_interfaces
= False
1413 if match_interfaces
:
1416 raise EngineException(
1417 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1421 vnfr
["member-vnf-index-ref"],
1426 # step 2. Update pdu
1428 "_admin.usageState": pdu
["_admin"]["usageState"],
1429 "_admin.usage.vnfr_id": None,
1430 "_admin.usage.nsr_id": None,
1431 "_admin.usage.vdur": None,
1435 {"_id": pdu
["_id"]},
1437 "_admin.usageState": "IN_USE",
1439 "vnfr_id": vnfr
["_id"],
1440 "nsr_id": vnfr
["nsr-id-ref"],
1441 "vdur": vdur
["vdu-id-ref"],
1450 "content": rollback_pdu
,
1454 # step 3. Fill vnfr info by filling vdur
1455 vdu_text
= "vdur.{}".format(vdur_index
)
1456 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1457 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1458 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1459 for pdu_interface
in pdu
["interfaces"]:
1460 if pdu_interface
["name"] == vdur_interface
["name"]:
1461 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1462 for k
, v
in pdu_interface
.items():
1466 ): # TODO: switch-xxxxx must be inserted
1467 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1468 vnfr_update_rollback
[
1469 iface_text
+ ".{}".format(k
)
1470 ] = vdur_interface
.get(v
)
1471 if pdu_interface
.get("ip-address"):
1472 if vdur_interface
.get(
1474 ) or vdur_interface
.get("mgmt-vnf"):
1475 vnfr_update_rollback
[
1476 vdu_text
+ ".ip-address"
1477 ] = vdur
.get("ip-address")
1478 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1481 if vdur_interface
.get("mgmt-vnf"):
1482 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1485 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1486 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1489 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1492 ifaces_forcing_vim_network
.append(
1494 "name": vdur_interface
.get("vnf-vld-id")
1495 or vdur_interface
.get("ns-vld-id"),
1496 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1497 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1500 if pdu_interface
.get("vim-network-id"):
1501 ifaces_forcing_vim_network
[-1][
1503 ] = pdu_interface
["vim-network-id"]
1504 if pdu_interface
.get("vim-network-name"):
1505 ifaces_forcing_vim_network
[-1][
1507 ] = pdu_interface
["vim-network-name"]
1510 return ifaces_forcing_vim_network
1512 def _look_for_k8scluster(
1513 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1516 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1517 Fills vnfr.kdur with the selected k8scluster
1519 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1520 :param rollback: list with the database modifications to rollback if needed
1521 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1522 :param vim_account: vim_account where this vnfr should be deployed
1523 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1524 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1525 of the changed vnfr is needed
1527 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1528 "vim-network-name": used at VIM
1529 "name": interface name
1530 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1531 "ns-vld-id": NSD vld where this interface is connected.
1532 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1535 ifaces_forcing_vim_network
= []
1536 if not vnfr
.get("kdur"):
1537 return ifaces_forcing_vim_network
1539 kdu_filter
= self
._get
_project
_filter
(session
)
1540 kdu_filter
["vim_account"] = vim_account
1541 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1542 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1544 k8s_requirements
= {} # just for logging
1545 for k8scluster
in available_k8sclusters
:
1546 if not vnfr
.get("k8s-cluster"):
1549 if vnfr
["k8s-cluster"].get("cni"):
1550 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1551 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1552 k8scluster
.get("cni", ())
1555 # restrict by version
1556 if vnfr
["k8s-cluster"].get("version"):
1557 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1558 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1560 # restrict by number of networks
1561 if vnfr
["k8s-cluster"].get("nets"):
1562 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1563 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1564 vnfr
["k8s-cluster"]["nets"]
1569 raise EngineException(
1570 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1571 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1575 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1576 # step 3. Fill vnfr info by filling kdur
1577 kdu_text
= "kdur.{}.".format(kdur_index
)
1578 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1579 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1581 # step 4. Check VIM networks that forces the selected k8s_cluster
1582 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1583 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1584 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1585 # get a network from k8s_cluster nets. If name matches use this, if not use other
1586 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1587 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1588 k8scluster_net_list
.remove(kdur_net
["id"])
1590 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1591 k8scluster_net_list
.pop(0)
1592 vnfr_update_rollback
[
1593 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1595 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1597 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1599 ifaces_forcing_vim_network
.append(
1601 "name": kdur_net
.get("vnf-vld-id")
1602 or kdur_net
.get("ns-vld-id"),
1603 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1604 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1605 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1608 # TODO check that this forcing is not incompatible with other forcing
1609 return ifaces_forcing_vim_network
1611 def _update_vnfrs_from_nsd(self
, nsr
):
1616 step
= "Getting vnf_profiles from nsd"
1617 vnf_profiles
= nsd
.get("df", [{}])[0].get("vnf-profile", ())
1618 vld_fixed_ip_connection_point_data
= {}
1620 step
= "Getting ip-address info from vnf_profile if it exists"
1621 for vnfp
in vnf_profiles
:
1622 # Checking ip-address info from nsd.vnf_profile and storing
1623 for vlc
in vnfp
.get("virtual-link-connectivity", ()):
1624 for cpd
in vlc
.get("constituent-cpd-id", ()):
1625 if cpd
.get("ip-address"):
1626 step
= "Storing ip-address info"
1627 vld_fixed_ip_connection_point_data
.update({vlc
.get("virtual-link-profile-id") + '.' + cpd
.get("constituent-base-element-id"): {
1628 "vnfd-connection-point-ref": cpd
.get(
1629 "constituent-cpd-id"),
1630 "ip-address": cpd
.get(
1633 # Inserting ip address to vnfr
1634 if len(vld_fixed_ip_connection_point_data
) > 0:
1635 step
= "Getting vnfrs"
1636 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1637 for item
in vld_fixed_ip_connection_point_data
.keys():
1638 step
= "Filtering vnfrs"
1639 vnfr
= next(filter(lambda vnfr
: vnfr
["member-vnf-index-ref"] == item
.split('.')[1], vnfrs
), None)
1642 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1643 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1644 step
= "Looking for matched interface"
1646 iface
.get("external-connection-point-ref")
1647 == vld_fixed_ip_connection_point_data
[item
].get("vnfd-connection-point-ref") and
1648 iface
.get("ns-vld-id") == item
.split('.')[0]
1651 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1652 vdur_index
, iface_index
1654 step
= "Storing info in order to update vnfr"
1656 vnfr_update_text
+ ".ip-address"
1657 ] = increment_ip_mac(
1658 vld_fixed_ip_connection_point_data
[item
].get("ip-address"),
1659 vdur
.get("count-index", 0), )
1660 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1662 step
= "updating vnfr at database"
1663 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1671 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
1673 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1676 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1680 vnfr_update_rollback
= {}
1681 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1682 # update vim-account-id
1684 vim_account
= indata
["vimAccountId"]
1685 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1686 # check instantiate parameters
1687 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1688 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1690 if vnf_inst_params
.get("vimAccountId"):
1691 vim_account
= vnf_inst_params
.get("vimAccountId")
1692 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1694 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1695 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1696 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1697 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1699 for iface_inst_param
in get_iterable(
1700 vdu_inst_param
.get("interface")
1702 iface_index
, _
= next(
1704 for i
in enumerate(vdur
["interfaces"])
1705 if i
[1]["name"] == iface_inst_param
["name"]
1707 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1708 vdur_index
, iface_index
1710 if iface_inst_param
.get("ip-address"):
1712 vnfr_update_text
+ ".ip-address"
1713 ] = increment_ip_mac(
1714 iface_inst_param
.get("ip-address"),
1715 vdur
.get("count-index", 0),
1717 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1718 if iface_inst_param
.get("mac-address"):
1720 vnfr_update_text
+ ".mac-address"
1721 ] = increment_ip_mac(
1722 iface_inst_param
.get("mac-address"),
1723 vdur
.get("count-index", 0),
1725 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1726 if iface_inst_param
.get("floating-ip-required"):
1728 vnfr_update_text
+ ".floating-ip-required"
1730 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1731 # TODO update vld with the ip-profile
1732 for ivld_inst_param
in get_iterable(
1733 vnf_inst_params
.get("internal-vld")
1735 for icp_inst_param
in get_iterable(
1736 ivld_inst_param
.get("internal-connection-point")
1739 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1740 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1742 iface
.get("internal-connection-point-ref")
1743 == icp_inst_param
["id-ref"]
1745 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1746 vdur_index
, iface_index
1748 if icp_inst_param
.get("ip-address"):
1750 vnfr_update_text
+ ".ip-address"
1751 ] = increment_ip_mac(
1752 icp_inst_param
.get("ip-address"),
1753 vdur
.get("count-index", 0),
1756 vnfr_update_text
+ ".fixed-ip"
1758 if icp_inst_param
.get("mac-address"):
1760 vnfr_update_text
+ ".mac-address"
1761 ] = increment_ip_mac(
1762 icp_inst_param
.get("mac-address"),
1763 vdur
.get("count-index", 0),
1766 vnfr_update_text
+ ".fixed-mac"
1769 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1770 for vld_inst_param
in get_iterable(indata
.get("vld")):
1771 for vnfcp_inst_param
in get_iterable(
1772 vld_inst_param
.get("vnfd-connection-point-ref")
1774 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
1777 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1778 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1780 iface
.get("external-connection-point-ref")
1781 == vnfcp_inst_param
["vnfd-connection-point-ref"]
1783 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1784 vdur_index
, iface_index
1786 if vnfcp_inst_param
.get("ip-address"):
1788 vnfr_update_text
+ ".ip-address"
1789 ] = increment_ip_mac(
1790 vnfcp_inst_param
.get("ip-address"),
1791 vdur
.get("count-index", 0),
1793 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1794 if vnfcp_inst_param
.get("mac-address"):
1796 vnfr_update_text
+ ".mac-address"
1797 ] = increment_ip_mac(
1798 vnfcp_inst_param
.get("mac-address"),
1799 vdur
.get("count-index", 0),
1801 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1804 vnfr_update
["vim-account-id"] = vim_account
1805 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
1808 vnfr_update
["vca-id"] = vca_id
1809 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
1812 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
1813 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1817 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
1818 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1820 # update database vnfr
1821 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1827 "content": vnfr_update_rollback
,
1831 # Update indada in case pdu forces to use a concrete vim-network-name
1832 # TODO check if user has already insert a vim-network-name and raises an error
1833 if not ifaces_forcing_vim_network
:
1835 for iface_info
in ifaces_forcing_vim_network
:
1836 if iface_info
.get("ns-vld-id"):
1837 if "vld" not in indata
:
1839 indata
["vld"].append(
1841 key
: iface_info
[key
]
1842 for key
in ("name", "vim-network-name", "vim-network-id")
1843 if iface_info
.get(key
)
1847 elif iface_info
.get("vnf-vld-id"):
1848 if "vnf" not in indata
:
1850 indata
["vnf"].append(
1852 "member-vnf-index": member_vnf_index
,
1855 key
: iface_info
[key
]
1861 if iface_info
.get(key
)
1868 def _create_nslcmop(nsr_id
, operation
, params
):
1870 Creates a ns-lcm-opp content to be stored at database.
1871 :param nsr_id: internal id of the instance
1872 :param operation: instantiate, terminate, scale, action, ...
1873 :param params: user parameters for the operation
1874 :return: dictionary following SOL005 format
1881 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1882 "queuePosition": None,
1884 "errorMessage": None,
1885 "detailedStatus": None,
1886 "statusEnteredTime": now
,
1887 "nsInstanceId": nsr_id
,
1888 "lcmOperationType": operation
,
1890 "isAutomaticInvocation": False,
1891 "operationParams": params
,
1892 "isCancelPending": False,
1894 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1895 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1900 def _get_enabled_vims(self
, session
):
1902 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1903 :param session: current session with user information
1905 db_filter
= self
._get
_project
_filter
(session
)
1906 db_filter
["_admin.operationalState"] = "ENABLED"
1907 vims
= self
.db
.get_list("vim_accounts", db_filter
)
1910 vimAccounts
.append(vim
["_id"])
1923 Performs a new operation over a ns
1924 :param rollback: list to append created items at database in case a rollback must to be done
1925 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1926 :param indata: descriptor with the parameters of the operation. It must contains among others
1927 nsInstanceId: _id of the nsr to perform the operation
1928 operation: it can be: instantiate, terminate, action, TODO: update, heal
1929 :param kwargs: used to override the indata descriptor
1930 :param headers: http request headers
1931 :return: id of the nslcmops
1934 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
1936 db_filter
= self
._get
_project
_filter
(session
)
1937 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1938 nsis
= self
.db
.get_one(
1939 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
1942 raise EngineException(
1943 "The NS instance {} cannot be terminated because is used by the slice {}".format(
1946 http_code
=HTTPStatus
.CONFLICT
,
1950 # Override descriptor with query string kwargs
1951 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
1952 operation
= indata
["lcmOperationType"]
1953 nsInstanceId
= indata
["nsInstanceId"]
1955 validate_input(indata
, self
.operation_schema
[operation
])
1956 # get ns from nsr_id
1957 _filter
= BaseTopic
._get
_project
_filter
(session
)
1958 _filter
["_id"] = nsInstanceId
1959 nsr
= self
.db
.get_one("nsrs", _filter
)
1962 if operation
== "terminate" and slice_object
is False:
1963 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
1965 not nsr
["_admin"].get("nsState")
1966 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
1968 if operation
== "terminate" and indata
.get("autoremove"):
1969 # NSR must be deleted
1973 ) # a none in this case is used to indicate not instantiated. It can be removed
1974 if operation
!= "instantiate":
1975 raise EngineException(
1976 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1977 nsInstanceId
, operation
1979 HTTPStatus
.CONFLICT
,
1982 if operation
== "instantiate" and not session
["force"]:
1983 raise EngineException(
1984 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1985 nsInstanceId
, operation
1987 HTTPStatus
.CONFLICT
,
1989 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
1991 if operation
== "instantiate":
1992 self
._update
_vnfrs
_from
_nsd
(nsr
)
1993 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
1995 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
1996 _id
= nslcmop_desc
["_id"]
1998 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
2000 if indata
.get("placement-engine"):
2001 # Save valid vim accounts in lcm operation descriptor
2002 nslcmop_desc
["operationParams"][
2004 ] = self
._get
_enabled
_vims
(session
)
2005 self
.db
.create("nslcmops", nslcmop_desc
)
2006 rollback
.append({"topic": "nslcmops", "_id": _id
})
2007 if not slice_object
:
2008 self
.msg
.write("ns", operation
, nslcmop_desc
)
2010 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
2011 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2012 # except DbException as e:
2013 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2015 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2016 raise EngineException(
2017 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2020 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2021 raise EngineException(
2022 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2026 class NsiTopic(BaseTopic
):
2029 quota_name
= "slice_instances"
2031 def __init__(self
, db
, fs
, msg
, auth
):
2032 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2033 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
2036 def _format_ns_request(ns_request
):
2037 formated_request
= copy(ns_request
)
2038 # TODO: Add request params
2039 return formated_request
2042 def _format_addional_params(slice_request
):
2044 Get and format user additional params for NS or VNF
2045 :param slice_request: User instantiation additional parameters
2046 :return: a formatted copy of additional params or None if not supplied
2048 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
2049 if additional_params
:
2050 for k
, v
in additional_params
.items():
2051 if not isinstance(k
, str):
2052 raise EngineException(
2053 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2057 if "." in k
or "$" in k
:
2058 raise EngineException(
2059 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2063 if isinstance(v
, (dict, tuple, list)):
2064 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2065 return additional_params
2067 def _check_descriptor_dependencies(self
, session
, descriptor
):
2069 Check that the dependent descriptors exist on a new descriptor or edition
2070 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2071 :param descriptor: descriptor to be inserted or edit
2072 :return: None or raises exception
2074 if not descriptor
.get("nst-ref"):
2076 nstd_id
= descriptor
["nst-ref"]
2077 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
2078 raise EngineException(
2079 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2082 http_code
=HTTPStatus
.CONFLICT
,
2085 def check_conflict_on_del(self
, session
, _id
, db_content
):
2087 Check that NSI is not instantiated
2088 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2089 :param _id: nsi internal id
2090 :param db_content: The database content of the _id
2091 :return: None or raises EngineException with the conflict
2093 if session
["force"]:
2096 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2097 raise EngineException(
2098 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2099 "Launch 'terminate' operation first; or force deletion".format(_id
),
2100 http_code
=HTTPStatus
.CONFLICT
,
2103 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2105 Deletes associated nsilcmops from database. Deletes associated filesystem.
2106 Set usageState of nst
2107 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2108 :param _id: server internal id
2109 :param db_content: The database content of the descriptor
2110 :param not_send_msg: To not send message (False) or store content (list) instead
2111 :return: None if ok or raises EngineException with the problem
2114 # Deleting the nsrs belonging to nsir
2116 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2117 nsr_id
= nsrs_detailed_item
["nsrId"]
2118 if nsrs_detailed_item
.get("shared"):
2120 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2121 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2122 "_id.ne": nsir
["_id"],
2124 nsi
= self
.db
.get_one(
2125 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2127 if nsi
: # last one using nsr
2130 self
.nsrTopic
.delete(
2131 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2133 except (DbException
, EngineException
) as e
:
2134 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2139 # delete related nsilcmops database entries
2140 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2142 # Check and set used NST usage state
2143 nsir_admin
= nsir
.get("_admin")
2144 if nsir_admin
and nsir_admin
.get("nst-id"):
2145 # check if used by another NSI
2146 nsis_list
= self
.db
.get_one(
2148 {"nst-id": nsir_admin
["nst-id"]},
2149 fail_on_empty
=False,
2155 {"_id": nsir_admin
["nst-id"]},
2156 {"_admin.usageState": "NOT_IN_USE"},
2159 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2161 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2162 :param rollback: list to append the created items at database in case a rollback must be done
2163 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2164 :param indata: params to be used for the nsir
2165 :param kwargs: used to override the indata descriptor
2166 :param headers: http request headers
2167 :return: the _id of nsi descriptor created at database
2171 step
= "checking quotas"
2172 self
.check_quota(session
)
2175 slice_request
= self
._remove
_envelop
(indata
)
2176 # Override descriptor with query string kwargs
2177 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2178 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2181 step
= "getting nstd id='{}' from database".format(
2182 slice_request
.get("nstId")
2184 _filter
= self
._get
_project
_filter
(session
)
2185 _filter
["_id"] = slice_request
["nstId"]
2186 nstd
= self
.db
.get_one("nsts", _filter
)
2187 # check NST is not disabled
2188 step
= "checking NST operationalState"
2189 if nstd
["_admin"]["operationalState"] == "DISABLED":
2190 raise EngineException(
2191 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2192 "instance".format(slice_request
["nstId"]),
2193 http_code
=HTTPStatus
.CONFLICT
,
2197 # check NSD is not disabled
2198 step
= "checking operationalState"
2199 if nstd
["_admin"]["operationalState"] == "DISABLED":
2200 raise EngineException(
2201 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2202 "a network slice".format(slice_request
["nstId"]),
2203 http_code
=HTTPStatus
.CONFLICT
,
2206 nstd
.pop("_admin", None)
2207 nstd_id
= nstd
.pop("_id", None)
2208 nsi_id
= str(uuid4())
2209 step
= "filling nsi_descriptor with input data"
2214 "name": slice_request
["nsiName"],
2215 "description": slice_request
.get("nsiDescription", ""),
2216 "datacenter": slice_request
["vimAccountId"],
2217 "nst-ref": nstd
["id"],
2218 "instantiation_parameters": slice_request
,
2219 "network-slice-template": nstd
,
2223 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2226 step
= "creating nsi at database"
2228 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2230 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2231 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2232 nsi_descriptor
["_admin"]["deployed"] = {}
2233 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2234 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2236 # Creating netslice-vld for the RO.
2237 step
= "creating netslice-vld at database"
2239 # Building the vlds list to be deployed
2240 # From netslice descriptors, creating the initial list
2243 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2244 # Getting template Instantiation parameters from NST
2245 nsi_vld
= deepcopy(netslice_vlds
)
2246 nsi_vld
["shared-nsrs-list"] = []
2247 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2248 nsi_vlds
.append(nsi_vld
)
2250 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2251 # Creating netslice-subnet_record.
2255 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2256 for member_ns
in nstd
["netslice-subnet"]:
2257 nsd_id
= member_ns
["nsd-ref"]
2258 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2259 member_ns
["nsd-ref"], member_ns
["id"]
2261 if nsd_id
not in needed_nsds
:
2263 _filter
["id"] = nsd_id
2264 nsd
= self
.db
.get_one(
2265 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2269 needed_nsds
[nsd_id
] = nsd
2271 nsd
= needed_nsds
[nsd_id
]
2272 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2273 services
.append(member_ns
)
2275 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2276 member_ns
["nsd-ref"], member_ns
["id"]
2279 # creates Network Services records (NSRs)
2280 step
= "creating nsrs at database using NsrTopic.new()"
2281 ns_params
= slice_request
.get("netslice-subnet")
2283 nsi_netslice_subnet
= []
2284 for service
in services
:
2285 # Check if the netslice-subnet is shared and if it is share if the nss exists
2288 # Is the nss shared and instantiated?
2289 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2290 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2293 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2294 nsi
= self
.db
.get_one(
2295 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2297 if nsi
and service
.get("is-shared-nss"):
2298 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2299 for nsrs_detailed_item
in nsrs_detailed_list
:
2300 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2301 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2302 _id_nsr
= nsrs_detailed_item
["nsrId"]
2304 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2305 if netslice_subnet
["nss-id"] == service
["id"]:
2306 indata_ns
= netslice_subnet
2310 if service
.get("instantiation-parameters"):
2311 indata_ns
= deepcopy(service
["instantiation-parameters"])
2312 # del service["instantiation-parameters"]
2314 indata_ns
["nsdId"] = service
["_id"]
2315 indata_ns
["nsName"] = (
2316 slice_request
.get("nsiName") + "." + service
["id"]
2318 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2319 indata_ns
["nsDescription"] = service
["description"]
2320 if slice_request
.get("ssh_keys"):
2321 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2324 for ns_param
in ns_params
:
2325 if ns_param
.get("id") == service
["id"]:
2326 copy_ns_param
= deepcopy(ns_param
)
2327 del copy_ns_param
["id"]
2328 indata_ns
.update(copy_ns_param
)
2331 # Creates Nsr objects
2332 _id_nsr
, _
= self
.nsrTopic
.new(
2333 rollback
, session
, indata_ns
, kwargs
, headers
2337 "shared": service
.get("is-shared-nss"),
2338 "nsd-id": service
["nsd-ref"],
2339 "nss-id": service
["id"],
2340 "nslcmop_instantiate": None,
2342 indata_ns
["nss-id"] = service
["id"]
2343 nsrs_list
.append(nsrs_item
)
2344 nsi_netslice_subnet
.append(indata_ns
)
2345 nsr_ref
= {"nsr-ref": _id_nsr
}
2346 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2348 # Adding the nsrs list to the nsi
2349 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2350 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2352 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2355 # Creating the entry in the database
2356 self
.db
.create("nsis", nsi_descriptor
)
2357 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2359 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2360 self
.logger
.exception(
2361 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2363 raise EngineException("Error {}: {}".format(step
, e
))
2364 except ValidationError
as e
:
2365 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2367 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2368 raise EngineException(
2369 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2373 class NsiLcmOpTopic(BaseTopic
):
2376 operation_schema
= { # mapping between operation and jsonschema to validate
2377 "instantiate": nsi_instantiate
,
2381 def __init__(self
, db
, fs
, msg
, auth
):
2382 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2383 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2385 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2387 Check that user has enter right parameters for the operation
2388 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2389 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2390 :param indata: descriptor with the parameters of the operation
2394 nstd
= nsir
["network-slice-template"]
2396 def check_valid_netslice_subnet_id(nstId
):
2397 # TODO change to vnfR (??)
2398 for netslice_subnet
in nstd
["netslice-subnet"]:
2399 if nstId
== netslice_subnet
["id"]:
2400 nsd_id
= netslice_subnet
["nsd-ref"]
2401 if nsd_id
not in nsds
:
2402 _filter
= self
._get
_project
_filter
(session
)
2403 _filter
["id"] = nsd_id
2404 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2407 raise EngineException(
2408 "Invalid parameter nstId='{}' is not one of the "
2409 "nst:netslice-subnet".format(nstId
)
2412 if operation
== "instantiate":
2413 # check the existance of netslice-subnet items
2414 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2415 check_valid_netslice_subnet_id(in_nst
["id"])
2417 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2423 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2424 "statusEnteredTime": now
,
2425 "netsliceInstanceId": netsliceInstanceId
,
2426 "lcmOperationType": operation
,
2428 "isAutomaticInvocation": False,
2429 "operationParams": params
,
2430 "isCancelPending": False,
2432 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2433 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2434 + netsliceInstanceId
,
2439 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2440 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2441 if nst_sb_item
.get("is-shared-nss"):
2442 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2443 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2444 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2445 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2446 "nss-connection-point-ref"
2449 admin_subnet_item
["nss-id"]
2450 == admin_vld_nss_cp_ref_item
["nss-ref"]
2453 not nsr_item
["nsrId"]
2454 in admin_vld_item
["shared-nsrs-list"]
2456 admin_vld_item
["shared-nsrs-list"].append(
2460 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2463 {"_id": nsir
["_id"]},
2464 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2467 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2469 Performs a new operation over a ns
2470 :param rollback: list to append created items at database in case a rollback must to be done
2471 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2472 :param indata: descriptor with the parameters of the operation. It must contains among others
2473 netsliceInstanceId: _id of the nsir to perform the operation
2474 operation: it can be: instantiate, terminate, action, TODO: update, heal
2475 :param kwargs: used to override the indata descriptor
2476 :param headers: http request headers
2477 :return: id of the nslcmops
2480 # Override descriptor with query string kwargs
2481 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2482 operation
= indata
["lcmOperationType"]
2483 netsliceInstanceId
= indata
["netsliceInstanceId"]
2484 validate_input(indata
, self
.operation_schema
[operation
])
2486 # get nsi from netsliceInstanceId
2487 _filter
= self
._get
_project
_filter
(session
)
2488 _filter
["_id"] = netsliceInstanceId
2489 nsir
= self
.db
.get_one("nsis", _filter
)
2490 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2495 not nsir
["_admin"].get("nsiState")
2496 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2498 if operation
== "terminate" and indata
.get("autoremove"):
2499 # NSIR must be deleted
2503 ) # a none in this case is used to indicate not instantiated. It can be removed
2504 if operation
!= "instantiate":
2505 raise EngineException(
2506 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2507 netsliceInstanceId
, operation
2509 HTTPStatus
.CONFLICT
,
2512 if operation
== "instantiate" and not session
["force"]:
2513 raise EngineException(
2514 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2515 netsliceInstanceId
, operation
2517 HTTPStatus
.CONFLICT
,
2520 # Creating all the NS_operation (nslcmop)
2521 # Get service list from db
2522 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2524 # nslcmops_item = None
2525 for index
, nsr_item
in enumerate(nsrs_list
):
2526 nsr_id
= nsr_item
["nsrId"]
2527 if nsr_item
.get("shared"):
2528 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2529 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2531 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2533 _filter
["_id.ne"] = netsliceInstanceId
2534 nsi
= self
.db
.get_one(
2535 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2537 if operation
== "terminate":
2539 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2543 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2546 ): # other nsi is using this nsr and it needs this nsr instantiated
2547 continue # do not create nsilcmop
2549 # looks the first nsi fulfilling the conditions but not being the current NSIR
2551 nsi_nsr_item
= next(
2553 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2554 if n
["nsrId"] == nsr_id
2556 and n
["nslcmop_instantiate"]
2558 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2559 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2561 "_admin.nsrs-detailed-list.{}".format(
2565 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2566 # continue to not create nslcmop since nsrs is shared and nsrs was created
2569 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2574 "lcmOperationType": operation
,
2575 "nsInstanceId": nsr_id
,
2576 # Including netslice_id in the ns instantiate Operation
2577 "netsliceInstanceId": netsliceInstanceId
,
2579 if operation
== "instantiate":
2580 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2581 indata_ns
.update(service
["instantiate_params"])
2583 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2584 # message via kafka bus
2585 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2586 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2588 nslcmops
.append(nslcmop
)
2589 if operation
== "instantiate":
2591 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2595 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2596 except (DbException
, EngineException
) as e
:
2597 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2600 + "skipping NS={} because not found".format(nsr_id
)
2607 indata
["nslcmops_ids"] = nslcmops
2608 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2610 nsilcmop_desc
= self
._create
_nsilcmop
(
2611 session
, netsliceInstanceId
, operation
, indata
2614 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2616 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2617 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2618 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2620 except ValidationError
as e
:
2621 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2623 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2624 raise EngineException(
2625 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2628 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2629 raise EngineException(
2630 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR