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_action
, ns_scale
, nsi_instantiate
22 from osm_nbi
.base_topic
import BaseTopic
, EngineException
, get_iterable
, deep_get
23 # from descriptor_topics import DescriptorTopic
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 re
import match
# For checking that additional parameter names are valid Jinja2 identifiers
30 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
33 class NsrTopic(BaseTopic
):
36 schema_new
= ns_instantiate
38 def __init__(self
, db
, fs
, msg
, auth
):
39 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
41 def _check_descriptor_dependencies(self
, session
, descriptor
):
43 Check that the dependent descriptors exist on a new descriptor or edition
44 :param session: client session information
45 :param descriptor: descriptor to be inserted or edit
46 :return: None or raises exception
48 if not descriptor
.get("nsdId"):
50 nsd_id
= descriptor
["nsdId"]
51 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
52 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
53 http_code
=HTTPStatus
.CONFLICT
)
56 def format_on_new(content
, project_id
=None, make_public
=False):
57 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
58 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
61 def check_conflict_on_del(self
, session
, _id
, db_content
):
63 Check that NSR is not instantiated
64 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
65 :param _id: nsr internal id
66 :param db_content: The database content of the nsr
67 :return: None or raises EngineException with the conflict
72 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
73 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
74 "Launch 'terminate' operation first; or force deletion".format(_id
),
75 http_code
=HTTPStatus
.CONFLICT
)
77 def delete_extra(self
, session
, _id
, db_content
):
79 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
80 Set usageState of pdu, vnfd, nsd
81 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
82 :param _id: server internal id
83 :param db_content: The database content of the descriptor
84 :return: None if ok or raises EngineException with the problem
86 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
87 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
88 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
90 # set all used pdus as free
91 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
92 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
96 used_nsd_id
= nsr
.get("nsd-id")
98 # check if used by another NSR
99 nsrs_list
= self
.db
.get_one("nsrs", {"nsd-id": used_nsd_id
},
100 fail_on_empty
=False, fail_on_more
=False)
102 self
.db
.set_one("nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"})
104 # Set VNFD usageState
105 used_vnfd_id_list
= nsr
.get("vnfd-id")
106 if used_vnfd_id_list
:
107 for used_vnfd_id
in used_vnfd_id_list
:
108 # check if used by another NSR
109 nsrs_list
= self
.db
.get_one("nsrs", {"vnfd-id": used_vnfd_id
},
110 fail_on_empty
=False, fail_on_more
=False)
112 self
.db
.set_one("vnfds", {"_id": used_vnfd_id
}, {"_admin.usageState": "NOT_IN_USE"})
115 def _format_ns_request(ns_request
):
116 formated_request
= copy(ns_request
)
117 formated_request
.pop("additionalParamsForNs", None)
118 formated_request
.pop("additionalParamsForVnf", None)
119 return formated_request
122 def _format_addional_params(ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None):
124 Get and format user additional params for NS or VNF
125 :param ns_request: User instantiation additional parameters
126 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
127 :param descriptor: If not None it check that needed parameters of descriptor are supplied
128 :return: a formatted copy of additional params or None if not supplied
130 additional_params
= None
131 if not member_vnf_index
:
132 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
133 where_
= "additionalParamsForNs"
134 elif ns_request
.get("additionalParamsForVnf"):
135 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index
)
136 item
= next((x
for x
in ns_request
["additionalParamsForVnf"] if x
["member-vnf-index"] == member_vnf_index
),
139 additional_params
= copy(item
.get("additionalParams")) or {}
140 if vdu_id
and item
.get("additionalParamsForVdu"):
141 item_vdu
= next((x
for x
in item
["additionalParamsForVdu"] if x
["vdu_id"] == vdu_id
), None)
142 if item_vdu
and item_vdu
.get("additionalParams"):
143 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
144 additional_params
= item_vdu
["additionalParams"]
146 additional_params
= {}
147 if item
.get("additionalParamsForKdu"):
148 item_kdu
= next((x
for x
in item
["additionalParamsForKdu"] if x
["kdu_name"] == kdu_name
), None)
149 if item_kdu
and item_kdu
.get("additionalParams"):
150 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(kdu_name
)
151 additional_params
= item_kdu
["additionalParams"]
153 if additional_params
:
154 for k
, v
in additional_params
.items():
155 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
156 if not kdu_name
and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k
):
157 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
158 "and underscores, and cannot start with a digit"
160 # END Check that additional parameter names are valid Jinja2 identifiers
161 if not isinstance(k
, str):
162 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
163 if "." in k
or "$" in k
:
164 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
165 if isinstance(v
, (dict, tuple, list)):
166 additional_params
[k
] = "!!yaml " + safe_dump(v
)
169 # check that enough parameters are supplied for the initial-config-primitive
170 # TODO: check for cloud-init
173 initial_primitives
= None
175 vdud
= next(x
for x
in descriptor
["vdu"] if x
["id"] == vdu_id
)
176 initial_primitives
= deep_get(vdud
, ("vdu-configuration", "initial-config-primitive"))
178 initial_primitives
= deep_get(descriptor
, ("vnf-configuration", "initial-config-primitive"))
180 initial_primitives
= deep_get(descriptor
, ("ns-configuration", "initial-config-primitive"))
182 for initial_primitive
in get_iterable(initial_primitives
):
183 for param
in get_iterable(initial_primitive
.get("parameter")):
184 if param
["value"].startswith("<") and param
["value"].endswith(">"):
185 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
187 if not additional_params
or param
["value"][1:-1] not in additional_params
:
188 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
189 "initial-config-primitive[name={}] not supplied".
190 format(param
["value"], descriptor
["id"],
191 initial_primitive
["name"]))
193 return additional_params
or None
195 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
197 Creates a new nsr into database. It also creates needed vnfrs
198 :param rollback: list to append the created items at database in case a rollback must be done
199 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
200 :param indata: params to be used for the nsr
201 :param kwargs: used to override the indata descriptor
202 :param headers: http request headers
203 :return: the _id of nsr descriptor created at database. Or an exception of type
204 EngineException, ValidationError, DbException, FsException, MsgException.
205 Note: Exceptions are not captured on purpose. They should be captured at called
209 step
= "checking quotas"
210 self
.check_quota(session
)
212 step
= "validating input parameters"
213 ns_request
= self
._remove
_envelop
(indata
)
214 # Override descriptor with query string kwargs
215 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
216 self
._validate
_input
_new
(ns_request
, session
["force"])
219 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
220 _filter
= self
._get
_project
_filter
(session
)
221 _filter
["_id"] = ns_request
["nsdId"]
222 nsd
= self
.db
.get_one("nsds", _filter
)
225 nsr_id
= str(uuid4())
228 step
= "filling nsr from input data"
230 "name": ns_request
["nsName"],
231 "name-ref": ns_request
["nsName"],
232 "short-name": ns_request
["nsName"],
233 "admin-status": "ENABLED",
235 "datacenter": ns_request
["vimAccountId"],
236 "resource-orchestrator": "osmopenmano",
237 "description": ns_request
.get("nsDescription", ""),
238 "constituent-vnfr-ref": [],
240 "operational-status": "init", # typedef ns-operational-
241 "config-status": "init", # typedef config-states
242 "detailed-status": "scheduled",
244 "orchestration-progress": {},
245 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
248 "nsd-name-ref": nsd
["name"],
249 "operational-events": [], # "id", "timestamp", "description", "event",
250 "nsd-ref": nsd
["id"],
251 "nsd-id": nsd
["_id"],
253 "instantiate_params": self
._format
_ns
_request
(ns_request
),
254 "additionalParamsForNs": self
._format
_addional
_params
(ns_request
, descriptor
=nsd
),
255 "ns-instance-config-ref": nsr_id
,
258 # "input-parameter": xpath, value,
259 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
261 ns_request
["nsr_id"] = nsr_id
264 nsr_descriptor
["vld"] = []
265 for nsd_vld
in nsd
.get("vld"):
266 nsr_descriptor
["vld"].append(
267 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in nsd_vld
})
271 for member_vnf
in nsd
.get("constituent-vnfd", ()):
272 vnfd_id
= member_vnf
["vnfd-id-ref"]
273 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
274 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
275 if vnfd_id
not in needed_vnfds
:
277 _filter
["id"] = vnfd_id
278 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
281 needed_vnfds
[vnfd_id
] = vnfd
282 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
284 vnfd
= needed_vnfds
[vnfd_id
]
285 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
286 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
287 vnfr_id
= str(uuid4())
291 "nsr-id-ref": nsr_id
,
292 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
293 "additionalParamsForVnf": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
296 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
298 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
299 "vim-account-id": None,
301 "connection-point": [],
302 "ip-address": None, # mgmt-interface filled by LCM
306 if vnfd
.get("internal-vld"):
307 vnfr_descriptor
["vld"] = []
308 for vnfd_vld
in vnfd
.get("internal-vld"):
309 vnfr_descriptor
["vld"].append(
310 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
313 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
314 for cp
in vnfd
.get("connection-point", ()):
317 "connection-point-id": cp
.get("id"),
319 # "ip-address", "mac-address" # filled by LCM
320 # vim-id # TODO it would be nice having a vim port id
322 vnfr_descriptor
["connection-point"].append(vnf_cp
)
324 # Create k8s-cluster information
325 if vnfd
.get("k8s-cluster"):
326 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
327 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
328 if net
.get("external-connection-point-ref"):
329 for nsd_vld
in get_iterable(nsd
.get("vld")):
330 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
331 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
332 net
["external-connection-point-ref"] and \
333 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
334 net
["ns-vld-id"] = nsd_vld
["id"]
339 elif net
.get("internal-connection-point-ref"):
340 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
341 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
342 if vnfd_ivld_icp
.get("id-ref") == net
["internal-connection-point-ref"]:
343 net
["vnf-vld-id"] = vnfd_ivld
["id"]
349 for kdu
in get_iterable(vnfd
.get("kdu")):
350 kdur
= {x
: kdu
[x
] for x
in kdu
if x
in ("helm-chart", "juju-bundle")}
351 kdur
["kdu-name"] = kdu
["name"]
352 # TODO "name": "" Name of the VDU in the VIM
353 kdur
["ip-address"] = None # mgmt-interface filled by LCM
354 kdur
["k8s-cluster"] = {}
355 kdur
["additionalParams"] = self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
356 kdu_name
=kdu
["name"], descriptor
=vnfd
)
357 if not vnfr_descriptor
.get("kdur"):
358 vnfr_descriptor
["kdur"] = []
359 vnfr_descriptor
["kdur"].append(kdur
)
361 for vdu
in vnfd
.get("vdu", ()):
363 "vdu-id-ref": vdu
["id"],
364 # TODO "name": "" Name of the VDU in the VIM
365 "ip-address": None, # mgmt-interface filled by LCM
366 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
367 "internal-connection-point": [],
369 "additionalParams": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
370 vdu_id
=vdu
["id"], descriptor
=vnfd
)
372 if vdu
.get("pdu-type"):
373 vdur
["pdu-type"] = vdu
["pdu-type"]
374 # TODO volumes: name, volume-id
375 for icp
in vdu
.get("internal-connection-point", ()):
378 "connection-point-id": icp
["id"],
379 "name": icp
.get("name"),
380 # "ip-address", "mac-address" # filled by LCM
381 # vim-id # TODO it would be nice having a vim port id
383 vdur
["internal-connection-point"].append(vdu_icp
)
384 for iface
in vdu
.get("interface", ()):
386 "name": iface
.get("name"),
387 # "ip-address", "mac-address" # filled by LCM
388 # vim-id # TODO it would be nice having a vim port id
390 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
391 vdu_iface
["mgmt-vnf"] = True
392 if iface
.get("mgmt-interface"):
393 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
395 # look for network where this interface is connected
396 if iface
.get("external-connection-point-ref"):
397 for nsd_vld
in get_iterable(nsd
.get("vld")):
398 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
399 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
400 iface
["external-connection-point-ref"] and \
401 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
402 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
407 elif iface
.get("internal-connection-point-ref"):
408 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
409 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
410 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
411 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
417 vdur
["interfaces"].append(vdu_iface
)
418 count
= vdu
.get("count", 1)
421 count
= int(count
) # TODO remove when descriptor serialized with payngbind
422 for index
in range(0, count
):
424 vdur
= deepcopy(vdur
)
425 vdur
["_id"] = str(uuid4())
426 vdur
["count-index"] = index
427 vnfr_descriptor
["vdur"].append(vdur
)
429 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
430 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
433 self
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
434 self
.db
.create("vnfrs", vnfr_descriptor
)
435 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
436 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
438 step
= "creating nsr at database"
439 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
440 self
.db
.create("nsrs", nsr_descriptor
)
441 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
443 step
= "creating nsr temporal folder"
444 self
.fs
.mkdir(nsr_id
)
447 except (ValidationError
, EngineException
, DbException
, MsgException
, FsException
) as e
:
448 raise type(e
)("{} while '{}".format(e
, step
), http_code
=e
.http_code
)
450 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
451 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
454 class VnfrTopic(BaseTopic
):
458 def __init__(self
, db
, fs
, msg
, auth
):
459 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
461 def delete(self
, session
, _id
, dry_run
=False):
462 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
464 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
465 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
467 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
468 # Not used because vnfrs are created and deleted by NsrTopic class directly
469 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
472 class NsLcmOpTopic(BaseTopic
):
475 operation_schema
= { # mapping between operation and jsonschema to validate
476 "instantiate": ns_instantiate
,
482 def __init__(self
, db
, fs
, msg
, auth
):
483 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
485 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
487 Check that user has enter right parameters for the operation
488 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
489 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
490 :param indata: descriptor with the parameters of the operation
493 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
498 def check_valid_vnf_member_index(member_vnf_index
):
499 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
500 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
501 return vnf_member_index_to_vnfd
[member_vnf_index
]
502 vnfr
= self
.db
.get_one("vnfrs",
503 {"nsr-id-ref": nsr
["_id"], "member-vnf-index-ref": member_vnf_index
},
506 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
507 "nsd:constituent-vnfd".format(member_vnf_index
))
508 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
510 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
511 format(vnfr
["vnfd-id"]))
512 vnf_member_index_to_vnfd
[member_vnf_index
] = vnfd
# add to cache, avoiding a later look for
515 def check_valid_vdu(vnfd
, vdu_id
):
516 for vdud
in get_iterable(vnfd
.get("vdu")):
517 if vdud
["id"] == vdu_id
:
520 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id
))
522 def check_valid_kdu(vnfd
, kdu_name
):
523 for kdud
in get_iterable(vnfd
.get("kdu")):
524 if kdud
["name"] == kdu_name
:
527 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name
))
529 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
531 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
532 for vdu
in get_iterable(vnfd
.get("vdu")):
533 if in_vdu
["id"] == vdu
["id"]:
534 for volume
in get_iterable(in_vdu
.get("volume")):
535 for volumed
in get_iterable(vdu
.get("volumes")):
536 if volumed
["name"] == volume
["name"]:
539 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
540 "volume:name='{}' is not present at vnfd:vdu:volumes list".
541 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
543 for in_iface
in get_iterable(in_vdu
["interface"]):
544 for iface
in get_iterable(vdu
.get("interface")):
545 if in_iface
["name"] == iface
["name"]:
548 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
549 "interface[name='{}'] is not present at vnfd:vdu:interface"
550 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
554 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
555 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
557 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
558 for ivld
in get_iterable(vnfd
.get("internal-vld")):
559 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
560 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
561 for icp
in ivld
["internal-connection-point"]:
562 if in_icp
["id-ref"] == icp
["id-ref"]:
565 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
566 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
567 "vnfd:internal-vld:name/id:internal-connection-point"
568 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
569 in_icp
["id-ref"], vnfd
["id"]))
572 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
573 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
574 in_ivld
["name"], vnfd
["id"]))
576 def check_valid_vim_account(vim_account
):
577 if vim_account
in vim_accounts
:
580 db_filter
= self
._get
_project
_filter
(session
)
581 db_filter
["_id"] = vim_account
582 self
.db
.get_one("vim_accounts", db_filter
)
584 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
585 vim_accounts
.append(vim_account
)
587 def check_valid_wim_account(wim_account
):
588 if not isinstance(wim_account
, str):
590 elif wim_account
in wim_accounts
:
593 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
594 db_filter
["_id"] = wim_account
595 self
.db
.get_one("wim_accounts", db_filter
)
597 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
598 wim_accounts
.append(wim_account
)
600 if operation
== "action":
601 # check vnf_member_index
602 if indata
.get("vnf_member_index"):
603 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
604 if indata
.get("member_vnf_index"):
605 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
606 if indata
.get("vdu_id"):
607 vdud
= check_valid_vdu(vnfd
, indata
["vdu_id"])
608 descriptor_configuration
= vdud
.get("vdu-configuration", {}).get("config-primitive")
609 elif indata
.get("kdu_name"):
610 kdud
= check_valid_kdu(vnfd
, indata
["kdu_name"])
611 descriptor_configuration
= kdud
.get("kdu-configuration", {}).get("config-primitive")
613 descriptor_configuration
= vnfd
.get("vnf-configuration", {}).get("config-primitive")
615 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
617 # For k8s allows default primitives without validating the parameters
618 if indata
.get("kdu_name") and indata
["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
619 # TODO should be checked that rollback only can contains revsision_numbe????
620 if not indata
.get("member_vnf_index"):
621 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
622 .format(indata
["primitive"]))
624 # if not, check primitive
625 for config_primitive
in get_iterable(descriptor_configuration
):
626 if indata
["primitive"] == config_primitive
["name"]:
627 # check needed primitive_params are provided
628 if indata
.get("primitive_params"):
629 in_primitive_params_copy
= copy(indata
["primitive_params"])
631 in_primitive_params_copy
= {}
632 for paramd
in get_iterable(config_primitive
.get("parameter")):
633 if paramd
["name"] in in_primitive_params_copy
:
634 del in_primitive_params_copy
[paramd
["name"]]
635 elif not paramd
.get("default-value"):
636 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
637 paramd
["name"], indata
["primitive"]))
638 # check no extra primitive params are provided
639 if in_primitive_params_copy
:
640 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
641 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
644 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
645 if operation
== "scale":
646 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
647 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
648 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
651 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
652 "present at vnfd:scaling-group-descriptor".format(
653 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
654 if operation
== "instantiate":
656 check_valid_vim_account(indata
["vimAccountId"])
657 check_valid_wim_account(indata
.get("wimAccountId"))
658 for in_vnf
in get_iterable(indata
.get("vnf")):
659 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
660 _check_vnf_instantiation_params(in_vnf
, vnfd
)
661 if in_vnf
.get("vimAccountId"):
662 check_valid_vim_account(in_vnf
["vimAccountId"])
664 for in_vld
in get_iterable(indata
.get("vld")):
665 check_valid_wim_account(in_vld
.get("wimAccountId"))
666 for vldd
in get_iterable(nsd
.get("vld")):
667 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
670 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
673 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
675 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
676 (ip_address, ...) information.
677 Modifies PDU _admin.usageState to 'IN_USE'
678 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
679 :param rollback: list with the database modifications to rollback if needed
680 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
681 :param vim_account: vim_account where this vnfr should be deployed
682 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
683 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
684 of the changed vnfr is needed
686 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
687 "vim-network-name": used at VIM
688 "name": interface name
689 "vnf-vld-id": internal VNFD vld where this interface is connected, or
690 "ns-vld-id": NSD vld where this interface is connected.
691 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
694 ifaces_forcing_vim_network
= []
695 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
696 if not vdur
.get("pdu-type"):
698 pdu_type
= vdur
.get("pdu-type")
699 pdu_filter
= self
._get
_project
_filter
(session
)
700 pdu_filter
["vim_accounts"] = vim_account
701 pdu_filter
["type"] = pdu_type
702 pdu_filter
["_admin.operationalState"] = "ENABLED"
703 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
704 # TODO feature 1417: "shared": True,
706 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
707 for pdu
in available_pdus
:
708 # step 1 check if this pdu contains needed interfaces:
709 match_interfaces
= True
710 for vdur_interface
in vdur
["interfaces"]:
711 for pdu_interface
in pdu
["interfaces"]:
712 if pdu_interface
["name"] == vdur_interface
["name"]:
713 # TODO feature 1417: match per mgmt type
715 else: # no interface found for name
716 match_interfaces
= False
721 raise EngineException(
722 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
723 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
727 "_admin.usageState": pdu
["_admin"]["usageState"],
728 "_admin.usage.vnfr_id": None,
729 "_admin.usage.nsr_id": None,
730 "_admin.usage.vdur": None,
732 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
733 {"_admin.usageState": "IN_USE",
734 "_admin.usage": {"vnfr_id": vnfr
["_id"],
735 "nsr_id": vnfr
["nsr-id-ref"],
736 "vdur": vdur
["vdu-id-ref"]}
738 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
740 # step 3. Fill vnfr info by filling vdur
741 vdu_text
= "vdur.{}".format(vdur_index
)
742 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
743 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
744 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
745 for pdu_interface
in pdu
["interfaces"]:
746 if pdu_interface
["name"] == vdur_interface
["name"]:
747 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
748 for k
, v
in pdu_interface
.items():
749 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
750 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
751 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
752 if pdu_interface
.get("ip-address"):
753 if vdur_interface
.get("mgmt-interface"):
754 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
755 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
756 if vdur_interface
.get("mgmt-vnf"):
757 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
758 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
759 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
760 ifaces_forcing_vim_network
.append({
761 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
762 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
763 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
764 if pdu_interface
.get("vim-network-id"):
765 ifaces_forcing_vim_network
[-1]["vim-network-id"] = pdu_interface
["vim-network-id"]
766 if pdu_interface
.get("vim-network-name"):
767 ifaces_forcing_vim_network
[-1]["vim-network-name"] = pdu_interface
["vim-network-name"]
770 return ifaces_forcing_vim_network
772 def _look_for_k8scluster(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
774 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
775 Fills vnfr.kdur with the selected k8scluster
777 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
778 :param rollback: list with the database modifications to rollback if needed
779 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
780 :param vim_account: vim_account where this vnfr should be deployed
781 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
782 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
783 of the changed vnfr is needed
785 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
786 "vim-network-name": used at VIM
787 "name": interface name
788 "vnf-vld-id": internal VNFD vld where this interface is connected, or
789 "ns-vld-id": NSD vld where this interface is connected.
790 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
793 ifaces_forcing_vim_network
= []
794 if not vnfr
.get("kdur"):
795 return ifaces_forcing_vim_network
797 kdu_filter
= self
._get
_project
_filter
(session
)
798 kdu_filter
["vim_account"] = vim_account
799 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
800 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
802 k8s_requirements
= {} # just for logging
803 for k8scluster
in available_k8sclusters
:
804 if not vnfr
.get("k8s-cluster"):
807 if vnfr
["k8s-cluster"].get("cni"):
808 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
809 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(k8scluster
.get("cni", ())):
811 # restrict by version
812 if vnfr
["k8s-cluster"].get("version"):
813 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
814 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
816 # restrict by number of networks
817 if vnfr
["k8s-cluster"].get("nets"):
818 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
819 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(vnfr
["k8s-cluster"]["nets"]):
823 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
824 .format(k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]))
826 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
827 # step 3. Fill vnfr info by filling kdur
828 kdu_text
= "kdur.{}.".format(kdur_index
)
829 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
830 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
832 # step 4. Check VIM networks that forces the selected k8s_cluster
833 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
834 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
835 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
836 # get a network from k8s_cluster nets. If name matches use this, if not use other
837 if kdur_net
["id"] in k8scluster_net_list
: # name matches
838 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
839 k8scluster_net_list
.remove(kdur_net
["id"])
841 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
842 k8scluster_net_list
.pop(0)
843 vnfr_update_rollback
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = None
844 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
845 if vim_net
and (kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")):
846 ifaces_forcing_vim_network
.append({
847 "name": kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id"),
848 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
849 "ns-vld-id": kdur_net
.get("ns-vld-id"),
850 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
852 # TODO check that this forcing is not incompatible with other forcing
853 return ifaces_forcing_vim_network
855 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
858 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
862 vnfr_update_rollback
= {}
863 member_vnf_index
= vnfr
["member-vnf-index-ref"]
864 # update vim-account-id
866 vim_account
= indata
["vimAccountId"]
867 # check instantiate parameters
868 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
869 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
871 if vnf_inst_params
.get("vimAccountId"):
872 vim_account
= vnf_inst_params
.get("vimAccountId")
874 vnfr_update
["vim-account-id"] = vim_account
875 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
878 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
879 vnfr_update_rollback
)
882 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
883 vnfr_update_rollback
)
884 # update database vnfr
885 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
886 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
888 # Update indada in case pdu forces to use a concrete vim-network-name
889 # TODO check if user has already insert a vim-network-name and raises an error
890 if not ifaces_forcing_vim_network
:
892 for iface_info
in ifaces_forcing_vim_network
:
893 if iface_info
.get("ns-vld-id"):
894 if "vld" not in indata
:
896 indata
["vld"].append({key
: iface_info
[key
] for key
in
897 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
899 elif iface_info
.get("vnf-vld-id"):
900 if "vnf" not in indata
:
902 indata
["vnf"].append({
903 "member-vnf-index": member_vnf_index
,
904 "internal-vld": [{key
: iface_info
[key
] for key
in
905 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
909 def _create_nslcmop(nsr_id
, operation
, params
):
911 Creates a ns-lcm-opp content to be stored at database.
912 :param nsr_id: internal id of the instance
913 :param operation: instantiate, terminate, scale, action, ...
914 :param params: user parameters for the operation
915 :return: dictionary following SOL005 format
922 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
923 "statusEnteredTime": now
,
924 "nsInstanceId": nsr_id
,
925 "lcmOperationType": operation
,
927 "isAutomaticInvocation": False,
928 "operationParams": params
,
929 "isCancelPending": False,
931 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
932 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
937 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
939 Performs a new operation over a ns
940 :param rollback: list to append created items at database in case a rollback must to be done
941 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
942 :param indata: descriptor with the parameters of the operation. It must contains among others
943 nsInstanceId: _id of the nsr to perform the operation
944 operation: it can be: instantiate, terminate, action, TODO: update, heal
945 :param kwargs: used to override the indata descriptor
946 :param headers: http request headers
947 :return: id of the nslcmops
949 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
951 db_filter
= self
._get
_project
_filter
(session
)
952 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
953 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
955 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
956 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
959 # Override descriptor with query string kwargs
960 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
961 operation
= indata
["lcmOperationType"]
962 nsInstanceId
= indata
["nsInstanceId"]
964 validate_input(indata
, self
.operation_schema
[operation
])
966 _filter
= BaseTopic
._get
_project
_filter
(session
)
967 _filter
["_id"] = nsInstanceId
968 nsr
= self
.db
.get_one("nsrs", _filter
)
971 if operation
== "terminate" and slice_object
is False:
972 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
973 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
974 if operation
== "terminate" and indata
.get("autoremove"):
975 # NSR must be deleted
976 return None, None # a none in this case is used to indicate not instantiated. It can be removed
977 if operation
!= "instantiate":
978 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
979 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
981 if operation
== "instantiate" and not session
["force"]:
982 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
983 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
984 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
986 if operation
== "instantiate":
987 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
989 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
990 _id
= nslcmop_desc
["_id"]
991 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
992 self
.db
.create("nslcmops", nslcmop_desc
)
993 rollback
.append({"topic": "nslcmops", "_id": _id
})
995 self
.msg
.write("ns", operation
, nslcmop_desc
)
997 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
998 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
999 # except DbException as e:
1000 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1002 def delete(self
, session
, _id
, dry_run
=False):
1003 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1005 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1006 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1009 class NsiTopic(BaseTopic
):
1013 def __init__(self
, db
, fs
, msg
, auth
):
1014 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1015 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
1018 def _format_ns_request(ns_request
):
1019 formated_request
= copy(ns_request
)
1020 # TODO: Add request params
1021 return formated_request
1024 def _format_addional_params(slice_request
):
1026 Get and format user additional params for NS or VNF
1027 :param slice_request: User instantiation additional parameters
1028 :return: a formatted copy of additional params or None if not supplied
1030 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
1031 if additional_params
:
1032 for k
, v
in additional_params
.items():
1033 if not isinstance(k
, str):
1034 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1036 if "." in k
or "$" in k
:
1037 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1039 if isinstance(v
, (dict, tuple, list)):
1040 additional_params
[k
] = "!!yaml " + safe_dump(v
)
1041 return additional_params
1043 def _check_descriptor_dependencies(self
, session
, descriptor
):
1045 Check that the dependent descriptors exist on a new descriptor or edition
1046 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1047 :param descriptor: descriptor to be inserted or edit
1048 :return: None or raises exception
1050 if not descriptor
.get("nst-ref"):
1052 nstd_id
= descriptor
["nst-ref"]
1053 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
1054 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
1055 http_code
=HTTPStatus
.CONFLICT
)
1057 def check_conflict_on_del(self
, session
, _id
, db_content
):
1059 Check that NSI is not instantiated
1060 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1061 :param _id: nsi internal id
1062 :param db_content: The database content of the _id
1063 :return: None or raises EngineException with the conflict
1065 if session
["force"]:
1068 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
1069 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1070 "Launch 'terminate' operation first; or force deletion".format(_id
),
1071 http_code
=HTTPStatus
.CONFLICT
)
1073 def delete_extra(self
, session
, _id
, db_content
):
1075 Deletes associated nsilcmops from database. Deletes associated filesystem.
1076 Set usageState of nst
1077 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1078 :param _id: server internal id
1079 :param db_content: The database content of the descriptor
1080 :return: None if ok or raises EngineException with the problem
1083 # Deleting the nsrs belonging to nsir
1085 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
1086 nsr_id
= nsrs_detailed_item
["nsrId"]
1087 if nsrs_detailed_item
.get("shared"):
1088 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1089 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
1090 "_id.ne": nsir
["_id"]}
1091 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1092 if nsi
: # last one using nsr
1095 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False)
1096 except (DbException
, EngineException
) as e
:
1097 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1102 # delete related nsilcmops database entries
1103 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
1105 # Check and set used NST usage state
1106 nsir_admin
= nsir
.get("_admin")
1107 if nsir_admin
and nsir_admin
.get("nst-id"):
1108 # check if used by another NSI
1109 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
1110 fail_on_empty
=False, fail_on_more
=False)
1112 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1114 # def delete(self, session, _id, dry_run=False):
1116 # Delete item by its internal _id
1117 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1118 # :param _id: server internal id
1119 # :param dry_run: make checking but do not delete
1120 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1122 # # TODO add admin to filter, validate rights
1123 # BaseTopic.delete(self, session, _id, dry_run=True)
1127 # # Deleting the nsrs belonging to nsir
1128 # nsir = self.db.get_one("nsis", {"_id": _id})
1129 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1130 # nsr_id = nsrs_detailed_item["nsrId"]
1131 # if nsrs_detailed_item.get("shared"):
1132 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1133 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1134 # "_id.ne": nsir["_id"]}
1135 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1136 # if nsi: # last one using nsr
1139 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1140 # except (DbException, EngineException) as e:
1141 # if e.http_code == HTTPStatus.NOT_FOUND:
1145 # # deletes NetSlice instance object
1146 # v = self.db.del_one("nsis", {"_id": _id})
1148 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1149 # _filter = {"netsliceInstanceId": _id}
1150 # self.db.del_list("nsilcmops", _filter)
1152 # # Search if nst is being used by other nsi
1153 # nsir_admin = nsir.get("_admin")
1155 # if nsir_admin.get("nst-id"):
1156 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1157 # fail_on_empty=False, fail_on_more=False)
1159 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1162 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1164 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1165 :param rollback: list to append the created items at database in case a rollback must be done
1166 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1167 :param indata: params to be used for the nsir
1168 :param kwargs: used to override the indata descriptor
1169 :param headers: http request headers
1170 :return: the _id of nsi descriptor created at database
1174 step
= "checking quotas"
1175 self
.check_quota(session
)
1178 slice_request
= self
._remove
_envelop
(indata
)
1179 # Override descriptor with query string kwargs
1180 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
1181 self
._validate
_input
_new
(slice_request
, session
["force"])
1184 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1185 _filter
= self
._get
_project
_filter
(session
)
1186 _filter
["_id"] = slice_request
["nstId"]
1187 nstd
= self
.db
.get_one("nsts", _filter
)
1190 nstd
.pop("_admin", None)
1191 nstd_id
= nstd
.pop("_id", None)
1192 nsi_id
= str(uuid4())
1193 step
= "filling nsi_descriptor with input data"
1198 "name": slice_request
["nsiName"],
1199 "description": slice_request
.get("nsiDescription", ""),
1200 "datacenter": slice_request
["vimAccountId"],
1201 "nst-ref": nstd
["id"],
1202 "instantiation_parameters": slice_request
,
1203 "network-slice-template": nstd
,
1207 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1210 step
= "creating nsi at database"
1211 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1212 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1213 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1214 nsi_descriptor
["_admin"]["deployed"] = {}
1215 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1216 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1218 # Creating netslice-vld for the RO.
1219 step
= "creating netslice-vld at database"
1221 # Building the vlds list to be deployed
1222 # From netslice descriptors, creating the initial list
1225 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1226 # Getting template Instantiation parameters from NST
1227 nsi_vld
= deepcopy(netslice_vlds
)
1228 nsi_vld
["shared-nsrs-list"] = []
1229 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1230 nsi_vlds
.append(nsi_vld
)
1232 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1233 # Creating netslice-subnet_record.
1237 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1238 for member_ns
in nstd
["netslice-subnet"]:
1239 nsd_id
= member_ns
["nsd-ref"]
1240 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1241 member_ns
["nsd-ref"], member_ns
["id"])
1242 if nsd_id
not in needed_nsds
:
1244 _filter
["id"] = nsd_id
1245 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1248 needed_nsds
[nsd_id
] = nsd
1250 nsd
= needed_nsds
[nsd_id
]
1251 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1252 services
.append(member_ns
)
1254 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1255 member_ns
["nsd-ref"], member_ns
["id"])
1257 # creates Network Services records (NSRs)
1258 step
= "creating nsrs at database using NsrTopic.new()"
1259 ns_params
= slice_request
.get("netslice-subnet")
1261 nsi_netslice_subnet
= []
1262 for service
in services
:
1263 # Check if the netslice-subnet is shared and if it is share if the nss exists
1266 # Is the nss shared and instantiated?
1267 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1268 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1269 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1270 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1271 if nsi
and service
.get("is-shared-nss"):
1272 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1273 for nsrs_detailed_item
in nsrs_detailed_list
:
1274 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1275 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1276 _id_nsr
= nsrs_detailed_item
["nsrId"]
1278 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1279 if netslice_subnet
["nss-id"] == service
["id"]:
1280 indata_ns
= netslice_subnet
1284 if service
.get("instantiation-parameters"):
1285 indata_ns
= deepcopy(service
["instantiation-parameters"])
1286 # del service["instantiation-parameters"]
1288 indata_ns
["nsdId"] = service
["_id"]
1289 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1290 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1291 indata_ns
["nsDescription"] = service
["description"]
1292 if slice_request
.get("ssh_keys"):
1293 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1296 for ns_param
in ns_params
:
1297 if ns_param
.get("id") == service
["id"]:
1298 copy_ns_param
= deepcopy(ns_param
)
1299 del copy_ns_param
["id"]
1300 indata_ns
.update(copy_ns_param
)
1303 # Creates Nsr objects
1304 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1305 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1306 "nss-id": service
["id"], "nslcmop_instantiate": None}
1307 indata_ns
["nss-id"] = service
["id"]
1308 nsrs_list
.append(nsrs_item
)
1309 nsi_netslice_subnet
.append(indata_ns
)
1310 nsr_ref
= {"nsr-ref": _id_nsr
}
1311 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1313 # Adding the nsrs list to the nsi
1314 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1315 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1316 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1318 # Creating the entry in the database
1319 self
.db
.create("nsis", nsi_descriptor
)
1320 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1322 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1323 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1324 raise EngineException("Error {}: {}".format(step
, e
))
1325 except ValidationError
as e
:
1326 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1328 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1329 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1332 class NsiLcmOpTopic(BaseTopic
):
1335 operation_schema
= { # mapping between operation and jsonschema to validate
1336 "instantiate": nsi_instantiate
,
1340 def __init__(self
, db
, fs
, msg
, auth
):
1341 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1342 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
1344 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1346 Check that user has enter right parameters for the operation
1347 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1348 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1349 :param indata: descriptor with the parameters of the operation
1353 nstd
= nsir
["network-slice-template"]
1355 def check_valid_netslice_subnet_id(nstId
):
1356 # TODO change to vnfR (??)
1357 for netslice_subnet
in nstd
["netslice-subnet"]:
1358 if nstId
== netslice_subnet
["id"]:
1359 nsd_id
= netslice_subnet
["nsd-ref"]
1360 if nsd_id
not in nsds
:
1361 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1364 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1365 "nst:netslice-subnet".format(nstId
))
1366 if operation
== "instantiate":
1367 # check the existance of netslice-subnet items
1368 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1369 check_valid_netslice_subnet_id(in_nst
["id"])
1371 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1377 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1378 "statusEnteredTime": now
,
1379 "netsliceInstanceId": netsliceInstanceId
,
1380 "lcmOperationType": operation
,
1382 "isAutomaticInvocation": False,
1383 "operationParams": params
,
1384 "isCancelPending": False,
1386 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1387 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1392 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1393 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1394 if nst_sb_item
.get("is-shared-nss"):
1395 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1396 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1397 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1398 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1399 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1400 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1401 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1403 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1404 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1406 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1408 Performs a new operation over a ns
1409 :param rollback: list to append created items at database in case a rollback must to be done
1410 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1411 :param indata: descriptor with the parameters of the operation. It must contains among others
1412 netsliceInstanceId: _id of the nsir to perform the operation
1413 operation: it can be: instantiate, terminate, action, TODO: update, heal
1414 :param kwargs: used to override the indata descriptor
1415 :param headers: http request headers
1416 :return: id of the nslcmops
1419 # Override descriptor with query string kwargs
1420 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1421 operation
= indata
["lcmOperationType"]
1422 netsliceInstanceId
= indata
["netsliceInstanceId"]
1423 validate_input(indata
, self
.operation_schema
[operation
])
1425 # get nsi from netsliceInstanceId
1426 _filter
= self
._get
_project
_filter
(session
)
1427 _filter
["_id"] = netsliceInstanceId
1428 nsir
= self
.db
.get_one("nsis", _filter
)
1432 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1433 if operation
== "terminate" and indata
.get("autoremove"):
1434 # NSIR must be deleted
1435 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1436 if operation
!= "instantiate":
1437 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1438 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1440 if operation
== "instantiate" and not session
["force"]:
1441 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1442 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1444 # Creating all the NS_operation (nslcmop)
1445 # Get service list from db
1446 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1448 # nslcmops_item = None
1449 for index
, nsr_item
in enumerate(nsrs_list
):
1451 if nsr_item
.get("shared"):
1452 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1453 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item
["nsrId"]
1454 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1455 _filter
["_id.ne"] = netsliceInstanceId
1456 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1457 if operation
== "terminate":
1458 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1459 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1461 # looks the first nsi fulfilling the conditions but not being the current NSIR
1463 nsi_admin_shared
= nsi
["_admin"]["nsrs-detailed-list"]
1464 for nsi_nsr_item
in nsi_admin_shared
:
1465 if nsi_nsr_item
["nsd-id"] == nsr_item
["nsd-id"] and nsi_nsr_item
["shared"]:
1466 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1467 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1468 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1469 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1471 # continue to not create nslcmop since nsrs is shared and nsrs was created
1474 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1477 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1479 indata_ns
= service
["instantiate_params"]
1480 indata_ns
["lcmOperationType"] = operation
1481 indata_ns
["nsInstanceId"] = service
["_id"]
1482 # Including netslice_id in the ns instantiate Operation
1483 indata_ns
["netsliceInstanceId"] = netsliceInstanceId
1484 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1485 # message via kafka bus
1486 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
,
1488 nslcmops
.append(nslcmop
)
1489 if operation
== "terminate":
1491 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1492 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1493 except (DbException
, EngineException
) as e
:
1494 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1495 self
.logger
.info("HTTPStatus.NOT_FOUND")
1501 indata
["nslcmops_ids"] = nslcmops
1502 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1504 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1505 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1506 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1507 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1508 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1510 except ValidationError
as e
:
1511 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1513 def delete(self
, session
, _id
, dry_run
=False):
1514 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1516 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1517 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)