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
, not_send_msg
=None):
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 :param not_send_msg: To not send message (False) or store content (list) instead
85 :return: None if ok or raises EngineException with the problem
87 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
88 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
89 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
91 # set all used pdus as free
92 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
93 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
97 used_nsd_id
= nsr
.get("nsd-id")
99 # check if used by another NSR
100 nsrs_list
= self
.db
.get_one("nsrs", {"nsd-id": used_nsd_id
},
101 fail_on_empty
=False, fail_on_more
=False)
103 self
.db
.set_one("nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"})
105 # Set VNFD usageState
106 used_vnfd_id_list
= nsr
.get("vnfd-id")
107 if used_vnfd_id_list
:
108 for used_vnfd_id
in used_vnfd_id_list
:
109 # check if used by another NSR
110 nsrs_list
= self
.db
.get_one("nsrs", {"vnfd-id": used_vnfd_id
},
111 fail_on_empty
=False, fail_on_more
=False)
113 self
.db
.set_one("vnfds", {"_id": used_vnfd_id
}, {"_admin.usageState": "NOT_IN_USE"})
116 def _format_ns_request(ns_request
):
117 formated_request
= copy(ns_request
)
118 formated_request
.pop("additionalParamsForNs", None)
119 formated_request
.pop("additionalParamsForVnf", None)
120 return formated_request
123 def _format_addional_params(ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None):
125 Get and format user additional params for NS or VNF
126 :param ns_request: User instantiation additional parameters
127 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
128 :param descriptor: If not None it check that needed parameters of descriptor are supplied
129 :return: a formatted copy of additional params or None if not supplied
131 additional_params
= None
132 if not member_vnf_index
:
133 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
134 where_
= "additionalParamsForNs"
135 elif ns_request
.get("additionalParamsForVnf"):
136 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index
)
137 item
= next((x
for x
in ns_request
["additionalParamsForVnf"] if x
["member-vnf-index"] == member_vnf_index
),
140 additional_params
= copy(item
.get("additionalParams")) or {}
141 if vdu_id
and item
.get("additionalParamsForVdu"):
142 item_vdu
= next((x
for x
in item
["additionalParamsForVdu"] if x
["vdu_id"] == vdu_id
), None)
143 if item_vdu
and item_vdu
.get("additionalParams"):
144 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
145 additional_params
= item_vdu
["additionalParams"]
147 additional_params
= {}
148 if item
.get("additionalParamsForKdu"):
149 item_kdu
= next((x
for x
in item
["additionalParamsForKdu"] if x
["kdu_name"] == kdu_name
), None)
150 if item_kdu
and item_kdu
.get("additionalParams"):
151 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(kdu_name
)
152 additional_params
= item_kdu
["additionalParams"]
154 if additional_params
:
155 for k
, v
in additional_params
.items():
156 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
157 if not kdu_name
and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k
):
158 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
159 "and underscores, and cannot start with a digit"
161 # END Check that additional parameter names are valid Jinja2 identifiers
162 if not isinstance(k
, str):
163 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
164 if "." in k
or "$" in k
:
165 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
166 if isinstance(v
, (dict, tuple, list)):
167 additional_params
[k
] = "!!yaml " + safe_dump(v
)
170 # check that enough parameters are supplied for the initial-config-primitive
171 # TODO: check for cloud-init
174 initial_primitives
= None
176 vdud
= next(x
for x
in descriptor
["vdu"] if x
["id"] == vdu_id
)
177 initial_primitives
= deep_get(vdud
, ("vdu-configuration", "initial-config-primitive"))
179 initial_primitives
= deep_get(descriptor
, ("vnf-configuration", "initial-config-primitive"))
181 initial_primitives
= deep_get(descriptor
, ("ns-configuration", "initial-config-primitive"))
183 for initial_primitive
in get_iterable(initial_primitives
):
184 for param
in get_iterable(initial_primitive
.get("parameter")):
185 if param
["value"].startswith("<") and param
["value"].endswith(">"):
186 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
188 if not additional_params
or param
["value"][1:-1] not in additional_params
:
189 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
190 "initial-config-primitive[name={}] not supplied".
191 format(param
["value"], descriptor
["id"],
192 initial_primitive
["name"]))
194 return additional_params
or None
196 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
198 Creates a new nsr into database. It also creates needed vnfrs
199 :param rollback: list to append the created items at database in case a rollback must be done
200 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
201 :param indata: params to be used for the nsr
202 :param kwargs: used to override the indata descriptor
203 :param headers: http request headers
204 :return: the _id of nsr descriptor created at database. Or an exception of type
205 EngineException, ValidationError, DbException, FsException, MsgException.
206 Note: Exceptions are not captured on purpose. They should be captured at called
210 step
= "checking quotas"
211 self
.check_quota(session
)
213 step
= "validating input parameters"
214 ns_request
= self
._remove
_envelop
(indata
)
215 # Override descriptor with query string kwargs
216 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
217 self
._validate
_input
_new
(ns_request
, session
["force"])
220 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
221 _filter
= self
._get
_project
_filter
(session
)
222 _filter
["_id"] = ns_request
["nsdId"]
223 nsd
= self
.db
.get_one("nsds", _filter
)
226 nsr_id
= str(uuid4())
229 step
= "filling nsr from input data"
231 "name": ns_request
["nsName"],
232 "name-ref": ns_request
["nsName"],
233 "short-name": ns_request
["nsName"],
234 "admin-status": "ENABLED",
235 "nsState": "NOT_INSTANTIATED",
236 "currentOperation": "IDLE",
237 "currentOperationID": None,
238 "errorDescription": None,
240 "deploymentStatus": None,
241 "configurationStatus": None,
244 "datacenter": ns_request
["vimAccountId"],
245 "resource-orchestrator": "osmopenmano",
246 "description": ns_request
.get("nsDescription", ""),
247 "constituent-vnfr-ref": [],
249 "operational-status": "init", # typedef ns-operational-
250 "config-status": "init", # typedef config-states
251 "detailed-status": "scheduled",
253 "orchestration-progress": {},
254 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
257 "nsd-name-ref": nsd
["name"],
258 "operational-events": [], # "id", "timestamp", "description", "event",
259 "nsd-ref": nsd
["id"],
260 "nsd-id": nsd
["_id"],
262 "instantiate_params": self
._format
_ns
_request
(ns_request
),
263 "additionalParamsForNs": self
._format
_addional
_params
(ns_request
, descriptor
=nsd
),
264 "ns-instance-config-ref": nsr_id
,
267 # "input-parameter": xpath, value,
268 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
270 ns_request
["nsr_id"] = nsr_id
273 nsr_descriptor
["vld"] = []
274 for nsd_vld
in nsd
.get("vld"):
275 nsr_descriptor
["vld"].append(
276 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in nsd_vld
})
280 for member_vnf
in nsd
.get("constituent-vnfd", ()):
281 vnfd_id
= member_vnf
["vnfd-id-ref"]
282 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
283 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
284 if vnfd_id
not in needed_vnfds
:
286 _filter
["id"] = vnfd_id
287 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
290 needed_vnfds
[vnfd_id
] = vnfd
291 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
293 vnfd
= needed_vnfds
[vnfd_id
]
294 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
295 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
296 vnfr_id
= str(uuid4())
300 "nsr-id-ref": nsr_id
,
301 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
302 "additionalParamsForVnf": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
305 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
307 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
308 "vim-account-id": None,
310 "connection-point": [],
311 "ip-address": None, # mgmt-interface filled by LCM
315 if vnfd
.get("internal-vld"):
316 vnfr_descriptor
["vld"] = []
317 for vnfd_vld
in vnfd
.get("internal-vld"):
318 vnfr_descriptor
["vld"].append(
319 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
322 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
323 for cp
in vnfd
.get("connection-point", ()):
326 "connection-point-id": cp
.get("id"),
328 # "ip-address", "mac-address" # filled by LCM
329 # vim-id # TODO it would be nice having a vim port id
331 vnfr_descriptor
["connection-point"].append(vnf_cp
)
333 # Create k8s-cluster information
334 if vnfd
.get("k8s-cluster"):
335 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
336 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
337 if net
.get("external-connection-point-ref"):
338 for nsd_vld
in get_iterable(nsd
.get("vld")):
339 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
340 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
341 net
["external-connection-point-ref"] and \
342 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
343 net
["ns-vld-id"] = nsd_vld
["id"]
348 elif net
.get("internal-connection-point-ref"):
349 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
350 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
351 if vnfd_ivld_icp
.get("id-ref") == net
["internal-connection-point-ref"]:
352 net
["vnf-vld-id"] = vnfd_ivld
["id"]
358 for kdu
in get_iterable(vnfd
.get("kdu")):
359 kdur
= {x
: kdu
[x
] for x
in kdu
if x
in ("helm-chart", "juju-bundle")}
360 kdur
["kdu-name"] = kdu
["name"]
361 # TODO "name": "" Name of the VDU in the VIM
362 kdur
["ip-address"] = None # mgmt-interface filled by LCM
363 kdur
["k8s-cluster"] = {}
364 kdur
["additionalParams"] = self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
365 kdu_name
=kdu
["name"], descriptor
=vnfd
)
366 if not vnfr_descriptor
.get("kdur"):
367 vnfr_descriptor
["kdur"] = []
368 vnfr_descriptor
["kdur"].append(kdur
)
370 for vdu
in vnfd
.get("vdu", ()):
372 "vdu-id-ref": vdu
["id"],
373 # TODO "name": "" Name of the VDU in the VIM
374 "ip-address": None, # mgmt-interface filled by LCM
375 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
376 "internal-connection-point": [],
378 "additionalParams": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
379 vdu_id
=vdu
["id"], descriptor
=vnfd
)
381 if vdu
.get("pdu-type"):
382 vdur
["pdu-type"] = vdu
["pdu-type"]
383 # TODO volumes: name, volume-id
384 for icp
in vdu
.get("internal-connection-point", ()):
387 "connection-point-id": icp
["id"],
388 "name": icp
.get("name"),
389 # "ip-address", "mac-address" # filled by LCM
390 # vim-id # TODO it would be nice having a vim port id
392 vdur
["internal-connection-point"].append(vdu_icp
)
393 for iface
in vdu
.get("interface", ()):
395 "name": iface
.get("name"),
396 # "ip-address", "mac-address" # filled by LCM
397 # vim-id # TODO it would be nice having a vim port id
399 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
400 vdu_iface
["mgmt-vnf"] = True
401 if iface
.get("mgmt-interface"):
402 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
404 # look for network where this interface is connected
405 if iface
.get("external-connection-point-ref"):
406 for nsd_vld
in get_iterable(nsd
.get("vld")):
407 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
408 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
409 iface
["external-connection-point-ref"] and \
410 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
411 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
416 elif iface
.get("internal-connection-point-ref"):
417 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
418 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
419 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
420 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
426 vdur
["interfaces"].append(vdu_iface
)
427 count
= vdu
.get("count", 1)
430 count
= int(count
) # TODO remove when descriptor serialized with payngbind
431 for index
in range(0, count
):
433 vdur
= deepcopy(vdur
)
434 vdur
["_id"] = str(uuid4())
435 vdur
["count-index"] = index
436 vnfr_descriptor
["vdur"].append(vdur
)
438 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
439 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
442 self
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
443 self
.db
.create("vnfrs", vnfr_descriptor
)
444 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
445 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
447 step
= "creating nsr at database"
448 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
449 self
.db
.create("nsrs", nsr_descriptor
)
450 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
452 step
= "creating nsr temporal folder"
453 self
.fs
.mkdir(nsr_id
)
456 except (ValidationError
, EngineException
, DbException
, MsgException
, FsException
) as e
:
457 raise type(e
)("{} while '{}".format(e
, step
), http_code
=e
.http_code
)
459 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
460 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
463 class VnfrTopic(BaseTopic
):
467 def __init__(self
, db
, fs
, msg
, auth
):
468 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
470 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
471 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
473 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
474 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
476 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
477 # Not used because vnfrs are created and deleted by NsrTopic class directly
478 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
481 class NsLcmOpTopic(BaseTopic
):
484 operation_schema
= { # mapping between operation and jsonschema to validate
485 "instantiate": ns_instantiate
,
491 def __init__(self
, db
, fs
, msg
, auth
):
492 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
494 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
496 Check that user has enter right parameters for the operation
497 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
498 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
499 :param indata: descriptor with the parameters of the operation
502 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
507 def check_valid_vnf_member_index(member_vnf_index
):
508 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
509 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
510 return vnf_member_index_to_vnfd
[member_vnf_index
]
511 vnfr
= self
.db
.get_one("vnfrs",
512 {"nsr-id-ref": nsr
["_id"], "member-vnf-index-ref": member_vnf_index
},
515 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
516 "nsd:constituent-vnfd".format(member_vnf_index
))
517 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
519 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
520 format(vnfr
["vnfd-id"]))
521 vnf_member_index_to_vnfd
[member_vnf_index
] = vnfd
# add to cache, avoiding a later look for
524 def check_valid_vdu(vnfd
, vdu_id
):
525 for vdud
in get_iterable(vnfd
.get("vdu")):
526 if vdud
["id"] == vdu_id
:
529 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id
))
531 def check_valid_kdu(vnfd
, kdu_name
):
532 for kdud
in get_iterable(vnfd
.get("kdu")):
533 if kdud
["name"] == kdu_name
:
536 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name
))
538 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
540 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
541 for vdu
in get_iterable(vnfd
.get("vdu")):
542 if in_vdu
["id"] == vdu
["id"]:
543 for volume
in get_iterable(in_vdu
.get("volume")):
544 for volumed
in get_iterable(vdu
.get("volumes")):
545 if volumed
["name"] == volume
["name"]:
548 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
549 "volume:name='{}' is not present at vnfd:vdu:volumes list".
550 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
552 for in_iface
in get_iterable(in_vdu
["interface"]):
553 for iface
in get_iterable(vdu
.get("interface")):
554 if in_iface
["name"] == iface
["name"]:
557 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
558 "interface[name='{}'] is not present at vnfd:vdu:interface"
559 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
563 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
564 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
566 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
567 for ivld
in get_iterable(vnfd
.get("internal-vld")):
568 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
569 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
570 for icp
in ivld
["internal-connection-point"]:
571 if in_icp
["id-ref"] == icp
["id-ref"]:
574 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
575 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
576 "vnfd:internal-vld:name/id:internal-connection-point"
577 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
578 in_icp
["id-ref"], vnfd
["id"]))
581 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
582 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
583 in_ivld
["name"], vnfd
["id"]))
585 def check_valid_vim_account(vim_account
):
586 if vim_account
in vim_accounts
:
589 db_filter
= self
._get
_project
_filter
(session
)
590 db_filter
["_id"] = vim_account
591 self
.db
.get_one("vim_accounts", db_filter
)
593 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
594 vim_accounts
.append(vim_account
)
596 def check_valid_wim_account(wim_account
):
597 if not isinstance(wim_account
, str):
599 elif wim_account
in wim_accounts
:
602 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
603 db_filter
["_id"] = wim_account
604 self
.db
.get_one("wim_accounts", db_filter
)
606 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
607 wim_accounts
.append(wim_account
)
609 if operation
== "action":
610 # check vnf_member_index
611 if indata
.get("vnf_member_index"):
612 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
613 if indata
.get("member_vnf_index"):
614 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
615 if indata
.get("vdu_id"):
616 vdud
= check_valid_vdu(vnfd
, indata
["vdu_id"])
617 descriptor_configuration
= vdud
.get("vdu-configuration", {}).get("config-primitive")
618 elif indata
.get("kdu_name"):
619 kdud
= check_valid_kdu(vnfd
, indata
["kdu_name"])
620 descriptor_configuration
= kdud
.get("kdu-configuration", {}).get("config-primitive")
622 descriptor_configuration
= vnfd
.get("vnf-configuration", {}).get("config-primitive")
624 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
626 # For k8s allows default primitives without validating the parameters
627 if indata
.get("kdu_name") and indata
["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
628 # TODO should be checked that rollback only can contains revsision_numbe????
629 if not indata
.get("member_vnf_index"):
630 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
631 .format(indata
["primitive"]))
633 # if not, check primitive
634 for config_primitive
in get_iterable(descriptor_configuration
):
635 if indata
["primitive"] == config_primitive
["name"]:
636 # check needed primitive_params are provided
637 if indata
.get("primitive_params"):
638 in_primitive_params_copy
= copy(indata
["primitive_params"])
640 in_primitive_params_copy
= {}
641 for paramd
in get_iterable(config_primitive
.get("parameter")):
642 if paramd
["name"] in in_primitive_params_copy
:
643 del in_primitive_params_copy
[paramd
["name"]]
644 elif not paramd
.get("default-value"):
645 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
646 paramd
["name"], indata
["primitive"]))
647 # check no extra primitive params are provided
648 if in_primitive_params_copy
:
649 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
650 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
653 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
654 if operation
== "scale":
655 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
656 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
657 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
660 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
661 "present at vnfd:scaling-group-descriptor".format(
662 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
663 if operation
== "instantiate":
665 check_valid_vim_account(indata
["vimAccountId"])
666 check_valid_wim_account(indata
.get("wimAccountId"))
667 for in_vnf
in get_iterable(indata
.get("vnf")):
668 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
669 _check_vnf_instantiation_params(in_vnf
, vnfd
)
670 if in_vnf
.get("vimAccountId"):
671 check_valid_vim_account(in_vnf
["vimAccountId"])
673 for in_vld
in get_iterable(indata
.get("vld")):
674 check_valid_wim_account(in_vld
.get("wimAccountId"))
675 for vldd
in get_iterable(nsd
.get("vld")):
676 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
679 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
682 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
684 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
685 (ip_address, ...) information.
686 Modifies PDU _admin.usageState to 'IN_USE'
687 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
688 :param rollback: list with the database modifications to rollback if needed
689 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
690 :param vim_account: vim_account where this vnfr should be deployed
691 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
692 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
693 of the changed vnfr is needed
695 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
696 "vim-network-name": used at VIM
697 "name": interface name
698 "vnf-vld-id": internal VNFD vld where this interface is connected, or
699 "ns-vld-id": NSD vld where this interface is connected.
700 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
703 ifaces_forcing_vim_network
= []
704 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
705 if not vdur
.get("pdu-type"):
707 pdu_type
= vdur
.get("pdu-type")
708 pdu_filter
= self
._get
_project
_filter
(session
)
709 pdu_filter
["vim_accounts"] = vim_account
710 pdu_filter
["type"] = pdu_type
711 pdu_filter
["_admin.operationalState"] = "ENABLED"
712 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
713 # TODO feature 1417: "shared": True,
715 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
716 for pdu
in available_pdus
:
717 # step 1 check if this pdu contains needed interfaces:
718 match_interfaces
= True
719 for vdur_interface
in vdur
["interfaces"]:
720 for pdu_interface
in pdu
["interfaces"]:
721 if pdu_interface
["name"] == vdur_interface
["name"]:
722 # TODO feature 1417: match per mgmt type
724 else: # no interface found for name
725 match_interfaces
= False
730 raise EngineException(
731 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
732 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
736 "_admin.usageState": pdu
["_admin"]["usageState"],
737 "_admin.usage.vnfr_id": None,
738 "_admin.usage.nsr_id": None,
739 "_admin.usage.vdur": None,
741 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
742 {"_admin.usageState": "IN_USE",
743 "_admin.usage": {"vnfr_id": vnfr
["_id"],
744 "nsr_id": vnfr
["nsr-id-ref"],
745 "vdur": vdur
["vdu-id-ref"]}
747 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
749 # step 3. Fill vnfr info by filling vdur
750 vdu_text
= "vdur.{}".format(vdur_index
)
751 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
752 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
753 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
754 for pdu_interface
in pdu
["interfaces"]:
755 if pdu_interface
["name"] == vdur_interface
["name"]:
756 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
757 for k
, v
in pdu_interface
.items():
758 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
759 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
760 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
761 if pdu_interface
.get("ip-address"):
762 if vdur_interface
.get("mgmt-interface"):
763 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
764 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
765 if vdur_interface
.get("mgmt-vnf"):
766 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
767 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
768 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
769 ifaces_forcing_vim_network
.append({
770 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
771 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
772 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
773 if pdu_interface
.get("vim-network-id"):
774 ifaces_forcing_vim_network
[-1]["vim-network-id"] = pdu_interface
["vim-network-id"]
775 if pdu_interface
.get("vim-network-name"):
776 ifaces_forcing_vim_network
[-1]["vim-network-name"] = pdu_interface
["vim-network-name"]
779 return ifaces_forcing_vim_network
781 def _look_for_k8scluster(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
783 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
784 Fills vnfr.kdur with the selected k8scluster
786 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
787 :param rollback: list with the database modifications to rollback if needed
788 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
789 :param vim_account: vim_account where this vnfr should be deployed
790 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
791 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
792 of the changed vnfr is needed
794 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
795 "vim-network-name": used at VIM
796 "name": interface name
797 "vnf-vld-id": internal VNFD vld where this interface is connected, or
798 "ns-vld-id": NSD vld where this interface is connected.
799 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
802 ifaces_forcing_vim_network
= []
803 if not vnfr
.get("kdur"):
804 return ifaces_forcing_vim_network
806 kdu_filter
= self
._get
_project
_filter
(session
)
807 kdu_filter
["vim_account"] = vim_account
808 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
809 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
811 k8s_requirements
= {} # just for logging
812 for k8scluster
in available_k8sclusters
:
813 if not vnfr
.get("k8s-cluster"):
816 if vnfr
["k8s-cluster"].get("cni"):
817 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
818 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(k8scluster
.get("cni", ())):
820 # restrict by version
821 if vnfr
["k8s-cluster"].get("version"):
822 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
823 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
825 # restrict by number of networks
826 if vnfr
["k8s-cluster"].get("nets"):
827 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
828 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(vnfr
["k8s-cluster"]["nets"]):
832 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
833 .format(k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]))
835 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
836 # step 3. Fill vnfr info by filling kdur
837 kdu_text
= "kdur.{}.".format(kdur_index
)
838 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
839 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
841 # step 4. Check VIM networks that forces the selected k8s_cluster
842 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
843 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
844 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
845 # get a network from k8s_cluster nets. If name matches use this, if not use other
846 if kdur_net
["id"] in k8scluster_net_list
: # name matches
847 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
848 k8scluster_net_list
.remove(kdur_net
["id"])
850 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
851 k8scluster_net_list
.pop(0)
852 vnfr_update_rollback
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = None
853 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
854 if vim_net
and (kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")):
855 ifaces_forcing_vim_network
.append({
856 "name": kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id"),
857 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
858 "ns-vld-id": kdur_net
.get("ns-vld-id"),
859 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
861 # TODO check that this forcing is not incompatible with other forcing
862 return ifaces_forcing_vim_network
864 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
867 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
871 vnfr_update_rollback
= {}
872 member_vnf_index
= vnfr
["member-vnf-index-ref"]
873 # update vim-account-id
875 vim_account
= indata
["vimAccountId"]
876 # check instantiate parameters
877 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
878 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
880 if vnf_inst_params
.get("vimAccountId"):
881 vim_account
= vnf_inst_params
.get("vimAccountId")
883 vnfr_update
["vim-account-id"] = vim_account
884 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
887 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
888 vnfr_update_rollback
)
891 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
892 vnfr_update_rollback
)
893 # update database vnfr
894 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
895 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
897 # Update indada in case pdu forces to use a concrete vim-network-name
898 # TODO check if user has already insert a vim-network-name and raises an error
899 if not ifaces_forcing_vim_network
:
901 for iface_info
in ifaces_forcing_vim_network
:
902 if iface_info
.get("ns-vld-id"):
903 if "vld" not in indata
:
905 indata
["vld"].append({key
: iface_info
[key
] for key
in
906 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
908 elif iface_info
.get("vnf-vld-id"):
909 if "vnf" not in indata
:
911 indata
["vnf"].append({
912 "member-vnf-index": member_vnf_index
,
913 "internal-vld": [{key
: iface_info
[key
] for key
in
914 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
918 def _create_nslcmop(nsr_id
, operation
, params
):
920 Creates a ns-lcm-opp content to be stored at database.
921 :param nsr_id: internal id of the instance
922 :param operation: instantiate, terminate, scale, action, ...
923 :param params: user parameters for the operation
924 :return: dictionary following SOL005 format
931 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
932 "queuePosition": None,
934 "errorMessage": None,
935 "detailedStatus": None,
936 "statusEnteredTime": now
,
937 "nsInstanceId": nsr_id
,
938 "lcmOperationType": operation
,
940 "isAutomaticInvocation": False,
941 "operationParams": params
,
942 "isCancelPending": False,
944 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
945 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
950 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
952 Performs a new operation over a ns
953 :param rollback: list to append created items at database in case a rollback must to be done
954 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
955 :param indata: descriptor with the parameters of the operation. It must contains among others
956 nsInstanceId: _id of the nsr to perform the operation
957 operation: it can be: instantiate, terminate, action, TODO: update, heal
958 :param kwargs: used to override the indata descriptor
959 :param headers: http request headers
960 :return: id of the nslcmops
962 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
964 db_filter
= self
._get
_project
_filter
(session
)
965 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
966 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
968 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
969 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
972 # Override descriptor with query string kwargs
973 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
974 operation
= indata
["lcmOperationType"]
975 nsInstanceId
= indata
["nsInstanceId"]
977 validate_input(indata
, self
.operation_schema
[operation
])
979 _filter
= BaseTopic
._get
_project
_filter
(session
)
980 _filter
["_id"] = nsInstanceId
981 nsr
= self
.db
.get_one("nsrs", _filter
)
984 if operation
== "terminate" and slice_object
is False:
985 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
986 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
987 if operation
== "terminate" and indata
.get("autoremove"):
988 # NSR must be deleted
989 return None, None # a none in this case is used to indicate not instantiated. It can be removed
990 if operation
!= "instantiate":
991 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
992 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
994 if operation
== "instantiate" and not session
["force"]:
995 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
996 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
997 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
999 if operation
== "instantiate":
1000 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
1002 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
1003 _id
= nslcmop_desc
["_id"]
1004 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1005 self
.db
.create("nslcmops", nslcmop_desc
)
1006 rollback
.append({"topic": "nslcmops", "_id": _id
})
1007 if not slice_object
:
1008 self
.msg
.write("ns", operation
, nslcmop_desc
)
1010 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
1011 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1012 # except DbException as e:
1013 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1015 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1016 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1018 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1019 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1022 class NsiTopic(BaseTopic
):
1026 def __init__(self
, db
, fs
, msg
, auth
):
1027 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1028 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
1031 def _format_ns_request(ns_request
):
1032 formated_request
= copy(ns_request
)
1033 # TODO: Add request params
1034 return formated_request
1037 def _format_addional_params(slice_request
):
1039 Get and format user additional params for NS or VNF
1040 :param slice_request: User instantiation additional parameters
1041 :return: a formatted copy of additional params or None if not supplied
1043 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
1044 if additional_params
:
1045 for k
, v
in additional_params
.items():
1046 if not isinstance(k
, str):
1047 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1049 if "." in k
or "$" in k
:
1050 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1052 if isinstance(v
, (dict, tuple, list)):
1053 additional_params
[k
] = "!!yaml " + safe_dump(v
)
1054 return additional_params
1056 def _check_descriptor_dependencies(self
, session
, descriptor
):
1058 Check that the dependent descriptors exist on a new descriptor or edition
1059 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1060 :param descriptor: descriptor to be inserted or edit
1061 :return: None or raises exception
1063 if not descriptor
.get("nst-ref"):
1065 nstd_id
= descriptor
["nst-ref"]
1066 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
1067 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
1068 http_code
=HTTPStatus
.CONFLICT
)
1070 def check_conflict_on_del(self
, session
, _id
, db_content
):
1072 Check that NSI is not instantiated
1073 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1074 :param _id: nsi internal id
1075 :param db_content: The database content of the _id
1076 :return: None or raises EngineException with the conflict
1078 if session
["force"]:
1081 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
1082 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1083 "Launch 'terminate' operation first; or force deletion".format(_id
),
1084 http_code
=HTTPStatus
.CONFLICT
)
1086 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
1088 Deletes associated nsilcmops from database. Deletes associated filesystem.
1089 Set usageState of nst
1090 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1091 :param _id: server internal id
1092 :param db_content: The database content of the descriptor
1093 :param not_send_msg: To not send message (False) or store content (list) instead
1094 :return: None if ok or raises EngineException with the problem
1097 # Deleting the nsrs belonging to nsir
1099 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
1100 nsr_id
= nsrs_detailed_item
["nsrId"]
1101 if nsrs_detailed_item
.get("shared"):
1102 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1103 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
1104 "_id.ne": nsir
["_id"]}
1105 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1106 if nsi
: # last one using nsr
1109 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
)
1110 except (DbException
, EngineException
) as e
:
1111 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1116 # delete related nsilcmops database entries
1117 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
1119 # Check and set used NST usage state
1120 nsir_admin
= nsir
.get("_admin")
1121 if nsir_admin
and nsir_admin
.get("nst-id"):
1122 # check if used by another NSI
1123 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
1124 fail_on_empty
=False, fail_on_more
=False)
1126 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1128 # def delete(self, session, _id, dry_run=False):
1130 # Delete item by its internal _id
1131 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1132 # :param _id: server internal id
1133 # :param dry_run: make checking but do not delete
1134 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1136 # # TODO add admin to filter, validate rights
1137 # BaseTopic.delete(self, session, _id, dry_run=True)
1141 # # Deleting the nsrs belonging to nsir
1142 # nsir = self.db.get_one("nsis", {"_id": _id})
1143 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1144 # nsr_id = nsrs_detailed_item["nsrId"]
1145 # if nsrs_detailed_item.get("shared"):
1146 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1147 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1148 # "_id.ne": nsir["_id"]}
1149 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1150 # if nsi: # last one using nsr
1153 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1154 # except (DbException, EngineException) as e:
1155 # if e.http_code == HTTPStatus.NOT_FOUND:
1159 # # deletes NetSlice instance object
1160 # v = self.db.del_one("nsis", {"_id": _id})
1162 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1163 # _filter = {"netsliceInstanceId": _id}
1164 # self.db.del_list("nsilcmops", _filter)
1166 # # Search if nst is being used by other nsi
1167 # nsir_admin = nsir.get("_admin")
1169 # if nsir_admin.get("nst-id"):
1170 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1171 # fail_on_empty=False, fail_on_more=False)
1173 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1176 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1178 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1179 :param rollback: list to append the created items at database in case a rollback must be done
1180 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1181 :param indata: params to be used for the nsir
1182 :param kwargs: used to override the indata descriptor
1183 :param headers: http request headers
1184 :return: the _id of nsi descriptor created at database
1188 step
= "checking quotas"
1189 self
.check_quota(session
)
1192 slice_request
= self
._remove
_envelop
(indata
)
1193 # Override descriptor with query string kwargs
1194 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
1195 self
._validate
_input
_new
(slice_request
, session
["force"])
1198 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1199 _filter
= self
._get
_project
_filter
(session
)
1200 _filter
["_id"] = slice_request
["nstId"]
1201 nstd
= self
.db
.get_one("nsts", _filter
)
1204 nstd
.pop("_admin", None)
1205 nstd_id
= nstd
.pop("_id", None)
1206 nsi_id
= str(uuid4())
1207 step
= "filling nsi_descriptor with input data"
1212 "name": slice_request
["nsiName"],
1213 "description": slice_request
.get("nsiDescription", ""),
1214 "datacenter": slice_request
["vimAccountId"],
1215 "nst-ref": nstd
["id"],
1216 "instantiation_parameters": slice_request
,
1217 "network-slice-template": nstd
,
1221 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1224 step
= "creating nsi at database"
1225 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1226 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1227 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1228 nsi_descriptor
["_admin"]["deployed"] = {}
1229 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1230 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1232 # Creating netslice-vld for the RO.
1233 step
= "creating netslice-vld at database"
1235 # Building the vlds list to be deployed
1236 # From netslice descriptors, creating the initial list
1239 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1240 # Getting template Instantiation parameters from NST
1241 nsi_vld
= deepcopy(netslice_vlds
)
1242 nsi_vld
["shared-nsrs-list"] = []
1243 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1244 nsi_vlds
.append(nsi_vld
)
1246 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1247 # Creating netslice-subnet_record.
1251 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1252 for member_ns
in nstd
["netslice-subnet"]:
1253 nsd_id
= member_ns
["nsd-ref"]
1254 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1255 member_ns
["nsd-ref"], member_ns
["id"])
1256 if nsd_id
not in needed_nsds
:
1258 _filter
["id"] = nsd_id
1259 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1262 needed_nsds
[nsd_id
] = nsd
1264 nsd
= needed_nsds
[nsd_id
]
1265 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1266 services
.append(member_ns
)
1268 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1269 member_ns
["nsd-ref"], member_ns
["id"])
1271 # creates Network Services records (NSRs)
1272 step
= "creating nsrs at database using NsrTopic.new()"
1273 ns_params
= slice_request
.get("netslice-subnet")
1275 nsi_netslice_subnet
= []
1276 for service
in services
:
1277 # Check if the netslice-subnet is shared and if it is share if the nss exists
1280 # Is the nss shared and instantiated?
1281 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1282 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1283 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1284 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1285 if nsi
and service
.get("is-shared-nss"):
1286 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1287 for nsrs_detailed_item
in nsrs_detailed_list
:
1288 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1289 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1290 _id_nsr
= nsrs_detailed_item
["nsrId"]
1292 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1293 if netslice_subnet
["nss-id"] == service
["id"]:
1294 indata_ns
= netslice_subnet
1298 if service
.get("instantiation-parameters"):
1299 indata_ns
= deepcopy(service
["instantiation-parameters"])
1300 # del service["instantiation-parameters"]
1302 indata_ns
["nsdId"] = service
["_id"]
1303 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1304 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1305 indata_ns
["nsDescription"] = service
["description"]
1306 if slice_request
.get("ssh_keys"):
1307 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1310 for ns_param
in ns_params
:
1311 if ns_param
.get("id") == service
["id"]:
1312 copy_ns_param
= deepcopy(ns_param
)
1313 del copy_ns_param
["id"]
1314 indata_ns
.update(copy_ns_param
)
1317 # Creates Nsr objects
1318 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1319 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1320 "nss-id": service
["id"], "nslcmop_instantiate": None}
1321 indata_ns
["nss-id"] = service
["id"]
1322 nsrs_list
.append(nsrs_item
)
1323 nsi_netslice_subnet
.append(indata_ns
)
1324 nsr_ref
= {"nsr-ref": _id_nsr
}
1325 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1327 # Adding the nsrs list to the nsi
1328 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1329 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1330 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1332 # Creating the entry in the database
1333 self
.db
.create("nsis", nsi_descriptor
)
1334 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1336 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1337 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1338 raise EngineException("Error {}: {}".format(step
, e
))
1339 except ValidationError
as e
:
1340 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1342 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1343 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1346 class NsiLcmOpTopic(BaseTopic
):
1349 operation_schema
= { # mapping between operation and jsonschema to validate
1350 "instantiate": nsi_instantiate
,
1354 def __init__(self
, db
, fs
, msg
, auth
):
1355 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1356 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
1358 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1360 Check that user has enter right parameters for the operation
1361 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1362 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1363 :param indata: descriptor with the parameters of the operation
1367 nstd
= nsir
["network-slice-template"]
1369 def check_valid_netslice_subnet_id(nstId
):
1370 # TODO change to vnfR (??)
1371 for netslice_subnet
in nstd
["netslice-subnet"]:
1372 if nstId
== netslice_subnet
["id"]:
1373 nsd_id
= netslice_subnet
["nsd-ref"]
1374 if nsd_id
not in nsds
:
1375 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1378 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1379 "nst:netslice-subnet".format(nstId
))
1380 if operation
== "instantiate":
1381 # check the existance of netslice-subnet items
1382 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1383 check_valid_netslice_subnet_id(in_nst
["id"])
1385 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1391 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1392 "statusEnteredTime": now
,
1393 "netsliceInstanceId": netsliceInstanceId
,
1394 "lcmOperationType": operation
,
1396 "isAutomaticInvocation": False,
1397 "operationParams": params
,
1398 "isCancelPending": False,
1400 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1401 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1406 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1407 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1408 if nst_sb_item
.get("is-shared-nss"):
1409 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1410 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1411 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1412 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1413 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1414 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1415 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1417 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1418 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1420 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1422 Performs a new operation over a ns
1423 :param rollback: list to append created items at database in case a rollback must to be done
1424 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1425 :param indata: descriptor with the parameters of the operation. It must contains among others
1426 netsliceInstanceId: _id of the nsir to perform the operation
1427 operation: it can be: instantiate, terminate, action, TODO: update, heal
1428 :param kwargs: used to override the indata descriptor
1429 :param headers: http request headers
1430 :return: id of the nslcmops
1433 # Override descriptor with query string kwargs
1434 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1435 operation
= indata
["lcmOperationType"]
1436 netsliceInstanceId
= indata
["netsliceInstanceId"]
1437 validate_input(indata
, self
.operation_schema
[operation
])
1439 # get nsi from netsliceInstanceId
1440 _filter
= self
._get
_project
_filter
(session
)
1441 _filter
["_id"] = netsliceInstanceId
1442 nsir
= self
.db
.get_one("nsis", _filter
)
1446 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1447 if operation
== "terminate" and indata
.get("autoremove"):
1448 # NSIR must be deleted
1449 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1450 if operation
!= "instantiate":
1451 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1452 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1454 if operation
== "instantiate" and not session
["force"]:
1455 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1456 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1458 # Creating all the NS_operation (nslcmop)
1459 # Get service list from db
1460 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1462 # nslcmops_item = None
1463 for index
, nsr_item
in enumerate(nsrs_list
):
1465 if nsr_item
.get("shared"):
1466 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1467 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item
["nsrId"]
1468 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1469 _filter
["_id.ne"] = netsliceInstanceId
1470 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1471 if operation
== "terminate":
1472 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1473 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1475 # looks the first nsi fulfilling the conditions but not being the current NSIR
1477 nsi_admin_shared
= nsi
["_admin"]["nsrs-detailed-list"]
1478 for nsi_nsr_item
in nsi_admin_shared
:
1479 if nsi_nsr_item
["nsd-id"] == nsr_item
["nsd-id"] and nsi_nsr_item
["shared"]:
1480 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1481 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1482 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1483 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1485 # continue to not create nslcmop since nsrs is shared and nsrs was created
1488 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1491 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1493 indata_ns
= service
["instantiate_params"]
1494 indata_ns
["lcmOperationType"] = operation
1495 indata_ns
["nsInstanceId"] = service
["_id"]
1496 # Including netslice_id in the ns instantiate Operation
1497 indata_ns
["netsliceInstanceId"] = netsliceInstanceId
1498 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1499 # message via kafka bus
1500 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
,
1502 nslcmops
.append(nslcmop
)
1503 if operation
== "terminate":
1505 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1506 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1507 except (DbException
, EngineException
) as e
:
1508 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1509 self
.logger
.info("HTTPStatus.NOT_FOUND")
1515 indata
["nslcmops_ids"] = nslcmops
1516 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1518 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1519 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1520 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1521 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1522 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1524 except ValidationError
as e
:
1525 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1527 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1528 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1530 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1531 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)