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 validation
import validate_input
, ValidationError
, ns_instantiate
, ns_action
, ns_scale
, nsi_instantiate
22 from base_topic
import BaseTopic
, EngineException
, get_iterable
23 from descriptor_topics
import DescriptorTopic
25 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
28 class NsrTopic(BaseTopic
):
32 def __init__(self
, db
, fs
, msg
):
33 BaseTopic
.__init
__(self
, db
, fs
, msg
)
35 def _check_descriptor_dependencies(self
, session
, descriptor
):
37 Check that the dependent descriptors exist on a new descriptor or edition
38 :param session: client session information
39 :param descriptor: descriptor to be inserted or edit
40 :return: None or raises exception
42 if not descriptor
.get("nsdId"):
44 nsd_id
= descriptor
["nsdId"]
45 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
46 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
47 http_code
=HTTPStatus
.CONFLICT
)
50 def format_on_new(content
, project_id
=None, make_public
=False):
51 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
52 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
54 def check_conflict_on_del(self
, session
, _id
, force
=False):
57 nsr
= self
.db
.get_one("nsrs", {"_id": _id
})
58 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
59 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
60 "Launch 'terminate' operation first; or force deletion".format(_id
),
61 http_code
=HTTPStatus
.CONFLICT
)
63 def delete(self
, session
, _id
, force
=False, dry_run
=False):
65 Delete item by its internal _id
66 :param session: contains the used login username, working project, and admin rights
67 :param _id: server internal id
68 :param force: indicates if deletion must be forced in case of conflict
69 :param dry_run: make checking but do not delete
70 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
72 # TODO add admin to filter, validate rights
73 BaseTopic
.delete(self
, session
, _id
, force
, dry_run
=True)
77 v
= self
.db
.del_one("nsrs", {"_id": _id
})
78 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
79 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
80 # set all used pdus as free
81 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
82 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
83 self
._send
_msg
("deleted", {"_id": _id
})
86 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False):
88 Creates a new nsr into database. It also creates needed vnfrs
89 :param rollback: list to append the created items at database in case a rollback must be done
90 :param session: contains the used login username and working project
91 :param indata: params to be used for the nsr
92 :param kwargs: used to override the indata descriptor
93 :param headers: http request headers
94 :param force: If True avoid some dependence checks
95 :param make_public: Make the created item public to all projects
96 :return: the _id of nsr descriptor created at database
100 ns_request
= self
._remove
_envelop
(indata
)
101 # Override descriptor with query string kwargs
102 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
103 self
._validate
_input
_new
(ns_request
, force
)
107 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
108 _filter
= {"_id": ns_request
["nsdId"]}
109 _filter
.update(BaseTopic
._get
_project
_filter
(session
, write
=False, show_all
=True))
110 nsd
= self
.db
.get_one("nsds", _filter
)
112 nsr_id
= str(uuid4())
114 step
= "filling nsr from input data"
116 "name": ns_request
["nsName"],
117 "name-ref": ns_request
["nsName"],
118 "short-name": ns_request
["nsName"],
119 "admin-status": "ENABLED",
121 "datacenter": ns_request
["vimAccountId"],
122 "resource-orchestrator": "osmopenmano",
123 "description": ns_request
.get("nsDescription", ""),
124 "constituent-vnfr-ref": [],
126 "operational-status": "init", # typedef ns-operational-
127 "config-status": "init", # typedef config-states
128 "detailed-status": "scheduled",
130 "orchestration-progress": {},
131 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
134 "nsd-name-ref": nsd
["name"],
135 "operational-events": [], # "id", "timestamp", "description", "event",
136 "nsd-ref": nsd
["id"],
137 "instantiate_params": ns_request
,
138 "ns-instance-config-ref": nsr_id
,
141 # "input-parameter": xpath, value,
142 "ssh-authorized-key": ns_request
.get("key-pair-ref"), # TODO remove
144 ns_request
["nsr_id"] = nsr_id
147 nsr_descriptor
["vld"] = []
148 for nsd_vld
in nsd
.get("vld"):
149 nsr_descriptor
["vld"].append(
150 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name") if key
in nsd_vld
})
154 for member_vnf
in nsd
.get("constituent-vnfd", ()):
155 vnfd_id
= member_vnf
["vnfd-id-ref"]
156 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
157 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
158 if vnfd_id
not in needed_vnfds
:
160 vnfd
= DescriptorTopic
.get_one_by_id(self
.db
, session
, "vnfds", vnfd_id
)
162 needed_vnfds
[vnfd_id
] = vnfd
164 vnfd
= needed_vnfds
[vnfd_id
]
165 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
166 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
167 vnfr_id
= str(uuid4())
171 "nsr-id-ref": nsr_id
,
172 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
174 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
176 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
177 "vim-account-id": None,
179 "connection-point": [],
180 "ip-address": None, # mgmt-interface filled by LCM
184 if vnfd
.get("internal-vld"):
185 vnfr_descriptor
["vld"] = []
186 for vnfd_vld
in vnfd
.get("internal-vld"):
187 vnfr_descriptor
["vld"].append(
188 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name") if key
in vnfd_vld
})
190 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
191 for cp
in vnfd
.get("connection-point", ()):
194 "connection-point-id": cp
.get("id"),
196 # "ip-address", "mac-address" # filled by LCM
197 # vim-id # TODO it would be nice having a vim port id
199 vnfr_descriptor
["connection-point"].append(vnf_cp
)
200 for vdu
in vnfd
.get("vdu", ()):
202 "vdu-id-ref": vdu
["id"],
203 # TODO "name": "" Name of the VDU in the VIM
204 "ip-address": None, # mgmt-interface filled by LCM
205 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
206 "internal-connection-point": [],
209 if vdu
.get("pdu-type"):
210 vdur
["pdu-type"] = vdu
["pdu-type"]
211 # TODO volumes: name, volume-id
212 for icp
in vdu
.get("internal-connection-point", ()):
215 "connection-point-id": icp
["id"],
216 "name": icp
.get("name"),
217 # "ip-address", "mac-address" # filled by LCM
218 # vim-id # TODO it would be nice having a vim port id
220 vdur
["internal-connection-point"].append(vdu_icp
)
221 for iface
in vdu
.get("interface", ()):
223 "name": iface
.get("name"),
224 # "ip-address", "mac-address" # filled by LCM
225 # vim-id # TODO it would be nice having a vim port id
227 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
228 vdu_iface
["mgmt-vnf"] = True
229 if iface
.get("mgmt-interface"):
230 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
232 # look for network where this interface is connected
233 if iface
.get("external-connection-point-ref"):
234 for nsd_vld
in get_iterable(nsd
.get("vld")):
235 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
236 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
237 iface
["external-connection-point-ref"] and \
238 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
239 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
244 elif iface
.get("internal-connection-point-ref"):
245 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
246 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
247 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
248 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
254 vdur
["interfaces"].append(vdu_iface
)
255 count
= vdu
.get("count", 1)
258 count
= int(count
) # TODO remove when descriptor serialized with payngbind
259 for index
in range(0, count
):
261 vdur
= deepcopy(vdur
)
262 vdur
["_id"] = str(uuid4())
263 vdur
["count-index"] = index
264 vnfr_descriptor
["vdur"].append(vdur
)
266 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
267 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
270 BaseTopic
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=make_public
)
271 self
.db
.create("vnfrs", vnfr_descriptor
)
272 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
273 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
275 step
= "creating nsr at database"
276 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=make_public
)
277 self
.db
.create("nsrs", nsr_descriptor
)
278 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
280 except Exception as e
:
281 self
.logger
.exception("Exception {} at NsrTopic.new()".format(e
), exc_info
=True)
282 raise EngineException("Error {}: {}".format(step
, e
))
283 except ValidationError
as e
:
284 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
286 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
287 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
290 class VnfrTopic(BaseTopic
):
294 def __init__(self
, db
, fs
, msg
):
295 BaseTopic
.__init
__(self
, db
, fs
, msg
)
297 def delete(self
, session
, _id
, force
=False, dry_run
=False):
298 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
300 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
301 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
303 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False):
304 # Not used because vnfrs are created and deleted by NsrTopic class directly
305 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
308 class NsLcmOpTopic(BaseTopic
):
311 operation_schema
= { # mapping between operation and jsonschema to validate
312 "instantiate": ns_instantiate
,
318 def __init__(self
, db
, fs
, msg
):
319 BaseTopic
.__init
__(self
, db
, fs
, msg
)
321 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
323 Check that user has enter right parameters for the operation
325 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
326 :param indata: descriptor with the parameters of the operation
333 def check_valid_vnf_member_index(member_vnf_index
):
334 # TODO change to vnfR
335 for vnf
in nsd
["constituent-vnfd"]:
336 if member_vnf_index
== vnf
["member-vnf-index"]:
337 vnfd_id
= vnf
["vnfd-id-ref"]
338 if vnfd_id
not in vnfds
:
339 vnfds
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
340 return vnfds
[vnfd_id
]
342 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
343 "nsd:constituent-vnfd".format(member_vnf_index
))
345 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
347 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
348 for vdu
in get_iterable(vnfd
.get("vdu")):
349 if in_vdu
["id"] == vdu
["id"]:
350 for volume
in get_iterable(in_vdu
.get("volume")):
351 for volumed
in get_iterable(vdu
.get("volumes")):
352 if volumed
["name"] == volume
["name"]:
355 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
356 "volume:name='{}' is not present at vnfd:vdu:volumes list".
357 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
359 for in_iface
in get_iterable(in_vdu
["interface"]):
360 for iface
in get_iterable(vdu
.get("interface")):
361 if in_iface
["name"] == iface
["name"]:
364 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
365 "interface[name='{}'] is not present at vnfd:vdu:interface"
366 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
370 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
371 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
373 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
374 for ivld
in get_iterable(vnfd
.get("internal-vld")):
375 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
376 for in_icp
in get_iterable(in_ivld
["internal-connection-point"]):
377 for icp
in ivld
["internal-connection-point"]:
378 if in_icp
["id-ref"] == icp
["id-ref"]:
381 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
382 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
383 "vnfd:internal-vld:name/id:internal-connection-point"
384 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
385 in_icp
["id-ref"], vnfd
["id"]))
388 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
389 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
390 in_ivld
["name"], vnfd
["id"]))
392 def check_valid_vim_account(vim_account
):
393 if vim_account
in vim_accounts
:
396 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
397 db_filter
["_id"] = vim_account
398 self
.db
.get_one("vim_accounts", db_filter
)
400 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
401 vim_accounts
.append(vim_account
)
403 if operation
== "action":
404 # check vnf_member_index
405 if indata
.get("vnf_member_index"):
406 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
407 if not indata
.get("member_vnf_index"):
408 raise EngineException("Missing 'member_vnf_index' parameter")
409 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
411 for config_primitive
in get_iterable(vnfd
.get("vnf-configuration", {}).get("config-primitive")):
412 if indata
["primitive"] == config_primitive
["name"]:
413 # check needed primitive_params are provided
414 if indata
.get("primitive_params"):
415 in_primitive_params_copy
= copy(indata
["primitive_params"])
417 in_primitive_params_copy
= {}
418 for paramd
in get_iterable(config_primitive
.get("parameter")):
419 if paramd
["name"] in in_primitive_params_copy
:
420 del in_primitive_params_copy
[paramd
["name"]]
421 elif not paramd
.get("default-value"):
422 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
423 paramd
["name"], indata
["primitive"]))
424 # check no extra primitive params are provided
425 if in_primitive_params_copy
:
426 raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
427 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
430 raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata
["primitive"]))
431 if operation
== "scale":
432 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
433 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
434 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
437 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
438 "present at vnfd:scaling-group-descriptor".format(
439 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
440 if operation
== "instantiate":
442 check_valid_vim_account(indata
["vimAccountId"])
443 for in_vnf
in get_iterable(indata
.get("vnf")):
444 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
445 _check_vnf_instantiation_params(in_vnf
, vnfd
)
446 if in_vnf
.get("vimAccountId"):
447 check_valid_vim_account(in_vnf
["vimAccountId"])
449 for in_vld
in get_iterable(indata
.get("vld")):
450 for vldd
in get_iterable(nsd
.get("vld")):
451 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
454 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
457 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
459 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
460 (ip_address, ...) information.
461 Modifies PDU _admin.usageState to 'IN_USE'
463 :param session: client session information
464 :param rollback: list with the database modifications to rollback if needed
465 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
466 :param vim_account: vim_account where this vnfr should be deployed
467 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
468 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
469 of the changed vnfr is needed
471 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
472 "vim-network-name": used at VIM
473 "name": interface name
474 "vnf-vld-id": internal VNFD vld where this interface is connected, or
475 "ns-vld-id": NSD vld where this interface is connected.
476 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
479 ifaces_forcing_vim_network
= []
480 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
481 if not vdur
.get("pdu-type"):
483 pdu_type
= vdur
.get("pdu-type")
484 pdu_filter
= self
._get
_project
_filter
(session
, write
=True, show_all
=True)
485 pdu_filter
["vim_accounts"] = vim_account
486 pdu_filter
["type"] = pdu_type
487 pdu_filter
["_admin.operationalState"] = "ENABLED"
488 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
489 # TODO feature 1417: "shared": True,
491 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
492 for pdu
in available_pdus
:
493 # step 1 check if this pdu contains needed interfaces:
494 match_interfaces
= True
495 for vdur_interface
in vdur
["interfaces"]:
496 for pdu_interface
in pdu
["interfaces"]:
497 if pdu_interface
["name"] == vdur_interface
["name"]:
498 # TODO feature 1417: match per mgmt type
500 else: # no interface found for name
501 match_interfaces
= False
506 raise EngineException(
507 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
508 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
512 "_admin.usageState": pdu
["_admin"]["usageState"],
513 "_admin.usage.vnfr_id": None,
514 "_admin.usage.nsr_id": None,
515 "_admin.usage.vdur": None,
517 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
518 {"_admin.usageState": "IN_USE",
519 "_admin.usage.vnfr_id": vnfr
["_id"],
520 "_admin.usage.nsr_id": vnfr
["nsr-id-ref"],
521 "_admin.usage.vdur": vdur
["vdu-id-ref"]}
523 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
525 # step 3. Fill vnfr info by filling vdur
526 vdu_text
= "vdur.{}".format(vdur_index
)
527 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
528 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
529 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
530 for pdu_interface
in pdu
["interfaces"]:
531 if pdu_interface
["name"] == vdur_interface
["name"]:
532 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
533 for k
, v
in pdu_interface
.items():
534 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
535 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
536 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
537 if pdu_interface
.get("ip-address"):
538 if vdur_interface
.get("mgmt-interface"):
539 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
540 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
541 if vdur_interface
.get("mgmt-vnf"):
542 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
543 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
544 if pdu_interface
.get("vim-network-name"): # or pdu_interface.get("vim-network-id"):
545 ifaces_forcing_vim_network
.append({
546 # "vim-network-id": pdu_interface.get("vim-network-id"),
547 "vim-network-name": pdu_interface
.get("vim-network-name"),
548 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
549 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
550 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
553 return ifaces_forcing_vim_network
555 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
559 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
563 vnfr_update_rollback
= {}
564 member_vnf_index
= vnfr
["member-vnf-index-ref"]
565 # update vim-account-id
567 vim_account
= indata
["vimAccountId"]
568 # check instantiate parameters
569 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
570 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
572 if vnf_inst_params
.get("vimAccountId"):
573 vim_account
= vnf_inst_params
.get("vimAccountId")
575 vnfr_update
["vim-account-id"] = vim_account
576 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
579 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
580 vnfr_update_rollback
)
582 # updata database vnfr
583 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
584 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
586 # Update indada in case pdu forces to use a concrete vim-network-name
587 # TODO check if user has already insert a vim-network-name and raises an error
588 if not ifaces_forcing_vim_network
:
590 for iface_info
in ifaces_forcing_vim_network
:
591 if iface_info
.get("ns-vld-id"):
592 if "vld" not in indata
:
594 indata
["vld"].append({key
: iface_info
[key
] for key
in
595 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
597 elif iface_info
.get("vnf-vld-id"):
598 if "vnf" not in indata
:
600 indata
["vnf"].append({
601 "member-vnf-index": member_vnf_index
,
602 "internal-vld": [{key
: iface_info
[key
] for key
in
603 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
607 def _create_nslcmop(nsr_id
, operation
, params
):
609 Creates a ns-lcm-opp content to be stored at database.
610 :param nsr_id: internal id of the instance
611 :param operation: instantiate, terminate, scale, action, ...
612 :param params: user parameters for the operation
613 :return: dictionary following SOL005 format
620 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
621 "statusEnteredTime": now
,
622 "nsInstanceId": nsr_id
,
623 "lcmOperationType": operation
,
625 "isAutomaticInvocation": False,
626 "operationParams": params
,
627 "isCancelPending": False,
629 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
630 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
635 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False,
638 Performs a new operation over a ns
639 :param rollback: list to append created items at database in case a rollback must to be done
640 :param session: contains the used login username and working project
641 :param indata: descriptor with the parameters of the operation. It must contains among others
642 nsInstanceId: _id of the nsr to perform the operation
643 operation: it can be: instantiate, terminate, action, TODO: update, heal
644 :param kwargs: used to override the indata descriptor
645 :param headers: http request headers
646 :param force: If True avoid some dependence checks
647 :param make_public: Make the created item public to all projects
648 :return: id of the nslcmops
651 # Override descriptor with query string kwargs
652 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
653 operation
= indata
["lcmOperationType"]
654 nsInstanceId
= indata
["nsInstanceId"]
656 validate_input(indata
, self
.operation_schema
[operation
])
658 _filter
= BaseTopic
._get
_project
_filter
(session
, write
=True, show_all
=False)
659 _filter
["_id"] = nsInstanceId
660 nsr
= self
.db
.get_one("nsrs", _filter
)
663 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
664 if operation
== "terminate" and indata
.get("autoremove"):
665 # NSR must be deleted
666 return self
.delete(session
, nsInstanceId
)
667 if operation
!= "instantiate":
668 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
669 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
671 if operation
== "instantiate" and not indata
.get("force"):
672 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
673 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
674 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
676 if operation
== "instantiate":
677 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
679 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
680 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=make_public
)
681 _id
= self
.db
.create("nslcmops", nslcmop_desc
)
682 rollback
.append({"topic": "nslcmops", "_id": _id
})
684 self
.msg
.write("ns", operation
, nslcmop_desc
)
686 except ValidationError
as e
:
687 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
688 # except DbException as e:
689 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
691 def delete(self
, session
, _id
, force
=False, dry_run
=False):
692 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
694 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
695 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
698 class NsiTopic(BaseTopic
):
702 def __init__(self
, db
, fs
, msg
):
703 BaseTopic
.__init
__(self
, db
, fs
, msg
)
705 def _check_descriptor_dependencies(self
, session
, descriptor
):
707 Check that the dependent descriptors exist on a new descriptor or edition
708 :param session: client session information
709 :param descriptor: descriptor to be inserted or edit
710 :return: None or raises exception
712 if not descriptor
.get("nst-ref"):
714 nstd_id
= descriptor
["nst-ref"]
715 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
716 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
717 http_code
=HTTPStatus
.CONFLICT
)
720 def format_on_new(content
, project_id
=None, make_public
=False):
721 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
723 def check_conflict_on_del(self
, session
, _id
, force
=False):
726 nsi
= self
.db
.get_one("nsis", {"_id": _id
})
727 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
728 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
729 "Launch 'terminate' operation first; or force deletion".format(_id
),
730 http_code
=HTTPStatus
.CONFLICT
)
732 def delete(self
, session
, _id
, force
=False, dry_run
=False):
734 Delete item by its internal _id
735 :param session: contains the used login username, working project, and admin rights
736 :param _id: server internal id
737 :param force: indicates if deletion must be forced in case of conflict
738 :param dry_run: make checking but do not delete
739 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
741 # TODO add admin to filter, validate rights
742 BaseTopic
.delete(self
, session
, _id
, force
, dry_run
=True)
746 # deletes NetSlice instance object
747 v
= self
.db
.del_one("nsis", {"_id": _id
})
749 # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
750 _filter
= {"netsliceInstanceId": _id
}
751 self
.db
.del_list("nsilcmops", _filter
)
753 _filter
= {"operationParams.netsliceInstanceId": _id
}
754 nslcmops_list
= self
.db
.get_list("nslcmops", _filter
)
756 for id_item
in nslcmops_list
:
757 _filter
= {"_id": id_item
}
758 nslcmop
= self
.db
.get_one("nslcmops", _filter
)
759 nsr_id
= nslcmop
["operationParams"]["nsr_id"]
760 NsrTopic
.delete(self
, session
, nsr_id
, force
=False, dry_run
=False)
761 self
._send
_msg
("deleted", {"_id": _id
})
764 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False):
766 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
767 :param rollback: list to append the created items at database in case a rollback must be done
768 :param session: contains the used login username and working project
769 :param indata: params to be used for the nsir
770 :param kwargs: used to override the indata descriptor
771 :param headers: http request headers
772 :param force: If True avoid some dependence checks
773 :param make_public: Make the created item public to all projects
774 :return: the _id of nsi descriptor created at database
778 slice_request
= self
._remove
_envelop
(indata
)
779 # Override descriptor with query string kwargs
780 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
781 self
._validate
_input
_new
(slice_request
, force
)
785 self
.logger
.info(str(slice_request
))
786 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
787 _filter
= {"_id": slice_request
["nstId"]}
788 _filter
.update(BaseTopic
._get
_project
_filter
(session
, write
=False, show_all
=True))
789 nstd
= self
.db
.get_one("nsts", _filter
)
790 nstd
.pop("_admin", None)
791 nstd
.pop("_id", None)
792 nsi_id
= str(uuid4())
793 step
= "filling nsi_descriptor with input data"
795 # "instantiation-parameters.netslice-subnet": []
796 # TODO: Equal as template for now
799 "name": slice_request
["nsiName"],
800 "description": slice_request
.get("nsiDescription", ""),
801 "datacenter": slice_request
["vimAccountId"],
802 "nst-ref": nstd
["id"],
803 # "instantiate_params": slice_request,
804 "instantiation-parameters": {
805 "netslice-subnet": []
807 "network-slice-template": nstd
,
811 # Creating netslice-subnet_record.
814 for member_ns
in nstd
["netslice-subnet"]:
815 nsd_id
= member_ns
["nsd-ref"]
816 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
817 member_ns
["nsd-ref"], member_ns
["id"])
818 if nsd_id
not in needed_nsds
:
820 nsd
= DescriptorTopic
.get_one_by_id(self
.db
, session
, "nsds", nsd_id
)
822 needed_nsds
[nsd_id
] = nsd
823 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
824 services
.append(member_ns
)
826 nsd
= needed_nsds
[nsd_id
]
827 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
828 services
.append(member_ns
)
830 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
831 member_ns
["nsd-ref"], member_ns
["id"])
833 step
= "creating nsi at database"
834 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=make_public
)
835 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
837 ns_params
= indata
.get("ns")
839 # creates Network Services records (NSRs)
840 step
= "creating nsrs at database using NsrTopic.new()"
842 for service
in services
:
844 indata_ns
["nsdId"] = service
["_id"]
845 indata_ns
["nsName"] = service
["id"]
846 indata_ns
["vimAccountId"] = indata
.get("vimAccountId")
847 indata_ns
["nsDescription"] = service
["description"]
848 indata_ns
["key-pair-ref"] = None
849 # NsrTopic(rollback, session, indata_ns, kwargs, headers, force)
850 # Overwriting ns_params filtering by nsName == netslice-subnet.id
852 for ns_param
in ns_params
:
853 if ns_param
["nsName"] == service
["id"]:
854 indata_ns
.update(ns_param
)
855 _id_nsr
= NsrTopic
.new(self
, rollback
, session
, indata_ns
, kwargs
, headers
, force
)
856 nsrs_item
= {"nsrId": _id_nsr
}
857 nsrs_list
.append(nsrs_item
)
859 # Adding the nsrs list to the nsi
860 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
861 # Creating the entry in the database
862 self
.db
.create("nsis", nsi_descriptor
)
863 rollback
.append({"topic": "nsis", "_id": nsi_id
})
865 except Exception as e
:
866 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
867 raise EngineException("Error {}: {}".format(step
, e
))
868 except ValidationError
as e
:
869 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
871 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
872 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
875 class NsiLcmOpTopic(BaseTopic
):
878 operation_schema
= { # mapping between operation and jsonschema to validate
879 "instantiate": nsi_instantiate
,
883 def __init__(self
, db
, fs
, msg
):
884 BaseTopic
.__init
__(self
, db
, fs
, msg
)
886 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
888 Check that user has enter right parameters for the operation
890 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
891 :param indata: descriptor with the parameters of the operation
895 nstd
= nsir
["network-slice-template"]
897 def check_valid_netslice_subnet_id(nsId
):
898 # TODO change to vnfR (??)
899 for ns
in nstd
["netslice-subnet"]:
901 nsd_id
= ns
["nsd-ref"]
902 if nsd_id
not in nsds
:
903 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
906 raise EngineException("Invalid parameter nsId='{}' is not one of the "
907 "nst:netslice-subnet".format(nsId
))
908 if operation
== "instantiate":
909 # check the existance of netslice-subnet items
910 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
911 nstd
= check_valid_netslice_subnet_id(in_nst
["nsdId"])
913 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
919 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
920 "statusEnteredTime": now
,
921 "netsliceInstanceId": netsliceInstanceId
,
922 "lcmOperationType": operation
,
924 "isAutomaticInvocation": False,
925 "operationParams": params
,
926 "isCancelPending": False,
928 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
929 "nsInstance": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
934 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False):
936 Performs a new operation over a ns
937 :param rollback: list to append created items at database in case a rollback must to be done
938 :param session: contains the used login username and working project
939 :param indata: descriptor with the parameters of the operation. It must contains among others
940 nsiInstanceId: _id of the nsir to perform the operation
941 operation: it can be: instantiate, terminate, action, TODO: update, heal
942 :param kwargs: used to override the indata descriptor
943 :param headers: http request headers
944 :param force: If True avoid some dependence checks
945 :param make_public: Make the created item public to all projects
946 :return: id of the nslcmops
949 # Override descriptor with query string kwargs
950 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
951 operation
= indata
["lcmOperationType"]
952 nsiInstanceId
= indata
["nsiInstanceId"]
953 validate_input(indata
, self
.operation_schema
[operation
])
955 # get nsi from nsiInstanceId
956 _filter
= BaseTopic
._get
_project
_filter
(session
, write
=True, show_all
=False)
957 _filter
["_id"] = nsiInstanceId
958 nsir
= self
.db
.get_one("nsis", _filter
)
961 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
962 if operation
== "terminate" and indata
.get("autoremove"):
963 # NSIR must be deleted
964 return self
.delete(session
, nsiInstanceId
)
965 if operation
!= "instantiate":
966 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
967 nsiInstanceId
, operation
), HTTPStatus
.CONFLICT
)
969 if operation
== "instantiate" and not indata
.get("force"):
970 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
971 format(nsiInstanceId
, operation
), HTTPStatus
.CONFLICT
)
973 # Creating all the NS_operation (nslcmop)
974 # Get service list from db
975 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
977 for nsr_item
in nsrs_list
:
978 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
980 indata_ns
= service
["instantiate_params"]
981 indata_ns
["lcmOperationType"] = operation
982 indata_ns
["nsInstanceId"] = service
["_id"]
983 # Including netslice_id in the ns instantiate Operation
984 indata_ns
["netsliceInstanceId"] = nsiInstanceId
985 del indata_ns
["key-pair-ref"]
986 nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
)
987 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
988 # message via kafka bus
989 nslcmop
= nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
, force
, slice_object
=True)
990 nslcmops
.append(nslcmop
)
993 indata
["nslcmops_ids"] = nslcmops
994 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
995 nsilcmop_desc
= self
._create
_nsilcmop
(session
, nsiInstanceId
, operation
, indata
)
996 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=make_public
)
997 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
998 rollback
.append({"topic": "nsilcmops", "_id": _id
})
999 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1001 except ValidationError
as e
:
1002 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1003 # except DbException as e:
1004 # raise EngineException("Cannot get nsi_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1006 def delete(self
, session
, _id
, force
=False, dry_run
=False):
1007 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1009 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
1010 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)