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
24 from yaml
import safe_dump
26 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
29 class NsrTopic(BaseTopic
):
33 def __init__(self
, db
, fs
, msg
):
34 BaseTopic
.__init
__(self
, db
, fs
, msg
)
36 def _check_descriptor_dependencies(self
, session
, descriptor
):
38 Check that the dependent descriptors exist on a new descriptor or edition
39 :param session: client session information
40 :param descriptor: descriptor to be inserted or edit
41 :return: None or raises exception
43 if not descriptor
.get("nsdId"):
45 nsd_id
= descriptor
["nsdId"]
46 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
47 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
48 http_code
=HTTPStatus
.CONFLICT
)
51 def format_on_new(content
, project_id
=None, make_public
=False):
52 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
53 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
55 def check_conflict_on_del(self
, session
, _id
, force
=False):
58 nsr
= self
.db
.get_one("nsrs", {"_id": _id
})
59 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
60 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
61 "Launch 'terminate' operation first; or force deletion".format(_id
),
62 http_code
=HTTPStatus
.CONFLICT
)
64 def delete(self
, session
, _id
, force
=False, dry_run
=False):
66 Delete item by its internal _id
67 :param session: contains the used login username, working project, and admin rights
68 :param _id: server internal id
69 :param force: indicates if deletion must be forced in case of conflict
70 :param dry_run: make checking but do not delete
71 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
73 # TODO add admin to filter, validate rights
74 BaseTopic
.delete(self
, session
, _id
, force
, dry_run
=True)
78 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
79 v
= self
.db
.del_one("nsrs", {"_id": _id
})
80 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
81 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
82 # set all used pdus as free
83 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
84 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
85 self
._send
_msg
("deleted", {"_id": _id
})
89 def _format_ns_request(ns_request
):
90 formated_request
= copy(ns_request
)
91 formated_request
.pop("additionalParamsForNs", None)
92 formated_request
.pop("additionalParamsForVnf", None)
93 return formated_request
96 def _format_addional_params(ns_request
, member_vnf_index
=None, descriptor
=None):
98 Get and format user additional params for NS or VNF
99 :param ns_request: User instantiation additional parameters
100 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
101 :param descriptor: If not None it check that needed parameters of descriptor are supplied
102 :return: a formated copy of additional params or None if not supplied
104 additional_params
= None
105 if not member_vnf_index
:
106 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
107 where_
= "additionalParamsForNs"
108 elif ns_request
.get("additionalParamsForVnf"):
109 for additionalParamsForVnf
in get_iterable(ns_request
.get("additionalParamsForVnf")):
110 if additionalParamsForVnf
["member-vnf-index"] == member_vnf_index
:
111 additional_params
= copy(additionalParamsForVnf
.get("additionalParams"))
112 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
113 additionalParamsForVnf
["member-vnf-index"])
115 if additional_params
:
116 for k
, v
in additional_params
.items():
117 if not isinstance(k
, str):
118 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
119 if "." in k
or "$" in k
:
120 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
121 if isinstance(v
, (dict, tuple, list)):
122 additional_params
[k
] = "!!yaml " + safe_dump(v
)
125 # check that enough parameters are supplied for the initial-config-primitive
126 # TODO: check for cloud-init
128 if descriptor
.get("vnf-configuration"):
129 for initial_primitive
in get_iterable(
130 descriptor
["vnf-configuration"].get("initial-config-primitive")):
131 for param
in get_iterable(initial_primitive
.get("parameter")):
132 if param
["value"].startswith("<") and param
["value"].endswith(">"):
133 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>"):
135 if not additional_params
or param
["value"][1:-1] not in additional_params
:
136 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
137 "initial-config-primitive[name={}] not supplied".
138 format(param
["value"], descriptor
["id"],
139 initial_primitive
["name"]))
141 return additional_params
143 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False):
145 Creates a new nsr into database. It also creates needed vnfrs
146 :param rollback: list to append the created items at database in case a rollback must be done
147 :param session: contains the used login username and working project
148 :param indata: params to be used for the nsr
149 :param kwargs: used to override the indata descriptor
150 :param headers: http request headers
151 :param force: If True avoid some dependence checks
152 :param make_public: Make the created item public to all projects
153 :return: the _id of nsr descriptor created at database
157 ns_request
= self
._remove
_envelop
(indata
)
158 # Override descriptor with query string kwargs
159 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
160 self
._validate
_input
_new
(ns_request
, force
)
164 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
165 _filter
= {"_id": ns_request
["nsdId"]}
166 _filter
.update(BaseTopic
._get
_project
_filter
(session
, write
=False, show_all
=True))
167 nsd
= self
.db
.get_one("nsds", _filter
)
169 nsr_id
= str(uuid4())
172 step
= "filling nsr from input data"
174 "name": ns_request
["nsName"],
175 "name-ref": ns_request
["nsName"],
176 "short-name": ns_request
["nsName"],
177 "admin-status": "ENABLED",
179 "datacenter": ns_request
["vimAccountId"],
180 "resource-orchestrator": "osmopenmano",
181 "description": ns_request
.get("nsDescription", ""),
182 "constituent-vnfr-ref": [],
184 "operational-status": "init", # typedef ns-operational-
185 "config-status": "init", # typedef config-states
186 "detailed-status": "scheduled",
188 "orchestration-progress": {},
189 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
192 "nsd-name-ref": nsd
["name"],
193 "operational-events": [], # "id", "timestamp", "description", "event",
194 "nsd-ref": nsd
["id"],
195 "nsd-id": nsd
["_id"],
196 "instantiate_params": self
._format
_ns
_request
(ns_request
),
197 "additionalParamsForNs": self
._format
_addional
_params
(ns_request
),
198 "ns-instance-config-ref": nsr_id
,
201 # "input-parameter": xpath, value,
202 "ssh-authorized-key": ns_request
.get("key-pair-ref"), # TODO remove
204 ns_request
["nsr_id"] = nsr_id
207 nsr_descriptor
["vld"] = []
208 for nsd_vld
in nsd
.get("vld"):
209 nsr_descriptor
["vld"].append(
210 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in nsd_vld
})
214 for member_vnf
in nsd
.get("constituent-vnfd", ()):
215 vnfd_id
= member_vnf
["vnfd-id-ref"]
216 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
217 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
218 if vnfd_id
not in needed_vnfds
:
220 vnfd
= DescriptorTopic
.get_one_by_id(self
.db
, session
, "vnfds", vnfd_id
)
222 needed_vnfds
[vnfd_id
] = vnfd
224 vnfd
= needed_vnfds
[vnfd_id
]
225 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
226 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
227 vnfr_id
= str(uuid4())
231 "nsr-id-ref": nsr_id
,
232 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
233 "additionalParamsForVnf": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
236 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
238 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
239 "vim-account-id": None,
241 "connection-point": [],
242 "ip-address": None, # mgmt-interface filled by LCM
246 if vnfd
.get("internal-vld"):
247 vnfr_descriptor
["vld"] = []
248 for vnfd_vld
in vnfd
.get("internal-vld"):
249 vnfr_descriptor
["vld"].append(
250 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
253 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
254 for cp
in vnfd
.get("connection-point", ()):
257 "connection-point-id": cp
.get("id"),
259 # "ip-address", "mac-address" # filled by LCM
260 # vim-id # TODO it would be nice having a vim port id
262 vnfr_descriptor
["connection-point"].append(vnf_cp
)
263 for vdu
in vnfd
.get("vdu", ()):
265 "vdu-id-ref": vdu
["id"],
266 # TODO "name": "" Name of the VDU in the VIM
267 "ip-address": None, # mgmt-interface filled by LCM
268 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
269 "internal-connection-point": [],
272 if vdu
.get("pdu-type"):
273 vdur
["pdu-type"] = vdu
["pdu-type"]
274 # TODO volumes: name, volume-id
275 for icp
in vdu
.get("internal-connection-point", ()):
278 "connection-point-id": icp
["id"],
279 "name": icp
.get("name"),
280 # "ip-address", "mac-address" # filled by LCM
281 # vim-id # TODO it would be nice having a vim port id
283 vdur
["internal-connection-point"].append(vdu_icp
)
284 for iface
in vdu
.get("interface", ()):
286 "name": iface
.get("name"),
287 # "ip-address", "mac-address" # filled by LCM
288 # vim-id # TODO it would be nice having a vim port id
290 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
291 vdu_iface
["mgmt-vnf"] = True
292 if iface
.get("mgmt-interface"):
293 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
295 # look for network where this interface is connected
296 if iface
.get("external-connection-point-ref"):
297 for nsd_vld
in get_iterable(nsd
.get("vld")):
298 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
299 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
300 iface
["external-connection-point-ref"] and \
301 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
302 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
307 elif iface
.get("internal-connection-point-ref"):
308 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
309 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
310 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
311 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
317 vdur
["interfaces"].append(vdu_iface
)
318 count
= vdu
.get("count", 1)
321 count
= int(count
) # TODO remove when descriptor serialized with payngbind
322 for index
in range(0, count
):
324 vdur
= deepcopy(vdur
)
325 vdur
["_id"] = str(uuid4())
326 vdur
["count-index"] = index
327 vnfr_descriptor
["vdur"].append(vdur
)
329 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
330 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
333 BaseTopic
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=make_public
)
334 self
.db
.create("vnfrs", vnfr_descriptor
)
335 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
336 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
338 step
= "creating nsr at database"
339 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=make_public
)
340 self
.db
.create("nsrs", nsr_descriptor
)
341 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
343 step
= "creating nsr temporal folder"
344 self
.fs
.mkdir(nsr_id
)
347 except Exception as e
:
348 self
.logger
.exception("Exception {} at NsrTopic.new()".format(e
), exc_info
=True)
349 raise EngineException("Error {}: {}".format(step
, e
))
350 except ValidationError
as e
:
351 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
353 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
354 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
357 class VnfrTopic(BaseTopic
):
361 def __init__(self
, db
, fs
, msg
):
362 BaseTopic
.__init
__(self
, db
, fs
, msg
)
364 def delete(self
, session
, _id
, force
=False, dry_run
=False):
365 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
367 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
368 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
370 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False):
371 # Not used because vnfrs are created and deleted by NsrTopic class directly
372 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
375 class NsLcmOpTopic(BaseTopic
):
378 operation_schema
= { # mapping between operation and jsonschema to validate
379 "instantiate": ns_instantiate
,
385 def __init__(self
, db
, fs
, msg
):
386 BaseTopic
.__init
__(self
, db
, fs
, msg
)
388 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
390 Check that user has enter right parameters for the operation
392 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
393 :param indata: descriptor with the parameters of the operation
400 def check_valid_vnf_member_index(member_vnf_index
):
401 # TODO change to vnfR
402 for vnf
in nsd
["constituent-vnfd"]:
403 if member_vnf_index
== vnf
["member-vnf-index"]:
404 vnfd_id
= vnf
["vnfd-id-ref"]
405 if vnfd_id
not in vnfds
:
406 vnfds
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
407 return vnfds
[vnfd_id
]
409 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
410 "nsd:constituent-vnfd".format(member_vnf_index
))
412 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
414 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
415 for vdu
in get_iterable(vnfd
.get("vdu")):
416 if in_vdu
["id"] == vdu
["id"]:
417 for volume
in get_iterable(in_vdu
.get("volume")):
418 for volumed
in get_iterable(vdu
.get("volumes")):
419 if volumed
["name"] == volume
["name"]:
422 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
423 "volume:name='{}' is not present at vnfd:vdu:volumes list".
424 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
426 for in_iface
in get_iterable(in_vdu
["interface"]):
427 for iface
in get_iterable(vdu
.get("interface")):
428 if in_iface
["name"] == iface
["name"]:
431 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
432 "interface[name='{}'] is not present at vnfd:vdu:interface"
433 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
437 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
438 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
440 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
441 for ivld
in get_iterable(vnfd
.get("internal-vld")):
442 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
443 for in_icp
in get_iterable(in_ivld
["internal-connection-point"]):
444 for icp
in ivld
["internal-connection-point"]:
445 if in_icp
["id-ref"] == icp
["id-ref"]:
448 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
449 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
450 "vnfd:internal-vld:name/id:internal-connection-point"
451 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
452 in_icp
["id-ref"], vnfd
["id"]))
455 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
456 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
457 in_ivld
["name"], vnfd
["id"]))
459 def check_valid_vim_account(vim_account
):
460 if vim_account
in vim_accounts
:
463 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
464 db_filter
["_id"] = vim_account
465 self
.db
.get_one("vim_accounts", db_filter
)
467 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
468 vim_accounts
.append(vim_account
)
470 if operation
== "action":
471 # check vnf_member_index
472 if indata
.get("vnf_member_index"):
473 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
474 if not indata
.get("member_vnf_index"):
475 raise EngineException("Missing 'member_vnf_index' parameter")
476 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
478 for config_primitive
in get_iterable(vnfd
.get("vnf-configuration", {}).get("config-primitive")):
479 if indata
["primitive"] == config_primitive
["name"]:
480 # check needed primitive_params are provided
481 if indata
.get("primitive_params"):
482 in_primitive_params_copy
= copy(indata
["primitive_params"])
484 in_primitive_params_copy
= {}
485 for paramd
in get_iterable(config_primitive
.get("parameter")):
486 if paramd
["name"] in in_primitive_params_copy
:
487 del in_primitive_params_copy
[paramd
["name"]]
488 elif not paramd
.get("default-value"):
489 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
490 paramd
["name"], indata
["primitive"]))
491 # check no extra primitive params are provided
492 if in_primitive_params_copy
:
493 raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
494 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
497 raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata
["primitive"]))
498 if operation
== "scale":
499 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
500 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
501 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
504 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
505 "present at vnfd:scaling-group-descriptor".format(
506 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
507 if operation
== "instantiate":
509 check_valid_vim_account(indata
["vimAccountId"])
510 for in_vnf
in get_iterable(indata
.get("vnf")):
511 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
512 _check_vnf_instantiation_params(in_vnf
, vnfd
)
513 if in_vnf
.get("vimAccountId"):
514 check_valid_vim_account(in_vnf
["vimAccountId"])
516 for in_vld
in get_iterable(indata
.get("vld")):
517 for vldd
in get_iterable(nsd
.get("vld")):
518 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
521 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
524 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
526 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
527 (ip_address, ...) information.
528 Modifies PDU _admin.usageState to 'IN_USE'
530 :param session: client session information
531 :param rollback: list with the database modifications to rollback if needed
532 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
533 :param vim_account: vim_account where this vnfr should be deployed
534 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
535 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
536 of the changed vnfr is needed
538 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
539 "vim-network-name": used at VIM
540 "name": interface name
541 "vnf-vld-id": internal VNFD vld where this interface is connected, or
542 "ns-vld-id": NSD vld where this interface is connected.
543 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
546 ifaces_forcing_vim_network
= []
547 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
548 if not vdur
.get("pdu-type"):
550 pdu_type
= vdur
.get("pdu-type")
551 pdu_filter
= self
._get
_project
_filter
(session
, write
=True, show_all
=True)
552 pdu_filter
["vim_accounts"] = vim_account
553 pdu_filter
["type"] = pdu_type
554 pdu_filter
["_admin.operationalState"] = "ENABLED"
555 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
556 # TODO feature 1417: "shared": True,
558 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
559 for pdu
in available_pdus
:
560 # step 1 check if this pdu contains needed interfaces:
561 match_interfaces
= True
562 for vdur_interface
in vdur
["interfaces"]:
563 for pdu_interface
in pdu
["interfaces"]:
564 if pdu_interface
["name"] == vdur_interface
["name"]:
565 # TODO feature 1417: match per mgmt type
567 else: # no interface found for name
568 match_interfaces
= False
573 raise EngineException(
574 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
575 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
579 "_admin.usageState": pdu
["_admin"]["usageState"],
580 "_admin.usage.vnfr_id": None,
581 "_admin.usage.nsr_id": None,
582 "_admin.usage.vdur": None,
584 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
585 {"_admin.usageState": "IN_USE",
586 "_admin.usage": {"vnfr_id": vnfr
["_id"],
587 "nsr_id": vnfr
["nsr-id-ref"],
588 "vdur": vdur
["vdu-id-ref"]}
590 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
592 # step 3. Fill vnfr info by filling vdur
593 vdu_text
= "vdur.{}".format(vdur_index
)
594 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
595 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
596 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
597 for pdu_interface
in pdu
["interfaces"]:
598 if pdu_interface
["name"] == vdur_interface
["name"]:
599 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
600 for k
, v
in pdu_interface
.items():
601 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
602 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
603 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
604 if pdu_interface
.get("ip-address"):
605 if vdur_interface
.get("mgmt-interface"):
606 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
607 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
608 if vdur_interface
.get("mgmt-vnf"):
609 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
610 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
611 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
612 ifaces_forcing_vim_network
.append({
613 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
614 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
615 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
616 if pdu_interface
.get("vim-network-id"):
617 ifaces_forcing_vim_network
.append({
618 "vim-network-id": pdu_interface
.get("vim-network-id")})
619 if pdu_interface
.get("vim-network-name"):
620 ifaces_forcing_vim_network
.append({
621 "vim-network-name": pdu_interface
.get("vim-network-name")})
624 return ifaces_forcing_vim_network
626 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
630 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
634 vnfr_update_rollback
= {}
635 member_vnf_index
= vnfr
["member-vnf-index-ref"]
636 # update vim-account-id
638 vim_account
= indata
["vimAccountId"]
639 # check instantiate parameters
640 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
641 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
643 if vnf_inst_params
.get("vimAccountId"):
644 vim_account
= vnf_inst_params
.get("vimAccountId")
646 vnfr_update
["vim-account-id"] = vim_account
647 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
650 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
651 vnfr_update_rollback
)
653 # updata database vnfr
654 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
655 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
657 # Update indada in case pdu forces to use a concrete vim-network-name
658 # TODO check if user has already insert a vim-network-name and raises an error
659 if not ifaces_forcing_vim_network
:
661 for iface_info
in ifaces_forcing_vim_network
:
662 if iface_info
.get("ns-vld-id"):
663 if "vld" not in indata
:
665 indata
["vld"].append({key
: iface_info
[key
] for key
in
666 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
668 elif iface_info
.get("vnf-vld-id"):
669 if "vnf" not in indata
:
671 indata
["vnf"].append({
672 "member-vnf-index": member_vnf_index
,
673 "internal-vld": [{key
: iface_info
[key
] for key
in
674 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
678 def _create_nslcmop(nsr_id
, operation
, params
):
680 Creates a ns-lcm-opp content to be stored at database.
681 :param nsr_id: internal id of the instance
682 :param operation: instantiate, terminate, scale, action, ...
683 :param params: user parameters for the operation
684 :return: dictionary following SOL005 format
691 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
692 "statusEnteredTime": now
,
693 "nsInstanceId": nsr_id
,
694 "lcmOperationType": operation
,
696 "isAutomaticInvocation": False,
697 "operationParams": params
,
698 "isCancelPending": False,
700 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
701 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
706 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False,
709 Performs a new operation over a ns
710 :param rollback: list to append created items at database in case a rollback must to be done
711 :param session: contains the used login username and working project
712 :param indata: descriptor with the parameters of the operation. It must contains among others
713 nsInstanceId: _id of the nsr to perform the operation
714 operation: it can be: instantiate, terminate, action, TODO: update, heal
715 :param kwargs: used to override the indata descriptor
716 :param headers: http request headers
717 :param force: If True avoid some dependence checks
718 :param make_public: Make the created item public to all projects
719 :return: id of the nslcmops
722 # Override descriptor with query string kwargs
723 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
724 operation
= indata
["lcmOperationType"]
725 nsInstanceId
= indata
["nsInstanceId"]
727 validate_input(indata
, self
.operation_schema
[operation
])
729 _filter
= BaseTopic
._get
_project
_filter
(session
, write
=True, show_all
=False)
730 _filter
["_id"] = nsInstanceId
731 nsr
= self
.db
.get_one("nsrs", _filter
)
734 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
735 if operation
== "terminate" and indata
.get("autoremove"):
736 # NSR must be deleted
737 return None # a none in this case is used to indicate not instantiated. It can be removed
738 if operation
!= "instantiate":
739 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
740 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
742 if operation
== "instantiate" and not indata
.get("force"):
743 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
744 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
745 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
747 if operation
== "instantiate":
748 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
750 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
751 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=make_public
)
752 _id
= self
.db
.create("nslcmops", nslcmop_desc
)
753 rollback
.append({"topic": "nslcmops", "_id": _id
})
755 self
.msg
.write("ns", operation
, nslcmop_desc
)
757 except ValidationError
as e
:
758 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
759 # except DbException as e:
760 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
762 def delete(self
, session
, _id
, force
=False, dry_run
=False):
763 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
765 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
766 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
769 class NsiTopic(BaseTopic
):
773 def __init__(self
, db
, fs
, msg
):
774 BaseTopic
.__init
__(self
, db
, fs
, msg
)
775 self
.nsrTopic
= NsrTopic(db
, fs
, msg
)
778 def _format_ns_request(ns_request
):
779 formated_request
= copy(ns_request
)
780 # TODO: Add request params
781 return formated_request
784 def _format_addional_params(slice_request
):
786 Get and format user additional params for NS or VNF
787 :param slice_request: User instantiation additional parameters
788 :return: a formatted copy of additional params or None if not supplied
790 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
791 if additional_params
:
792 for k
, v
in additional_params
.items():
793 if not isinstance(k
, str):
794 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
796 if "." in k
or "$" in k
:
797 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
799 if isinstance(v
, (dict, tuple, list)):
800 additional_params
[k
] = "!!yaml " + safe_dump(v
)
801 return additional_params
803 def _check_descriptor_dependencies(self
, session
, descriptor
):
805 Check that the dependent descriptors exist on a new descriptor or edition
806 :param session: client session information
807 :param descriptor: descriptor to be inserted or edit
808 :return: None or raises exception
810 if not descriptor
.get("nst-ref"):
812 nstd_id
= descriptor
["nst-ref"]
813 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
814 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
815 http_code
=HTTPStatus
.CONFLICT
)
818 def format_on_new(content
, project_id
=None, make_public
=False):
819 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
821 def check_conflict_on_del(self
, session
, _id
, force
=False):
824 nsi
= self
.db
.get_one("nsis", {"_id": _id
})
825 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
826 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
827 "Launch 'terminate' operation first; or force deletion".format(_id
),
828 http_code
=HTTPStatus
.CONFLICT
)
830 def delete(self
, session
, _id
, force
=False, dry_run
=False):
832 Delete item by its internal _id
833 :param session: contains the used login username, working project, and admin rights
834 :param _id: server internal id
835 :param force: indicates if deletion must be forced in case of conflict
836 :param dry_run: make checking but do not delete
837 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
839 # TODO add admin to filter, validate rights
840 BaseTopic
.delete(self
, session
, _id
, force
, dry_run
=True)
844 # deletes NetSlice instance object
845 v
= self
.db
.del_one("nsis", {"_id": _id
})
847 # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
848 _filter
= {"netsliceInstanceId": _id
}
849 self
.db
.del_list("nsilcmops", _filter
)
851 _filter
= {"operationParams.netsliceInstanceId": _id
}
852 nslcmops_list
= self
.db
.get_list("nslcmops", _filter
)
854 for id_item
in nslcmops_list
:
855 _filter
= {"_id": id_item
}
856 nslcmop
= self
.db
.get_one("nslcmops", _filter
)
857 nsr_id
= nslcmop
["operationParams"]["nsr_id"]
858 self
.nsrTopic
.delete(session
, nsr_id
, force
=False, dry_run
=False)
859 self
._send
_msg
("deleted", {"_id": _id
})
862 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False):
864 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
865 :param rollback: list to append the created items at database in case a rollback must be done
866 :param session: contains the used login username and working project
867 :param indata: params to be used for the nsir
868 :param kwargs: used to override the indata descriptor
869 :param headers: http request headers
870 :param force: If True avoid some dependence checks
871 :param make_public: Make the created item public to all projects
872 :return: the _id of nsi descriptor created at database
876 slice_request
= self
._remove
_envelop
(indata
)
877 # Override descriptor with query string kwargs
878 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
879 self
._validate
_input
_new
(slice_request
, force
)
883 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
884 _filter
= {"_id": slice_request
["nstId"]}
885 _filter
.update(BaseTopic
._get
_project
_filter
(session
, write
=False, show_all
=True))
886 nstd
= self
.db
.get_one("nsts", _filter
)
887 nstd
.pop("_admin", None)
888 nstd
.pop("_id", None)
889 nsi_id
= str(uuid4())
890 step
= "filling nsi_descriptor with input data"
895 "name": slice_request
["nsiName"],
896 "description": slice_request
.get("nsiDescription", ""),
897 "datacenter": slice_request
["vimAccountId"],
898 "nst-ref": nstd
["id"],
899 "instantiation_parameters": slice_request
,
900 "network-slice-template": nstd
,
904 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
907 step
= "creating nsi at database"
908 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=make_public
)
909 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
910 nsi_descriptor
["_admin"]["netslice-subnet"] = None
912 # Creating netslice-vld for the RO.
913 step
= "creating netslice-vld at database"
914 instantiation_parameters
= slice_request
916 # Building the vlds list to be deployed
917 # From netslice descriptors, creating the initial list
919 if nstd
.get("netslice-vld"):
920 # Building VLDs from NST
921 for netslice_vlds
in nstd
["netslice-vld"]:
923 # Adding nst vld name and global vimAccountId for netslice vld creation
924 nsi_vld
["name"] = netslice_vlds
["name"]
925 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
926 # Getting template Instantiation parameters from NST
927 for netslice_vld
in netslice_vlds
["nss-connection-point-ref"]:
928 for netslice_subnet
in nstd
["netslice-subnet"]:
929 nsi_vld
["nsd-ref"] = netslice_subnet
["nsd-ref"]
930 nsi_vld
["nsd-connection-point-ref"] = netslice_vld
["nsd-connection-point-ref"]
931 # Obtaining the vimAccountId from template instantiation parameter
932 if netslice_subnet
.get("instantiation-parameters"):
933 # Taking the vimAccountId from NST netslice-subnet instantiation parameters
934 if netslice_subnet
["instantiation-parameters"].get("vimAccountId"):
935 netsn
= netslice_subnet
["instantiation-parameters"]["vimAccountId"]
936 nsi_vld
["vimAccountId"] = netsn
937 # Obtaining the vimAccountId from user instantiation parameter
938 if instantiation_parameters
.get("netslice-subnet"):
939 for ins_param
in instantiation_parameters
["netslice-subnet"]:
940 if ins_param
.get("id") == netslice_vld
["nss-ref"]:
941 if ins_param
.get("vimAccountId"):
942 nsi_vld
["vimAccountId"] = ins_param
["vimAccountId"]
943 # Adding vim-network-name / vim-network-id defined by the user to vld
944 if instantiation_parameters
.get("netslice-vld"):
945 for ins_param
in instantiation_parameters
["netslice-vld"]:
946 if ins_param
["name"] == netslice_vlds
["name"]:
947 if ins_param
.get("vim-network-name"):
948 nsi_vld
["vim-network-name"] = ins_param
.get("vim-network-name")
949 if ins_param
.get("vim-network-id"):
950 nsi_vld
["vim-network-id"] = ins_param
.get("vim-network-id")
951 if netslice_vlds
.get("mgmt-network"):
952 nsi_vld
["mgmt-network"] = netslice_vlds
.get("mgmt-network")
953 nsi_vlds
.append(nsi_vld
)
955 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
956 # Creating netslice-subnet_record.
960 for member_ns
in nstd
["netslice-subnet"]:
961 nsd_id
= member_ns
["nsd-ref"]
962 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
963 member_ns
["nsd-ref"], member_ns
["id"])
964 if nsd_id
not in needed_nsds
:
966 nsd
= DescriptorTopic
.get_one_by_id(self
.db
, session
, "nsds", nsd_id
)
968 needed_nsds
[nsd_id
] = nsd
969 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
970 services
.append(member_ns
)
972 nsd
= needed_nsds
[nsd_id
]
973 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
974 services
.append(member_ns
)
976 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
977 member_ns
["nsd-ref"], member_ns
["id"])
979 # check additionalParamsForSubnet contains a valid id
980 if slice_request
.get("additionalParamsForSubnet"):
981 for additional_params_subnet
in get_iterable(slice_request
.get("additionalParamsForSubnet")):
982 for service
in services
:
983 if additional_params_subnet
["id"] == service
["id"]:
986 raise EngineException("Error at additionalParamsForSubnet:id='{}' not match any "
987 "netslice-subnet:id".format(additional_params_subnet
["id"]))
989 # creates Network Services records (NSRs)
990 step
= "creating nsrs at database using NsrTopic.new()"
991 ns_params
= slice_request
.get("netslice-subnet")
994 nsi_netslice_subnet
= []
995 for service
in services
:
997 indata_ns
["nsdId"] = service
["_id"]
998 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
999 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1000 indata_ns
["nsDescription"] = service
["description"]
1001 indata_ns
["key-pair-ref"] = None
1002 for additional_params_subnet
in get_iterable(slice_request
.get("additionalParamsForSubnet")):
1003 if additional_params_subnet
["id"] == service
["id"]:
1004 if additional_params_subnet
.get("additionalParamsForNs"):
1005 indata_ns
["additionalParamsForNs"] = additional_params_subnet
["additionalParamsForNs"]
1006 if additional_params_subnet
.get("additionalParamsForVnf"):
1007 indata_ns
["additionalParamsForVnf"] = additional_params_subnet
["additionalParamsForVnf"]
1010 # NsrTopic(rollback, session, indata_ns, kwargs, headers, force)
1011 # Overwriting ns_params filtering by nsName == netslice-subnet.id
1014 for ns_param
in ns_params
:
1015 if ns_param
.get("id") == service
["id"]:
1016 copy_ns_param
= deepcopy(ns_param
)
1017 del copy_ns_param
["id"]
1018 indata_ns
.update(copy_ns_param
)
1019 # TODO: Improve network selection via networkID
1020 # Override the instantiation parameters for netslice-vld provided by user
1023 for nsi_vld
in nsi_vlds
:
1024 nsd
= self
.db
.get_one("nsds", {"id": nsi_vld
["nsd-ref"]})
1025 if nsd
["connection-point"]:
1026 for cp_item
in nsd
["connection-point"]:
1027 if cp_item
["name"] == nsi_vld
["nsd-connection-point-ref"]:
1028 vld_id_ref
= cp_item
["vld-id-ref"]
1029 # Mapping the vim-network-name or vim-network-id instantiation parameters
1030 if nsi_vld
.get("vim-network-id"):
1031 vnid
= nsi_vld
.get("vim-network-id")
1032 if type(vnid
) is not dict:
1033 vim_network_id
= {slice_request
.get("vimAccountId"): vnid
}
1035 vim_network_id
= vnid
1036 indata_ns_list
.append({"name": vld_id_ref
, "vim-network-id": vim_network_id
})
1037 # Case not vim-network-name instantiation parameter
1038 elif nsi_vld
.get("vim-network-name"):
1039 vnm
= nsi_vld
.get("vim-network-name")
1040 if type(vnm
) is not dict:
1041 vim_network_name
= {slice_request
.get("vimAccountId"): vnm
}
1043 vim_network_name
= vnm
1044 indata_ns_list
.append({"name": vld_id_ref
,
1045 "vim-network-name": vim_network_name
})
1046 # Case neither vim-network-name nor vim-network-id provided
1048 indata_ns_list
.append({"name": vld_id_ref
})
1050 indata_ns
["vld"] = indata_ns_list
1052 # Creates Nsr objects
1053 _id_nsr
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
, force
)
1054 nsrs_item
= {"nsrId": _id_nsr
}
1055 nsrs_list
.append(nsrs_item
)
1056 nsi_netslice_subnet
.append(indata_ns
)
1057 nsr_ref
= {"nsr-ref": _id_nsr
}
1058 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1060 # Adding the nsrs list to the nsi
1061 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1062 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1063 # Creating the entry in the database
1064 self
.db
.create("nsis", nsi_descriptor
)
1065 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1067 except Exception as e
:
1068 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1069 raise EngineException("Error {}: {}".format(step
, e
))
1070 except ValidationError
as e
:
1071 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1073 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
1074 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1077 class NsiLcmOpTopic(BaseTopic
):
1080 operation_schema
= { # mapping between operation and jsonschema to validate
1081 "instantiate": nsi_instantiate
,
1085 def __init__(self
, db
, fs
, msg
):
1086 BaseTopic
.__init
__(self
, db
, fs
, msg
)
1088 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1090 Check that user has enter right parameters for the operation
1092 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1093 :param indata: descriptor with the parameters of the operation
1097 nstd
= nsir
["network-slice-template"]
1099 def check_valid_netslice_subnet_id(nstId
):
1100 # TODO change to vnfR (??)
1101 for netslice_subnet
in nstd
["netslice-subnet"]:
1102 if nstId
== netslice_subnet
["id"]:
1103 nsd_id
= netslice_subnet
["nsd-ref"]
1104 if nsd_id
not in nsds
:
1105 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1108 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1109 "nst:netslice-subnet".format(nstId
))
1110 if operation
== "instantiate":
1111 # check the existance of netslice-subnet items
1112 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1113 check_valid_netslice_subnet_id(in_nst
["id"])
1115 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1121 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1122 "statusEnteredTime": now
,
1123 "netsliceInstanceId": netsliceInstanceId
,
1124 "lcmOperationType": operation
,
1126 "isAutomaticInvocation": False,
1127 "operationParams": params
,
1128 "isCancelPending": False,
1130 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1131 "nsInstance": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1136 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, force
=False, make_public
=False):
1138 Performs a new operation over a ns
1139 :param rollback: list to append created items at database in case a rollback must to be done
1140 :param session: contains the used login username and working project
1141 :param indata: descriptor with the parameters of the operation. It must contains among others
1142 nsiInstanceId: _id of the nsir to perform the operation
1143 operation: it can be: instantiate, terminate, action, TODO: update, heal
1144 :param kwargs: used to override the indata descriptor
1145 :param headers: http request headers
1146 :param force: If True avoid some dependence checks
1147 :param make_public: Make the created item public to all projects
1148 :return: id of the nslcmops
1151 # Override descriptor with query string kwargs
1152 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1153 operation
= indata
["lcmOperationType"]
1154 nsiInstanceId
= indata
["nsiInstanceId"]
1155 validate_input(indata
, self
.operation_schema
[operation
])
1157 # get nsi from nsiInstanceId
1158 _filter
= BaseTopic
._get
_project
_filter
(session
, write
=True, show_all
=False)
1159 _filter
["_id"] = nsiInstanceId
1160 nsir
= self
.db
.get_one("nsis", _filter
)
1163 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1164 if operation
== "terminate" and indata
.get("autoremove"):
1165 # NSIR must be deleted
1166 return None # a none in this case is used to indicate not instantiated. It can be removed
1167 if operation
!= "instantiate":
1168 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1169 nsiInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1171 if operation
== "instantiate" and not indata
.get("force"):
1172 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1173 format(nsiInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1175 # Creating all the NS_operation (nslcmop)
1176 # Get service list from db
1177 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1179 for nsr_item
in nsrs_list
:
1180 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1182 indata_ns
= service
["instantiate_params"]
1183 indata_ns
["lcmOperationType"] = operation
1184 indata_ns
["nsInstanceId"] = service
["_id"]
1185 # Including netslice_id in the ns instantiate Operation
1186 indata_ns
["netsliceInstanceId"] = nsiInstanceId
1187 del indata_ns
["key-pair-ref"]
1188 nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
)
1189 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1190 # message via kafka bus
1191 nslcmop
= nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
, force
, slice_object
=True)
1192 nslcmops
.append(nslcmop
)
1195 indata
["nslcmops_ids"] = nslcmops
1196 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1197 nsilcmop_desc
= self
._create
_nsilcmop
(session
, nsiInstanceId
, operation
, indata
)
1198 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=make_public
)
1199 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1200 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1201 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1203 except ValidationError
as e
:
1204 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1205 # except DbException as e:
1206 # raise EngineException("Cannot get nsi_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1208 def delete(self
, session
, _id
, force
=False, dry_run
=False):
1209 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1211 def edit(self
, session
, _id
, indata
=None, kwargs
=None, force
=False, content
=None):
1212 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)