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 for df
in descriptor
.get("df", []):
181 # check that enough parameters are supplied for the initial-config-primitive
182 # TODO: check for cloud-init
184 initial_primitives
= []
185 if "lcm-operations-configuration" in df \
186 and "operate-vnf-op-config" in df
["lcm-operations-configuration"]:
187 for config
in df
["lcm-operations-configuration"]["operate-vnf-op-config"].get("day1-2", []):
188 for primitive
in get_iterable(config
.get("initial-config-primitive")):
189 initial_primitives
.append(primitive
)
191 initial_primitives
= deep_get(descriptor
, ("ns-configuration", "initial-config-primitive"))
193 for initial_primitive
in get_iterable(initial_primitives
):
194 for param
in get_iterable(initial_primitive
.get("parameter")):
195 if param
["value"].startswith("<") and param
["value"].endswith(">"):
196 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
198 if not additional_params
or param
["value"][1:-1] not in additional_params
:
199 raise EngineException("Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
200 "initial-config-primitive[name={}] not supplied".
201 format(param
["value"], descriptor
["id"],
202 initial_primitive
["name"]))
204 return additional_params
or None, other_params
or None
206 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
208 Creates a new nsr into database. It also creates needed vnfrs
209 :param rollback: list to append the created items at database in case a rollback must be done
210 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
211 :param indata: params to be used for the nsr
212 :param kwargs: used to override the indata descriptor
213 :param headers: http request headers
214 :return: the _id of nsr descriptor created at database. Or an exception of type
215 EngineException, ValidationError, DbException, FsException, MsgException.
216 Note: Exceptions are not captured on purpose. They should be captured at called
219 step
= "checking quotas"
220 self
.check_quota(session
)
222 step
= "validating input parameters"
223 ns_request
= self
._remove
_envelop
(indata
)
224 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
225 ns_request
= self
._validate
_input
_new
(ns_request
, session
["force"])
227 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
228 nsd
= self
._get
_nsd
_from
_db
(ns_request
["nsdId"], session
)
229 ns_k8s_namespace
= self
._get
_ns
_k
8s
_namespace
(nsd
, ns_request
, session
)
231 step
= "checking nsdOperationalState"
232 self
._check
_nsd
_operational
_state
(nsd
, ns_request
)
234 step
= "filling nsr from input data"
235 nsr_id
= str(uuid4())
236 nsr_descriptor
= self
._create
_nsr
_descriptor
_from
_nsd
(nsd
, ns_request
, nsr_id
)
240 # TODO: Change for multiple df support
241 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
242 for vnfp
in vnf_profiles
:
243 vnfd_id
= vnfp
.get("vnfd-id")
244 vnf_index
= vnfp
.get("id")
245 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(vnfd_id
, vnf_index
)
246 if vnfd_id
not in needed_vnfds
:
247 vnfd
= self
._get
_vnfd
_from
_db
(vnfd_id
, session
)
248 needed_vnfds
[vnfd_id
] = vnfd
249 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
251 vnfd
= needed_vnfds
[vnfd_id
]
253 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(vnfd_id
, vnf_index
)
254 vnfr_descriptor
= self
._create
_vnfr
_descriptor
_from
_vnfd
(nsd
, vnfd
, vnfd_id
, vnf_index
, nsr_descriptor
,
255 ns_request
, ns_k8s_namespace
)
257 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(vnfd_id
, vnf_index
)
258 self
._add
_vnfr
_to
_db
(vnfr_descriptor
, rollback
, session
)
259 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_descriptor
["id"])
261 step
= "creating nsr at database"
262 self
._add
_nsr
_to
_db
(nsr_descriptor
, rollback
, session
)
264 step
= "creating nsr temporal folder"
265 self
.fs
.mkdir(nsr_id
)
268 except (ValidationError
, EngineException
, DbException
, MsgException
, FsException
) as e
:
269 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
271 def _get_nsd_from_db(self
, nsd_id
, session
):
272 _filter
= self
._get
_project
_filter
(session
)
273 _filter
["_id"] = nsd_id
274 return self
.db
.get_one("nsds", _filter
)
276 def _get_vnfd_from_db(self
, vnfd_id
, session
):
277 _filter
= self
._get
_project
_filter
(session
)
278 _filter
["id"] = vnfd_id
279 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
283 def _add_nsr_to_db(self
, nsr_descriptor
, rollback
, session
):
284 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
285 self
.db
.create("nsrs", nsr_descriptor
)
286 rollback
.append({"topic": "nsrs", "_id": nsr_descriptor
["id"]})
288 def _add_vnfr_to_db(self
, vnfr_descriptor
, rollback
, session
):
289 self
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
290 self
.db
.create("vnfrs", vnfr_descriptor
)
291 rollback
.append({"topic": "vnfrs", "_id": vnfr_descriptor
["id"]})
293 def _check_nsd_operational_state(self
, nsd
, ns_request
):
294 if nsd
["_admin"]["operationalState"] == "DISABLED":
295 raise EngineException("nsd with id '{}' is DISABLED, and thus cannot be used to create "
296 "a network service".format(ns_request
["nsdId"]), http_code
=HTTPStatus
.CONFLICT
)
298 def _get_ns_k8s_namespace(self
, nsd
, ns_request
, session
):
299 additional_params
, _
= self
._format
_additional
_params
(ns_request
, descriptor
=nsd
)
300 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
301 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
302 if ns_request
and ns_request
.get("k8s-namespace"):
303 ns_k8s_namespace
= ns_request
["k8s-namespace"]
304 if additional_params
and additional_params
.get("k8s-namespace"):
305 ns_k8s_namespace
= additional_params
["k8s-namespace"]
307 return ns_k8s_namespace
309 def _create_nsr_descriptor_from_nsd(self
, nsd
, ns_request
, nsr_id
):
311 additional_params
, _
= self
._format
_additional
_params
(ns_request
, descriptor
=nsd
)
314 "name": ns_request
["nsName"],
315 "name-ref": ns_request
["nsName"],
316 "short-name": ns_request
["nsName"],
317 "admin-status": "ENABLED",
318 "nsState": "NOT_INSTANTIATED",
319 "currentOperation": "IDLE",
320 "currentOperationID": None,
321 "errorDescription": None,
323 "deploymentStatus": None,
324 "configurationStatus": None,
326 "nsd": {k
: v
for k
, v
in nsd
.items()},
327 "datacenter": ns_request
["vimAccountId"],
328 "resource-orchestrator": "osmopenmano",
329 "description": ns_request
.get("nsDescription", ""),
330 "constituent-vnfr-ref": [],
331 "operational-status": "init", # typedef ns-operational-
332 "config-status": "init", # typedef config-states
333 "detailed-status": "scheduled",
334 "orchestration-progress": {},
336 "nsd-name-ref": nsd
["name"],
337 "operational-events": [], # "id", "timestamp", "description", "event",
338 "nsd-ref": nsd
["id"],
339 "nsd-id": nsd
["_id"],
341 "instantiate_params": self
._format
_ns
_request
(ns_request
),
342 "additionalParamsForNs": additional_params
,
343 "ns-instance-config-ref": nsr_id
,
346 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
350 ns_request
["nsr_id"] = nsr_id
351 if ns_request
and ns_request
.get("config-units"):
352 nsr_descriptor
["config-units"] = ns_request
["config-units"]
355 if nsd
.get("virtual-link-desc"):
356 nsr_vld
= deepcopy(nsd
.get("virtual-link-desc", []))
357 # Fill each vld with vnfd-connection-point-ref data
358 # TODO: Change for multiple df support
359 all_vld_connection_point_data
= {vld
.get("id"): [] for vld
in nsr_vld
}
360 vnf_profiles
= nsd
.get("df", [[]])[0].get("vnf-profile", ())
361 for vnf_profile
in vnf_profiles
:
362 for vlc
in vnf_profile
.get("virtual-link-connectivity", ()):
363 for cpd
in vlc
.get("constituent-cpd-id", ()):
364 all_vld_connection_point_data
[vlc
.get("virtual-link-profile-id")].append({
365 "member-vnf-index-ref": cpd
.get("constituent-base-element-id"),
366 "vnfd-connection-point-ref": cpd
.get("constituent-cpd-id"),
367 "vnfd-id-ref": vnf_profile
.get("vnfd-id")
370 vnfd
= self
.db
.get_one("vnfds",
371 {"id": vnf_profile
.get("vnfd-id")},
375 for vdu
in vnfd
.get("vdu", ()):
378 # Find this vdu compute and storage descriptors
379 vdu_virtual_compute
= {}
380 vdu_virtual_storage
= {}
381 for vcd
in vnfd
.get("virtual-compute-desc", ()):
382 if vcd
.get("id") == vdu
.get("virtual-compute-desc"):
383 vdu_virtual_compute
= vcd
384 for vsd
in vnfd
.get("virtual-storage-desc", ()):
385 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
386 vdu_virtual_storage
= vsd
387 # Get this vdu vcpus, memory and storage info for flavor_data
388 if vdu_virtual_compute
.get("virtual-cpu", {}).get("num-virtual-cpu"):
389 flavor_data
["vcpu-count"] = vdu_virtual_compute
["virtual-cpu"]["num-virtual-cpu"]
390 if vdu_virtual_compute
.get("virtual-memory", {}).get("size"):
391 flavor_data
["memory-mb"] = float(vdu_virtual_compute
["virtual-memory"]["size"]) * 1024.0
392 if vdu_virtual_storage
.get("size-of-storage"):
393 flavor_data
["storage-gb"] = vdu_virtual_storage
["size-of-storage"]
394 # Get this vdu EPA info for guest_epa
395 if vdu_virtual_compute
.get("virtual-cpu", {}).get("cpu-quota"):
396 guest_epa
["cpu-quota"] = vdu_virtual_compute
["virtual-cpu"]["cpu-quota"]
397 if vdu_virtual_compute
.get("virtual-cpu", {}).get("pinning"):
398 vcpu_pinning
= vdu_virtual_compute
["virtual-cpu"]["pinning"]
399 if vcpu_pinning
.get("thread-policy"):
400 guest_epa
["cpu-thread-pinning-policy"] = vcpu_pinning
["thread-policy"]
401 if vcpu_pinning
.get("policy"):
402 cpu_policy
= "SHARED" if vcpu_pinning
["policy"] == "dynamic" else "DEDICATED"
403 guest_epa
["cpu-pinning-policy"] = cpu_policy
404 if vdu_virtual_compute
.get("virtual-memory", {}).get("mem-quota"):
405 guest_epa
["mem-quota"] = vdu_virtual_compute
["virtual-memory"]["mem-quota"]
406 if vdu_virtual_compute
.get("virtual-memory", {}).get("mempage-size"):
407 guest_epa
["mempage-size"] = vdu_virtual_compute
["virtual-memory"]["mempage-size"]
408 if vdu_virtual_compute
.get("virtual-memory", {}).get("numa-node-policy"):
409 guest_epa
["numa-node-policy"] = vdu_virtual_compute
["virtual-memory"]["numa-node-policy"]
410 if vdu_virtual_storage
.get("disk-io-quota"):
411 guest_epa
["disk-io-quota"] = vdu_virtual_storage
["disk-io-quota"]
414 flavor_data
["guest-epa"] = guest_epa
416 flavor_data
["name"] = vdu
["id"][:56] + "-flv"
417 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
418 nsr_descriptor
["flavor"].append(flavor_data
)
420 sw_image_id
= vdu
.get("sw-image-desc")
422 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, sw_image_id
)
423 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
425 # also add alternative images to the list of images
426 for alt_image
in vdu
.get("alternative-sw-image-desc", ()):
427 image_data
= self
._get
_image
_data
_from
_vnfd
(vnfd
, alt_image
)
428 self
._add
_image
_to
_nsr
(nsr_descriptor
, image_data
)
431 vld
["vnfd-connection-point-ref"] = all_vld_connection_point_data
.get(vld
.get("id"), [])
432 vld
["name"] = vld
["id"]
433 nsr_descriptor
["vld"] = nsr_vld
435 return nsr_descriptor
437 def _get_image_data_from_vnfd(self
, vnfd
, sw_image_id
):
438 sw_image_desc
= utils
.find_in_list(vnfd
.get("sw-image-desc", ()),
439 lambda sw
: sw
["id"] == sw_image_id
)
441 if sw_image_desc
.get("image"):
442 image_data
["image"] = sw_image_desc
["image"]
443 if sw_image_desc
.get("checksum"):
444 image_data
["image_checksum"] = sw_image_desc
["checksum"]["hash"]
445 if sw_image_desc
.get("vim-type"):
446 image_data
["vim-type"] = sw_image_desc
["vim-type"]
449 def _add_image_to_nsr(self
, nsr_descriptor
, image_data
):
451 Adds image to nsr checking first it is not already added
453 img
= next((f
for f
in nsr_descriptor
["image"] if
454 all(f
.get(k
) == image_data
[k
] for k
in image_data
)), None)
456 image_data
["id"] = str(len(nsr_descriptor
["image"]))
457 nsr_descriptor
["image"].append(image_data
)
459 def _create_vnfr_descriptor_from_vnfd(self
, nsd
, vnfd
, vnfd_id
, vnf_index
, nsr_descriptor
,
460 ns_request
, ns_k8s_namespace
):
461 vnfr_id
= str(uuid4())
462 nsr_id
= nsr_descriptor
["id"]
464 additional_params
, vnf_params
= self
._format
_additional
_params
(ns_request
, vnf_index
, descriptor
=vnfd
)
469 "nsr-id-ref": nsr_id
,
470 "member-vnf-index-ref": vnf_index
,
471 "additionalParamsForVnf": additional_params
,
473 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
475 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
476 "vim-account-id": None,
478 "connection-point": [],
479 "ip-address": None, # mgmt-interface filled by LCM
481 vnf_k8s_namespace
= ns_k8s_namespace
483 if vnf_params
.get("k8s-namespace"):
484 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
485 if vnf_params
.get("config-units"):
486 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
489 if vnfd
.get("int-virtual-link-desc"):
490 vnfr_descriptor
["vld"] = []
491 for vnfd_vld
in vnfd
.get("int-virtual-link-desc"):
492 vnfr_descriptor
["vld"].append({key
: vnfd_vld
[key
] for key
in vnfd_vld
})
494 for cp
in vnfd
.get("ext-cpd", ()):
496 "name": cp
.get("id"),
497 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
498 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
500 # "ip-address", "mac-address" # filled by LCM
501 # vim-id # TODO it would be nice having a vim port id
503 vnfr_descriptor
["connection-point"].append(vnf_cp
)
505 # Create k8s-cluster information
506 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
507 if vnfd
.get("k8s-cluster"):
508 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
509 all_k8s_cluster_nets_cpds
= {}
510 for cpd
in get_iterable(vnfd
.get("ext-cpd")):
511 if cpd
.get("k8s-cluster-net"):
512 all_k8s_cluster_nets_cpds
[cpd
.get("k8s-cluster-net")] = cpd
.get("id")
513 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
514 if net
.get("id") in all_k8s_cluster_nets_cpds
:
515 net
["external-connection-point-ref"] = all_k8s_cluster_nets_cpds
[net
.get("id")]
518 for kdu
in get_iterable(vnfd
.get("kdu")):
519 additional_params
, kdu_params
= self
._format
_additional
_params
(ns_request
,
521 kdu_name
=kdu
["name"],
523 kdu_k8s_namespace
= vnf_k8s_namespace
524 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
525 if kdu_params
and kdu_params
.get("k8s-namespace"):
526 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
529 "additionalParams": additional_params
,
530 "k8s-namespace": kdu_k8s_namespace
,
531 "kdu-name": kdu
["name"],
532 # TODO "name": "" Name of the VDU in the VIM
533 "ip-address": None, # mgmt-interface filled by LCM
536 if kdu_params
and kdu_params
.get("config-units"):
537 kdur
["config-units"] = kdu_params
["config-units"]
538 if kdu
.get("helm-version"):
539 kdur
["helm-version"] = kdu
["helm-version"]
540 for k8s_type
in ("helm-chart", "juju-bundle"):
541 if kdu
.get(k8s_type
):
542 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
543 if not vnfr_descriptor
.get("kdur"):
544 vnfr_descriptor
["kdur"] = []
545 vnfr_descriptor
["kdur"].append(kdur
)
547 vnfd_mgmt_cp
= vnfd
.get("mgmt-cp")
549 for vdu
in vnfd
.get("vdu", ()):
552 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"]["operate-vnf-op-config"]["day1-2"]
553 vdu_config
= utils
.find_in_list(configs
, lambda config
: config
["id"] == vdu
["id"])
558 external_connection_ee
= utils
.filter_in_list(
559 vdu_config
.get("execution-environment-list", []),
560 lambda ee
: "external-connection-point-ref" in ee
562 for ee
in external_connection_ee
:
563 vdu_mgmt_cp
.append(ee
["external-connection-point-ref"])
565 additional_params
, vdu_params
= self
._format
_additional
_params
(
566 ns_request
, vnf_index
, vdu_id
=vdu
["id"], descriptor
=vnfd
)
568 "vdu-id-ref": vdu
["id"],
569 # TODO "name": "" Name of the VDU in the VIM
570 "ip-address": None, # mgmt-interface filled by LCM
571 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
572 "internal-connection-point": [],
574 "additionalParams": additional_params
,
575 "vdu-name": vdu
["name"]
577 if vdu_params
and vdu_params
.get("config-units"):
578 vdur
["config-units"] = vdu_params
["config-units"]
579 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
580 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"]["boot-data-drive"]
581 if vdu
.get("pdu-type"):
582 vdur
["pdu-type"] = vdu
["pdu-type"]
583 vdur
["name"] = vdu
["pdu-type"]
584 # TODO volumes: name, volume-id
585 for icp
in vdu
.get("int-cpd", ()):
588 "connection-point-id": icp
["id"],
589 "name": icp
.get("id"),
592 if "port-security-enabled" in icp
:
593 vdu_icp
["port-security-enabled"] = icp
["port-security-enabled"]
595 if "port-security-disable-strategy" in icp
:
596 vdu_icp
["port-security-disable-strategy"] = icp
["port-security-disable-strategy"]
598 vdur
["internal-connection-point"].append(vdu_icp
)
600 for iface
in icp
.get("virtual-network-interface-requirement", ()):
601 iface_fields
= ("name", "mac-address")
602 vdu_iface
= {x
: iface
[x
] for x
in iface_fields
if iface
.get(x
) is not None}
604 vdu_iface
["internal-connection-point-ref"] = vdu_icp
["id"]
605 for ext_cp
in vnfd
.get("ext-cpd", ()):
606 if not ext_cp
.get("int-cpd"):
608 if ext_cp
["int-cpd"].get("vdu-id") != vdu
["id"]:
610 if icp
["id"] == ext_cp
["int-cpd"].get("cpd"):
611 vdu_iface
["external-connection-point-ref"] = ext_cp
.get("id")
614 if vnfd_mgmt_cp
and vdu_iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
615 vdu_iface
["mgmt-vnf"] = True
616 vdu_iface
["mgmt-interface"] = True
618 for ecp
in vdu_mgmt_cp
:
619 if vdu_iface
.get("external-connection-point-ref") == ecp
:
620 vdu_iface
["mgmt-interface"] = True
622 if iface
.get("virtual-interface"):
623 vdu_iface
.update(deepcopy(iface
["virtual-interface"]))
625 # look for network where this interface is connected
626 iface_ext_cp
= vdu_iface
.get("external-connection-point-ref")
628 # TODO: Change for multiple df support
629 for df
in get_iterable(nsd
.get("df")):
630 for vnf_profile
in get_iterable(df
.get("vnf-profile")):
631 for vlc_index
, vlc
in \
632 enumerate(get_iterable(vnf_profile
.get("virtual-link-connectivity"))):
633 for cpd
in get_iterable(vlc
.get("constituent-cpd-id")):
634 if cpd
.get("constituent-cpd-id") == iface_ext_cp
:
635 vdu_iface
["ns-vld-id"] = vlc
.get("virtual-link-profile-id")
636 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
637 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
638 nsr_descriptor
["vld"][vlc_index
]["pci-interfaces"] = True
640 elif vdu_iface
.get("internal-connection-point-ref"):
641 vdu_iface
["vnf-vld-id"] = icp
.get("int-virtual-link-desc")
642 # TODO: store fixed IP address in the record (if it exists in the ICP)
643 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
644 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
645 ivld_index
= utils
.find_index_in_list(vnfd
.get("int-virtual-link-desc", ()),
647 ivld
["id"] == icp
.get("int-virtual-link-desc")
649 vnfr_descriptor
["vld"][ivld_index
]["pci-interfaces"] = True
651 vdur
["interfaces"].append(vdu_iface
)
653 if vdu
.get("sw-image-desc"):
654 sw_image
= utils
.find_in_list(
655 vnfd
.get("sw-image-desc", ()),
656 lambda image
: image
["id"] == vdu
.get("sw-image-desc"))
657 nsr_sw_image_data
= utils
.find_in_list(
658 nsr_descriptor
["image"],
659 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image"))
661 vdur
["ns-image-id"] = nsr_sw_image_data
["id"]
663 if vdu
.get("alternative-sw-image-desc"):
665 for alt_image_id
in vdu
.get("alternative-sw-image-desc", ()):
666 sw_image
= utils
.find_in_list(
667 vnfd
.get("sw-image-desc", ()),
668 lambda image
: image
["id"] == alt_image_id
)
669 nsr_sw_image_data
= utils
.find_in_list(
670 nsr_descriptor
["image"],
671 lambda nsr_image
: (nsr_image
.get("image") == sw_image
.get("image"))
673 alt_image_ids
.append(nsr_sw_image_data
["id"])
674 vdur
["alt-image-ids"] = alt_image_ids
676 flavor_data_name
= vdu
["id"][:56] + "-flv"
677 nsr_flavor_desc
= utils
.find_in_list(
678 nsr_descriptor
["flavor"],
679 lambda flavor
: flavor
["name"] == flavor_data_name
)
682 vdur
["ns-flavor-id"] = nsr_flavor_desc
["id"]
684 count
= int(vdu
.get("count", 1))
685 for index
in range(0, count
):
686 vdur
= deepcopy(vdur
)
687 for iface
in vdur
["interfaces"]:
688 if iface
.get("ip-address"):
689 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
690 if iface
.get("mac-address"):
691 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
693 vdur
["_id"] = str(uuid4())
694 vdur
["id"] = vdur
["_id"]
695 vdur
["count-index"] = index
696 vnfr_descriptor
["vdur"].append(vdur
)
698 return vnfr_descriptor
700 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
701 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
704 class VnfrTopic(BaseTopic
):
708 def __init__(self
, db
, fs
, msg
, auth
):
709 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
711 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
712 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
714 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
715 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
717 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
718 # Not used because vnfrs are created and deleted by NsrTopic class directly
719 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
722 class NsLcmOpTopic(BaseTopic
):
725 operation_schema
= { # mapping between operation and jsonschema to validate
726 "instantiate": ns_instantiate
,
729 "terminate": ns_terminate
,
732 def __init__(self
, db
, fs
, msg
, auth
):
733 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
735 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
737 Check that user has enter right parameters for the operation
738 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
739 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
740 :param indata: descriptor with the parameters of the operation
743 if operation
== "action":
744 self
._check
_action
_ns
_operation
(indata
, nsr
)
745 elif operation
== "scale":
746 self
._check
_scale
_ns
_operation
(indata
, nsr
)
747 elif operation
== "instantiate":
748 self
._check
_instantiate
_ns
_operation
(indata
, nsr
, session
)
750 def _check_action_ns_operation(self
, indata
, nsr
):
752 # check vnf_member_index
753 if indata
.get("vnf_member_index"):
754 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
755 if indata
.get("member_vnf_index"):
756 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(indata
["member_vnf_index"], nsr
["_id"])
758 configs
= vnfd
.get("df")[0]["lcm-operations-configuration"]["operate-vnf-op-config"]["day1-2"]
762 if indata
.get("vdu_id"):
763 self
._check
_valid
_vdu
(vnfd
, indata
["vdu_id"])
764 descriptor_configuration
= utils
.find_in_list(
766 lambda config
: config
["id"] == indata
["vdu_id"]
767 ).get("config-primitive")
768 elif indata
.get("kdu_name"):
769 self
._check
_valid
_kdu
(vnfd
, indata
["kdu_name"])
770 descriptor_configuration
= utils
.find_in_list(
772 lambda config
: config
["id"] == indata
.get("kdu_name")
773 ).get("config-primitive")
775 descriptor_configuration
= utils
.find_in_list(
777 lambda config
: config
["id"] == vnfd
["id"]
778 ).get("config-primitive")
780 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
782 # For k8s allows default primitives without validating the parameters
783 if indata
.get("kdu_name") and indata
["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
784 # TODO should be checked that rollback only can contains revsision_numbe????
785 if not indata
.get("member_vnf_index"):
786 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
787 .format(indata
["primitive"]))
789 # if not, check primitive
790 for config_primitive
in get_iterable(descriptor_configuration
):
791 if indata
["primitive"] == config_primitive
["name"]:
792 # check needed primitive_params are provided
793 if indata
.get("primitive_params"):
794 in_primitive_params_copy
= copy(indata
["primitive_params"])
796 in_primitive_params_copy
= {}
797 for paramd
in get_iterable(config_primitive
.get("parameter")):
798 if paramd
["name"] in in_primitive_params_copy
:
799 del in_primitive_params_copy
[paramd
["name"]]
800 elif not paramd
.get("default-value"):
801 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
802 paramd
["name"], indata
["primitive"]))
803 # check no extra primitive params are provided
804 if in_primitive_params_copy
:
805 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
806 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
809 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
811 def _check_scale_ns_operation(self
, indata
, nsr
):
812 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"],
814 for scaling_aspect
in get_iterable(vnfd
.get("df", ())[0]["scaling-aspect"]):
815 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_aspect
["id"]:
818 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
819 "present at vnfd:scaling-aspect"
820 .format(indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
822 def _check_instantiate_ns_operation(self
, indata
, nsr
, session
):
823 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
827 self
._check
_valid
_vim
_account
(indata
["vimAccountId"], vim_accounts
, session
)
828 self
._check
_valid
_wim
_account
(indata
.get("wimAccountId"), wim_accounts
, session
)
829 for in_vnf
in get_iterable(indata
.get("vnf")):
830 member_vnf_index
= in_vnf
["member-vnf-index"]
831 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
832 vnfd
= vnf_member_index_to_vnfd
[member_vnf_index
]
834 vnfd
= self
._get
_vnfd
_from
_vnf
_member
_index
(member_vnf_index
, nsr
["_id"])
835 vnf_member_index_to_vnfd
[member_vnf_index
] = vnfd
# add to cache, avoiding a later look for
836 self
._check
_vnf
_instantiation
_params
(in_vnf
, vnfd
)
837 if in_vnf
.get("vimAccountId"):
838 self
._check
_valid
_vim
_account
(in_vnf
["vimAccountId"], vim_accounts
, session
)
840 for in_vld
in get_iterable(indata
.get("vld")):
841 self
._check
_valid
_wim
_account
(in_vld
.get("wimAccountId"), wim_accounts
, session
)
842 for vldd
in get_iterable(nsd
.get("virtual-link-desc")):
843 if in_vld
["name"] == vldd
["id"]:
846 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
849 def _get_vnfd_from_vnf_member_index(self
, member_vnf_index
, nsr_id
):
850 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
851 vnfr
= self
.db
.get_one("vnfrs",
852 {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": member_vnf_index
},
855 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
856 "nsd:constituent-vnfd".format(member_vnf_index
))
857 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
859 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
860 format(vnfr
["vnfd-id"]))
863 def _check_valid_vdu(self
, vnfd
, vdu_id
):
864 for vdud
in get_iterable(vnfd
.get("vdu")):
865 if vdud
["id"] == vdu_id
:
868 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id
))
870 def _check_valid_kdu(self
, vnfd
, kdu_name
):
871 for kdud
in get_iterable(vnfd
.get("kdu")):
872 if kdud
["name"] == kdu_name
:
875 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name
))
877 def _check_vnf_instantiation_params(self
, in_vnf
, vnfd
):
878 for in_vdu
in get_iterable(in_vnf
.get("vdu")):
879 for vdu
in get_iterable(vnfd
.get("vdu")):
880 if in_vdu
["id"] == vdu
["id"]:
881 for volume
in get_iterable(in_vdu
.get("volume")):
882 for volumed
in get_iterable(vdu
.get("virtual-storage-desc")):
883 if volumed
["id"] == volume
["name"]:
886 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
887 "volume:name='{}' is not present at "
888 "vnfd:vdu:virtual-storage-desc list".
889 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
893 for cpd
in get_iterable(vdu
.get("int-cpd")):
894 for iface
in get_iterable(cpd
.get("virtual-network-interface-requirement")):
895 vdu_if_names
.add(iface
.get("name"))
897 for in_iface
in get_iterable(in_vdu
["interface"]):
898 if in_iface
["name"] in vdu_if_names
:
901 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
902 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd"
903 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
908 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
909 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
911 vnfd_ivlds_cpds
= {ivld
.get("id"): set() for ivld
in get_iterable(vnfd
.get("int-virtual-link-desc"))}
912 for vdu
in get_iterable(vnfd
.get("vdu")):
913 for cpd
in get_iterable(vnfd
.get("int-cpd")):
914 if cpd
.get("int-virtual-link-desc"):
915 vnfd_ivlds_cpds
[cpd
.get("int-virtual-link-desc")] = cpd
.get("id")
917 for in_ivld
in get_iterable(in_vnf
.get("internal-vld")):
918 if in_ivld
.get("name") in vnfd_ivlds_cpds
:
919 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
920 if in_icp
["id-ref"] in vnfd_ivlds_cpds
[in_ivld
.get("name")]:
923 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
924 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
925 "vnfd:internal-vld:name/id:internal-connection-point"
926 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
929 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
930 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
931 in_ivld
["name"], vnfd
["id"]))
933 def _check_valid_vim_account(self
, vim_account
, vim_accounts
, session
):
934 if vim_account
in vim_accounts
:
937 db_filter
= self
._get
_project
_filter
(session
)
938 db_filter
["_id"] = vim_account
939 self
.db
.get_one("vim_accounts", db_filter
)
941 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
942 vim_accounts
.append(vim_account
)
944 def _check_valid_wim_account(self
, wim_account
, wim_accounts
, session
):
945 if not isinstance(wim_account
, str):
947 if wim_account
in wim_accounts
:
950 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
951 db_filter
["_id"] = wim_account
952 self
.db
.get_one("wim_accounts", db_filter
)
954 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
955 wim_accounts
.append(wim_account
)
957 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
959 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
960 (ip_address, ...) information.
961 Modifies PDU _admin.usageState to 'IN_USE'
962 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
963 :param rollback: list with the database modifications to rollback if needed
964 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
965 :param vim_account: vim_account where this vnfr should be deployed
966 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
967 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
968 of the changed vnfr is needed
970 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
971 "vim-network-name": used at VIM
972 "name": interface name
973 "vnf-vld-id": internal VNFD vld where this interface is connected, or
974 "ns-vld-id": NSD vld where this interface is connected.
975 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
978 ifaces_forcing_vim_network
= []
979 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
980 if not vdur
.get("pdu-type"):
982 pdu_type
= vdur
.get("pdu-type")
983 pdu_filter
= self
._get
_project
_filter
(session
)
984 pdu_filter
["vim_accounts"] = vim_account
985 pdu_filter
["type"] = pdu_type
986 pdu_filter
["_admin.operationalState"] = "ENABLED"
987 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
988 # TODO feature 1417: "shared": True,
990 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
991 for pdu
in available_pdus
:
992 # step 1 check if this pdu contains needed interfaces:
993 match_interfaces
= True
994 for vdur_interface
in vdur
["interfaces"]:
995 for pdu_interface
in pdu
["interfaces"]:
996 if pdu_interface
["name"] == vdur_interface
["name"]:
997 # TODO feature 1417: match per mgmt type
999 else: # no interface found for name
1000 match_interfaces
= False
1002 if match_interfaces
:
1005 raise EngineException(
1006 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1007 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
1009 # step 2. Update pdu
1011 "_admin.usageState": pdu
["_admin"]["usageState"],
1012 "_admin.usage.vnfr_id": None,
1013 "_admin.usage.nsr_id": None,
1014 "_admin.usage.vdur": None,
1016 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
1017 {"_admin.usageState": "IN_USE",
1018 "_admin.usage": {"vnfr_id": vnfr
["_id"],
1019 "nsr_id": vnfr
["nsr-id-ref"],
1020 "vdur": vdur
["vdu-id-ref"]}
1022 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
1024 # step 3. Fill vnfr info by filling vdur
1025 vdu_text
= "vdur.{}".format(vdur_index
)
1026 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
1027 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
1028 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
1029 for pdu_interface
in pdu
["interfaces"]:
1030 if pdu_interface
["name"] == vdur_interface
["name"]:
1031 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
1032 for k
, v
in pdu_interface
.items():
1033 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
1034 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
1035 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
1036 if pdu_interface
.get("ip-address"):
1037 if vdur_interface
.get("mgmt-interface") or vdur_interface
.get("mgmt-vnf"):
1038 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
1039 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
1040 if vdur_interface
.get("mgmt-vnf"):
1041 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
1042 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
1043 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
1044 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
1045 ifaces_forcing_vim_network
.append({
1046 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
1047 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
1048 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
1049 if pdu_interface
.get("vim-network-id"):
1050 ifaces_forcing_vim_network
[-1]["vim-network-id"] = pdu_interface
["vim-network-id"]
1051 if pdu_interface
.get("vim-network-name"):
1052 ifaces_forcing_vim_network
[-1]["vim-network-name"] = pdu_interface
["vim-network-name"]
1055 return ifaces_forcing_vim_network
1057 def _look_for_k8scluster(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
1059 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1060 Fills vnfr.kdur with the selected k8scluster
1062 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1063 :param rollback: list with the database modifications to rollback if needed
1064 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1065 :param vim_account: vim_account where this vnfr should be deployed
1066 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1067 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1068 of the changed vnfr is needed
1070 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1071 "vim-network-name": used at VIM
1072 "name": interface name
1073 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1074 "ns-vld-id": NSD vld where this interface is connected.
1075 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1078 ifaces_forcing_vim_network
= []
1079 if not vnfr
.get("kdur"):
1080 return ifaces_forcing_vim_network
1082 kdu_filter
= self
._get
_project
_filter
(session
)
1083 kdu_filter
["vim_account"] = vim_account
1084 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1085 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
1087 k8s_requirements
= {} # just for logging
1088 for k8scluster
in available_k8sclusters
:
1089 if not vnfr
.get("k8s-cluster"):
1092 if vnfr
["k8s-cluster"].get("cni"):
1093 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
1094 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(k8scluster
.get("cni", ())):
1096 # restrict by version
1097 if vnfr
["k8s-cluster"].get("version"):
1098 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
1099 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
1101 # restrict by number of networks
1102 if vnfr
["k8s-cluster"].get("nets"):
1103 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
1104 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(vnfr
["k8s-cluster"]["nets"]):
1108 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
1109 .format(k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]))
1111 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
1112 # step 3. Fill vnfr info by filling kdur
1113 kdu_text
= "kdur.{}.".format(kdur_index
)
1114 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
1115 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
1117 # step 4. Check VIM networks that forces the selected k8s_cluster
1118 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
1119 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
1120 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
1121 # get a network from k8s_cluster nets. If name matches use this, if not use other
1122 if kdur_net
["id"] in k8scluster_net_list
: # name matches
1123 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
1124 k8scluster_net_list
.remove(kdur_net
["id"])
1126 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
1127 k8scluster_net_list
.pop(0)
1128 vnfr_update_rollback
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = None
1129 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
1130 if vim_net
and (kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")):
1131 ifaces_forcing_vim_network
.append({
1132 "name": kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id"),
1133 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
1134 "ns-vld-id": kdur_net
.get("ns-vld-id"),
1135 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
1137 # TODO check that this forcing is not incompatible with other forcing
1138 return ifaces_forcing_vim_network
1140 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
1143 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1147 vnfr_update_rollback
= {}
1148 member_vnf_index
= vnfr
["member-vnf-index-ref"]
1149 # update vim-account-id
1151 vim_account
= indata
["vimAccountId"]
1152 # check instantiate parameters
1153 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
1154 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
1156 if vnf_inst_params
.get("vimAccountId"):
1157 vim_account
= vnf_inst_params
.get("vimAccountId")
1159 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1160 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
1161 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1162 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
1164 for iface_inst_param
in get_iterable(vdu_inst_param
.get("interface")):
1165 iface_index
, _
= next(i
for i
in enumerate(vdur
["interfaces"])
1166 if i
[1]["name"] == iface_inst_param
["name"])
1167 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
1168 if iface_inst_param
.get("ip-address"):
1169 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1170 iface_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1171 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1172 if iface_inst_param
.get("mac-address"):
1173 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1174 iface_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1175 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1176 if iface_inst_param
.get("floating-ip-required"):
1177 vnfr_update
[vnfr_update_text
+ ".floating-ip-required"] = True
1178 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1179 # TODO update vld with the ip-profile
1180 for ivld_inst_param
in get_iterable(vnf_inst_params
.get("internal-vld")):
1181 for icp_inst_param
in get_iterable(ivld_inst_param
.get("internal-connection-point")):
1183 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1184 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1185 if iface
.get("internal-connection-point-ref") == icp_inst_param
["id-ref"]:
1186 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
1187 if icp_inst_param
.get("ip-address"):
1188 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1189 icp_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1190 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1191 if icp_inst_param
.get("mac-address"):
1192 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1193 icp_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1194 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1196 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1197 for vld_inst_param
in get_iterable(indata
.get("vld")):
1198 for vnfcp_inst_param
in get_iterable(vld_inst_param
.get("vnfd-connection-point-ref")):
1199 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
1202 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1203 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1204 if iface
.get("external-connection-point-ref") == \
1205 vnfcp_inst_param
["vnfd-connection-point-ref"]:
1206 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
1207 if vnfcp_inst_param
.get("ip-address"):
1208 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1209 vnfcp_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1210 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1211 if vnfcp_inst_param
.get("mac-address"):
1212 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1213 vnfcp_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1214 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1217 vnfr_update
["vim-account-id"] = vim_account
1218 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
1221 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
1222 vnfr_update_rollback
)
1225 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
1226 vnfr_update_rollback
)
1227 # update database vnfr
1228 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1229 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
1231 # Update indada in case pdu forces to use a concrete vim-network-name
1232 # TODO check if user has already insert a vim-network-name and raises an error
1233 if not ifaces_forcing_vim_network
:
1235 for iface_info
in ifaces_forcing_vim_network
:
1236 if iface_info
.get("ns-vld-id"):
1237 if "vld" not in indata
:
1239 indata
["vld"].append({key
: iface_info
[key
] for key
in
1240 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
1242 elif iface_info
.get("vnf-vld-id"):
1243 if "vnf" not in indata
:
1245 indata
["vnf"].append({
1246 "member-vnf-index": member_vnf_index
,
1247 "internal-vld": [{key
: iface_info
[key
] for key
in
1248 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
1252 def _create_nslcmop(nsr_id
, operation
, params
):
1254 Creates a ns-lcm-opp content to be stored at database.
1255 :param nsr_id: internal id of the instance
1256 :param operation: instantiate, terminate, scale, action, ...
1257 :param params: user parameters for the operation
1258 :return: dictionary following SOL005 format
1265 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1266 "queuePosition": None,
1268 "errorMessage": None,
1269 "detailedStatus": None,
1270 "statusEnteredTime": now
,
1271 "nsInstanceId": nsr_id
,
1272 "lcmOperationType": operation
,
1274 "isAutomaticInvocation": False,
1275 "operationParams": params
,
1276 "isCancelPending": False,
1278 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1279 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1284 def _get_enabled_vims(self
, session
):
1286 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1287 :param session: current session with user information
1289 db_filter
= self
._get
_project
_filter
(session
)
1290 db_filter
["_admin.operationalState"] = "ENABLED"
1291 vims
= self
.db
.get_list("vim_accounts", db_filter
)
1294 vimAccounts
.append(vim
['_id'])
1297 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
1299 Performs a new operation over a ns
1300 :param rollback: list to append created items at database in case a rollback must to be done
1301 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1302 :param indata: descriptor with the parameters of the operation. It must contains among others
1303 nsInstanceId: _id of the nsr to perform the operation
1304 operation: it can be: instantiate, terminate, action, TODO: update, heal
1305 :param kwargs: used to override the indata descriptor
1306 :param headers: http request headers
1307 :return: id of the nslcmops
1309 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
1311 db_filter
= self
._get
_project
_filter
(session
)
1312 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1313 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
1315 raise EngineException("The NS instance {} cannot be terminated because is used by the slice {}".format(
1316 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
1319 # Override descriptor with query string kwargs
1320 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
1321 operation
= indata
["lcmOperationType"]
1322 nsInstanceId
= indata
["nsInstanceId"]
1324 validate_input(indata
, self
.operation_schema
[operation
])
1325 # get ns from nsr_id
1326 _filter
= BaseTopic
._get
_project
_filter
(session
)
1327 _filter
["_id"] = nsInstanceId
1328 nsr
= self
.db
.get_one("nsrs", _filter
)
1331 if operation
== "terminate" and slice_object
is False:
1332 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
1333 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1334 if operation
== "terminate" and indata
.get("autoremove"):
1335 # NSR must be deleted
1336 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1337 if operation
!= "instantiate":
1338 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1339 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1341 if operation
== "instantiate" and not session
["force"]:
1342 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1343 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1344 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
1346 if operation
== "instantiate":
1347 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
1349 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
1350 _id
= nslcmop_desc
["_id"]
1351 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1352 if indata
.get("placement-engine"):
1353 # Save valid vim accounts in lcm operation descriptor
1354 nslcmop_desc
['operationParams']['validVimAccounts'] = self
._get
_enabled
_vims
(session
)
1355 self
.db
.create("nslcmops", nslcmop_desc
)
1356 rollback
.append({"topic": "nslcmops", "_id": _id
})
1357 if not slice_object
:
1358 self
.msg
.write("ns", operation
, nslcmop_desc
)
1360 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
1361 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1362 # except DbException as e:
1363 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1365 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1366 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1368 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1369 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1372 class NsiTopic(BaseTopic
):
1375 quota_name
= "slice_instances"
1377 def __init__(self
, db
, fs
, msg
, auth
):
1378 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1379 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
1382 def _format_ns_request(ns_request
):
1383 formated_request
= copy(ns_request
)
1384 # TODO: Add request params
1385 return formated_request
1388 def _format_addional_params(slice_request
):
1390 Get and format user additional params for NS or VNF
1391 :param slice_request: User instantiation additional parameters
1392 :return: a formatted copy of additional params or None if not supplied
1394 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
1395 if additional_params
:
1396 for k
, v
in additional_params
.items():
1397 if not isinstance(k
, str):
1398 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1400 if "." in k
or "$" in k
:
1401 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1403 if isinstance(v
, (dict, tuple, list)):
1404 additional_params
[k
] = "!!yaml " + safe_dump(v
)
1405 return additional_params
1407 def _check_descriptor_dependencies(self
, session
, descriptor
):
1409 Check that the dependent descriptors exist on a new descriptor or edition
1410 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1411 :param descriptor: descriptor to be inserted or edit
1412 :return: None or raises exception
1414 if not descriptor
.get("nst-ref"):
1416 nstd_id
= descriptor
["nst-ref"]
1417 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
1418 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
1419 http_code
=HTTPStatus
.CONFLICT
)
1421 def check_conflict_on_del(self
, session
, _id
, db_content
):
1423 Check that NSI is not instantiated
1424 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1425 :param _id: nsi internal id
1426 :param db_content: The database content of the _id
1427 :return: None or raises EngineException with the conflict
1429 if session
["force"]:
1432 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
1433 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1434 "Launch 'terminate' operation first; or force deletion".format(_id
),
1435 http_code
=HTTPStatus
.CONFLICT
)
1437 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
1439 Deletes associated nsilcmops from database. Deletes associated filesystem.
1440 Set usageState of nst
1441 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1442 :param _id: server internal id
1443 :param db_content: The database content of the descriptor
1444 :param not_send_msg: To not send message (False) or store content (list) instead
1445 :return: None if ok or raises EngineException with the problem
1448 # Deleting the nsrs belonging to nsir
1450 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
1451 nsr_id
= nsrs_detailed_item
["nsrId"]
1452 if nsrs_detailed_item
.get("shared"):
1453 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1454 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
1455 "_id.ne": nsir
["_id"]}
1456 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1457 if nsi
: # last one using nsr
1460 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
)
1461 except (DbException
, EngineException
) as e
:
1462 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1467 # delete related nsilcmops database entries
1468 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
1470 # Check and set used NST usage state
1471 nsir_admin
= nsir
.get("_admin")
1472 if nsir_admin
and nsir_admin
.get("nst-id"):
1473 # check if used by another NSI
1474 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
1475 fail_on_empty
=False, fail_on_more
=False)
1477 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1479 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1481 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1482 :param rollback: list to append the created items at database in case a rollback must be done
1483 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1484 :param indata: params to be used for the nsir
1485 :param kwargs: used to override the indata descriptor
1486 :param headers: http request headers
1487 :return: the _id of nsi descriptor created at database
1491 step
= "checking quotas"
1492 self
.check_quota(session
)
1495 slice_request
= self
._remove
_envelop
(indata
)
1496 # Override descriptor with query string kwargs
1497 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
1498 slice_request
= self
._validate
_input
_new
(slice_request
, session
["force"])
1501 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1502 _filter
= self
._get
_project
_filter
(session
)
1503 _filter
["_id"] = slice_request
["nstId"]
1504 nstd
= self
.db
.get_one("nsts", _filter
)
1505 # check NST is not disabled
1506 step
= "checking NST operationalState"
1507 if nstd
["_admin"]["operationalState"] == "DISABLED":
1508 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
1509 "instance".format(slice_request
["nstId"]), http_code
=HTTPStatus
.CONFLICT
)
1512 # check NSD is not disabled
1513 step
= "checking operationalState"
1514 if nstd
["_admin"]["operationalState"] == "DISABLED":
1515 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create "
1516 "a network slice".format(slice_request
["nstId"]), http_code
=HTTPStatus
.CONFLICT
)
1518 nstd
.pop("_admin", None)
1519 nstd_id
= nstd
.pop("_id", None)
1520 nsi_id
= str(uuid4())
1521 step
= "filling nsi_descriptor with input data"
1526 "name": slice_request
["nsiName"],
1527 "description": slice_request
.get("nsiDescription", ""),
1528 "datacenter": slice_request
["vimAccountId"],
1529 "nst-ref": nstd
["id"],
1530 "instantiation_parameters": slice_request
,
1531 "network-slice-template": nstd
,
1535 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1538 step
= "creating nsi at database"
1539 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1540 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1541 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1542 nsi_descriptor
["_admin"]["deployed"] = {}
1543 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1544 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1546 # Creating netslice-vld for the RO.
1547 step
= "creating netslice-vld at database"
1549 # Building the vlds list to be deployed
1550 # From netslice descriptors, creating the initial list
1553 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1554 # Getting template Instantiation parameters from NST
1555 nsi_vld
= deepcopy(netslice_vlds
)
1556 nsi_vld
["shared-nsrs-list"] = []
1557 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1558 nsi_vlds
.append(nsi_vld
)
1560 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1561 # Creating netslice-subnet_record.
1565 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1566 for member_ns
in nstd
["netslice-subnet"]:
1567 nsd_id
= member_ns
["nsd-ref"]
1568 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1569 member_ns
["nsd-ref"], member_ns
["id"])
1570 if nsd_id
not in needed_nsds
:
1572 _filter
["id"] = nsd_id
1573 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1576 needed_nsds
[nsd_id
] = nsd
1578 nsd
= needed_nsds
[nsd_id
]
1579 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1580 services
.append(member_ns
)
1582 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1583 member_ns
["nsd-ref"], member_ns
["id"])
1585 # creates Network Services records (NSRs)
1586 step
= "creating nsrs at database using NsrTopic.new()"
1587 ns_params
= slice_request
.get("netslice-subnet")
1589 nsi_netslice_subnet
= []
1590 for service
in services
:
1591 # Check if the netslice-subnet is shared and if it is share if the nss exists
1594 # Is the nss shared and instantiated?
1595 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1596 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1597 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1598 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1599 if nsi
and service
.get("is-shared-nss"):
1600 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1601 for nsrs_detailed_item
in nsrs_detailed_list
:
1602 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1603 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1604 _id_nsr
= nsrs_detailed_item
["nsrId"]
1606 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1607 if netslice_subnet
["nss-id"] == service
["id"]:
1608 indata_ns
= netslice_subnet
1612 if service
.get("instantiation-parameters"):
1613 indata_ns
= deepcopy(service
["instantiation-parameters"])
1614 # del service["instantiation-parameters"]
1616 indata_ns
["nsdId"] = service
["_id"]
1617 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1618 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1619 indata_ns
["nsDescription"] = service
["description"]
1620 if slice_request
.get("ssh_keys"):
1621 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1624 for ns_param
in ns_params
:
1625 if ns_param
.get("id") == service
["id"]:
1626 copy_ns_param
= deepcopy(ns_param
)
1627 del copy_ns_param
["id"]
1628 indata_ns
.update(copy_ns_param
)
1631 # Creates Nsr objects
1632 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1633 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1634 "nss-id": service
["id"], "nslcmop_instantiate": None}
1635 indata_ns
["nss-id"] = service
["id"]
1636 nsrs_list
.append(nsrs_item
)
1637 nsi_netslice_subnet
.append(indata_ns
)
1638 nsr_ref
= {"nsr-ref": _id_nsr
}
1639 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1641 # Adding the nsrs list to the nsi
1642 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1643 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1644 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1646 # Creating the entry in the database
1647 self
.db
.create("nsis", nsi_descriptor
)
1648 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1650 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1651 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1652 raise EngineException("Error {}: {}".format(step
, e
))
1653 except ValidationError
as e
:
1654 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1656 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1657 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1660 class NsiLcmOpTopic(BaseTopic
):
1663 operation_schema
= { # mapping between operation and jsonschema to validate
1664 "instantiate": nsi_instantiate
,
1668 def __init__(self
, db
, fs
, msg
, auth
):
1669 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1670 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
1672 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1674 Check that user has enter right parameters for the operation
1675 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1676 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1677 :param indata: descriptor with the parameters of the operation
1681 nstd
= nsir
["network-slice-template"]
1683 def check_valid_netslice_subnet_id(nstId
):
1684 # TODO change to vnfR (??)
1685 for netslice_subnet
in nstd
["netslice-subnet"]:
1686 if nstId
== netslice_subnet
["id"]:
1687 nsd_id
= netslice_subnet
["nsd-ref"]
1688 if nsd_id
not in nsds
:
1689 _filter
= self
._get
_project
_filter
(session
)
1690 _filter
["id"] = nsd_id
1691 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
1694 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1695 "nst:netslice-subnet".format(nstId
))
1696 if operation
== "instantiate":
1697 # check the existance of netslice-subnet items
1698 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1699 check_valid_netslice_subnet_id(in_nst
["id"])
1701 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1707 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1708 "statusEnteredTime": now
,
1709 "netsliceInstanceId": netsliceInstanceId
,
1710 "lcmOperationType": operation
,
1712 "isAutomaticInvocation": False,
1713 "operationParams": params
,
1714 "isCancelPending": False,
1716 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1717 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1722 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1723 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1724 if nst_sb_item
.get("is-shared-nss"):
1725 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1726 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1727 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1728 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1729 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1730 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1731 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1733 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1734 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1736 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1738 Performs a new operation over a ns
1739 :param rollback: list to append created items at database in case a rollback must to be done
1740 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1741 :param indata: descriptor with the parameters of the operation. It must contains among others
1742 netsliceInstanceId: _id of the nsir to perform the operation
1743 operation: it can be: instantiate, terminate, action, TODO: update, heal
1744 :param kwargs: used to override the indata descriptor
1745 :param headers: http request headers
1746 :return: id of the nslcmops
1749 # Override descriptor with query string kwargs
1750 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1751 operation
= indata
["lcmOperationType"]
1752 netsliceInstanceId
= indata
["netsliceInstanceId"]
1753 validate_input(indata
, self
.operation_schema
[operation
])
1755 # get nsi from netsliceInstanceId
1756 _filter
= self
._get
_project
_filter
(session
)
1757 _filter
["_id"] = netsliceInstanceId
1758 nsir
= self
.db
.get_one("nsis", _filter
)
1759 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
1763 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1764 if operation
== "terminate" and indata
.get("autoremove"):
1765 # NSIR must be deleted
1766 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1767 if operation
!= "instantiate":
1768 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1769 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1771 if operation
== "instantiate" and not session
["force"]:
1772 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1773 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1775 # Creating all the NS_operation (nslcmop)
1776 # Get service list from db
1777 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1779 # nslcmops_item = None
1780 for index
, nsr_item
in enumerate(nsrs_list
):
1781 nsr_id
= nsr_item
["nsrId"]
1782 if nsr_item
.get("shared"):
1783 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1784 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1785 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1786 _filter
["_id.ne"] = netsliceInstanceId
1787 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1788 if operation
== "terminate":
1789 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1790 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1791 if nsi
: # other nsi is using this nsr and it needs this nsr instantiated
1792 continue # do not create nsilcmop
1794 # looks the first nsi fulfilling the conditions but not being the current NSIR
1796 nsi_nsr_item
= next(n
for n
in nsi
["_admin"]["nsrs-detailed-list"] if
1797 n
["nsrId"] == nsr_id
and n
["shared"] and
1798 n
["nslcmop_instantiate"])
1799 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1800 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1801 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1802 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1803 # continue to not create nslcmop since nsrs is shared and nsrs was created
1806 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1811 "lcmOperationType": operation
,
1812 "nsInstanceId": nsr_id
,
1813 # Including netslice_id in the ns instantiate Operation
1814 "netsliceInstanceId": netsliceInstanceId
,
1816 if operation
== "instantiate":
1817 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1818 indata_ns
.update(service
["instantiate_params"])
1820 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1821 # message via kafka bus
1822 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, None, headers
,
1824 nslcmops
.append(nslcmop
)
1825 if operation
== "instantiate":
1826 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1827 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1828 except (DbException
, EngineException
) as e
:
1829 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1830 self
.logger
.info(logging_prefix
+ "skipping NS={} because not found".format(nsr_id
))
1836 indata
["nslcmops_ids"] = nslcmops
1837 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1839 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1840 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1841 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1842 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1843 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1845 except ValidationError
as e
:
1846 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1848 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1849 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1851 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1852 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)