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 _get_vim_account(self
, vim_id
: str, session
):
437 db_filter
= self
._get
_project
_filter
(session
)
438 db_filter
["_id"] = vim_id
439 return self
.db
.get_one("vim_accounts", db_filter
)
441 raise EngineException(
442 "Invalid vimAccountId='{}' not present for the project".format(
447 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
, session
):
449 additional_params
, _
= self
._format
_additional
_params
(
450 ns_request
, descriptor
=nsd
454 "name": ns_request
["nsName"],
455 "name-ref": ns_request
["nsName"],
456 "short-name": ns_request
["nsName"],
457 "admin-status": "ENABLED",
458 "nsState": "NOT_INSTANTIATED",
459 "currentOperation": "IDLE",
460 "currentOperationID": None,
461 "errorDescription": None,
463 "deploymentStatus": None,
464 "configurationStatus": None,
466 "nsd": {k
: v
for k
, v
in nsd
.items()},
467 "datacenter": ns_request
["vimAccountId"],
468 "resource-orchestrator": "osmopenmano",
469 "description": ns_request
.get("nsDescription", ""),
470 "constituent-vnfr-ref": [],
471 "operational-status": "init", # typedef ns-operational-
472 "config-status": "init", # typedef config-states
473 "detailed-status": "scheduled",
474 "orchestration-progress": {},
476 "nsd-name-ref": nsd
["name"],
477 "operational-events": [], # "id", "timestamp", "description", "event",
478 "nsd-ref": nsd
["id"],
479 "nsd-id": nsd
["_id"],
481 "instantiate_params": self
._format
_ns
_request
(ns_request
),
482 "additionalParamsForNs": additional_params
,
483 "ns-instance-config-ref": nsr_id
,
486 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
490 ns_request
["nsr_id"] = nsr_id
491 if ns_request
and ns_request
.get("config-units"):
492 nsr_descriptor
["config-units"] = ns_request
["config-units"]
493 vim_account_id
= nsr_descriptor
["instantiate_params"].get("vimAccountId")
495 vca_id
= self
._get
_vim
_account
(vim_account_id
, session
).get("vca")
496 nsr_descriptor
["instantiate_params"]["vcaId"] = vca_id
498 if nsd
.get("virtual-link-desc"):
499 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
500 # Fill each vld with vnfd-connection-point-ref data
501 # TODO: Change for multiple df support
502 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
503 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
504 for vnf_profile
in vnf_profiles
:
505 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
506 for cpd
in vlc
.get("constituent-cpd-id", ()):
507 all_vld_connection_point_data
[
508 vlc
.get("virtual-link-profile-id")
511 "member-vnf-index-ref": cpd
.get(
512 "constituent-base-element-id"
514 "vnfd-connection-point-ref": cpd
.get(
517 "vnfd-id-ref": vnf_profile
.get("vnfd-id"),
521 vnfd
= self
._get
_vnfd
_from
_db
(vnf_profile
.get("vnfd-id"), session
)
523 for vdu
in vnfd
.get("vdu", ()):
526 # Find this vdu compute and storage descriptors
527 vdu_virtual_compute
= {}
528 vdu_virtual_storage
= {}
529 for vcd
in vnfd
.get("virtual-compute-desc", ()):
530 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
531 vdu_virtual_compute
= vcd
532 for vsd
in vnfd
.get("virtual-storage-desc", ()):
533 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
534 vdu_virtual_storage
= vsd
535 # Get this vdu vcpus, memory and storage info for flavor_data
536 if vdu_virtual_compute
.get("virtual-cpu", {}).get(
539 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"][
542 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
543 flavor_data
["memory-mb"] = (
544 float(vdu_virtual_compute
["virtual-memory"]["size"])
547 if vdu_virtual_storage
.get("size-of-storage"):
548 flavor_data
["storage-gb"] = vdu_virtual_storage
[
551 # Get this vdu EPA info for guest_epa
552 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
553 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"][
556 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
557 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
558 if vcpu_pinning
.get("thread-policy"):
559 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
[
562 if vcpu_pinning
.get("policy"):
565 if vcpu_pinning
["policy"] == "dynamic"
568 guest_epa
["cpu-pinning-policy"] = cpu_policy
569 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
570 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"][
573 if vdu_virtual_compute
.get("virtual-memory", {}).get(
576 guest_epa
["mempage-size"] = vdu_virtual_compute
[
579 if vdu_virtual_compute
.get("virtual-memory", {}).get(
582 guest_epa
["numa-node-policy"] = vdu_virtual_compute
[
584 ]["numa-node-policy"]
585 if vdu_virtual_storage
.get("disk-io-quota"):
586 guest_epa
["disk-io-quota"] = vdu_virtual_storage
[
591 flavor_data
["guest-epa"] = guest_epa
593 flavor_data
["name"] = vdu
["id"][:56] + "-flv"
594 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
595 nsr_descriptor
["flavor"].append(flavor_data
)
597 sw_image_id
= vdu
.get("sw-image-desc")
599 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
600 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
602 # also add alternative images to the list of images
603 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
604 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
605 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
608 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(
611 vld
["name"] = vld
["id"]
612 nsr_descriptor
["vld"] = nsr_vld
614 return nsr_descriptor
616 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
617 sw_image_desc
= utils
.find_in_list(
618 vnfd
.get("sw-image-desc", ()), lambda sw
: sw
["id"] == sw_image_id
621 if sw_image_desc
.get("image"):
622 image_data
["image"] = sw_image_desc
["image"]
623 if sw_image_desc
.get("checksum"):
624 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
625 if sw_image_desc
.get("vim-type"):
626 image_data
["vim-type"] = sw_image_desc
["vim-type"]
629 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
631 Adds image to nsr checking first it is not already added
636 for f
in nsr_descriptor
["image"]
637 if all(f
.get(k
) == image_data
[k
] for k
in image_data
)
642 image_data
["id"] = str(len(nsr_descriptor
["image"]))
643 nsr_descriptor
["image"].append(image_data
)
645 def _create_vnfr_descriptor_from_vnfd(
655 vnfr_id
= str(uuid4())
656 nsr_id
= nsr_descriptor
["id"]
658 additional_params
, vnf_params
= self
._format
_additional
_params
(
659 ns_request
, vnf_index
, descriptor
=vnfd
665 "nsr-id-ref": nsr_id
,
666 "member-vnf-index-ref": vnf_index
,
667 "additionalParamsForVnf": additional_params
,
669 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
671 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
672 "vim-account-id": None,
675 "connection-point": [],
676 "ip-address": None, # mgmt-interface filled by LCM
678 vnf_k8s_namespace
= ns_k8s_namespace
680 if vnf_params
.get("k8s-namespace"):
681 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
682 if vnf_params
.get("config-units"):
683 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
686 if vnfd
.get("int-virtual-link-desc"):
687 vnfr_descriptor
["vld"] = []
688 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
689 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
691 for cp
in vnfd
.get("ext-cpd", ()):
693 "name": cp
.get("id"),
694 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
695 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
697 # "ip-address", "mac-address" # filled by LCM
698 # vim-id # TODO it would be nice having a vim port id
700 vnfr_descriptor
["connection-point"].append(vnf_cp
)
702 # Create k8s-cluster information
703 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
704 if vnfd
.get("k8s-cluster"):
705 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
706 all_k8s_cluster_nets_cpds
= {}
707 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
708 if cpd
.get("k8s-cluster-net"):
709 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get(
712 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
713 if net
.get("id") in all_k8s_cluster_nets_cpds
:
714 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[
719 for kdu
in get_iterable(vnfd
.get("kdu")):
720 additional_params
, kdu_params
= self
._format
_additional
_params
(
721 ns_request
, vnf_index
, kdu_name
=kdu
["name"], descriptor
=vnfd
723 kdu_k8s_namespace
= vnf_k8s_namespace
724 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
725 if kdu_params
and kdu_params
.get("k8s-namespace"):
726 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
727 kdu_deployment_name
= ""
728 if kdu_params
and kdu_params
.get("kdu-deployment-name"):
729 kdu_deployment_name
= kdu_params
.get("kdu-deployment-name")
732 "additionalParams": additional_params
,
733 "k8s-namespace": kdu_k8s_namespace
,
734 "kdu-deployment-name": kdu_deployment_name
,
735 "kdu-name": kdu
["name"],
736 # TODO "name": "" Name of the VDU in the VIM
737 "ip-address": None, # mgmt-interface filled by LCM
740 if kdu_params
and kdu_params
.get("config-units"):
741 kdur
["config-units"] = kdu_params
["config-units"]
742 if kdu
.get("helm-version"):
743 kdur
["helm-version"] = kdu
["helm-version"]
744 for k8s_type
in ("helm-chart", "juju-bundle"):
745 if kdu
.get(k8s_type
):
746 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
747 if not vnfr_descriptor
.get("kdur"):
748 vnfr_descriptor
["kdur"] = []
749 vnfr_descriptor
["kdur"].append(kdur
)
751 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
753 for vdu
in vnfd
.get("vdu", ()):
756 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
757 "operate-vnf-op-config"
759 vdu_config
= utils
.find_in_list(
760 configs
, lambda config
: config
["id"] == vdu
["id"]
766 vdu_instantiation_level
= utils
.find_in_list(
767 vnfd
.get("df")[0]["instantiation-level"][0]["vdu-level"],
768 lambda a_vdu_profile
: a_vdu_profile
["vdu-id"] == vdu
["id"],
771 vdu_instantiation_level
= None
774 external_connection_ee
= utils
.filter_in_list(
775 vdu_config
.get("execution-environment-list", []),
776 lambda ee
: "external-connection-point-ref" in ee
,
778 for ee
in external_connection_ee
:
779 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
781 additional_params
, vdu_params
= self
._format
_additional
_params
(
782 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
785 "vdu-id-ref": vdu
["id"],
786 # TODO "name": "" Name of the VDU in the VIM
787 "ip-address": None, # mgmt-interface filled by LCM
788 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
789 "internal-connection-point": [],
791 "additionalParams": additional_params
,
792 "vdu-name": vdu
["name"],
794 if vdu_params
and vdu_params
.get("config-units"):
795 vdur
["config-units"] = vdu_params
["config-units"]
796 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
797 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"][
800 if vdu
.get("pdu-type"):
801 vdur
["pdu-type"] = vdu
["pdu-type"]
802 vdur
["name"] = vdu
["pdu-type"]
803 # TODO volumes: name, volume-id
804 for icp
in vdu
.get("int-cpd", ()):
807 "connection-point-id": icp
["id"],
808 "name": icp
.get("id"),
811 vdur
["internal-connection-point"].append(vdu_icp
)
813 for iface
in icp
.get("virtual-network-interface-requirement", ()):
814 iface_fields
= ("name", "mac-address")
816 x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None
819 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
820 if "port-security-enabled" in icp
:
821 vdu_iface
["port-security-enabled"] = icp
[
822 "port-security-enabled"
825 if "port-security-disable-strategy" in icp
:
826 vdu_iface
["port-security-disable-strategy"] = icp
[
827 "port-security-disable-strategy"
830 for ext_cp
in vnfd
.get("ext-cpd", ()):
831 if not ext_cp
.get("int-cpd"):
833 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
835 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
836 vdu_iface
["external-connection-point-ref"] = ext_cp
.get(
840 if "port-security-enabled" in ext_cp
:
841 vdu_iface
["port-security-enabled"] = ext_cp
[
842 "port-security-enabled"
845 if "port-security-disable-strategy" in ext_cp
:
846 vdu_iface
["port-security-disable-strategy"] = ext_cp
[
847 "port-security-disable-strategy"
854 and vdu_iface
.get("external-connection-point-ref")
857 vdu_iface
["mgmt-vnf"] = True
858 vdu_iface
["mgmt-interface"] = True
860 for ecp
in vdu_mgmt_cp
:
861 if vdu_iface
.get("external-connection-point-ref") == ecp
:
862 vdu_iface
["mgmt-interface"] = True
864 if iface
.get("virtual-interface"):
865 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
867 # look for network where this interface is connected
868 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
870 # TODO: Change for multiple df support
871 for df
in get_iterable(nsd
.get("df")):
872 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
873 for vlc_index
, vlc
in enumerate(
875 vnf_profile
.get("virtual-link-connectivity")
878 for cpd
in get_iterable(
879 vlc
.get("constituent-cpd-id")
882 cpd
.get("constituent-cpd-id")
885 vdu_iface
["ns-vld-id"] = vlc
.get(
886 "virtual-link-profile-id"
888 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
889 if vdu_iface
.get("type") in (
893 nsr_descriptor
["vld"][vlc_index
][
897 elif vdu_iface
.get("internal-connection-point-ref"):
898 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
899 # TODO: store fixed IP address in the record (if it exists in the ICP)
900 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
901 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
902 ivld_index
= utils
.find_index_in_list(
903 vnfd
.get("int-virtual-link-desc", ()),
904 lambda ivld
: ivld
["id"]
905 == icp
.get("int-virtual-link-desc"),
907 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
909 vdur
["interfaces"].append(vdu_iface
)
911 if vdu
.get("sw-image-desc"):
912 sw_image
= utils
.find_in_list(
913 vnfd
.get("sw-image-desc", ()),
914 lambda image
: image
["id"] == vdu
.get("sw-image-desc"),
916 nsr_sw_image_data
= utils
.find_in_list(
917 nsr_descriptor
["image"],
918 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image")),
920 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
922 if vdu
.get("alternative-sw-image-desc"):
924 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
925 sw_image
= utils
.find_in_list(
926 vnfd
.get("sw-image-desc", ()),
927 lambda image
: image
["id"] == alt_image_id
,
929 nsr_sw_image_data
= utils
.find_in_list(
930 nsr_descriptor
["image"],
932 nsr_image
.get("image") == sw_image
.get("image")
935 alt_image_ids
.append(nsr_sw_image_data
["id"])
936 vdur
["alt-image-ids"] = alt_image_ids
938 flavor_data_name
= vdu
["id"][:56] + "-flv"
939 nsr_flavor_desc
= utils
.find_in_list(
940 nsr_descriptor
["flavor"],
941 lambda flavor
: flavor
["name"] == flavor_data_name
,
945 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
947 if vdu_instantiation_level
:
948 count
= vdu_instantiation_level
.get("number-of-instances")
952 for index
in range(0, count
):
953 vdur
= deepcopy(vdur
)
954 for iface
in vdur
["interfaces"]:
955 if iface
.get("ip-address") and index
!= 0:
956 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
957 if iface
.get("mac-address") and index
!= 0:
958 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
960 vdur
["_id"] = str(uuid4())
961 vdur
["id"] = vdur
["_id"]
962 vdur
["count-index"] = index
963 vnfr_descriptor
["vdur"].append(vdur
)
965 return vnfr_descriptor
967 def vca_status_refresh(self
, session
, ns_instance_content
, filter_q
):
969 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
970 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
971 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
972 :param ns_instance_content: ns instance content
973 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
976 time_now
, time_delta
= time(), time() - ns_instance_content
["_admin"]["modified"]
977 force_refresh
= isinstance(filter_q
, dict) and filter_q
.get('vcaStatusRefresh') == 'true'
978 threshold_reached
= time_delta
> 120
979 if force_refresh
or threshold_reached
:
980 operation
, _id
= "vca_status_refresh", ns_instance_content
["_id"]
981 ns_instance_content
["_admin"]["modified"] = time_now
982 self
.db
.set_one(self
.topic
, {"_id": _id
}, ns_instance_content
)
983 nslcmop_desc
= NsLcmOpTopic
._create
_nslcmop
(_id
, operation
, None)
984 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
985 nslcmop_desc
["_admin"].pop("nsState")
986 self
.msg
.write("ns", operation
, nslcmop_desc
)
989 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
991 Get complete information on an ns instance.
992 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
993 :param _id: string, ns instance id
994 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
995 :param api_req: True if this call is serving an external API request. False if serving internal request.
996 :return: dictionary, raise exception if not found.
998 ns_instance_content
= super().show(session
, _id
, api_req
)
999 self
.vca_status_refresh(session
, ns_instance_content
, filter_q
)
1000 return ns_instance_content
1002 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1003 raise EngineException(
1004 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1008 class VnfrTopic(BaseTopic
):
1012 def __init__(self
, db
, fs
, msg
, auth
):
1013 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1015 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1016 raise EngineException(
1017 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1020 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1021 raise EngineException(
1022 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1025 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1026 # Not used because vnfrs are created and deleted by NsrTopic class directly
1027 raise EngineException(
1028 "Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1032 class NsLcmOpTopic(BaseTopic
):
1035 operation_schema
= { # mapping between operation and jsonschema to validate
1036 "instantiate": ns_instantiate
,
1037 "action": ns_action
,
1039 "terminate": ns_terminate
,
1042 def __init__(self
, db
, fs
, msg
, auth
):
1043 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1045 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
1047 Check that user has enter right parameters for the operation
1048 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1049 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1050 :param indata: descriptor with the parameters of the operation
1053 if operation
== "action":
1054 self
._check
_action
_ns
_operation
(indata
, nsr
)
1055 elif operation
== "scale":
1056 self
._check
_scale
_ns
_operation
(indata
, nsr
)
1057 elif operation
== "instantiate":
1058 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
1060 def _check_action_ns_operation(self
, indata
, nsr
):
1062 # check vnf_member_index
1063 if indata
.get("vnf_member_index"):
1064 indata
["member_vnf_index"] = indata
.pop(
1066 ) # for backward compatibility
1067 if indata
.get("member_vnf_index"):
1068 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1069 indata
["member_vnf_index"], nsr
["_id"]
1072 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"][
1073 "operate-vnf-op-config"
1078 if indata
.get("vdu_id"):
1079 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
1080 descriptor_configuration
= utils
.find_in_list(
1081 configs
, lambda config
: config
["id"] == indata
["vdu_id"]
1083 elif indata
.get("kdu_name"):
1084 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
1085 descriptor_configuration
= utils
.find_in_list(
1086 configs
, lambda config
: config
["id"] == indata
.get("kdu_name")
1089 descriptor_configuration
= utils
.find_in_list(
1090 configs
, lambda config
: config
["id"] == vnfd
["id"]
1092 if descriptor_configuration
is not None:
1093 descriptor_configuration
= descriptor_configuration
.get(
1097 descriptor_configuration
= nsd
.get("ns-configuration", {}).get(
1101 # For k8s allows default primitives without validating the parameters
1102 if indata
.get("kdu_name") and indata
["primitive"] in (
1109 # TODO should be checked that rollback only can contains revsision_numbe????
1110 if not indata
.get("member_vnf_index"):
1111 raise EngineException(
1112 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1117 # if not, check primitive
1118 for config_primitive
in get_iterable(descriptor_configuration
):
1119 if indata
["primitive"] == config_primitive
["name"]:
1120 # check needed primitive_params are provided
1121 if indata
.get("primitive_params"):
1122 in_primitive_params_copy
= copy(indata
["primitive_params"])
1124 in_primitive_params_copy
= {}
1125 for paramd
in get_iterable(config_primitive
.get("parameter")):
1126 if paramd
["name"] in in_primitive_params_copy
:
1127 del in_primitive_params_copy
[paramd
["name"]]
1128 elif not paramd
.get("default-value"):
1129 raise EngineException(
1130 "Needed parameter {} not provided for primitive '{}'".format(
1131 paramd
["name"], indata
["primitive"]
1134 # check no extra primitive params are provided
1135 if in_primitive_params_copy
:
1136 raise EngineException(
1137 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1138 list(in_primitive_params_copy
.keys()), indata
["primitive"]
1143 raise EngineException(
1144 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1149 def _check_scale_ns_operation(self
, indata
, nsr
):
1150 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1151 indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr
["_id"]
1153 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
1155 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1156 == scaling_aspect
["id"]
1160 raise EngineException(
1161 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1162 "present at vnfd:scaling-aspect".format(
1163 indata
["scaleVnfData"]["scaleByStepData"][
1164 "scaling-group-descriptor"
1169 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
1170 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
1174 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
1175 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
1176 for in_vnf
in get_iterable(indata
.get("vnf")):
1177 member_vnf_index
= in_vnf
["member-vnf-index"]
1178 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
1179 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
1181 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(
1182 member_vnf_index
, nsr
["_id"]
1184 vnf_member_index_to_vnfd
[
1186 ] = vnfd
# add to cache, avoiding a later look for
1187 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
1188 if in_vnf
.get("vimAccountId"):
1189 self
._check
_valid
_vim
_account
(
1190 in_vnf
["vimAccountId"], vim_accounts
, session
1193 for in_vld
in get_iterable(indata
.get("vld")):
1194 self
._check
_valid
_wim
_account
(
1195 in_vld
.get("wimAccountId"), wim_accounts
, session
1197 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
1198 if in_vld
["name"] == vldd
["id"]:
1201 raise EngineException(
1202 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1207 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
1208 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1209 vnfr
= self
.db
.get_one(
1211 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
1212 fail_on_empty
=False,
1215 raise EngineException(
1216 "Invalid parameter member_vnf_index='{}' is not one of the "
1217 "nsd:constituent-vnfd".format(member_vnf_index
)
1219 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
1221 raise EngineException(
1222 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1228 def _check_valid_vdu(self
, vnfd
, vdu_id
):
1229 for vdud
in get_iterable(vnfd
.get("vdu")):
1230 if vdud
["id"] == vdu_id
:
1233 raise EngineException(
1234 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1239 def _check_valid_kdu(self
, vnfd
, kdu_name
):
1240 for kdud
in get_iterable(vnfd
.get("kdu")):
1241 if kdud
["name"] == kdu_name
:
1244 raise EngineException(
1245 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1250 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
1251 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
1252 for vdu
in get_iterable(vnfd
.get("vdu")):
1253 if in_vdu
["id"] == vdu
["id"]:
1254 for volume
in get_iterable(in_vdu
.get("volume")):
1255 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
1256 if volumed
["id"] == volume
["name"]:
1259 raise EngineException(
1260 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1261 "volume:name='{}' is not present at "
1262 "vnfd:vdu:virtual-storage-desc list".format(
1263 in_vnf
["member-vnf-index"],
1269 vdu_if_names
= set()
1270 for cpd
in get_iterable(vdu
.get("int-cpd")):
1271 for iface
in get_iterable(
1272 cpd
.get("virtual-network-interface-requirement")
1274 vdu_if_names
.add(iface
.get("name"))
1276 for in_iface
in get_iterable(in_vdu
["interface"]):
1277 if in_iface
["name"] in vdu_if_names
:
1280 raise EngineException(
1281 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1282 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1283 in_vnf
["member-vnf-index"],
1291 raise EngineException(
1292 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1293 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"])
1297 ivld
.get("id"): set()
1298 for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))
1300 for vdu
in get_iterable(vnfd
.get("vdu")):
1301 for cpd
in get_iterable(vnfd
.get("int-cpd")):
1302 if cpd
.get("int-virtual-link-desc"):
1303 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
1305 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
1306 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
1307 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
1308 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
1311 raise EngineException(
1312 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1313 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1314 "vnfd:internal-vld:name/id:internal-connection-point".format(
1315 in_vnf
["member-vnf-index"],
1321 raise EngineException(
1322 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1323 " is not present at vnfd '{}'".format(
1324 in_vnf
["member-vnf-index"], in_ivld
["name"], vnfd
["id"]
1328 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
1329 if vim_account
in vim_accounts
:
1332 db_filter
= self
._get
_project
_filter
(session
)
1333 db_filter
["_id"] = vim_account
1334 self
.db
.get_one("vim_accounts", db_filter
)
1336 raise EngineException(
1337 "Invalid vimAccountId='{}' not present for the project".format(
1341 vim_accounts
.append(vim_account
)
1343 def _get_vim_account(self
, vim_id
: str, session
):
1345 db_filter
= self
._get
_project
_filter
(session
)
1346 db_filter
["_id"] = vim_id
1347 return self
.db
.get_one("vim_accounts", db_filter
)
1349 raise EngineException(
1350 "Invalid vimAccountId='{}' not present for the project".format(
1355 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
1356 if not isinstance(wim_account
, str):
1358 if wim_account
in wim_accounts
:
1361 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
1362 db_filter
["_id"] = wim_account
1363 self
.db
.get_one("wim_accounts", db_filter
)
1365 raise EngineException(
1366 "Invalid wimAccountId='{}' not present for the project".format(
1370 wim_accounts
.append(wim_account
)
1373 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1376 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1377 (ip_address, ...) information.
1378 Modifies PDU _admin.usageState to 'IN_USE'
1379 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1380 :param rollback: list with the database modifications to rollback if needed
1381 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1382 :param vim_account: vim_account where this vnfr should be deployed
1383 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1384 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1385 of the changed vnfr is needed
1387 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1388 "vim-network-name": used at VIM
1389 "name": interface name
1390 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1391 "ns-vld-id": NSD vld where this interface is connected.
1392 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1395 ifaces_forcing_vim_network
= []
1396 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
1397 if not vdur
.get("pdu-type"):
1399 pdu_type
= vdur
.get("pdu-type")
1400 pdu_filter
= self
._get
_project
_filter
(session
)
1401 pdu_filter
["vim_accounts"] = vim_account
1402 pdu_filter
["type"] = pdu_type
1403 pdu_filter
["_admin.operationalState"] = "ENABLED"
1404 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
1405 # TODO feature 1417: "shared": True,
1407 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
1408 for pdu
in available_pdus
:
1409 # step 1 check if this pdu contains needed interfaces:
1410 match_interfaces
= True
1411 for vdur_interface
in vdur
["interfaces"]:
1412 for pdu_interface
in pdu
["interfaces"]:
1413 if pdu_interface
["name"] == vdur_interface
["name"]:
1414 # TODO feature 1417: match per mgmt type
1416 else: # no interface found for name
1417 match_interfaces
= False
1419 if match_interfaces
:
1422 raise EngineException(
1423 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1427 vnfr
["member-vnf-index-ref"],
1432 # step 2. Update pdu
1434 "_admin.usageState": pdu
["_admin"]["usageState"],
1435 "_admin.usage.vnfr_id": None,
1436 "_admin.usage.nsr_id": None,
1437 "_admin.usage.vdur": None,
1441 {"_id": pdu
["_id"]},
1443 "_admin.usageState": "IN_USE",
1445 "vnfr_id": vnfr
["_id"],
1446 "nsr_id": vnfr
["nsr-id-ref"],
1447 "vdur": vdur
["vdu-id-ref"],
1456 "content": rollback_pdu
,
1460 # step 3. Fill vnfr info by filling vdur
1461 vdu_text
= "vdur.{}".format(vdur_index
)
1462 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1463 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1464 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1465 for pdu_interface
in pdu
["interfaces"]:
1466 if pdu_interface
["name"] == vdur_interface
["name"]:
1467 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1468 for k
, v
in pdu_interface
.items():
1472 ): # TODO: switch-xxxxx must be inserted
1473 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1474 vnfr_update_rollback
[
1475 iface_text
+ ".{}".format(k
)
1476 ] = vdur_interface
.get(v
)
1477 if pdu_interface
.get("ip-address"):
1478 if vdur_interface
.get(
1480 ) or vdur_interface
.get("mgmt-vnf"):
1481 vnfr_update_rollback
[
1482 vdu_text
+ ".ip-address"
1483 ] = vdur
.get("ip-address")
1484 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1487 if vdur_interface
.get("mgmt-vnf"):
1488 vnfr_update_rollback
["ip-address"] = vnfr
.get(
1491 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1492 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
[
1495 if pdu_interface
.get("vim-network-name") or pdu_interface
.get(
1498 ifaces_forcing_vim_network
.append(
1500 "name": vdur_interface
.get("vnf-vld-id")
1501 or vdur_interface
.get("ns-vld-id"),
1502 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1503 "ns-vld-id": vdur_interface
.get("ns-vld-id"),
1506 if pdu_interface
.get("vim-network-id"):
1507 ifaces_forcing_vim_network
[-1][
1509 ] = pdu_interface
["vim-network-id"]
1510 if pdu_interface
.get("vim-network-name"):
1511 ifaces_forcing_vim_network
[-1][
1513 ] = pdu_interface
["vim-network-name"]
1516 return ifaces_forcing_vim_network
1518 def _look_for_k8scluster(
1519 self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1522 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1523 Fills vnfr.kdur with the selected k8scluster
1525 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1526 :param rollback: list with the database modifications to rollback if needed
1527 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1528 :param vim_account: vim_account where this vnfr should be deployed
1529 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1530 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1531 of the changed vnfr is needed
1533 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1534 "vim-network-name": used at VIM
1535 "name": interface name
1536 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1537 "ns-vld-id": NSD vld where this interface is connected.
1538 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1541 ifaces_forcing_vim_network
= []
1542 if not vnfr
.get("kdur"):
1543 return ifaces_forcing_vim_network
1545 kdu_filter
= self
._get
_project
_filter
(session
)
1546 kdu_filter
["vim_account"] = vim_account
1547 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1548 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1550 k8s_requirements
= {} # just for logging
1551 for k8scluster
in available_k8sclusters
:
1552 if not vnfr
.get("k8s-cluster"):
1555 if vnfr
["k8s-cluster"].get("cni"):
1556 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1557 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(
1558 k8scluster
.get("cni", ())
1561 # restrict by version
1562 if vnfr
["k8s-cluster"].get("version"):
1563 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1564 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1566 # restrict by number of networks
1567 if vnfr
["k8s-cluster"].get("nets"):
1568 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1569 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(
1570 vnfr
["k8s-cluster"]["nets"]
1575 raise EngineException(
1576 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1577 k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]
1581 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1582 # step 3. Fill vnfr info by filling kdur
1583 kdu_text
= "kdur.{}.".format(kdur_index
)
1584 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1585 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1587 # step 4. Check VIM networks that forces the selected k8s_cluster
1588 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1589 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1590 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1591 # get a network from k8s_cluster nets. If name matches use this, if not use other
1592 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1593 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1594 k8scluster_net_list
.remove(kdur_net
["id"])
1596 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1597 k8scluster_net_list
.pop(0)
1598 vnfr_update_rollback
[
1599 "k8s-cluster.nets.{}.vim_net".format(net_index
)
1601 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1603 kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")
1605 ifaces_forcing_vim_network
.append(
1607 "name": kdur_net
.get("vnf-vld-id")
1608 or kdur_net
.get("ns-vld-id"),
1609 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1610 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1611 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1614 # TODO check that this forcing is not incompatible with other forcing
1615 return ifaces_forcing_vim_network
1617 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1620 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1624 vnfr_update_rollback
= {}
1625 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1626 # update vim-account-id
1628 vim_account
= indata
["vimAccountId"]
1629 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1630 # check instantiate parameters
1631 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1632 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1634 if vnf_inst_params
.get("vimAccountId"):
1635 vim_account
= vnf_inst_params
.get("vimAccountId")
1636 vca_id
= self
._get
_vim
_account
(vim_account
, session
).get("vca")
1638 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1639 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1640 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1641 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1643 for iface_inst_param
in get_iterable(
1644 vdu_inst_param
.get("interface")
1646 iface_index
, _
= next(
1648 for i
in enumerate(vdur
["interfaces"])
1649 if i
[1]["name"] == iface_inst_param
["name"]
1651 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1652 vdur_index
, iface_index
1654 if iface_inst_param
.get("ip-address"):
1656 vnfr_update_text
+ ".ip-address"
1657 ] = increment_ip_mac(
1658 iface_inst_param
.get("ip-address"),
1659 vdur
.get("count-index", 0),
1661 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1662 if iface_inst_param
.get("mac-address"):
1664 vnfr_update_text
+ ".mac-address"
1665 ] = increment_ip_mac(
1666 iface_inst_param
.get("mac-address"),
1667 vdur
.get("count-index", 0),
1669 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1670 if iface_inst_param
.get("floating-ip-required"):
1672 vnfr_update_text
+ ".floating-ip-required"
1674 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1675 # TODO update vld with the ip-profile
1676 for ivld_inst_param
in get_iterable(
1677 vnf_inst_params
.get("internal-vld")
1679 for icp_inst_param
in get_iterable(
1680 ivld_inst_param
.get("internal-connection-point")
1683 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1684 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1686 iface
.get("internal-connection-point-ref")
1687 == icp_inst_param
["id-ref"]
1689 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1690 vdur_index
, iface_index
1692 if icp_inst_param
.get("ip-address"):
1694 vnfr_update_text
+ ".ip-address"
1695 ] = increment_ip_mac(
1696 icp_inst_param
.get("ip-address"),
1697 vdur
.get("count-index", 0),
1700 vnfr_update_text
+ ".fixed-ip"
1702 if icp_inst_param
.get("mac-address"):
1704 vnfr_update_text
+ ".mac-address"
1705 ] = increment_ip_mac(
1706 icp_inst_param
.get("mac-address"),
1707 vdur
.get("count-index", 0),
1710 vnfr_update_text
+ ".fixed-mac"
1713 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1714 for vld_inst_param
in get_iterable(indata
.get("vld")):
1715 for vnfcp_inst_param
in get_iterable(
1716 vld_inst_param
.get("vnfd-connection-point-ref")
1718 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
1721 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1722 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1724 iface
.get("external-connection-point-ref")
1725 == vnfcp_inst_param
["vnfd-connection-point-ref"]
1727 vnfr_update_text
= "vdur.{}.interfaces.{}".format(
1728 vdur_index
, iface_index
1730 if vnfcp_inst_param
.get("ip-address"):
1732 vnfr_update_text
+ ".ip-address"
1733 ] = increment_ip_mac(
1734 vnfcp_inst_param
.get("ip-address"),
1735 vdur
.get("count-index", 0),
1737 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1738 if vnfcp_inst_param
.get("mac-address"):
1740 vnfr_update_text
+ ".mac-address"
1741 ] = increment_ip_mac(
1742 vnfcp_inst_param
.get("mac-address"),
1743 vdur
.get("count-index", 0),
1745 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1748 vnfr_update
["vim-account-id"] = vim_account
1749 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
1752 vnfr_update
["vca-id"] = vca_id
1753 vnfr_update_rollback
["vca-id"] = vnfr
.get("vca-id")
1756 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(
1757 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1761 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(
1762 session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
1764 # update database vnfr
1765 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1771 "content": vnfr_update_rollback
,
1775 # Update indada in case pdu forces to use a concrete vim-network-name
1776 # TODO check if user has already insert a vim-network-name and raises an error
1777 if not ifaces_forcing_vim_network
:
1779 for iface_info
in ifaces_forcing_vim_network
:
1780 if iface_info
.get("ns-vld-id"):
1781 if "vld" not in indata
:
1783 indata
["vld"].append(
1785 key
: iface_info
[key
]
1786 for key
in ("name", "vim-network-name", "vim-network-id")
1787 if iface_info
.get(key
)
1791 elif iface_info
.get("vnf-vld-id"):
1792 if "vnf" not in indata
:
1794 indata
["vnf"].append(
1796 "member-vnf-index": member_vnf_index
,
1799 key
: iface_info
[key
]
1805 if iface_info
.get(key
)
1812 def _create_nslcmop(nsr_id
, operation
, params
):
1814 Creates a ns-lcm-opp content to be stored at database.
1815 :param nsr_id: internal id of the instance
1816 :param operation: instantiate, terminate, scale, action, ...
1817 :param params: user parameters for the operation
1818 :return: dictionary following SOL005 format
1825 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1826 "queuePosition": None,
1828 "errorMessage": None,
1829 "detailedStatus": None,
1830 "statusEnteredTime": now
,
1831 "nsInstanceId": nsr_id
,
1832 "lcmOperationType": operation
,
1834 "isAutomaticInvocation": False,
1835 "operationParams": params
,
1836 "isCancelPending": False,
1838 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1839 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1844 def _get_enabled_vims(self
, session
):
1846 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1847 :param session: current session with user information
1849 db_filter
= self
._get
_project
_filter
(session
)
1850 db_filter
["_admin.operationalState"] = "ENABLED"
1851 vims
= self
.db
.get_list("vim_accounts", db_filter
)
1854 vimAccounts
.append(vim
["_id"])
1867 Performs a new operation over a ns
1868 :param rollback: list to append created items at database in case a rollback must to be done
1869 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1870 :param indata: descriptor with the parameters of the operation. It must contains among others
1871 nsInstanceId: _id of the nsr to perform the operation
1872 operation: it can be: instantiate, terminate, action, TODO: update, heal
1873 :param kwargs: used to override the indata descriptor
1874 :param headers: http request headers
1875 :return: id of the nslcmops
1878 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
1880 db_filter
= self
._get
_project
_filter
(session
)
1881 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1882 nsis
= self
.db
.get_one(
1883 "nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False
1886 raise EngineException(
1887 "The NS instance {} cannot be terminated because is used by the slice {}".format(
1890 http_code
=HTTPStatus
.CONFLICT
,
1894 # Override descriptor with query string kwargs
1895 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
1896 operation
= indata
["lcmOperationType"]
1897 nsInstanceId
= indata
["nsInstanceId"]
1899 validate_input(indata
, self
.operation_schema
[operation
])
1900 # get ns from nsr_id
1901 _filter
= BaseTopic
._get
_project
_filter
(session
)
1902 _filter
["_id"] = nsInstanceId
1903 nsr
= self
.db
.get_one("nsrs", _filter
)
1906 if operation
== "terminate" and slice_object
is False:
1907 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
1909 not nsr
["_admin"].get("nsState")
1910 or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED"
1912 if operation
== "terminate" and indata
.get("autoremove"):
1913 # NSR must be deleted
1917 ) # a none in this case is used to indicate not instantiated. It can be removed
1918 if operation
!= "instantiate":
1919 raise EngineException(
1920 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1921 nsInstanceId
, operation
1923 HTTPStatus
.CONFLICT
,
1926 if operation
== "instantiate" and not session
["force"]:
1927 raise EngineException(
1928 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1929 nsInstanceId
, operation
1931 HTTPStatus
.CONFLICT
,
1933 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
1935 if operation
== "instantiate":
1936 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
1938 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
1939 _id
= nslcmop_desc
["_id"]
1941 nslcmop_desc
, session
["project_id"], make_public
=session
["public"]
1943 if indata
.get("placement-engine"):
1944 # Save valid vim accounts in lcm operation descriptor
1945 nslcmop_desc
["operationParams"][
1947 ] = self
._get
_enabled
_vims
(session
)
1948 self
.db
.create("nslcmops", nslcmop_desc
)
1949 rollback
.append({"topic": "nslcmops", "_id": _id
})
1950 if not slice_object
:
1951 self
.msg
.write("ns", operation
, nslcmop_desc
)
1953 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
1954 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1955 # except DbException as e:
1956 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1958 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1959 raise EngineException(
1960 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1963 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1964 raise EngineException(
1965 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
1969 class NsiTopic(BaseTopic
):
1972 quota_name
= "slice_instances"
1974 def __init__(self
, db
, fs
, msg
, auth
):
1975 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1976 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
1979 def _format_ns_request(ns_request
):
1980 formated_request
= copy(ns_request
)
1981 # TODO: Add request params
1982 return formated_request
1985 def _format_addional_params(slice_request
):
1987 Get and format user additional params for NS or VNF
1988 :param slice_request: User instantiation additional parameters
1989 :return: a formatted copy of additional params or None if not supplied
1991 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
1992 if additional_params
:
1993 for k
, v
in additional_params
.items():
1994 if not isinstance(k
, str):
1995 raise EngineException(
1996 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2000 if "." in k
or "$" in k
:
2001 raise EngineException(
2002 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2006 if isinstance(v
, (dict, tuple, list)):
2007 additional_params
[k
] = "!!yaml " + safe_dump(v
)
2008 return additional_params
2010 def _check_descriptor_dependencies(self
, session
, descriptor
):
2012 Check that the dependent descriptors exist on a new descriptor or edition
2013 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2014 :param descriptor: descriptor to be inserted or edit
2015 :return: None or raises exception
2017 if not descriptor
.get("nst-ref"):
2019 nstd_id
= descriptor
["nst-ref"]
2020 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
2021 raise EngineException(
2022 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2025 http_code
=HTTPStatus
.CONFLICT
,
2028 def check_conflict_on_del(self
, session
, _id
, db_content
):
2030 Check that NSI is not instantiated
2031 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2032 :param _id: nsi internal id
2033 :param db_content: The database content of the _id
2034 :return: None or raises EngineException with the conflict
2036 if session
["force"]:
2039 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
2040 raise EngineException(
2041 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2042 "Launch 'terminate' operation first; or force deletion".format(_id
),
2043 http_code
=HTTPStatus
.CONFLICT
,
2046 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
2048 Deletes associated nsilcmops from database. Deletes associated filesystem.
2049 Set usageState of nst
2050 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2051 :param _id: server internal id
2052 :param db_content: The database content of the descriptor
2053 :param not_send_msg: To not send message (False) or store content (list) instead
2054 :return: None if ok or raises EngineException with the problem
2057 # Deleting the nsrs belonging to nsir
2059 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
2060 nsr_id
= nsrs_detailed_item
["nsrId"]
2061 if nsrs_detailed_item
.get("shared"):
2063 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2064 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
2065 "_id.ne": nsir
["_id"],
2067 nsi
= self
.db
.get_one(
2068 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2070 if nsi
: # last one using nsr
2073 self
.nsrTopic
.delete(
2074 session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
2076 except (DbException
, EngineException
) as e
:
2077 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2082 # delete related nsilcmops database entries
2083 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
2085 # Check and set used NST usage state
2086 nsir_admin
= nsir
.get("_admin")
2087 if nsir_admin
and nsir_admin
.get("nst-id"):
2088 # check if used by another NSI
2089 nsis_list
= self
.db
.get_one(
2091 {"nst-id": nsir_admin
["nst-id"]},
2092 fail_on_empty
=False,
2098 {"_id": nsir_admin
["nst-id"]},
2099 {"_admin.usageState": "NOT_IN_USE"},
2102 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2104 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2105 :param rollback: list to append the created items at database in case a rollback must be done
2106 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2107 :param indata: params to be used for the nsir
2108 :param kwargs: used to override the indata descriptor
2109 :param headers: http request headers
2110 :return: the _id of nsi descriptor created at database
2114 step
= "checking quotas"
2115 self
.check_quota(session
)
2118 slice_request
= self
._remove
_envelop
(indata
)
2119 # Override descriptor with query string kwargs
2120 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
2121 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
2124 step
= "getting nstd id='{}' from database".format(
2125 slice_request
.get("nstId")
2127 _filter
= self
._get
_project
_filter
(session
)
2128 _filter
["_id"] = slice_request
["nstId"]
2129 nstd
= self
.db
.get_one("nsts", _filter
)
2130 # check NST is not disabled
2131 step
= "checking NST operationalState"
2132 if nstd
["_admin"]["operationalState"] == "DISABLED":
2133 raise EngineException(
2134 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2135 "instance".format(slice_request
["nstId"]),
2136 http_code
=HTTPStatus
.CONFLICT
,
2140 # check NSD is not disabled
2141 step
= "checking operationalState"
2142 if nstd
["_admin"]["operationalState"] == "DISABLED":
2143 raise EngineException(
2144 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2145 "a network slice".format(slice_request
["nstId"]),
2146 http_code
=HTTPStatus
.CONFLICT
,
2149 nstd
.pop("_admin", None)
2150 nstd_id
= nstd
.pop("_id", None)
2151 nsi_id
= str(uuid4())
2152 step
= "filling nsi_descriptor with input data"
2157 "name": slice_request
["nsiName"],
2158 "description": slice_request
.get("nsiDescription", ""),
2159 "datacenter": slice_request
["vimAccountId"],
2160 "nst-ref": nstd
["id"],
2161 "instantiation_parameters": slice_request
,
2162 "network-slice-template": nstd
,
2166 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
),
2169 step
= "creating nsi at database"
2171 nsi_descriptor
, session
["project_id"], make_public
=session
["public"]
2173 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2174 nsi_descriptor
["_admin"]["netslice-subnet"] = None
2175 nsi_descriptor
["_admin"]["deployed"] = {}
2176 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
2177 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
2179 # Creating netslice-vld for the RO.
2180 step
= "creating netslice-vld at database"
2182 # Building the vlds list to be deployed
2183 # From netslice descriptors, creating the initial list
2186 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
2187 # Getting template Instantiation parameters from NST
2188 nsi_vld
= deepcopy(netslice_vlds
)
2189 nsi_vld
["shared-nsrs-list"] = []
2190 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
2191 nsi_vlds
.append(nsi_vld
)
2193 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
2194 # Creating netslice-subnet_record.
2198 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2199 for member_ns
in nstd
["netslice-subnet"]:
2200 nsd_id
= member_ns
["nsd-ref"]
2201 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
2202 member_ns
["nsd-ref"], member_ns
["id"]
2204 if nsd_id
not in needed_nsds
:
2206 _filter
["id"] = nsd_id
2207 nsd
= self
.db
.get_one(
2208 "nsds", _filter
, fail_on_empty
=True, fail_on_more
=True
2212 needed_nsds
[nsd_id
] = nsd
2214 nsd
= needed_nsds
[nsd_id
]
2215 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
2216 services
.append(member_ns
)
2218 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2219 member_ns
["nsd-ref"], member_ns
["id"]
2222 # creates Network Services records (NSRs)
2223 step
= "creating nsrs at database using NsrTopic.new()"
2224 ns_params
= slice_request
.get("netslice-subnet")
2226 nsi_netslice_subnet
= []
2227 for service
in services
:
2228 # Check if the netslice-subnet is shared and if it is share if the nss exists
2231 # Is the nss shared and instantiated?
2232 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2233 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
[
2236 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
2237 nsi
= self
.db
.get_one(
2238 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2240 if nsi
and service
.get("is-shared-nss"):
2241 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
2242 for nsrs_detailed_item
in nsrs_detailed_list
:
2243 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
2244 if nsrs_detailed_item
["nss-id"] == service
["id"]:
2245 _id_nsr
= nsrs_detailed_item
["nsrId"]
2247 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
2248 if netslice_subnet
["nss-id"] == service
["id"]:
2249 indata_ns
= netslice_subnet
2253 if service
.get("instantiation-parameters"):
2254 indata_ns
= deepcopy(service
["instantiation-parameters"])
2255 # del service["instantiation-parameters"]
2257 indata_ns
["nsdId"] = service
["_id"]
2258 indata_ns
["nsName"] = (
2259 slice_request
.get("nsiName") + "." + service
["id"]
2261 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
2262 indata_ns
["nsDescription"] = service
["description"]
2263 if slice_request
.get("ssh_keys"):
2264 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
2267 for ns_param
in ns_params
:
2268 if ns_param
.get("id") == service
["id"]:
2269 copy_ns_param
= deepcopy(ns_param
)
2270 del copy_ns_param
["id"]
2271 indata_ns
.update(copy_ns_param
)
2274 # Creates Nsr objects
2275 _id_nsr
, _
= self
.nsrTopic
.new(
2276 rollback
, session
, indata_ns
, kwargs
, headers
2280 "shared": service
.get("is-shared-nss"),
2281 "nsd-id": service
["nsd-ref"],
2282 "nss-id": service
["id"],
2283 "nslcmop_instantiate": None,
2285 indata_ns
["nss-id"] = service
["id"]
2286 nsrs_list
.append(nsrs_item
)
2287 nsi_netslice_subnet
.append(indata_ns
)
2288 nsr_ref
= {"nsr-ref": _id_nsr
}
2289 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
2291 # Adding the nsrs list to the nsi
2292 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
2293 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2295 "nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"}
2298 # Creating the entry in the database
2299 self
.db
.create("nsis", nsi_descriptor
)
2300 rollback
.append({"topic": "nsis", "_id": nsi_id
})
2302 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
2303 self
.logger
.exception(
2304 "Exception {} at NsiTopic.new()".format(e
), exc_info
=True
2306 raise EngineException("Error {}: {}".format(step
, e
))
2307 except ValidationError
as e
:
2308 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2310 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2311 raise EngineException(
2312 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2316 class NsiLcmOpTopic(BaseTopic
):
2319 operation_schema
= { # mapping between operation and jsonschema to validate
2320 "instantiate": nsi_instantiate
,
2324 def __init__(self
, db
, fs
, msg
, auth
):
2325 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
2326 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
2328 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
2330 Check that user has enter right parameters for the operation
2331 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2332 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2333 :param indata: descriptor with the parameters of the operation
2337 nstd
= nsir
["network-slice-template"]
2339 def check_valid_netslice_subnet_id(nstId
):
2340 # TODO change to vnfR (??)
2341 for netslice_subnet
in nstd
["netslice-subnet"]:
2342 if nstId
== netslice_subnet
["id"]:
2343 nsd_id
= netslice_subnet
["nsd-ref"]
2344 if nsd_id
not in nsds
:
2345 _filter
= self
._get
_project
_filter
(session
)
2346 _filter
["id"] = nsd_id
2347 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
2350 raise EngineException(
2351 "Invalid parameter nstId='{}' is not one of the "
2352 "nst:netslice-subnet".format(nstId
)
2355 if operation
== "instantiate":
2356 # check the existance of netslice-subnet items
2357 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
2358 check_valid_netslice_subnet_id(in_nst
["id"])
2360 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
2366 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2367 "statusEnteredTime": now
,
2368 "netsliceInstanceId": netsliceInstanceId
,
2369 "lcmOperationType": operation
,
2371 "isAutomaticInvocation": False,
2372 "operationParams": params
,
2373 "isCancelPending": False,
2375 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
2376 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2377 + netsliceInstanceId
,
2382 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
2383 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
2384 if nst_sb_item
.get("is-shared-nss"):
2385 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
2386 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
2387 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
2388 for admin_vld_nss_cp_ref_item
in admin_vld_item
[
2389 "nss-connection-point-ref"
2392 admin_subnet_item
["nss-id"]
2393 == admin_vld_nss_cp_ref_item
["nss-ref"]
2396 not nsr_item
["nsrId"]
2397 in admin_vld_item
["shared-nsrs-list"]
2399 admin_vld_item
["shared-nsrs-list"].append(
2403 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2406 {"_id": nsir
["_id"]},
2407 {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")},
2410 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
2412 Performs a new operation over a ns
2413 :param rollback: list to append created items at database in case a rollback must to be done
2414 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2415 :param indata: descriptor with the parameters of the operation. It must contains among others
2416 netsliceInstanceId: _id of the nsir to perform the operation
2417 operation: it can be: instantiate, terminate, action, TODO: update, heal
2418 :param kwargs: used to override the indata descriptor
2419 :param headers: http request headers
2420 :return: id of the nslcmops
2423 # Override descriptor with query string kwargs
2424 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
2425 operation
= indata
["lcmOperationType"]
2426 netsliceInstanceId
= indata
["netsliceInstanceId"]
2427 validate_input(indata
, self
.operation_schema
[operation
])
2429 # get nsi from netsliceInstanceId
2430 _filter
= self
._get
_project
_filter
(session
)
2431 _filter
["_id"] = netsliceInstanceId
2432 nsir
= self
.db
.get_one("nsis", _filter
)
2433 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
2438 not nsir
["_admin"].get("nsiState")
2439 or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2441 if operation
== "terminate" and indata
.get("autoremove"):
2442 # NSIR must be deleted
2446 ) # a none in this case is used to indicate not instantiated. It can be removed
2447 if operation
!= "instantiate":
2448 raise EngineException(
2449 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2450 netsliceInstanceId
, operation
2452 HTTPStatus
.CONFLICT
,
2455 if operation
== "instantiate" and not session
["force"]:
2456 raise EngineException(
2457 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2458 netsliceInstanceId
, operation
2460 HTTPStatus
.CONFLICT
,
2463 # Creating all the NS_operation (nslcmop)
2464 # Get service list from db
2465 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
2467 # nslcmops_item = None
2468 for index
, nsr_item
in enumerate(nsrs_list
):
2469 nsr_id
= nsr_item
["nsrId"]
2470 if nsr_item
.get("shared"):
2471 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2472 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2474 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2476 _filter
["_id.ne"] = netsliceInstanceId
2477 nsi
= self
.db
.get_one(
2478 "nsis", _filter
, fail_on_empty
=False, fail_on_more
=False
2480 if operation
== "terminate":
2482 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2486 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2489 ): # other nsi is using this nsr and it needs this nsr instantiated
2490 continue # do not create nsilcmop
2492 # looks the first nsi fulfilling the conditions but not being the current NSIR
2494 nsi_nsr_item
= next(
2496 for n
in nsi
["_admin"]["nsrs-detailed-list"]
2497 if n
["nsrId"] == nsr_id
2499 and n
["nslcmop_instantiate"]
2501 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2502 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
2504 "_admin.nsrs-detailed-list.{}".format(
2508 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2509 # continue to not create nslcmop since nsrs is shared and nsrs was created
2512 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
2517 "lcmOperationType": operation
,
2518 "nsInstanceId": nsr_id
,
2519 # Including netslice_id in the ns instantiate Operation
2520 "netsliceInstanceId": netsliceInstanceId
,
2522 if operation
== "instantiate":
2523 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2524 indata_ns
.update(service
["instantiate_params"])
2526 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2527 # message via kafka bus
2528 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(
2529 rollback
, session
, indata_ns
, None, headers
, slice_object
=True
2531 nslcmops
.append(nslcmop
)
2532 if operation
== "instantiate":
2534 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2538 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
2539 except (DbException
, EngineException
) as e
:
2540 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
2543 + "skipping NS={} because not found".format(nsr_id
)
2550 indata
["nslcmops_ids"] = nslcmops
2551 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
2553 nsilcmop_desc
= self
._create
_nsilcmop
(
2554 session
, netsliceInstanceId
, operation
, indata
2557 nsilcmop_desc
, session
["project_id"], make_public
=session
["public"]
2559 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
2560 rollback
.append({"topic": "nsilcmops", "_id": _id
})
2561 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
2563 except ValidationError
as e
:
2564 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
2566 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
2567 raise EngineException(
2568 "Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
2571 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
2572 raise EngineException(
2573 "Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR