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
25 from osm_common
.dbbase
import DbException
26 from re
import match
# For checking that additional parameter names are valid Jinja2 identifiers
28 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
31 class NsrTopic(BaseTopic
):
34 schema_new
= ns_instantiate
36 def __init__(self
, db
, fs
, msg
):
37 BaseTopic
.__init
__(self
, db
, fs
, msg
)
39 def _check_descriptor_dependencies(self
, session
, descriptor
):
41 Check that the dependent descriptors exist on a new descriptor or edition
42 :param session: client session information
43 :param descriptor: descriptor to be inserted or edit
44 :return: None or raises exception
46 if not descriptor
.get("nsdId"):
48 nsd_id
= descriptor
["nsdId"]
49 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
50 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
51 http_code
=HTTPStatus
.CONFLICT
)
54 def format_on_new(content
, project_id
=None, make_public
=False):
55 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
56 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
58 def check_conflict_on_del(self
, session
, _id
, db_content
):
60 Check that NSR is not instantiated
61 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
62 :param _id: nsr internal id
63 :param db_content: The database content of the nsr
64 :return: None or raises EngineException with the conflict
69 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
70 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
71 "Launch 'terminate' operation first; or force deletion".format(_id
),
72 http_code
=HTTPStatus
.CONFLICT
)
74 def delete_extra(self
, session
, _id
, db_content
):
76 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
77 Set usageState of pdu, vnfd, nsd
78 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
79 :param _id: server internal id
80 :param db_content: The database content of the descriptor
81 :return: None if ok or raises EngineException with the problem
83 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
84 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
85 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
87 # set all used pdus as free
88 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
89 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
93 used_nsd_id
= nsr
.get("nsd-id")
95 # check if used by another NSR
96 nsrs_list
= self
.db
.get_one("nsrs", {"nsd-id": used_nsd_id
},
97 fail_on_empty
=False, fail_on_more
=False)
99 self
.db
.set_one("nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"})
101 # Set VNFD usageState
102 used_vnfd_id_list
= nsr
.get("vnfd-id")
103 if used_vnfd_id_list
:
104 for used_vnfd_id
in used_vnfd_id_list
:
105 # check if used by another NSR
106 nsrs_list
= self
.db
.get_one("nsrs", {"vnfd-id": used_vnfd_id
},
107 fail_on_empty
=False, fail_on_more
=False)
109 self
.db
.set_one("vnfds", {"_id": used_vnfd_id
}, {"_admin.usageState": "NOT_IN_USE"})
112 def _format_ns_request(ns_request
):
113 formated_request
= copy(ns_request
)
114 formated_request
.pop("additionalParamsForNs", None)
115 formated_request
.pop("additionalParamsForVnf", None)
116 return formated_request
119 def _format_addional_params(ns_request
, member_vnf_index
=None, descriptor
=None):
121 Get and format user additional params for NS or VNF
122 :param ns_request: User instantiation additional parameters
123 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
124 :param descriptor: If not None it check that needed parameters of descriptor are supplied
125 :return: a formated copy of additional params or None if not supplied
127 additional_params
= None
128 if not member_vnf_index
:
129 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
130 where_
= "additionalParamsForNs"
131 elif ns_request
.get("additionalParamsForVnf"):
132 for additionalParamsForVnf
in get_iterable(ns_request
.get("additionalParamsForVnf")):
133 if additionalParamsForVnf
["member-vnf-index"] == member_vnf_index
:
134 additional_params
= copy(additionalParamsForVnf
.get("additionalParams"))
135 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
136 additionalParamsForVnf
["member-vnf-index"])
138 if additional_params
:
139 for k
, v
in additional_params
.items():
140 # BEGIN Check that additional parameter names are valid Jinja2 identifiers
141 if not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k
):
142 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
143 "and underscores, and cannot start with a digit"
145 # END Check that additional parameter names are valid Jinja2 identifiers
146 if not isinstance(k
, str):
147 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
148 if "." in k
or "$" in k
:
149 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
150 if isinstance(v
, (dict, tuple, list)):
151 additional_params
[k
] = "!!yaml " + safe_dump(v
)
154 # check that enough parameters are supplied for the initial-config-primitive
155 # TODO: check for cloud-init
157 if descriptor
.get("vnf-configuration"):
158 for initial_primitive
in get_iterable(
159 descriptor
["vnf-configuration"].get("initial-config-primitive")):
160 for param
in get_iterable(initial_primitive
.get("parameter")):
161 if param
["value"].startswith("<") and param
["value"].endswith(">"):
162 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>"):
164 if not additional_params
or param
["value"][1:-1] not in additional_params
:
165 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
166 "initial-config-primitive[name={}] not supplied".
167 format(param
["value"], descriptor
["id"],
168 initial_primitive
["name"]))
170 return additional_params
172 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
174 Creates a new nsr into database. It also creates needed vnfrs
175 :param rollback: list to append the created items at database in case a rollback must be done
176 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
177 :param indata: params to be used for the nsr
178 :param kwargs: used to override the indata descriptor
179 :param headers: http request headers
180 :return: the _id of nsr descriptor created at database
184 step
= "validating input parameters"
185 ns_request
= self
._remove
_envelop
(indata
)
186 # Override descriptor with query string kwargs
187 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
188 self
._validate
_input
_new
(ns_request
, session
["force"])
191 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
192 _filter
= self
._get
_project
_filter
(session
)
193 _filter
["_id"] = ns_request
["nsdId"]
194 nsd
= self
.db
.get_one("nsds", _filter
)
197 nsr_id
= str(uuid4())
200 step
= "filling nsr from input data"
202 "name": ns_request
["nsName"],
203 "name-ref": ns_request
["nsName"],
204 "short-name": ns_request
["nsName"],
205 "admin-status": "ENABLED",
207 "datacenter": ns_request
["vimAccountId"],
208 "resource-orchestrator": "osmopenmano",
209 "description": ns_request
.get("nsDescription", ""),
210 "constituent-vnfr-ref": [],
212 "operational-status": "init", # typedef ns-operational-
213 "config-status": "init", # typedef config-states
214 "detailed-status": "scheduled",
216 "orchestration-progress": {},
217 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
220 "nsd-name-ref": nsd
["name"],
221 "operational-events": [], # "id", "timestamp", "description", "event",
222 "nsd-ref": nsd
["id"],
223 "nsd-id": nsd
["_id"],
225 "instantiate_params": self
._format
_ns
_request
(ns_request
),
226 "additionalParamsForNs": self
._format
_addional
_params
(ns_request
),
227 "ns-instance-config-ref": nsr_id
,
230 # "input-parameter": xpath, value,
231 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
233 ns_request
["nsr_id"] = nsr_id
236 nsr_descriptor
["vld"] = []
237 for nsd_vld
in nsd
.get("vld"):
238 nsr_descriptor
["vld"].append(
239 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in nsd_vld
})
243 for member_vnf
in nsd
.get("constituent-vnfd", ()):
244 vnfd_id
= member_vnf
["vnfd-id-ref"]
245 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
246 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
247 if vnfd_id
not in needed_vnfds
:
249 _filter
["id"] = vnfd_id
250 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
253 needed_vnfds
[vnfd_id
] = vnfd
254 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
256 vnfd
= needed_vnfds
[vnfd_id
]
257 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
258 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
259 vnfr_id
= str(uuid4())
263 "nsr-id-ref": nsr_id
,
264 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
265 "additionalParamsForVnf": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
268 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
270 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
271 "vim-account-id": None,
273 "connection-point": [],
274 "ip-address": None, # mgmt-interface filled by LCM
278 if vnfd
.get("internal-vld"):
279 vnfr_descriptor
["vld"] = []
280 for vnfd_vld
in vnfd
.get("internal-vld"):
281 vnfr_descriptor
["vld"].append(
282 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
285 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
286 for cp
in vnfd
.get("connection-point", ()):
289 "connection-point-id": cp
.get("id"),
291 # "ip-address", "mac-address" # filled by LCM
292 # vim-id # TODO it would be nice having a vim port id
294 vnfr_descriptor
["connection-point"].append(vnf_cp
)
295 for vdu
in vnfd
.get("vdu", ()):
297 "vdu-id-ref": vdu
["id"],
298 # TODO "name": "" Name of the VDU in the VIM
299 "ip-address": None, # mgmt-interface filled by LCM
300 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
301 "internal-connection-point": [],
304 if vdu
.get("pdu-type"):
305 vdur
["pdu-type"] = vdu
["pdu-type"]
306 # TODO volumes: name, volume-id
307 for icp
in vdu
.get("internal-connection-point", ()):
310 "connection-point-id": icp
["id"],
311 "name": icp
.get("name"),
312 # "ip-address", "mac-address" # filled by LCM
313 # vim-id # TODO it would be nice having a vim port id
315 vdur
["internal-connection-point"].append(vdu_icp
)
316 for iface
in vdu
.get("interface", ()):
318 "name": iface
.get("name"),
319 # "ip-address", "mac-address" # filled by LCM
320 # vim-id # TODO it would be nice having a vim port id
322 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
323 vdu_iface
["mgmt-vnf"] = True
324 if iface
.get("mgmt-interface"):
325 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
327 # look for network where this interface is connected
328 if iface
.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 iface
["external-connection-point-ref"] and \
333 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
334 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
339 elif iface
.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") == iface
["internal-connection-point-ref"]:
343 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
349 vdur
["interfaces"].append(vdu_iface
)
350 count
= vdu
.get("count", 1)
353 count
= int(count
) # TODO remove when descriptor serialized with payngbind
354 for index
in range(0, count
):
356 vdur
= deepcopy(vdur
)
357 vdur
["_id"] = str(uuid4())
358 vdur
["count-index"] = index
359 vnfr_descriptor
["vdur"].append(vdur
)
361 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
362 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
365 BaseTopic
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
366 self
.db
.create("vnfrs", vnfr_descriptor
)
367 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
368 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
370 step
= "creating nsr at database"
371 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
372 self
.db
.create("nsrs", nsr_descriptor
)
373 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
375 step
= "creating nsr temporal folder"
376 self
.fs
.mkdir(nsr_id
)
379 except Exception as e
:
380 self
.logger
.exception("Exception {} at NsrTopic.new()".format(e
), exc_info
=True)
381 raise EngineException("Error {}: {}".format(step
, e
))
382 except ValidationError
as e
:
383 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
385 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
386 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
389 class VnfrTopic(BaseTopic
):
393 def __init__(self
, db
, fs
, msg
):
394 BaseTopic
.__init
__(self
, db
, fs
, msg
)
396 def delete(self
, session
, _id
, dry_run
=False):
397 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
399 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
400 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
402 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
403 # Not used because vnfrs are created and deleted by NsrTopic class directly
404 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
407 class NsLcmOpTopic(BaseTopic
):
410 operation_schema
= { # mapping between operation and jsonschema to validate
411 "instantiate": ns_instantiate
,
417 def __init__(self
, db
, fs
, msg
):
418 BaseTopic
.__init
__(self
, db
, fs
, msg
)
420 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
422 Check that user has enter right parameters for the operation
423 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
424 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
425 :param indata: descriptor with the parameters of the operation
433 def check_valid_vnf_member_index(member_vnf_index
):
434 # TODO change to vnfR
435 for vnf
in nsd
["constituent-vnfd"]:
436 if member_vnf_index
== vnf
["member-vnf-index"]:
437 vnfd_id
= vnf
["vnfd-id-ref"]
438 if vnfd_id
not in vnfds
:
439 vnfds
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
440 return vnfds
[vnfd_id
]
442 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
443 "nsd:constituent-vnfd".format(member_vnf_index
))
445 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
447 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
448 for vdu
in get_iterable(vnfd
.get("vdu")):
449 if in_vdu
["id"] == vdu
["id"]:
450 for volume
in get_iterable(in_vdu
.get("volume")):
451 for volumed
in get_iterable(vdu
.get("volumes")):
452 if volumed
["name"] == volume
["name"]:
455 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
456 "volume:name='{}' is not present at vnfd:vdu:volumes list".
457 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
459 for in_iface
in get_iterable(in_vdu
["interface"]):
460 for iface
in get_iterable(vdu
.get("interface")):
461 if in_iface
["name"] == iface
["name"]:
464 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
465 "interface[name='{}'] is not present at vnfd:vdu:interface"
466 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
470 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
471 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
473 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
474 for ivld
in get_iterable(vnfd
.get("internal-vld")):
475 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
476 for in_icp
in get_iterable(in_ivld
["internal-connection-point"]):
477 for icp
in ivld
["internal-connection-point"]:
478 if in_icp
["id-ref"] == icp
["id-ref"]:
481 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
482 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
483 "vnfd:internal-vld:name/id:internal-connection-point"
484 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
485 in_icp
["id-ref"], vnfd
["id"]))
488 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
489 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
490 in_ivld
["name"], vnfd
["id"]))
492 def check_valid_vim_account(vim_account
):
493 if vim_account
in vim_accounts
:
496 db_filter
= self
._get
_project
_filter
(session
)
497 db_filter
["_id"] = vim_account
498 self
.db
.get_one("vim_accounts", db_filter
)
500 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
501 vim_accounts
.append(vim_account
)
503 def check_valid_wim_account(wim_account
):
504 if not isinstance(wim_account
, str):
506 elif wim_account
in wim_accounts
:
509 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
510 db_filter
["_id"] = wim_account
511 self
.db
.get_one("wim_accounts", db_filter
)
513 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
514 wim_accounts
.append(wim_account
)
516 if operation
== "action":
517 # check vnf_member_index
518 if indata
.get("vnf_member_index"):
519 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
520 if indata
.get("member_vnf_index"):
521 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
522 descriptor_configuration
= vnfd
.get("vnf-configuration", {}).get("config-primitive")
524 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
526 for config_primitive
in get_iterable(descriptor_configuration
):
527 if indata
["primitive"] == config_primitive
["name"]:
528 # check needed primitive_params are provided
529 if indata
.get("primitive_params"):
530 in_primitive_params_copy
= copy(indata
["primitive_params"])
532 in_primitive_params_copy
= {}
533 for paramd
in get_iterable(config_primitive
.get("parameter")):
534 if paramd
["name"] in in_primitive_params_copy
:
535 del in_primitive_params_copy
[paramd
["name"]]
536 elif not paramd
.get("default-value"):
537 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
538 paramd
["name"], indata
["primitive"]))
539 # check no extra primitive params are provided
540 if in_primitive_params_copy
:
541 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
542 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
545 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
546 if operation
== "scale":
547 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
548 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
549 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
552 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
553 "present at vnfd:scaling-group-descriptor".format(
554 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
555 if operation
== "instantiate":
557 check_valid_vim_account(indata
["vimAccountId"])
558 check_valid_wim_account(indata
.get("wimAccountId"))
559 for in_vnf
in get_iterable(indata
.get("vnf")):
560 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
561 _check_vnf_instantiation_params(in_vnf
, vnfd
)
562 if in_vnf
.get("vimAccountId"):
563 check_valid_vim_account(in_vnf
["vimAccountId"])
565 for in_vld
in get_iterable(indata
.get("vld")):
566 check_valid_wim_account(in_vld
.get("wimAccountId"))
567 for vldd
in get_iterable(nsd
.get("vld")):
568 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
571 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
574 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
576 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
577 (ip_address, ...) information.
578 Modifies PDU _admin.usageState to 'IN_USE'
580 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
581 :param rollback: list with the database modifications to rollback if needed
582 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
583 :param vim_account: vim_account where this vnfr should be deployed
584 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
585 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
586 of the changed vnfr is needed
588 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
589 "vim-network-name": used at VIM
590 "name": interface name
591 "vnf-vld-id": internal VNFD vld where this interface is connected, or
592 "ns-vld-id": NSD vld where this interface is connected.
593 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
596 ifaces_forcing_vim_network
= []
597 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
598 if not vdur
.get("pdu-type"):
600 pdu_type
= vdur
.get("pdu-type")
601 pdu_filter
= self
._get
_project
_filter
(session
)
602 pdu_filter
["vim_accounts"] = vim_account
603 pdu_filter
["type"] = pdu_type
604 pdu_filter
["_admin.operationalState"] = "ENABLED"
605 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
606 # TODO feature 1417: "shared": True,
608 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
609 for pdu
in available_pdus
:
610 # step 1 check if this pdu contains needed interfaces:
611 match_interfaces
= True
612 for vdur_interface
in vdur
["interfaces"]:
613 for pdu_interface
in pdu
["interfaces"]:
614 if pdu_interface
["name"] == vdur_interface
["name"]:
615 # TODO feature 1417: match per mgmt type
617 else: # no interface found for name
618 match_interfaces
= False
623 raise EngineException(
624 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
625 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
629 "_admin.usageState": pdu
["_admin"]["usageState"],
630 "_admin.usage.vnfr_id": None,
631 "_admin.usage.nsr_id": None,
632 "_admin.usage.vdur": None,
634 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
635 {"_admin.usageState": "IN_USE",
636 "_admin.usage": {"vnfr_id": vnfr
["_id"],
637 "nsr_id": vnfr
["nsr-id-ref"],
638 "vdur": vdur
["vdu-id-ref"]}
640 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
642 # step 3. Fill vnfr info by filling vdur
643 vdu_text
= "vdur.{}".format(vdur_index
)
644 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
645 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
646 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
647 for pdu_interface
in pdu
["interfaces"]:
648 if pdu_interface
["name"] == vdur_interface
["name"]:
649 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
650 for k
, v
in pdu_interface
.items():
651 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
652 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
653 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
654 if pdu_interface
.get("ip-address"):
655 if vdur_interface
.get("mgmt-interface"):
656 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
657 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
658 if vdur_interface
.get("mgmt-vnf"):
659 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
660 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
661 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
662 ifaces_forcing_vim_network
.append({
663 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
664 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
665 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
666 if pdu_interface
.get("vim-network-id"):
667 ifaces_forcing_vim_network
.append({
668 "vim-network-id": pdu_interface
.get("vim-network-id")})
669 if pdu_interface
.get("vim-network-name"):
670 ifaces_forcing_vim_network
.append({
671 "vim-network-name": pdu_interface
.get("vim-network-name")})
674 return ifaces_forcing_vim_network
676 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
680 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
684 vnfr_update_rollback
= {}
685 member_vnf_index
= vnfr
["member-vnf-index-ref"]
686 # update vim-account-id
688 vim_account
= indata
["vimAccountId"]
689 # check instantiate parameters
690 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
691 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
693 if vnf_inst_params
.get("vimAccountId"):
694 vim_account
= vnf_inst_params
.get("vimAccountId")
696 vnfr_update
["vim-account-id"] = vim_account
697 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
700 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
701 vnfr_update_rollback
)
703 # updata database vnfr
704 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
705 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
707 # Update indada in case pdu forces to use a concrete vim-network-name
708 # TODO check if user has already insert a vim-network-name and raises an error
709 if not ifaces_forcing_vim_network
:
711 for iface_info
in ifaces_forcing_vim_network
:
712 if iface_info
.get("ns-vld-id"):
713 if "vld" not in indata
:
715 indata
["vld"].append({key
: iface_info
[key
] for key
in
716 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
718 elif iface_info
.get("vnf-vld-id"):
719 if "vnf" not in indata
:
721 indata
["vnf"].append({
722 "member-vnf-index": member_vnf_index
,
723 "internal-vld": [{key
: iface_info
[key
] for key
in
724 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
728 def _create_nslcmop(nsr_id
, operation
, params
):
730 Creates a ns-lcm-opp content to be stored at database.
731 :param nsr_id: internal id of the instance
732 :param operation: instantiate, terminate, scale, action, ...
733 :param params: user parameters for the operation
734 :return: dictionary following SOL005 format
741 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
742 "statusEnteredTime": now
,
743 "nsInstanceId": nsr_id
,
744 "lcmOperationType": operation
,
746 "isAutomaticInvocation": False,
747 "operationParams": params
,
748 "isCancelPending": False,
750 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
751 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
756 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
758 Performs a new operation over a ns
759 :param rollback: list to append created items at database in case a rollback must to be done
760 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
761 :param indata: descriptor with the parameters of the operation. It must contains among others
762 nsInstanceId: _id of the nsr to perform the operation
763 operation: it can be: instantiate, terminate, action, TODO: update, heal
764 :param kwargs: used to override the indata descriptor
765 :param headers: http request headers
766 :return: id of the nslcmops
768 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
770 db_filter
= self
._get
_project
_filter
(session
)
771 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
772 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
774 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
775 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
778 # Override descriptor with query string kwargs
779 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
780 operation
= indata
["lcmOperationType"]
781 nsInstanceId
= indata
["nsInstanceId"]
783 validate_input(indata
, self
.operation_schema
[operation
])
785 _filter
= BaseTopic
._get
_project
_filter
(session
)
786 _filter
["_id"] = nsInstanceId
787 nsr
= self
.db
.get_one("nsrs", _filter
)
790 if operation
== "terminate" and slice_object
is False:
791 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
792 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
793 if operation
== "terminate" and indata
.get("autoremove"):
794 # NSR must be deleted
795 return None # a none in this case is used to indicate not instantiated. It can be removed
796 if operation
!= "instantiate":
797 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
798 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
800 if operation
== "instantiate" and not session
["force"]:
801 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
802 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
803 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
805 if operation
== "instantiate":
806 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
808 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
809 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
810 _id
= self
.db
.create("nslcmops", nslcmop_desc
)
811 rollback
.append({"topic": "nslcmops", "_id": _id
})
813 self
.msg
.write("ns", operation
, nslcmop_desc
)
815 except ValidationError
as e
:
816 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
817 # except DbException as e:
818 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
820 def delete(self
, session
, _id
, dry_run
=False):
821 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
823 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
824 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
827 class NsiTopic(BaseTopic
):
831 def __init__(self
, db
, fs
, msg
):
832 BaseTopic
.__init
__(self
, db
, fs
, msg
)
833 self
.nsrTopic
= NsrTopic(db
, fs
, msg
)
836 def _format_ns_request(ns_request
):
837 formated_request
= copy(ns_request
)
838 # TODO: Add request params
839 return formated_request
842 def _format_addional_params(slice_request
):
844 Get and format user additional params for NS or VNF
845 :param slice_request: User instantiation additional parameters
846 :return: a formatted copy of additional params or None if not supplied
848 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
849 if additional_params
:
850 for k
, v
in additional_params
.items():
851 if not isinstance(k
, str):
852 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
854 if "." in k
or "$" in k
:
855 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
857 if isinstance(v
, (dict, tuple, list)):
858 additional_params
[k
] = "!!yaml " + safe_dump(v
)
859 return additional_params
861 def _check_descriptor_dependencies(self
, session
, descriptor
):
863 Check that the dependent descriptors exist on a new descriptor or edition
864 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
865 :param descriptor: descriptor to be inserted or edit
866 :return: None or raises exception
868 if not descriptor
.get("nst-ref"):
870 nstd_id
= descriptor
["nst-ref"]
871 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
872 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
873 http_code
=HTTPStatus
.CONFLICT
)
875 def check_conflict_on_del(self
, session
, _id
, db_content
):
877 Check that NSI is not instantiated
878 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
879 :param _id: nsi internal id
880 :param db_content: The database content of the _id
881 :return: None or raises EngineException with the conflict
886 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
887 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
888 "Launch 'terminate' operation first; or force deletion".format(_id
),
889 http_code
=HTTPStatus
.CONFLICT
)
891 def delete_extra(self
, session
, _id
, db_content
):
893 Deletes associated nsilcmops from database. Deletes associated filesystem.
894 Set usageState of nst
895 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
896 :param _id: server internal id
897 :param db_content: The database content of the descriptor
898 :return: None if ok or raises EngineException with the problem
901 # Deleting the nsrs belonging to nsir
903 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
904 nsr_id
= nsrs_detailed_item
["nsrId"]
905 if nsrs_detailed_item
.get("shared"):
906 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
907 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
908 "_id.ne": nsir
["_id"]}
909 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
910 if nsi
: # last one using nsr
913 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False)
914 except (DbException
, EngineException
) as e
:
915 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
920 # delete related nsilcmops database entries
921 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
923 # Check and set used NST usage state
924 nsir_admin
= nsir
.get("_admin")
925 if nsir_admin
and nsir_admin
.get("nst-id"):
926 # check if used by another NSI
927 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
928 fail_on_empty
=False, fail_on_more
=False)
930 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
932 # def delete(self, session, _id, dry_run=False):
934 # Delete item by its internal _id
935 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
936 # :param _id: server internal id
937 # :param dry_run: make checking but do not delete
938 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
940 # # TODO add admin to filter, validate rights
941 # BaseTopic.delete(self, session, _id, dry_run=True)
945 # # Deleting the nsrs belonging to nsir
946 # nsir = self.db.get_one("nsis", {"_id": _id})
947 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
948 # nsr_id = nsrs_detailed_item["nsrId"]
949 # if nsrs_detailed_item.get("shared"):
950 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
951 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
952 # "_id.ne": nsir["_id"]}
953 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
954 # if nsi: # last one using nsr
957 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
958 # except (DbException, EngineException) as e:
959 # if e.http_code == HTTPStatus.NOT_FOUND:
963 # # deletes NetSlice instance object
964 # v = self.db.del_one("nsis", {"_id": _id})
966 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
967 # _filter = {"netsliceInstanceId": _id}
968 # self.db.del_list("nsilcmops", _filter)
970 # # Search if nst is being used by other nsi
971 # nsir_admin = nsir.get("_admin")
973 # if nsir_admin.get("nst-id"):
974 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
975 # fail_on_empty=False, fail_on_more=False)
977 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
980 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
982 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
983 :param rollback: list to append the created items at database in case a rollback must be done
984 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
985 :param indata: params to be used for the nsir
986 :param kwargs: used to override the indata descriptor
987 :param headers: http request headers
988 :return: the _id of nsi descriptor created at database
993 slice_request
= self
._remove
_envelop
(indata
)
994 # Override descriptor with query string kwargs
995 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
996 self
._validate
_input
_new
(slice_request
, session
["force"])
999 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1000 _filter
= self
._get
_project
_filter
(session
)
1001 _filter
["_id"] = slice_request
["nstId"]
1002 nstd
= self
.db
.get_one("nsts", _filter
)
1005 nstd
.pop("_admin", None)
1006 nstd_id
= nstd
.pop("_id", None)
1007 nsi_id
= str(uuid4())
1008 step
= "filling nsi_descriptor with input data"
1013 "name": slice_request
["nsiName"],
1014 "description": slice_request
.get("nsiDescription", ""),
1015 "datacenter": slice_request
["vimAccountId"],
1016 "nst-ref": nstd
["id"],
1017 "instantiation_parameters": slice_request
,
1018 "network-slice-template": nstd
,
1022 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1025 step
= "creating nsi at database"
1026 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1027 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1028 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1029 nsi_descriptor
["_admin"]["deployed"] = {}
1030 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1031 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1033 # Creating netslice-vld for the RO.
1034 step
= "creating netslice-vld at database"
1036 # Building the vlds list to be deployed
1037 # From netslice descriptors, creating the initial list
1040 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1041 # Getting template Instantiation parameters from NST
1042 nsi_vld
= deepcopy(netslice_vlds
)
1043 nsi_vld
["shared-nsrs-list"] = []
1044 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1045 nsi_vlds
.append(nsi_vld
)
1047 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1048 # Creating netslice-subnet_record.
1052 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1053 for member_ns
in nstd
["netslice-subnet"]:
1054 nsd_id
= member_ns
["nsd-ref"]
1055 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1056 member_ns
["nsd-ref"], member_ns
["id"])
1057 if nsd_id
not in needed_nsds
:
1059 _filter
["id"] = nsd_id
1060 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1063 needed_nsds
[nsd_id
] = nsd
1065 nsd
= needed_nsds
[nsd_id
]
1066 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1067 services
.append(member_ns
)
1069 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1070 member_ns
["nsd-ref"], member_ns
["id"])
1072 # creates Network Services records (NSRs)
1073 step
= "creating nsrs at database using NsrTopic.new()"
1074 ns_params
= slice_request
.get("netslice-subnet")
1076 nsi_netslice_subnet
= []
1077 for service
in services
:
1078 # Check if the netslice-subnet is shared and if it is share if the nss exists
1081 # Is the nss shared and instantiated?
1082 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1083 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1084 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1086 if nsi
and service
.get("is-shared-nss"):
1087 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1088 for nsrs_detailed_item
in nsrs_detailed_list
:
1089 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1090 _id_nsr
= nsrs_detailed_item
["nsrId"]
1092 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1093 if netslice_subnet
["nss-id"] == service
["id"]:
1094 indata_ns
= netslice_subnet
1098 if service
.get("instantiation-parameters"):
1099 indata_ns
= deepcopy(service
["instantiation-parameters"])
1100 # del service["instantiation-parameters"]
1102 indata_ns
["nsdId"] = service
["_id"]
1103 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1104 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1105 indata_ns
["nsDescription"] = service
["description"]
1106 if slice_request
.get("ssh_keys"):
1107 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1110 for ns_param
in ns_params
:
1111 if ns_param
.get("id") == service
["id"]:
1112 copy_ns_param
= deepcopy(ns_param
)
1113 del copy_ns_param
["id"]
1114 indata_ns
.update(copy_ns_param
)
1117 # Creates Nsr objects
1118 _id_nsr
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1119 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1120 "nslcmop_instantiate": None}
1121 indata_ns
["nss-id"] = service
["id"]
1122 nsrs_list
.append(nsrs_item
)
1123 nsi_netslice_subnet
.append(indata_ns
)
1124 nsr_ref
= {"nsr-ref": _id_nsr
}
1125 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1127 # Adding the nsrs list to the nsi
1128 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1129 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1130 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1132 # Creating the entry in the database
1133 self
.db
.create("nsis", nsi_descriptor
)
1134 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1136 except Exception as e
:
1137 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1138 raise EngineException("Error {}: {}".format(step
, e
))
1139 except ValidationError
as e
:
1140 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1142 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1143 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1146 class NsiLcmOpTopic(BaseTopic
):
1149 operation_schema
= { # mapping between operation and jsonschema to validate
1150 "instantiate": nsi_instantiate
,
1154 def __init__(self
, db
, fs
, msg
):
1155 BaseTopic
.__init
__(self
, db
, fs
, msg
)
1156 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
)
1158 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1160 Check that user has enter right parameters for the operation
1161 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1162 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1163 :param indata: descriptor with the parameters of the operation
1167 nstd
= nsir
["network-slice-template"]
1169 def check_valid_netslice_subnet_id(nstId
):
1170 # TODO change to vnfR (??)
1171 for netslice_subnet
in nstd
["netslice-subnet"]:
1172 if nstId
== netslice_subnet
["id"]:
1173 nsd_id
= netslice_subnet
["nsd-ref"]
1174 if nsd_id
not in nsds
:
1175 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1178 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1179 "nst:netslice-subnet".format(nstId
))
1180 if operation
== "instantiate":
1181 # check the existance of netslice-subnet items
1182 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1183 check_valid_netslice_subnet_id(in_nst
["id"])
1185 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1191 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1192 "statusEnteredTime": now
,
1193 "netsliceInstanceId": netsliceInstanceId
,
1194 "lcmOperationType": operation
,
1196 "isAutomaticInvocation": False,
1197 "operationParams": params
,
1198 "isCancelPending": False,
1200 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1201 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1206 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1207 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1208 if nst_sb_item
.get("is-shared-nss"):
1209 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1210 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1211 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1212 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1213 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1214 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1215 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1217 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1218 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1220 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1222 Performs a new operation over a ns
1223 :param rollback: list to append created items at database in case a rollback must to be done
1224 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1225 :param indata: descriptor with the parameters of the operation. It must contains among others
1226 netsliceInstanceId: _id of the nsir to perform the operation
1227 operation: it can be: instantiate, terminate, action, TODO: update, heal
1228 :param kwargs: used to override the indata descriptor
1229 :param headers: http request headers
1230 :return: id of the nslcmops
1233 # Override descriptor with query string kwargs
1234 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1235 operation
= indata
["lcmOperationType"]
1236 netsliceInstanceId
= indata
["netsliceInstanceId"]
1237 validate_input(indata
, self
.operation_schema
[operation
])
1239 # get nsi from netsliceInstanceId
1240 _filter
= self
._get
_project
_filter
(session
)
1241 _filter
["_id"] = netsliceInstanceId
1242 nsir
= self
.db
.get_one("nsis", _filter
)
1246 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1247 if operation
== "terminate" and indata
.get("autoremove"):
1248 # NSIR must be deleted
1249 return None # a none in this case is used to indicate not instantiated. It can be removed
1250 if operation
!= "instantiate":
1251 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1252 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1254 if operation
== "instantiate" and not session
["force"]:
1255 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1256 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1258 # Creating all the NS_operation (nslcmop)
1259 # Get service list from db
1260 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1262 # nslcmops_item = None
1263 for index
, nsr_item
in enumerate(nsrs_list
):
1265 if nsr_item
.get("shared"):
1266 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1267 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item
["nsrId"]
1268 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1269 _filter
["_id.ne"] = netsliceInstanceId
1270 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1271 if operation
== "terminate":
1272 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1273 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1275 # looks the first nsi fulfilling the conditions but not being the current NSIR
1277 nsi_admin_shared
= nsi
["_admin"]["nsrs-detailed-list"]
1278 for nsi_nsr_item
in nsi_admin_shared
:
1279 if nsi_nsr_item
["nsd-id"] == nsr_item
["nsd-id"] and nsi_nsr_item
["shared"]:
1280 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1281 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1282 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1283 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1285 # continue to not create nslcmop since nsrs is shared and nsrs was created
1288 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1291 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1293 indata_ns
= service
["instantiate_params"]
1294 indata_ns
["lcmOperationType"] = operation
1295 indata_ns
["nsInstanceId"] = service
["_id"]
1296 # Including netslice_id in the ns instantiate Operation
1297 indata_ns
["netsliceInstanceId"] = netsliceInstanceId
1298 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1299 # message via kafka bus
1300 nslcmop
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
,
1302 nslcmops
.append(nslcmop
)
1303 if operation
== "terminate":
1305 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1306 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1307 except (DbException
, EngineException
) as e
:
1308 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1309 self
.logger
.info("HTTPStatus.NOT_FOUND")
1315 indata
["nslcmops_ids"] = nslcmops
1316 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1318 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1319 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1320 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1321 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1322 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1324 except ValidationError
as e
:
1325 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1327 def delete(self
, session
, _id
, dry_run
=False):
1328 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1330 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1331 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)