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'
679 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
680 :param rollback: list with the database modifications to rollback if needed
681 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
682 :param vim_account: vim_account where this vnfr should be deployed
683 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
684 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
685 of the changed vnfr is needed
687 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
688 "vim-network-name": used at VIM
689 "name": interface name
690 "vnf-vld-id": internal VNFD vld where this interface is connected, or
691 "ns-vld-id": NSD vld where this interface is connected.
692 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
695 ifaces_forcing_vim_network
= []
696 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
697 if not vdur
.get("pdu-type"):
699 pdu_type
= vdur
.get("pdu-type")
700 pdu_filter
= self
._get
_project
_filter
(session
)
701 pdu_filter
["vim_accounts"] = vim_account
702 pdu_filter
["type"] = pdu_type
703 pdu_filter
["_admin.operationalState"] = "ENABLED"
704 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
705 # TODO feature 1417: "shared": True,
707 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
708 for pdu
in available_pdus
:
709 # step 1 check if this pdu contains needed interfaces:
710 match_interfaces
= True
711 for vdur_interface
in vdur
["interfaces"]:
712 for pdu_interface
in pdu
["interfaces"]:
713 if pdu_interface
["name"] == vdur_interface
["name"]:
714 # TODO feature 1417: match per mgmt type
716 else: # no interface found for name
717 match_interfaces
= False
722 raise EngineException(
723 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
724 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
728 "_admin.usageState": pdu
["_admin"]["usageState"],
729 "_admin.usage.vnfr_id": None,
730 "_admin.usage.nsr_id": None,
731 "_admin.usage.vdur": None,
733 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
734 {"_admin.usageState": "IN_USE",
735 "_admin.usage": {"vnfr_id": vnfr
["_id"],
736 "nsr_id": vnfr
["nsr-id-ref"],
737 "vdur": vdur
["vdu-id-ref"]}
739 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
741 # step 3. Fill vnfr info by filling vdur
742 vdu_text
= "vdur.{}".format(vdur_index
)
743 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
744 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
745 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
746 for pdu_interface
in pdu
["interfaces"]:
747 if pdu_interface
["name"] == vdur_interface
["name"]:
748 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
749 for k
, v
in pdu_interface
.items():
750 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
751 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
752 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
753 if pdu_interface
.get("ip-address"):
754 if vdur_interface
.get("mgmt-interface"):
755 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
756 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
757 if vdur_interface
.get("mgmt-vnf"):
758 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
759 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
760 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
761 ifaces_forcing_vim_network
.append({
762 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
763 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
764 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
765 if pdu_interface
.get("vim-network-id"):
766 ifaces_forcing_vim_network
[-1]["vim-network-id"] = pdu_interface
["vim-network-id"]
767 if pdu_interface
.get("vim-network-name"):
768 ifaces_forcing_vim_network
[-1]["vim-network-name"] = pdu_interface
["vim-network-name"]
771 return ifaces_forcing_vim_network
773 def _look_for_k8scluster(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
775 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
776 Fills vnfr.kdur with the selected k8scluster
778 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
779 :param rollback: list with the database modifications to rollback if needed
780 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
781 :param vim_account: vim_account where this vnfr should be deployed
782 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
783 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
784 of the changed vnfr is needed
786 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
787 "vim-network-name": used at VIM
788 "name": interface name
789 "vnf-vld-id": internal VNFD vld where this interface is connected, or
790 "ns-vld-id": NSD vld where this interface is connected.
791 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
794 ifaces_forcing_vim_network
= []
795 if not vnfr
.get("kdur"):
796 return ifaces_forcing_vim_network
798 kdu_filter
= self
._get
_project
_filter
(session
)
799 kdu_filter
["vim_account"] = vim_account
800 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
801 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
803 k8s_requirements
= {} # just for logging
804 for k8scluster
in available_k8sclusters
:
805 if not vnfr
.get("k8s-cluster"):
808 if vnfr
["k8s-cluster"].get("cni"):
809 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
810 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(k8scluster
.get("cni", ())):
812 # restrict by version
813 if vnfr
["k8s-cluster"].get("version"):
814 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
815 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
817 # restrict by number of networks
818 if vnfr
["k8s-cluster"].get("nets"):
819 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
820 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(vnfr
["k8s-cluster"]["nets"]):
824 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
825 .format(k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]))
827 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
828 # step 3. Fill vnfr info by filling kdur
829 kdu_text
= "kdur.{}.".format(kdur_index
)
830 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
831 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
833 # step 4. Check VIM networks that forces the selected k8s_cluster
834 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
835 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
836 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
837 # get a network from k8s_cluster nets. If name matches use this, if not use other
838 if kdur_net
["id"] in k8scluster_net_list
: # name matches
839 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
840 k8scluster_net_list
.remove(kdur_net
["id"])
842 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
843 k8scluster_net_list
.pop(0)
844 vnfr_update_rollback
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = None
845 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
846 if vim_net
and (kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")):
847 ifaces_forcing_vim_network
.append({
848 "name": kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id"),
849 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
850 "ns-vld-id": kdur_net
.get("ns-vld-id"),
851 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
853 # TODO check that this forcing is not incompatible with other forcing
854 return ifaces_forcing_vim_network
856 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
859 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
863 vnfr_update_rollback
= {}
864 member_vnf_index
= vnfr
["member-vnf-index-ref"]
865 # update vim-account-id
867 vim_account
= indata
["vimAccountId"]
868 # check instantiate parameters
869 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
870 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
872 if vnf_inst_params
.get("vimAccountId"):
873 vim_account
= vnf_inst_params
.get("vimAccountId")
875 vnfr_update
["vim-account-id"] = vim_account
876 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
879 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
880 vnfr_update_rollback
)
883 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
884 vnfr_update_rollback
)
885 # update database vnfr
886 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
887 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
889 # Update indada in case pdu forces to use a concrete vim-network-name
890 # TODO check if user has already insert a vim-network-name and raises an error
891 if not ifaces_forcing_vim_network
:
893 for iface_info
in ifaces_forcing_vim_network
:
894 if iface_info
.get("ns-vld-id"):
895 if "vld" not in indata
:
897 indata
["vld"].append({key
: iface_info
[key
] for key
in
898 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
900 elif iface_info
.get("vnf-vld-id"):
901 if "vnf" not in indata
:
903 indata
["vnf"].append({
904 "member-vnf-index": member_vnf_index
,
905 "internal-vld": [{key
: iface_info
[key
] for key
in
906 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
910 def _create_nslcmop(nsr_id
, operation
, params
):
912 Creates a ns-lcm-opp content to be stored at database.
913 :param nsr_id: internal id of the instance
914 :param operation: instantiate, terminate, scale, action, ...
915 :param params: user parameters for the operation
916 :return: dictionary following SOL005 format
923 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
924 "statusEnteredTime": now
,
925 "nsInstanceId": nsr_id
,
926 "lcmOperationType": operation
,
928 "isAutomaticInvocation": False,
929 "operationParams": params
,
930 "isCancelPending": False,
932 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
933 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
938 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
940 Performs a new operation over a ns
941 :param rollback: list to append created items at database in case a rollback must to be done
942 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
943 :param indata: descriptor with the parameters of the operation. It must contains among others
944 nsInstanceId: _id of the nsr to perform the operation
945 operation: it can be: instantiate, terminate, action, TODO: update, heal
946 :param kwargs: used to override the indata descriptor
947 :param headers: http request headers
948 :return: id of the nslcmops
950 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
952 db_filter
= self
._get
_project
_filter
(session
)
953 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
954 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
956 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
957 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
960 # Override descriptor with query string kwargs
961 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
962 operation
= indata
["lcmOperationType"]
963 nsInstanceId
= indata
["nsInstanceId"]
965 validate_input(indata
, self
.operation_schema
[operation
])
967 _filter
= BaseTopic
._get
_project
_filter
(session
)
968 _filter
["_id"] = nsInstanceId
969 nsr
= self
.db
.get_one("nsrs", _filter
)
972 if operation
== "terminate" and slice_object
is False:
973 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
974 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
975 if operation
== "terminate" and indata
.get("autoremove"):
976 # NSR must be deleted
977 return None, None # a none in this case is used to indicate not instantiated. It can be removed
978 if operation
!= "instantiate":
979 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
980 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
982 if operation
== "instantiate" and not session
["force"]:
983 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
984 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
985 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
987 if operation
== "instantiate":
988 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
990 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
991 _id
= nslcmop_desc
["_id"]
992 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
993 self
.db
.create("nslcmops", nslcmop_desc
)
994 rollback
.append({"topic": "nslcmops", "_id": _id
})
996 self
.msg
.write("ns", operation
, nslcmop_desc
)
998 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
999 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1000 # except DbException as e:
1001 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1003 def delete(self
, session
, _id
, dry_run
=False):
1004 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1006 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1007 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1010 class NsiTopic(BaseTopic
):
1014 def __init__(self
, db
, fs
, msg
, auth
):
1015 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1016 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
1019 def _format_ns_request(ns_request
):
1020 formated_request
= copy(ns_request
)
1021 # TODO: Add request params
1022 return formated_request
1025 def _format_addional_params(slice_request
):
1027 Get and format user additional params for NS or VNF
1028 :param slice_request: User instantiation additional parameters
1029 :return: a formatted copy of additional params or None if not supplied
1031 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
1032 if additional_params
:
1033 for k
, v
in additional_params
.items():
1034 if not isinstance(k
, str):
1035 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1037 if "." in k
or "$" in k
:
1038 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1040 if isinstance(v
, (dict, tuple, list)):
1041 additional_params
[k
] = "!!yaml " + safe_dump(v
)
1042 return additional_params
1044 def _check_descriptor_dependencies(self
, session
, descriptor
):
1046 Check that the dependent descriptors exist on a new descriptor or edition
1047 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1048 :param descriptor: descriptor to be inserted or edit
1049 :return: None or raises exception
1051 if not descriptor
.get("nst-ref"):
1053 nstd_id
= descriptor
["nst-ref"]
1054 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
1055 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
1056 http_code
=HTTPStatus
.CONFLICT
)
1058 def check_conflict_on_del(self
, session
, _id
, db_content
):
1060 Check that NSI is not instantiated
1061 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1062 :param _id: nsi internal id
1063 :param db_content: The database content of the _id
1064 :return: None or raises EngineException with the conflict
1066 if session
["force"]:
1069 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
1070 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1071 "Launch 'terminate' operation first; or force deletion".format(_id
),
1072 http_code
=HTTPStatus
.CONFLICT
)
1074 def delete_extra(self
, session
, _id
, db_content
):
1076 Deletes associated nsilcmops from database. Deletes associated filesystem.
1077 Set usageState of nst
1078 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1079 :param _id: server internal id
1080 :param db_content: The database content of the descriptor
1081 :return: None if ok or raises EngineException with the problem
1084 # Deleting the nsrs belonging to nsir
1086 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
1087 nsr_id
= nsrs_detailed_item
["nsrId"]
1088 if nsrs_detailed_item
.get("shared"):
1089 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1090 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
1091 "_id.ne": nsir
["_id"]}
1092 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1093 if nsi
: # last one using nsr
1096 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False)
1097 except (DbException
, EngineException
) as e
:
1098 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1103 # delete related nsilcmops database entries
1104 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
1106 # Check and set used NST usage state
1107 nsir_admin
= nsir
.get("_admin")
1108 if nsir_admin
and nsir_admin
.get("nst-id"):
1109 # check if used by another NSI
1110 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
1111 fail_on_empty
=False, fail_on_more
=False)
1113 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1115 # def delete(self, session, _id, dry_run=False):
1117 # Delete item by its internal _id
1118 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1119 # :param _id: server internal id
1120 # :param dry_run: make checking but do not delete
1121 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1123 # # TODO add admin to filter, validate rights
1124 # BaseTopic.delete(self, session, _id, dry_run=True)
1128 # # Deleting the nsrs belonging to nsir
1129 # nsir = self.db.get_one("nsis", {"_id": _id})
1130 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1131 # nsr_id = nsrs_detailed_item["nsrId"]
1132 # if nsrs_detailed_item.get("shared"):
1133 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1134 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1135 # "_id.ne": nsir["_id"]}
1136 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1137 # if nsi: # last one using nsr
1140 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1141 # except (DbException, EngineException) as e:
1142 # if e.http_code == HTTPStatus.NOT_FOUND:
1146 # # deletes NetSlice instance object
1147 # v = self.db.del_one("nsis", {"_id": _id})
1149 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1150 # _filter = {"netsliceInstanceId": _id}
1151 # self.db.del_list("nsilcmops", _filter)
1153 # # Search if nst is being used by other nsi
1154 # nsir_admin = nsir.get("_admin")
1156 # if nsir_admin.get("nst-id"):
1157 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1158 # fail_on_empty=False, fail_on_more=False)
1160 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1163 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1165 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1166 :param rollback: list to append the created items at database in case a rollback must be done
1167 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1168 :param indata: params to be used for the nsir
1169 :param kwargs: used to override the indata descriptor
1170 :param headers: http request headers
1171 :return: the _id of nsi descriptor created at database
1175 step
= "checking quotas"
1176 self
.check_quota(session
)
1179 slice_request
= self
._remove
_envelop
(indata
)
1180 # Override descriptor with query string kwargs
1181 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
1182 self
._validate
_input
_new
(slice_request
, session
["force"])
1185 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1186 _filter
= self
._get
_project
_filter
(session
)
1187 _filter
["_id"] = slice_request
["nstId"]
1188 nstd
= self
.db
.get_one("nsts", _filter
)
1191 nstd
.pop("_admin", None)
1192 nstd_id
= nstd
.pop("_id", None)
1193 nsi_id
= str(uuid4())
1194 step
= "filling nsi_descriptor with input data"
1199 "name": slice_request
["nsiName"],
1200 "description": slice_request
.get("nsiDescription", ""),
1201 "datacenter": slice_request
["vimAccountId"],
1202 "nst-ref": nstd
["id"],
1203 "instantiation_parameters": slice_request
,
1204 "network-slice-template": nstd
,
1208 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1211 step
= "creating nsi at database"
1212 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1213 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1214 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1215 nsi_descriptor
["_admin"]["deployed"] = {}
1216 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1217 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1219 # Creating netslice-vld for the RO.
1220 step
= "creating netslice-vld at database"
1222 # Building the vlds list to be deployed
1223 # From netslice descriptors, creating the initial list
1226 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1227 # Getting template Instantiation parameters from NST
1228 nsi_vld
= deepcopy(netslice_vlds
)
1229 nsi_vld
["shared-nsrs-list"] = []
1230 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1231 nsi_vlds
.append(nsi_vld
)
1233 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1234 # Creating netslice-subnet_record.
1238 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1239 for member_ns
in nstd
["netslice-subnet"]:
1240 nsd_id
= member_ns
["nsd-ref"]
1241 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1242 member_ns
["nsd-ref"], member_ns
["id"])
1243 if nsd_id
not in needed_nsds
:
1245 _filter
["id"] = nsd_id
1246 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1249 needed_nsds
[nsd_id
] = nsd
1251 nsd
= needed_nsds
[nsd_id
]
1252 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1253 services
.append(member_ns
)
1255 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1256 member_ns
["nsd-ref"], member_ns
["id"])
1258 # creates Network Services records (NSRs)
1259 step
= "creating nsrs at database using NsrTopic.new()"
1260 ns_params
= slice_request
.get("netslice-subnet")
1262 nsi_netslice_subnet
= []
1263 for service
in services
:
1264 # Check if the netslice-subnet is shared and if it is share if the nss exists
1267 # Is the nss shared and instantiated?
1268 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1269 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1270 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1271 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1272 if nsi
and service
.get("is-shared-nss"):
1273 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1274 for nsrs_detailed_item
in nsrs_detailed_list
:
1275 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1276 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1277 _id_nsr
= nsrs_detailed_item
["nsrId"]
1279 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1280 if netslice_subnet
["nss-id"] == service
["id"]:
1281 indata_ns
= netslice_subnet
1285 if service
.get("instantiation-parameters"):
1286 indata_ns
= deepcopy(service
["instantiation-parameters"])
1287 # del service["instantiation-parameters"]
1289 indata_ns
["nsdId"] = service
["_id"]
1290 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1291 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1292 indata_ns
["nsDescription"] = service
["description"]
1293 if slice_request
.get("ssh_keys"):
1294 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1297 for ns_param
in ns_params
:
1298 if ns_param
.get("id") == service
["id"]:
1299 copy_ns_param
= deepcopy(ns_param
)
1300 del copy_ns_param
["id"]
1301 indata_ns
.update(copy_ns_param
)
1304 # Creates Nsr objects
1305 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1306 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1307 "nss-id": service
["id"], "nslcmop_instantiate": None}
1308 indata_ns
["nss-id"] = service
["id"]
1309 nsrs_list
.append(nsrs_item
)
1310 nsi_netslice_subnet
.append(indata_ns
)
1311 nsr_ref
= {"nsr-ref": _id_nsr
}
1312 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1314 # Adding the nsrs list to the nsi
1315 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1316 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1317 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1319 # Creating the entry in the database
1320 self
.db
.create("nsis", nsi_descriptor
)
1321 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1323 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1324 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1325 raise EngineException("Error {}: {}".format(step
, e
))
1326 except ValidationError
as e
:
1327 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1329 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1330 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1333 class NsiLcmOpTopic(BaseTopic
):
1336 operation_schema
= { # mapping between operation and jsonschema to validate
1337 "instantiate": nsi_instantiate
,
1341 def __init__(self
, db
, fs
, msg
, auth
):
1342 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1343 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
1345 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1347 Check that user has enter right parameters for the operation
1348 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1349 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1350 :param indata: descriptor with the parameters of the operation
1354 nstd
= nsir
["network-slice-template"]
1356 def check_valid_netslice_subnet_id(nstId
):
1357 # TODO change to vnfR (??)
1358 for netslice_subnet
in nstd
["netslice-subnet"]:
1359 if nstId
== netslice_subnet
["id"]:
1360 nsd_id
= netslice_subnet
["nsd-ref"]
1361 if nsd_id
not in nsds
:
1362 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1365 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1366 "nst:netslice-subnet".format(nstId
))
1367 if operation
== "instantiate":
1368 # check the existance of netslice-subnet items
1369 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1370 check_valid_netslice_subnet_id(in_nst
["id"])
1372 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1378 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1379 "statusEnteredTime": now
,
1380 "netsliceInstanceId": netsliceInstanceId
,
1381 "lcmOperationType": operation
,
1383 "isAutomaticInvocation": False,
1384 "operationParams": params
,
1385 "isCancelPending": False,
1387 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1388 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1393 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1394 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1395 if nst_sb_item
.get("is-shared-nss"):
1396 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1397 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1398 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1399 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1400 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1401 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1402 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1404 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1405 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1407 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1409 Performs a new operation over a ns
1410 :param rollback: list to append created items at database in case a rollback must to be done
1411 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1412 :param indata: descriptor with the parameters of the operation. It must contains among others
1413 netsliceInstanceId: _id of the nsir to perform the operation
1414 operation: it can be: instantiate, terminate, action, TODO: update, heal
1415 :param kwargs: used to override the indata descriptor
1416 :param headers: http request headers
1417 :return: id of the nslcmops
1420 # Override descriptor with query string kwargs
1421 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1422 operation
= indata
["lcmOperationType"]
1423 netsliceInstanceId
= indata
["netsliceInstanceId"]
1424 validate_input(indata
, self
.operation_schema
[operation
])
1426 # get nsi from netsliceInstanceId
1427 _filter
= self
._get
_project
_filter
(session
)
1428 _filter
["_id"] = netsliceInstanceId
1429 nsir
= self
.db
.get_one("nsis", _filter
)
1433 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1434 if operation
== "terminate" and indata
.get("autoremove"):
1435 # NSIR must be deleted
1436 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1437 if operation
!= "instantiate":
1438 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1439 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1441 if operation
== "instantiate" and not session
["force"]:
1442 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1443 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1445 # Creating all the NS_operation (nslcmop)
1446 # Get service list from db
1447 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1449 # nslcmops_item = None
1450 for index
, nsr_item
in enumerate(nsrs_list
):
1452 if nsr_item
.get("shared"):
1453 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1454 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item
["nsrId"]
1455 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1456 _filter
["_id.ne"] = netsliceInstanceId
1457 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1458 if operation
== "terminate":
1459 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1460 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1462 # looks the first nsi fulfilling the conditions but not being the current NSIR
1464 nsi_admin_shared
= nsi
["_admin"]["nsrs-detailed-list"]
1465 for nsi_nsr_item
in nsi_admin_shared
:
1466 if nsi_nsr_item
["nsd-id"] == nsr_item
["nsd-id"] and nsi_nsr_item
["shared"]:
1467 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1468 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1469 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1470 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1472 # continue to not create nslcmop since nsrs is shared and nsrs was created
1475 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1478 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1480 indata_ns
= service
["instantiate_params"]
1481 indata_ns
["lcmOperationType"] = operation
1482 indata_ns
["nsInstanceId"] = service
["_id"]
1483 # Including netslice_id in the ns instantiate Operation
1484 indata_ns
["netsliceInstanceId"] = netsliceInstanceId
1485 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1486 # message via kafka bus
1487 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
,
1489 nslcmops
.append(nslcmop
)
1490 if operation
== "terminate":
1492 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1493 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1494 except (DbException
, EngineException
) as e
:
1495 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1496 self
.logger
.info("HTTPStatus.NOT_FOUND")
1502 indata
["nslcmops_ids"] = nslcmops
1503 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1505 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1506 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1507 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1508 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1509 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1511 except ValidationError
as e
:
1512 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1514 def delete(self
, session
, _id
, dry_run
=False):
1515 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1517 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1518 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)