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 validate_input
, ValidationError
, ns_instantiate
, ns_terminate
, ns_action
, ns_scale
,\
23 from osm_nbi
.base_topic
import BaseTopic
, EngineException
, get_iterable
, deep_get
, increment_ip_mac
24 from yaml
import safe_dump
25 from osm_common
.dbbase
import DbException
26 from osm_common
.msgbase
import MsgException
27 from osm_common
.fsbase
import FsException
28 from osm_nbi
import utils
29 from re
import match
# For checking that additional parameter names are valid Jinja2 identifiers
31 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
34 class NsrTopic(BaseTopic
):
37 quota_name
= "ns_instances"
38 schema_new
= ns_instantiate
40 def __init__(self
, db
, fs
, msg
, auth
):
41 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
43 def _check_descriptor_dependencies(self
, session
, descriptor
):
45 Check that the dependent descriptors exist on a new descriptor or edition
46 :param session: client session information
47 :param descriptor: descriptor to be inserted or edit
48 :return: None or raises exception
50 if not descriptor
.get("nsdId"):
52 nsd_id
= descriptor
["nsdId"]
53 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
54 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
55 http_code
=HTTPStatus
.CONFLICT
)
58 def format_on_new(content
, project_id
=None, make_public
=False):
59 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
60 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
63 def check_conflict_on_del(self
, session
, _id
, db_content
):
65 Check that NSR is not instantiated
66 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
67 :param _id: nsr internal id
68 :param db_content: The database content of the nsr
69 :return: None or raises EngineException with the conflict
74 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
75 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
76 "Launch 'terminate' operation first; or force deletion".format(_id
),
77 http_code
=HTTPStatus
.CONFLICT
)
79 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
81 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
82 Set usageState of pdu, vnfd, nsd
83 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
84 :param _id: server internal id
85 :param db_content: The database content of the descriptor
86 :param not_send_msg: To not send message (False) or store content (list) instead
87 :return: None if ok or raises EngineException with the problem
89 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
90 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
91 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
93 # set all used pdus as free
94 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
95 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
99 used_nsd_id
= nsr
.get("nsd-id")
101 # check if used by another NSR
102 nsrs_list
= self
.db
.get_one("nsrs", {"nsd-id": used_nsd_id
},
103 fail_on_empty
=False, fail_on_more
=False)
105 self
.db
.set_one("nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"})
107 # Set VNFD usageState
108 used_vnfd_id_list
= nsr
.get("vnfd-id")
109 if used_vnfd_id_list
:
110 for used_vnfd_id
in used_vnfd_id_list
:
111 # check if used by another NSR
112 nsrs_list
= self
.db
.get_one("nsrs", {"vnfd-id": used_vnfd_id
},
113 fail_on_empty
=False, fail_on_more
=False)
115 self
.db
.set_one("vnfds", {"_id": used_vnfd_id
}, {"_admin.usageState": "NOT_IN_USE"})
117 # delete extra ro_nsrs used for internal RO module
118 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
121 def _format_ns_request(ns_request
):
122 formated_request
= copy(ns_request
)
123 formated_request
.pop("additionalParamsForNs", None)
124 formated_request
.pop("additionalParamsForVnf", None)
125 return formated_request
128 def _format_additional_params(ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None):
130 Get and format user additional params for NS or VNF
131 :param ns_request: User instantiation additional parameters
132 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
133 :param descriptor: If not None it check that needed parameters of descriptor are supplied
134 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
136 additional_params
= None
138 if not member_vnf_index
:
139 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
140 where_
= "additionalParamsForNs"
141 elif ns_request
.get("additionalParamsForVnf"):
142 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index
)
143 item
= next((x
for x
in ns_request
["additionalParamsForVnf"] if x
["member-vnf-index"] == member_vnf_index
),
146 if not vdu_id
and not kdu_name
:
148 additional_params
= copy(item
.get("additionalParams")) or {}
149 if vdu_id
and item
.get("additionalParamsForVdu"):
150 item_vdu
= next((x
for x
in item
["additionalParamsForVdu"] if x
["vdu_id"] == vdu_id
), None)
151 other_params
= item_vdu
152 if item_vdu
and item_vdu
.get("additionalParams"):
153 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
154 additional_params
= item_vdu
["additionalParams"]
156 additional_params
= {}
157 if item
.get("additionalParamsForKdu"):
158 item_kdu
= next((x
for x
in item
["additionalParamsForKdu"] if x
["kdu_name"] == kdu_name
), None)
159 other_params
= item_kdu
160 if item_kdu
and item_kdu
.get("additionalParams"):
161 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(kdu_name
)
162 additional_params
= item_kdu
["additionalParams"]
164 if additional_params
:
165 for k
, v
in additional_params
.items():
166 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
167 if not kdu_name
and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k
):
168 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
169 "and underscores, and cannot start with a digit"
171 # END Check that additional parameter names are valid Jinja2 identifiers
172 if not isinstance(k
, str):
173 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
174 if "." in k
or "$" in k
:
175 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
176 if isinstance(v
, (dict, tuple, list)):
177 additional_params
[k
] = "!!yaml " + safe_dump(v
)
180 # check that enough parameters are supplied for the initial-config-primitive
181 # TODO: check for cloud-init
184 initial_primitives
= None
186 vdud
= next(x
for x
in descriptor
["vdu"] if x
["id"] == vdu_id
)
187 initial_primitives
= deep_get(vdud
, ("vdu-configuration", "initial-config-primitive"))
189 vnf_configurations
= get_iterable(descriptor
.get("vnf-configuration"))
190 initial_primitives
= []
191 for vnfc
in vnf_configurations
:
192 for primitive
in get_iterable(vnfc
.get("initial-config-primitive")):
193 initial_primitives
.append(primitive
)
195 initial_primitives
= deep_get(descriptor
, ("ns-configuration", "initial-config-primitive"))
197 for initial_primitive
in get_iterable(initial_primitives
):
198 for param
in get_iterable(initial_primitive
.get("parameter")):
199 if param
["value"].startswith("<") and param
["value"].endswith(">"):
200 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
202 if not additional_params
or param
["value"][1:-1] not in additional_params
:
203 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
204 "initial-config-primitive[name={}] not supplied".
205 format(param
["value"], descriptor
["id"],
206 initial_primitive
["name"]))
208 return additional_params
or None, other_params
or None
210 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
212 Creates a new nsr into database. It also creates needed vnfrs
213 :param rollback: list to append the created items at database in case a rollback must be done
214 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
215 :param indata: params to be used for the nsr
216 :param kwargs: used to override the indata descriptor
217 :param headers: http request headers
218 :return: the _id of nsr descriptor created at database. Or an exception of type
219 EngineException, ValidationError, DbException, FsException, MsgException.
220 Note: Exceptions are not captured on purpose. They should be captured at called
223 step
= "checking quotas"
224 self
.check_quota(session
)
226 step
= "validating input parameters"
227 ns_request
= self
._remove
_envelop
(indata
)
228 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
229 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
231 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
232 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
233 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
235 step
= "checking nsdOperationalState"
236 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
238 step
= "filling nsr from input data"
239 nsr_id
= str(uuid4())
240 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(nsd
, ns_request
, nsr_id
)
244 # TODO: Change for multiple df support
245 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
246 for vnfp
in vnf_profiles
:
247 vnfd_id
= vnfp
.get("vnfd-id")
248 vnf_index
= vnfp
.get("id")
249 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(vnfd_id
, vnf_index
)
250 if vnfd_id
not in needed_vnfds
:
251 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
252 needed_vnfds
[vnfd_id
] = vnfd
253 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
255 vnfd
= needed_vnfds
[vnfd_id
]
257 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(vnfd_id
, vnf_index
)
258 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(nsd
, vnfd
, vnfd_id
, vnf_index
, nsr_descriptor
,
259 ns_request
, ns_k8s_namespace
)
261 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(vnfd_id
, vnf_index
)
262 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
263 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
265 step
= "creating nsr at database"
266 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
268 step
= "creating nsr temporal folder"
269 self
.fs
.mkdir(nsr_id
)
272 except (ValidationError
, EngineException
, DbException
, MsgException
, FsException
) as e
:
273 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
275 def _get_nsd_from_db(self
, nsd_id
, session
):
276 _filter
= self
._get
_project
_filter
(session
)
277 _filter
["_id"] = nsd_id
278 return self
.db
.get_one("nsds", _filter
)
280 def _get_vnfd_from_db(self
, vnfd_id
, session
):
281 _filter
= self
._get
_project
_filter
(session
)
282 _filter
["id"] = vnfd_id
283 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
287 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
288 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
289 self
.db
.create("nsrs", nsr_descriptor
)
290 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
292 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
293 self
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
294 self
.db
.create("vnfrs", vnfr_descriptor
)
295 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
297 def _check_nsd_operational_state(self
, nsd
, ns_request
):
298 if nsd
["_admin"]["operationalState"] == "DISABLED":
299 raise EngineException("nsd with id '{}' is DISABLED, and thus cannot be used to create "
300 "a network service".format(ns_request
["nsdId"]), http_code
=HTTPStatus
.CONFLICT
)
302 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
303 additional_params
, _
= self
._format
_additional
_params
(ns_request
, descriptor
=nsd
)
304 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
305 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
306 if ns_request
and ns_request
.get("k8s-namespace"):
307 ns_k8s_namespace
= ns_request
["k8s-namespace"]
308 if additional_params
and additional_params
.get("k8s-namespace"):
309 ns_k8s_namespace
= additional_params
["k8s-namespace"]
311 return ns_k8s_namespace
313 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
):
315 additional_params
, _
= self
._format
_additional
_params
(ns_request
, descriptor
=nsd
)
318 "name": ns_request
["nsName"],
319 "name-ref": ns_request
["nsName"],
320 "short-name": ns_request
["nsName"],
321 "admin-status": "ENABLED",
322 "nsState": "NOT_INSTANTIATED",
323 "currentOperation": "IDLE",
324 "currentOperationID": None,
325 "errorDescription": None,
327 "deploymentStatus": None,
328 "configurationStatus": None,
330 "nsd": {k
: v
for k
, v
in nsd
.items()},
331 "datacenter": ns_request
["vimAccountId"],
332 "resource-orchestrator": "osmopenmano",
333 "description": ns_request
.get("nsDescription", ""),
334 "constituent-vnfr-ref": [],
335 "operational-status": "init", # typedef ns-operational-
336 "config-status": "init", # typedef config-states
337 "detailed-status": "scheduled",
338 "orchestration-progress": {},
340 "nsd-name-ref": nsd
["name"],
341 "operational-events": [], # "id", "timestamp", "description", "event",
342 "nsd-ref": nsd
["id"],
343 "nsd-id": nsd
["_id"],
345 "instantiate_params": self
._format
_ns
_request
(ns_request
),
346 "additionalParamsForNs": additional_params
,
347 "ns-instance-config-ref": nsr_id
,
350 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
354 ns_request
["nsr_id"] = nsr_id
355 if ns_request
and ns_request
.get("config-units"):
356 nsr_descriptor
["config-units"] = ns_request
["config-units"]
359 if nsd
.get("virtual-link-desc"):
360 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
361 # Fill each vld with vnfd-connection-point-ref data
362 # TODO: Change for multiple df support
363 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
364 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
365 for vnf_profile
in vnf_profiles
:
366 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
367 for cpd
in vlc
.get("constituent-cpd-id", ()):
368 all_vld_connection_point_data
[vlc
.get("virtual-link-profile-id")].append({
369 "member-vnf-index-ref": cpd
.get("constituent-base-element-id"),
370 "vnfd-connection-point-ref": cpd
.get("constituent-cpd-id"),
371 "vnfd-id-ref": vnf_profile
.get("vnfd-id")
374 vnfd
= self
.db
.get_one("vnfds",
375 {"id": vnf_profile
.get("vnfd-id")},
379 for vdu
in vnfd
.get("vdu", ()):
382 # Find this vdu compute and storage descriptors
383 vdu_virtual_compute
= {}
384 vdu_virtual_storage
= {}
385 for vcd
in vnfd
.get("virtual-compute-desc", ()):
386 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
387 vdu_virtual_compute
= vcd
388 for vsd
in vnfd
.get("virtual-storage-desc", ()):
389 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
390 vdu_virtual_storage
= vsd
391 # Get this vdu vcpus, memory and storage info for flavor_data
392 if vdu_virtual_compute
.get("virtual-cpu", {}).get("num-virtual-cpu"):
393 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"]["num-virtual-cpu"]
394 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
395 flavor_data
["memory-mb"] = float(vdu_virtual_compute
["virtual-memory"]["size"]) * 1024.0
396 if vdu_virtual_storage
.get("size-of-storage"):
397 flavor_data
["storage-gb"] = vdu_virtual_storage
["size-of-storage"]
398 # Get this vdu EPA info for guest_epa
399 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
400 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"]["cpu-quota"]
401 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
402 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
403 if vcpu_pinning
.get("thread-policy"):
404 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
["thread-policy"]
405 if vcpu_pinning
.get("policy"):
406 cpu_policy
= "SHARED" if vcpu_pinning
["policy"] == "dynamic" else "DEDICATED"
407 guest_epa
["cpu-pinning-policy"] = cpu_policy
408 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
409 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"]["mem-quota"]
410 if vdu_virtual_compute
.get("virtual-memory", {}).get("mempage-size"):
411 guest_epa
["mempage-size"] = vdu_virtual_compute
["virtual-memory"]["mempage-size"]
412 if vdu_virtual_compute
.get("virtual-memory", {}).get("numa-node-policy"):
413 guest_epa
["numa-node-policy"] = vdu_virtual_compute
["virtual-memory"]["numa-node-policy"]
414 if vdu_virtual_storage
.get("disk-io-quota"):
415 guest_epa
["disk-io-quota"] = vdu_virtual_storage
["disk-io-quota"]
418 flavor_data
["guest-epa"] = guest_epa
420 flavor_data
["name"] = vdu
["id"][:56] + "-flv"
421 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
422 nsr_descriptor
["flavor"].append(flavor_data
)
424 sw_image_id
= vdu
.get("sw-image-desc")
426 sw_image_desc
= utils
.find_in_list(vnfd
.get("sw-image-desc", ()),
427 lambda sw
: sw
["id"] == sw_image_id
)
429 if sw_image_desc
.get("image"):
430 image_data
["image"] = sw_image_desc
["image"]
431 if sw_image_desc
.get("checksum"):
432 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
433 img
= next((f
for f
in nsr_descriptor
["image"] if
434 all(f
.get(k
) == image_data
[k
] for k
in image_data
)), None)
436 image_data
["id"] = str(len(nsr_descriptor
["image"]))
437 nsr_descriptor
["image"].append(image_data
)
440 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(vld
.get("id"), [])
441 vld
["name"] = vld
["id"]
442 nsr_descriptor
["vld"] = nsr_vld
444 return nsr_descriptor
446 def _create_vnfr_descriptor_from_vnfd(self
, nsd
, vnfd
, vnfd_id
, vnf_index
, nsr_descriptor
,
447 ns_request
, ns_k8s_namespace
):
448 vnfr_id
= str(uuid4())
449 nsr_id
= nsr_descriptor
["id"]
451 additional_params
, vnf_params
= self
._format
_additional
_params
(ns_request
, vnf_index
, descriptor
=vnfd
)
456 "nsr-id-ref": nsr_id
,
457 "member-vnf-index-ref": vnf_index
,
458 "additionalParamsForVnf": additional_params
,
460 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
462 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
463 "vim-account-id": None,
465 "connection-point": [],
466 "ip-address": None, # mgmt-interface filled by LCM
468 vnf_k8s_namespace
= ns_k8s_namespace
470 if vnf_params
.get("k8s-namespace"):
471 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
472 if vnf_params
.get("config-units"):
473 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
476 if vnfd
.get("int-virtual-link-desc"):
477 vnfr_descriptor
["vld"] = []
478 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
479 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
481 for cp
in vnfd
.get("ext-cpd", ()):
483 "name": cp
.get("id"),
484 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
485 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
487 # "ip-address", "mac-address" # filled by LCM
488 # vim-id # TODO it would be nice having a vim port id
490 vnfr_descriptor
["connection-point"].append(vnf_cp
)
492 # Create k8s-cluster information
493 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
494 if vnfd
.get("k8s-cluster"):
495 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
496 all_k8s_cluster_nets_cpds
= {}
497 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
498 if cpd
.get("k8s-cluster-net"):
499 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get("id")
500 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
501 if net
.get("id") in all_k8s_cluster_nets_cpds
:
502 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[net
.get("id")]
505 for kdu
in get_iterable(vnfd
.get("kdu")):
506 additional_params
, kdu_params
= self
._format
_additional
_params
(ns_request
,
508 kdu_name
=kdu
["name"],
510 kdu_k8s_namespace
= vnf_k8s_namespace
511 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
512 if kdu_params
and kdu_params
.get("k8s-namespace"):
513 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
516 "additionalParams": additional_params
,
517 "k8s-namespace": kdu_k8s_namespace
,
518 "kdu-name": kdu
["name"],
519 # TODO "name": "" Name of the VDU in the VIM
520 "ip-address": None, # mgmt-interface filled by LCM
523 if kdu_params
and kdu_params
.get("config-units"):
524 kdur
["config-units"] = kdu_params
["config-units"]
525 if kdu
.get("helm-version"):
526 kdur
["helm-version"] = kdu
["helm-version"]
527 for k8s_type
in ("helm-chart", "juju-bundle"):
528 if kdu
.get(k8s_type
):
529 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
530 if not vnfr_descriptor
.get("kdur"):
531 vnfr_descriptor
["kdur"] = []
532 vnfr_descriptor
["kdur"].append(kdur
)
534 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
535 for vdu
in vnfd
.get("vdu", ()):
536 additional_params
, vdu_params
= self
._format
_additional
_params
(
537 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
)
539 "vdu-id-ref": vdu
["id"],
540 # TODO "name": "" Name of the VDU in the VIM
541 "ip-address": None, # mgmt-interface filled by LCM
542 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
543 "internal-connection-point": [],
545 "additionalParams": additional_params
,
546 "vdu-name": vdu
["name"]
548 if vdu_params
and vdu_params
.get("config-units"):
549 vdur
["config-units"] = vdu_params
["config-units"]
550 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
551 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"]["boot-data-drive"]
552 if vdu
.get("pdu-type"):
553 vdur
["pdu-type"] = vdu
["pdu-type"]
554 vdur
["name"] = vdu
["pdu-type"]
555 # TODO volumes: name, volume-id
556 for icp
in vdu
.get("int-cpd", ()):
559 "connection-point-id": icp
["id"],
560 "name": icp
.get("id"),
563 if "port-security-enabled" in icp
:
564 vdu_icp
["port-security-enabled"] = icp
["port-security-enabled"]
566 if "port-security-disable-strategy" in icp
:
567 vdu_icp
["port-security-disable-strategy"] = icp
["port-security-disable-strategy"]
569 vdur
["internal-connection-point"].append(vdu_icp
)
571 for iface
in icp
.get("virtual-network-interface-requirement", ()):
572 iface_fields
= ("name", "mac-address")
573 vdu_iface
= {x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None}
575 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
576 for ext_cp
in vnfd
.get("ext-cpd", ()):
577 if not ext_cp
.get("int-cpd"):
579 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
581 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
582 vdu_iface
["external-connection-point-ref"] = ext_cp
.get("id")
585 if vnfd_mgmt_cp
and vdu_iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
586 vdu_iface
["mgmt-vnf"] = True
587 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
589 if iface
.get("virtual-interface"):
590 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
592 # look for network where this interface is connected
593 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
595 # TODO: Change for multiple df support
596 for df
in get_iterable(nsd
.get("df")):
597 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
598 for vlc
in get_iterable(vnf_profile
.get("virtual-link-connectivity")):
599 for cpd
in get_iterable(vlc
.get("constituent-cpd-id")):
600 if cpd
.get("constituent-cpd-id") == iface_ext_cp
:
601 vdu_iface
["ns-vld-id"] = vlc
.get("virtual-link-profile-id")
603 elif vdu_iface
.get("internal-connection-point-ref"):
604 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
606 vdur
["interfaces"].append(vdu_iface
)
608 if vdu
.get("sw-image-desc"):
609 sw_image
= utils
.find_in_list(
610 vnfd
.get("sw-image-desc", ()),
611 lambda image
: image
["id"] == vdu
.get("sw-image-desc"))
612 nsr_sw_image_data
= utils
.find_in_list(
613 nsr_descriptor
["image"],
614 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image"))
616 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
618 flavor_data_name
= vdu
["id"][:56] + "-flv"
619 nsr_flavor_desc
= utils
.find_in_list(
620 nsr_descriptor
["flavor"],
621 lambda flavor
: flavor
["name"] == flavor_data_name
)
624 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
626 count
= int(vdu
.get("count", 1))
627 for index
in range(0, count
):
628 vdur
= deepcopy(vdur
)
629 for iface
in vdur
["interfaces"]:
630 if iface
.get("ip-address"):
631 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
632 if iface
.get("mac-address"):
633 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
635 vdur
["_id"] = str(uuid4())
636 vdur
["id"] = vdur
["_id"]
637 vdur
["count-index"] = index
638 vnfr_descriptor
["vdur"].append(vdur
)
640 return vnfr_descriptor
642 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
643 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
646 class VnfrTopic(BaseTopic
):
650 def __init__(self
, db
, fs
, msg
, auth
):
651 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
653 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
654 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
656 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
657 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
659 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
660 # Not used because vnfrs are created and deleted by NsrTopic class directly
661 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
664 class NsLcmOpTopic(BaseTopic
):
667 operation_schema
= { # mapping between operation and jsonschema to validate
668 "instantiate": ns_instantiate
,
671 "terminate": ns_terminate
,
674 def __init__(self
, db
, fs
, msg
, auth
):
675 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
677 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
679 Check that user has enter right parameters for the operation
680 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
681 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
682 :param indata: descriptor with the parameters of the operation
685 if operation
== "action":
686 self
._check
_action
_ns
_operation
(indata
, nsr
)
687 elif operation
== "scale":
688 self
._check
_scale
_ns
_operation
(indata
, nsr
)
689 elif operation
== "instantiate":
690 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
692 def _check_action_ns_operation(self
, indata
, nsr
):
694 # check vnf_member_index
695 if indata
.get("vnf_member_index"):
696 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
697 if indata
.get("member_vnf_index"):
698 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(indata
["member_vnf_index"], nsr
["_id"])
699 if indata
.get("vdu_id"):
700 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
701 # TODO: Change the [0] as vdu-configuration is now a list
702 descriptor_configuration
= vnfd
.get("vdu-configuration", [{}])[0].get("config-primitive")
703 elif indata
.get("kdu_name"):
704 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
705 # TODO: Change the [0] as kdu-configuration is now a list
706 kdud
= next((k
for k
in vnfd
["kdu"] if k
["name"] == indata
["kdu_name"]), None)
707 descriptor_configuration
= deep_get(kdud
, ("kdu-configuration", "config-primitive"))
709 # TODO: Change the [0] as vnf-configuration is now a list
710 descriptor_configuration
= vnfd
.get("vnf-configuration", [{}])[0].get("config-primitive")
712 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
714 # For k8s allows default primitives without validating the parameters
715 if indata
.get("kdu_name") and indata
["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
716 # TODO should be checked that rollback only can contains revsision_numbe????
717 if not indata
.get("member_vnf_index"):
718 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
719 .format(indata
["primitive"]))
721 # if not, check primitive
722 for config_primitive
in get_iterable(descriptor_configuration
):
723 if indata
["primitive"] == config_primitive
["name"]:
724 # check needed primitive_params are provided
725 if indata
.get("primitive_params"):
726 in_primitive_params_copy
= copy(indata
["primitive_params"])
728 in_primitive_params_copy
= {}
729 for paramd
in get_iterable(config_primitive
.get("parameter")):
730 if paramd
["name"] in in_primitive_params_copy
:
731 del in_primitive_params_copy
[paramd
["name"]]
732 elif not paramd
.get("default-value"):
733 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
734 paramd
["name"], indata
["primitive"]))
735 # check no extra primitive params are provided
736 if in_primitive_params_copy
:
737 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
738 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
741 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
743 def _check_scale_ns_operation(self
, indata
, nsr
):
744 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"],
746 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
747 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_aspect
["id"]:
750 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
751 "present at vnfd:scaling-aspect"
752 .format(indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
754 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
755 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
759 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
760 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
761 for in_vnf
in get_iterable(indata
.get("vnf")):
762 member_vnf_index
= in_vnf
["member-vnf-index"]
763 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
764 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
766 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(member_vnf_index
, nsr
["_id"])
767 vnf_member_index_to_vnfd
[member_vnf_index
] = vnfd
# add to cache, avoiding a later look for
768 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
769 if in_vnf
.get("vimAccountId"):
770 self
._check
_valid
_vim
_account
(in_vnf
["vimAccountId"], vim_accounts
, session
)
772 for in_vld
in get_iterable(indata
.get("vld")):
773 self
._check
_valid
_wim
_account
(in_vld
.get("wimAccountId"), wim_accounts
, session
)
774 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
775 if in_vld
["name"] == vldd
["id"]:
778 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
781 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
782 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
783 vnfr
= self
.db
.get_one("vnfrs",
784 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
787 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
788 "nsd:constituent-vnfd".format(member_vnf_index
))
789 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
791 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
792 format(vnfr
["vnfd-id"]))
795 def _check_valid_vdu(self
, vnfd
, vdu_id
):
796 for vdud
in get_iterable(vnfd
.get("vdu")):
797 if vdud
["id"] == vdu_id
:
800 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id
))
802 def _check_valid_kdu(self
, vnfd
, kdu_name
):
803 for kdud
in get_iterable(vnfd
.get("kdu")):
804 if kdud
["name"] == kdu_name
:
807 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name
))
809 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
810 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
811 for vdu
in get_iterable(vnfd
.get("vdu")):
812 if in_vdu
["id"] == vdu
["id"]:
813 for volume
in get_iterable(in_vdu
.get("volume")):
814 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
815 if volumed
["id"] == volume
["name"]:
818 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
819 "volume:name='{}' is not present at "
820 "vnfd:vdu:virtual-storage-desc list".
821 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
825 for cpd
in get_iterable(vdu
.get("int-cpd")):
826 for iface
in get_iterable(cpd
.get("virtual-network-interface-requirement")):
827 vdu_if_names
.add(iface
.get("name"))
829 for in_iface
in get_iterable(in_vdu
["interface"]):
830 if in_iface
["name"] in vdu_if_names
:
833 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
834 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd"
835 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
840 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
841 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
843 vnfd_ivlds_cpds
= {ivld
.get("id"): set() for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))}
844 for vdu
in get_iterable(vnfd
.get("vdu")):
845 for cpd
in get_iterable(vnfd
.get("int-cpd")):
846 if cpd
.get("int-virtual-link-desc"):
847 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
849 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
850 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
851 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
852 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
855 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
856 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
857 "vnfd:internal-vld:name/id:internal-connection-point"
858 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
861 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
862 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
863 in_ivld
["name"], vnfd
["id"]))
865 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
866 if vim_account
in vim_accounts
:
869 db_filter
= self
._get
_project
_filter
(session
)
870 db_filter
["_id"] = vim_account
871 self
.db
.get_one("vim_accounts", db_filter
)
873 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
874 vim_accounts
.append(vim_account
)
876 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
877 if not isinstance(wim_account
, str):
879 if wim_account
in wim_accounts
:
882 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
883 db_filter
["_id"] = wim_account
884 self
.db
.get_one("wim_accounts", db_filter
)
886 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
887 wim_accounts
.append(wim_account
)
889 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
891 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
892 (ip_address, ...) information.
893 Modifies PDU _admin.usageState to 'IN_USE'
894 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
895 :param rollback: list with the database modifications to rollback if needed
896 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
897 :param vim_account: vim_account where this vnfr should be deployed
898 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
899 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
900 of the changed vnfr is needed
902 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
903 "vim-network-name": used at VIM
904 "name": interface name
905 "vnf-vld-id": internal VNFD vld where this interface is connected, or
906 "ns-vld-id": NSD vld where this interface is connected.
907 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
910 ifaces_forcing_vim_network
= []
911 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
912 if not vdur
.get("pdu-type"):
914 pdu_type
= vdur
.get("pdu-type")
915 pdu_filter
= self
._get
_project
_filter
(session
)
916 pdu_filter
["vim_accounts"] = vim_account
917 pdu_filter
["type"] = pdu_type
918 pdu_filter
["_admin.operationalState"] = "ENABLED"
919 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
920 # TODO feature 1417: "shared": True,
922 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
923 for pdu
in available_pdus
:
924 # step 1 check if this pdu contains needed interfaces:
925 match_interfaces
= True
926 for vdur_interface
in vdur
["interfaces"]:
927 for pdu_interface
in pdu
["interfaces"]:
928 if pdu_interface
["name"] == vdur_interface
["name"]:
929 # TODO feature 1417: match per mgmt type
931 else: # no interface found for name
932 match_interfaces
= False
937 raise EngineException(
938 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
939 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
943 "_admin.usageState": pdu
["_admin"]["usageState"],
944 "_admin.usage.vnfr_id": None,
945 "_admin.usage.nsr_id": None,
946 "_admin.usage.vdur": None,
948 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
949 {"_admin.usageState": "IN_USE",
950 "_admin.usage": {"vnfr_id": vnfr
["_id"],
951 "nsr_id": vnfr
["nsr-id-ref"],
952 "vdur": vdur
["vdu-id-ref"]}
954 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
956 # step 3. Fill vnfr info by filling vdur
957 vdu_text
= "vdur.{}".format(vdur_index
)
958 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
959 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
960 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
961 for pdu_interface
in pdu
["interfaces"]:
962 if pdu_interface
["name"] == vdur_interface
["name"]:
963 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
964 for k
, v
in pdu_interface
.items():
965 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
966 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
967 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
968 if pdu_interface
.get("ip-address"):
969 if vdur_interface
.get("mgmt-interface") or vdur_interface
.get("mgmt-vnf"):
970 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
971 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
972 if vdur_interface
.get("mgmt-vnf"):
973 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
974 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
975 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
976 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
977 ifaces_forcing_vim_network
.append({
978 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
979 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
980 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
981 if pdu_interface
.get("vim-network-id"):
982 ifaces_forcing_vim_network
[-1]["vim-network-id"] = pdu_interface
["vim-network-id"]
983 if pdu_interface
.get("vim-network-name"):
984 ifaces_forcing_vim_network
[-1]["vim-network-name"] = pdu_interface
["vim-network-name"]
987 return ifaces_forcing_vim_network
989 def _look_for_k8scluster(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
991 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
992 Fills vnfr.kdur with the selected k8scluster
994 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
995 :param rollback: list with the database modifications to rollback if needed
996 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
997 :param vim_account: vim_account where this vnfr should be deployed
998 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
999 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1000 of the changed vnfr is needed
1002 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1003 "vim-network-name": used at VIM
1004 "name": interface name
1005 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1006 "ns-vld-id": NSD vld where this interface is connected.
1007 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1010 ifaces_forcing_vim_network
= []
1011 if not vnfr
.get("kdur"):
1012 return ifaces_forcing_vim_network
1014 kdu_filter
= self
._get
_project
_filter
(session
)
1015 kdu_filter
["vim_account"] = vim_account
1016 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1017 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1019 k8s_requirements
= {} # just for logging
1020 for k8scluster
in available_k8sclusters
:
1021 if not vnfr
.get("k8s-cluster"):
1024 if vnfr
["k8s-cluster"].get("cni"):
1025 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1026 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(k8scluster
.get("cni", ())):
1028 # restrict by version
1029 if vnfr
["k8s-cluster"].get("version"):
1030 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1031 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1033 # restrict by number of networks
1034 if vnfr
["k8s-cluster"].get("nets"):
1035 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1036 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(vnfr
["k8s-cluster"]["nets"]):
1040 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
1041 .format(k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]))
1043 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1044 # step 3. Fill vnfr info by filling kdur
1045 kdu_text
= "kdur.{}.".format(kdur_index
)
1046 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1047 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1049 # step 4. Check VIM networks that forces the selected k8s_cluster
1050 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1051 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1052 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1053 # get a network from k8s_cluster nets. If name matches use this, if not use other
1054 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1055 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1056 k8scluster_net_list
.remove(kdur_net
["id"])
1058 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1059 k8scluster_net_list
.pop(0)
1060 vnfr_update_rollback
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = None
1061 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1062 if vim_net
and (kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")):
1063 ifaces_forcing_vim_network
.append({
1064 "name": kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id"),
1065 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1066 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1067 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1069 # TODO check that this forcing is not incompatible with other forcing
1070 return ifaces_forcing_vim_network
1072 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1075 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1079 vnfr_update_rollback
= {}
1080 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1081 # update vim-account-id
1083 vim_account
= indata
["vimAccountId"]
1084 # check instantiate parameters
1085 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1086 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1088 if vnf_inst_params
.get("vimAccountId"):
1089 vim_account
= vnf_inst_params
.get("vimAccountId")
1091 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1092 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1093 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1094 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1096 for iface_inst_param
in get_iterable(vdu_inst_param
.get("interface")):
1097 iface_index
, _
= next(i
for i
in enumerate(vdur
["interfaces"])
1098 if i
[1]["name"] == iface_inst_param
["name"])
1099 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
1100 if iface_inst_param
.get("ip-address"):
1101 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1102 iface_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1103 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1104 if iface_inst_param
.get("mac-address"):
1105 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1106 iface_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1107 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1108 if iface_inst_param
.get("floating-ip-required"):
1109 vnfr_update
[vnfr_update_text
+ ".floating-ip-required"] = True
1110 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1111 # TODO update vld with the ip-profile
1112 for ivld_inst_param
in get_iterable(vnf_inst_params
.get("internal-vld")):
1113 for icp_inst_param
in get_iterable(ivld_inst_param
.get("internal-connection-point")):
1115 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1116 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1117 if iface
.get("internal-connection-point-ref") == icp_inst_param
["id-ref"]:
1118 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
1119 if icp_inst_param
.get("ip-address"):
1120 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1121 icp_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1122 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1123 if icp_inst_param
.get("mac-address"):
1124 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1125 icp_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1126 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1128 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1129 for vld_inst_param
in get_iterable(indata
.get("vld")):
1130 for vnfcp_inst_param
in get_iterable(vld_inst_param
.get("vnfd-connection-point-ref")):
1131 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
1134 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1135 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1136 if iface
.get("external-connection-point-ref") == \
1137 vnfcp_inst_param
["vnfd-connection-point-ref"]:
1138 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
1139 if vnfcp_inst_param
.get("ip-address"):
1140 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1141 vnfcp_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1142 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1143 if vnfcp_inst_param
.get("mac-address"):
1144 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1145 vnfcp_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1146 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1149 vnfr_update
["vim-account-id"] = vim_account
1150 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
1153 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
1154 vnfr_update_rollback
)
1157 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
1158 vnfr_update_rollback
)
1159 # update database vnfr
1160 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1161 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
1163 # Update indada in case pdu forces to use a concrete vim-network-name
1164 # TODO check if user has already insert a vim-network-name and raises an error
1165 if not ifaces_forcing_vim_network
:
1167 for iface_info
in ifaces_forcing_vim_network
:
1168 if iface_info
.get("ns-vld-id"):
1169 if "vld" not in indata
:
1171 indata
["vld"].append({key
: iface_info
[key
] for key
in
1172 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
1174 elif iface_info
.get("vnf-vld-id"):
1175 if "vnf" not in indata
:
1177 indata
["vnf"].append({
1178 "member-vnf-index": member_vnf_index
,
1179 "internal-vld": [{key
: iface_info
[key
] for key
in
1180 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
1184 def _create_nslcmop(nsr_id
, operation
, params
):
1186 Creates a ns-lcm-opp content to be stored at database.
1187 :param nsr_id: internal id of the instance
1188 :param operation: instantiate, terminate, scale, action, ...
1189 :param params: user parameters for the operation
1190 :return: dictionary following SOL005 format
1197 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1198 "queuePosition": None,
1200 "errorMessage": None,
1201 "detailedStatus": None,
1202 "statusEnteredTime": now
,
1203 "nsInstanceId": nsr_id
,
1204 "lcmOperationType": operation
,
1206 "isAutomaticInvocation": False,
1207 "operationParams": params
,
1208 "isCancelPending": False,
1210 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1211 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1216 def _get_enabled_vims(self
, session
):
1218 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1219 :param session: current session with user information
1221 db_filter
= self
._get
_project
_filter
(session
)
1222 db_filter
["_admin.operationalState"] = "ENABLED"
1223 vims
= self
.db
.get_list("vim_accounts", db_filter
)
1226 vimAccounts
.append(vim
['_id'])
1229 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
1231 Performs a new operation over a ns
1232 :param rollback: list to append created items at database in case a rollback must to be done
1233 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1234 :param indata: descriptor with the parameters of the operation. It must contains among others
1235 nsInstanceId: _id of the nsr to perform the operation
1236 operation: it can be: instantiate, terminate, action, TODO: update, heal
1237 :param kwargs: used to override the indata descriptor
1238 :param headers: http request headers
1239 :return: id of the nslcmops
1241 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
1243 db_filter
= self
._get
_project
_filter
(session
)
1244 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1245 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
1247 raise EngineException("The NS instance {} cannot be terminated because is used by the slice {}".format(
1248 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
1251 # Override descriptor with query string kwargs
1252 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
1253 operation
= indata
["lcmOperationType"]
1254 nsInstanceId
= indata
["nsInstanceId"]
1256 validate_input(indata
, self
.operation_schema
[operation
])
1257 # get ns from nsr_id
1258 _filter
= BaseTopic
._get
_project
_filter
(session
)
1259 _filter
["_id"] = nsInstanceId
1260 nsr
= self
.db
.get_one("nsrs", _filter
)
1263 if operation
== "terminate" and slice_object
is False:
1264 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
1265 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1266 if operation
== "terminate" and indata
.get("autoremove"):
1267 # NSR must be deleted
1268 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1269 if operation
!= "instantiate":
1270 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1271 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1273 if operation
== "instantiate" and not session
["force"]:
1274 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1275 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1276 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
1278 if operation
== "instantiate":
1279 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
1281 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
1282 _id
= nslcmop_desc
["_id"]
1283 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1284 if indata
.get("placement-engine"):
1285 # Save valid vim accounts in lcm operation descriptor
1286 nslcmop_desc
['operationParams']['validVimAccounts'] = self
._get
_enabled
_vims
(session
)
1287 self
.db
.create("nslcmops", nslcmop_desc
)
1288 rollback
.append({"topic": "nslcmops", "_id": _id
})
1289 if not slice_object
:
1290 self
.msg
.write("ns", operation
, nslcmop_desc
)
1292 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
1293 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1294 # except DbException as e:
1295 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1297 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1298 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1300 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1301 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1304 class NsiTopic(BaseTopic
):
1307 quota_name
= "slice_instances"
1309 def __init__(self
, db
, fs
, msg
, auth
):
1310 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1311 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
1314 def _format_ns_request(ns_request
):
1315 formated_request
= copy(ns_request
)
1316 # TODO: Add request params
1317 return formated_request
1320 def _format_addional_params(slice_request
):
1322 Get and format user additional params for NS or VNF
1323 :param slice_request: User instantiation additional parameters
1324 :return: a formatted copy of additional params or None if not supplied
1326 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
1327 if additional_params
:
1328 for k
, v
in additional_params
.items():
1329 if not isinstance(k
, str):
1330 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1332 if "." in k
or "$" in k
:
1333 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1335 if isinstance(v
, (dict, tuple, list)):
1336 additional_params
[k
] = "!!yaml " + safe_dump(v
)
1337 return additional_params
1339 def _check_descriptor_dependencies(self
, session
, descriptor
):
1341 Check that the dependent descriptors exist on a new descriptor or edition
1342 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1343 :param descriptor: descriptor to be inserted or edit
1344 :return: None or raises exception
1346 if not descriptor
.get("nst-ref"):
1348 nstd_id
= descriptor
["nst-ref"]
1349 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
1350 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
1351 http_code
=HTTPStatus
.CONFLICT
)
1353 def check_conflict_on_del(self
, session
, _id
, db_content
):
1355 Check that NSI is not instantiated
1356 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1357 :param _id: nsi internal id
1358 :param db_content: The database content of the _id
1359 :return: None or raises EngineException with the conflict
1361 if session
["force"]:
1364 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
1365 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1366 "Launch 'terminate' operation first; or force deletion".format(_id
),
1367 http_code
=HTTPStatus
.CONFLICT
)
1369 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
1371 Deletes associated nsilcmops from database. Deletes associated filesystem.
1372 Set usageState of nst
1373 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1374 :param _id: server internal id
1375 :param db_content: The database content of the descriptor
1376 :param not_send_msg: To not send message (False) or store content (list) instead
1377 :return: None if ok or raises EngineException with the problem
1380 # Deleting the nsrs belonging to nsir
1382 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
1383 nsr_id
= nsrs_detailed_item
["nsrId"]
1384 if nsrs_detailed_item
.get("shared"):
1385 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1386 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
1387 "_id.ne": nsir
["_id"]}
1388 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1389 if nsi
: # last one using nsr
1392 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
)
1393 except (DbException
, EngineException
) as e
:
1394 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1399 # delete related nsilcmops database entries
1400 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
1402 # Check and set used NST usage state
1403 nsir_admin
= nsir
.get("_admin")
1404 if nsir_admin
and nsir_admin
.get("nst-id"):
1405 # check if used by another NSI
1406 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
1407 fail_on_empty
=False, fail_on_more
=False)
1409 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1411 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1413 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1414 :param rollback: list to append the created items at database in case a rollback must be done
1415 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1416 :param indata: params to be used for the nsir
1417 :param kwargs: used to override the indata descriptor
1418 :param headers: http request headers
1419 :return: the _id of nsi descriptor created at database
1423 step
= "checking quotas"
1424 self
.check_quota(session
)
1427 slice_request
= self
._remove
_envelop
(indata
)
1428 # Override descriptor with query string kwargs
1429 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
1430 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
1433 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1434 _filter
= self
._get
_project
_filter
(session
)
1435 _filter
["_id"] = slice_request
["nstId"]
1436 nstd
= self
.db
.get_one("nsts", _filter
)
1437 # check NST is not disabled
1438 step
= "checking NST operationalState"
1439 if nstd
["_admin"]["operationalState"] == "DISABLED":
1440 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
1441 "instance".format(slice_request
["nstId"]), http_code
=HTTPStatus
.CONFLICT
)
1444 # check NSD is not disabled
1445 step
= "checking operationalState"
1446 if nstd
["_admin"]["operationalState"] == "DISABLED":
1447 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create "
1448 "a network slice".format(slice_request
["nstId"]), http_code
=HTTPStatus
.CONFLICT
)
1450 nstd
.pop("_admin", None)
1451 nstd_id
= nstd
.pop("_id", None)
1452 nsi_id
= str(uuid4())
1453 step
= "filling nsi_descriptor with input data"
1458 "name": slice_request
["nsiName"],
1459 "description": slice_request
.get("nsiDescription", ""),
1460 "datacenter": slice_request
["vimAccountId"],
1461 "nst-ref": nstd
["id"],
1462 "instantiation_parameters": slice_request
,
1463 "network-slice-template": nstd
,
1467 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1470 step
= "creating nsi at database"
1471 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1472 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1473 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1474 nsi_descriptor
["_admin"]["deployed"] = {}
1475 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1476 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1478 # Creating netslice-vld for the RO.
1479 step
= "creating netslice-vld at database"
1481 # Building the vlds list to be deployed
1482 # From netslice descriptors, creating the initial list
1485 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1486 # Getting template Instantiation parameters from NST
1487 nsi_vld
= deepcopy(netslice_vlds
)
1488 nsi_vld
["shared-nsrs-list"] = []
1489 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1490 nsi_vlds
.append(nsi_vld
)
1492 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1493 # Creating netslice-subnet_record.
1497 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1498 for member_ns
in nstd
["netslice-subnet"]:
1499 nsd_id
= member_ns
["nsd-ref"]
1500 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1501 member_ns
["nsd-ref"], member_ns
["id"])
1502 if nsd_id
not in needed_nsds
:
1504 _filter
["id"] = nsd_id
1505 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1508 needed_nsds
[nsd_id
] = nsd
1510 nsd
= needed_nsds
[nsd_id
]
1511 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1512 services
.append(member_ns
)
1514 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1515 member_ns
["nsd-ref"], member_ns
["id"])
1517 # creates Network Services records (NSRs)
1518 step
= "creating nsrs at database using NsrTopic.new()"
1519 ns_params
= slice_request
.get("netslice-subnet")
1521 nsi_netslice_subnet
= []
1522 for service
in services
:
1523 # Check if the netslice-subnet is shared and if it is share if the nss exists
1526 # Is the nss shared and instantiated?
1527 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1528 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1529 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1530 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1531 if nsi
and service
.get("is-shared-nss"):
1532 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1533 for nsrs_detailed_item
in nsrs_detailed_list
:
1534 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1535 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1536 _id_nsr
= nsrs_detailed_item
["nsrId"]
1538 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1539 if netslice_subnet
["nss-id"] == service
["id"]:
1540 indata_ns
= netslice_subnet
1544 if service
.get("instantiation-parameters"):
1545 indata_ns
= deepcopy(service
["instantiation-parameters"])
1546 # del service["instantiation-parameters"]
1548 indata_ns
["nsdId"] = service
["_id"]
1549 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1550 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1551 indata_ns
["nsDescription"] = service
["description"]
1552 if slice_request
.get("ssh_keys"):
1553 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1556 for ns_param
in ns_params
:
1557 if ns_param
.get("id") == service
["id"]:
1558 copy_ns_param
= deepcopy(ns_param
)
1559 del copy_ns_param
["id"]
1560 indata_ns
.update(copy_ns_param
)
1563 # Creates Nsr objects
1564 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1565 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1566 "nss-id": service
["id"], "nslcmop_instantiate": None}
1567 indata_ns
["nss-id"] = service
["id"]
1568 nsrs_list
.append(nsrs_item
)
1569 nsi_netslice_subnet
.append(indata_ns
)
1570 nsr_ref
= {"nsr-ref": _id_nsr
}
1571 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1573 # Adding the nsrs list to the nsi
1574 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1575 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1576 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1578 # Creating the entry in the database
1579 self
.db
.create("nsis", nsi_descriptor
)
1580 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1582 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1583 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1584 raise EngineException("Error {}: {}".format(step
, e
))
1585 except ValidationError
as e
:
1586 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1588 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1589 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1592 class NsiLcmOpTopic(BaseTopic
):
1595 operation_schema
= { # mapping between operation and jsonschema to validate
1596 "instantiate": nsi_instantiate
,
1600 def __init__(self
, db
, fs
, msg
, auth
):
1601 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1602 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
1604 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1606 Check that user has enter right parameters for the operation
1607 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1608 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1609 :param indata: descriptor with the parameters of the operation
1613 nstd
= nsir
["network-slice-template"]
1615 def check_valid_netslice_subnet_id(nstId
):
1616 # TODO change to vnfR (??)
1617 for netslice_subnet
in nstd
["netslice-subnet"]:
1618 if nstId
== netslice_subnet
["id"]:
1619 nsd_id
= netslice_subnet
["nsd-ref"]
1620 if nsd_id
not in nsds
:
1621 _filter
= self
._get
_project
_filter
(session
)
1622 _filter
["id"] = nsd_id
1623 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
1626 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1627 "nst:netslice-subnet".format(nstId
))
1628 if operation
== "instantiate":
1629 # check the existance of netslice-subnet items
1630 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1631 check_valid_netslice_subnet_id(in_nst
["id"])
1633 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1639 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1640 "statusEnteredTime": now
,
1641 "netsliceInstanceId": netsliceInstanceId
,
1642 "lcmOperationType": operation
,
1644 "isAutomaticInvocation": False,
1645 "operationParams": params
,
1646 "isCancelPending": False,
1648 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1649 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1654 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1655 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1656 if nst_sb_item
.get("is-shared-nss"):
1657 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1658 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1659 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1660 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1661 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1662 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1663 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1665 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1666 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1668 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1670 Performs a new operation over a ns
1671 :param rollback: list to append created items at database in case a rollback must to be done
1672 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1673 :param indata: descriptor with the parameters of the operation. It must contains among others
1674 netsliceInstanceId: _id of the nsir to perform the operation
1675 operation: it can be: instantiate, terminate, action, TODO: update, heal
1676 :param kwargs: used to override the indata descriptor
1677 :param headers: http request headers
1678 :return: id of the nslcmops
1681 # Override descriptor with query string kwargs
1682 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1683 operation
= indata
["lcmOperationType"]
1684 netsliceInstanceId
= indata
["netsliceInstanceId"]
1685 validate_input(indata
, self
.operation_schema
[operation
])
1687 # get nsi from netsliceInstanceId
1688 _filter
= self
._get
_project
_filter
(session
)
1689 _filter
["_id"] = netsliceInstanceId
1690 nsir
= self
.db
.get_one("nsis", _filter
)
1691 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
1695 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1696 if operation
== "terminate" and indata
.get("autoremove"):
1697 # NSIR must be deleted
1698 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1699 if operation
!= "instantiate":
1700 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1701 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1703 if operation
== "instantiate" and not session
["force"]:
1704 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1705 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1707 # Creating all the NS_operation (nslcmop)
1708 # Get service list from db
1709 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1711 # nslcmops_item = None
1712 for index
, nsr_item
in enumerate(nsrs_list
):
1713 nsr_id
= nsr_item
["nsrId"]
1714 if nsr_item
.get("shared"):
1715 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1716 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1717 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1718 _filter
["_id.ne"] = netsliceInstanceId
1719 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1720 if operation
== "terminate":
1721 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1722 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1723 if nsi
: # other nsi is using this nsr and it needs this nsr instantiated
1724 continue # do not create nsilcmop
1726 # looks the first nsi fulfilling the conditions but not being the current NSIR
1728 nsi_nsr_item
= next(n
for n
in nsi
["_admin"]["nsrs-detailed-list"] if
1729 n
["nsrId"] == nsr_id
and n
["shared"] and
1730 n
["nslcmop_instantiate"])
1731 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1732 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1733 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1734 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1735 # continue to not create nslcmop since nsrs is shared and nsrs was created
1738 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1743 "lcmOperationType": operation
,
1744 "nsInstanceId": nsr_id
,
1745 # Including netslice_id in the ns instantiate Operation
1746 "netsliceInstanceId": netsliceInstanceId
,
1748 if operation
== "instantiate":
1749 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1750 indata_ns
.update(service
["instantiate_params"])
1752 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1753 # message via kafka bus
1754 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, None, headers
,
1756 nslcmops
.append(nslcmop
)
1757 if operation
== "instantiate":
1758 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1759 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1760 except (DbException
, EngineException
) as e
:
1761 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1762 self
.logger
.info(logging_prefix
+ "skipping NS={} because not found".format(nsr_id
))
1768 indata
["nslcmops_ids"] = nslcmops
1769 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1771 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1772 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1773 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1774 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1775 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1777 except ValidationError
as e
:
1778 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1780 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1781 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1783 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1784 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)