1 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 from uuid
import uuid4
18 from http
import HTTPStatus
20 from copy
import copy
, deepcopy
21 from osm_nbi
.validation
import validate_input
, ValidationError
, ns_instantiate
, ns_action
, ns_scale
, nsi_instantiate
22 from osm_nbi
.base_topic
import BaseTopic
, EngineException
, get_iterable
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"
59 def check_conflict_on_del(self
, session
, _id
, db_content
):
61 Check that NSR is not instantiated
62 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
63 :param _id: nsr internal id
64 :param db_content: The database content of the nsr
65 :return: None or raises EngineException with the conflict
70 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
71 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
72 "Launch 'terminate' operation first; or force deletion".format(_id
),
73 http_code
=HTTPStatus
.CONFLICT
)
75 def delete_extra(self
, session
, _id
, db_content
):
77 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
78 Set usageState of pdu, vnfd, nsd
79 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
80 :param _id: server internal id
81 :param db_content: The database content of the descriptor
82 :return: None if ok or raises EngineException with the problem
84 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
85 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
86 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
88 # set all used pdus as free
89 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
90 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
94 used_nsd_id
= nsr
.get("nsd-id")
96 # check if used by another NSR
97 nsrs_list
= self
.db
.get_one("nsrs", {"nsd-id": used_nsd_id
},
98 fail_on_empty
=False, fail_on_more
=False)
100 self
.db
.set_one("nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"})
102 # Set VNFD usageState
103 used_vnfd_id_list
= nsr
.get("vnfd-id")
104 if used_vnfd_id_list
:
105 for used_vnfd_id
in used_vnfd_id_list
:
106 # check if used by another NSR
107 nsrs_list
= self
.db
.get_one("nsrs", {"vnfd-id": used_vnfd_id
},
108 fail_on_empty
=False, fail_on_more
=False)
110 self
.db
.set_one("vnfds", {"_id": used_vnfd_id
}, {"_admin.usageState": "NOT_IN_USE"})
113 def _format_ns_request(ns_request
):
114 formated_request
= copy(ns_request
)
115 formated_request
.pop("additionalParamsForNs", None)
116 formated_request
.pop("additionalParamsForVnf", None)
117 return formated_request
120 def _format_addional_params(ns_request
, member_vnf_index
=None, descriptor
=None):
122 Get and format user additional params for NS or VNF
123 :param ns_request: User instantiation additional parameters
124 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
125 :param descriptor: If not None it check that needed parameters of descriptor are supplied
126 :return: a formated copy of additional params or None if not supplied
128 additional_params
= None
129 if not member_vnf_index
:
130 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
131 where_
= "additionalParamsForNs"
132 elif ns_request
.get("additionalParamsForVnf"):
133 for additionalParamsForVnf
in get_iterable(ns_request
.get("additionalParamsForVnf")):
134 if additionalParamsForVnf
["member-vnf-index"] == member_vnf_index
:
135 additional_params
= copy(additionalParamsForVnf
.get("additionalParams"))
136 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
137 additionalParamsForVnf
["member-vnf-index"])
139 if additional_params
:
140 for k
, v
in additional_params
.items():
141 # BEGIN Check that additional parameter names are valid Jinja2 identifiers
142 if not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k
):
143 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
144 "and underscores, and cannot start with a digit"
146 # END Check that additional parameter names are valid Jinja2 identifiers
147 if not isinstance(k
, str):
148 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
149 if "." in k
or "$" in k
:
150 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
151 if isinstance(v
, (dict, tuple, list)):
152 additional_params
[k
] = "!!yaml " + safe_dump(v
)
155 # check that enough parameters are supplied for the initial-config-primitive
156 # TODO: check for cloud-init
158 if descriptor
.get("vnf-configuration"):
159 for initial_primitive
in get_iterable(
160 descriptor
["vnf-configuration"].get("initial-config-primitive")):
161 for param
in get_iterable(initial_primitive
.get("parameter")):
162 if param
["value"].startswith("<") and param
["value"].endswith(">"):
163 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>"):
165 if not additional_params
or param
["value"][1:-1] not in additional_params
:
166 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
167 "initial-config-primitive[name={}] not supplied".
168 format(param
["value"], descriptor
["id"],
169 initial_primitive
["name"]))
171 return additional_params
173 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
175 Creates a new nsr into database. It also creates needed vnfrs
176 :param rollback: list to append the created items at database in case a rollback must be done
177 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
178 :param indata: params to be used for the nsr
179 :param kwargs: used to override the indata descriptor
180 :param headers: http request headers
181 :return: the _id of nsr descriptor created at database
185 step
= "validating input parameters"
186 ns_request
= self
._remove
_envelop
(indata
)
187 # Override descriptor with query string kwargs
188 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
189 self
._validate
_input
_new
(ns_request
, session
["force"])
192 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
193 _filter
= self
._get
_project
_filter
(session
)
194 _filter
["_id"] = ns_request
["nsdId"]
195 nsd
= self
.db
.get_one("nsds", _filter
)
198 nsr_id
= str(uuid4())
201 step
= "filling nsr from input data"
203 "name": ns_request
["nsName"],
204 "name-ref": ns_request
["nsName"],
205 "short-name": ns_request
["nsName"],
206 "admin-status": "ENABLED",
208 "datacenter": ns_request
["vimAccountId"],
209 "resource-orchestrator": "osmopenmano",
210 "description": ns_request
.get("nsDescription", ""),
211 "constituent-vnfr-ref": [],
213 "operational-status": "init", # typedef ns-operational-
214 "config-status": "init", # typedef config-states
215 "detailed-status": "scheduled",
217 "orchestration-progress": {},
218 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
221 "nsd-name-ref": nsd
["name"],
222 "operational-events": [], # "id", "timestamp", "description", "event",
223 "nsd-ref": nsd
["id"],
224 "nsd-id": nsd
["_id"],
226 "instantiate_params": self
._format
_ns
_request
(ns_request
),
227 "additionalParamsForNs": self
._format
_addional
_params
(ns_request
),
228 "ns-instance-config-ref": nsr_id
,
231 # "input-parameter": xpath, value,
232 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
234 ns_request
["nsr_id"] = nsr_id
237 nsr_descriptor
["vld"] = []
238 for nsd_vld
in nsd
.get("vld"):
239 nsr_descriptor
["vld"].append(
240 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in nsd_vld
})
244 for member_vnf
in nsd
.get("constituent-vnfd", ()):
245 vnfd_id
= member_vnf
["vnfd-id-ref"]
246 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
247 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
248 if vnfd_id
not in needed_vnfds
:
250 _filter
["id"] = vnfd_id
251 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
254 needed_vnfds
[vnfd_id
] = vnfd
255 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
257 vnfd
= needed_vnfds
[vnfd_id
]
258 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
259 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
260 vnfr_id
= str(uuid4())
264 "nsr-id-ref": nsr_id
,
265 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
266 "additionalParamsForVnf": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
269 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
271 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
272 "vim-account-id": None,
274 "connection-point": [],
275 "ip-address": None, # mgmt-interface filled by LCM
279 if vnfd
.get("internal-vld"):
280 vnfr_descriptor
["vld"] = []
281 for vnfd_vld
in vnfd
.get("internal-vld"):
282 vnfr_descriptor
["vld"].append(
283 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
286 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
287 for cp
in vnfd
.get("connection-point", ()):
290 "connection-point-id": cp
.get("id"),
292 # "ip-address", "mac-address" # filled by LCM
293 # vim-id # TODO it would be nice having a vim port id
295 vnfr_descriptor
["connection-point"].append(vnf_cp
)
296 for vdu
in vnfd
.get("vdu", ()):
298 "vdu-id-ref": vdu
["id"],
299 # TODO "name": "" Name of the VDU in the VIM
300 "ip-address": None, # mgmt-interface filled by LCM
301 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
302 "internal-connection-point": [],
305 if vdu
.get("pdu-type"):
306 vdur
["pdu-type"] = vdu
["pdu-type"]
307 # TODO volumes: name, volume-id
308 for icp
in vdu
.get("internal-connection-point", ()):
311 "connection-point-id": icp
["id"],
312 "name": icp
.get("name"),
313 # "ip-address", "mac-address" # filled by LCM
314 # vim-id # TODO it would be nice having a vim port id
316 vdur
["internal-connection-point"].append(vdu_icp
)
317 for iface
in vdu
.get("interface", ()):
319 "name": iface
.get("name"),
320 # "ip-address", "mac-address" # filled by LCM
321 # vim-id # TODO it would be nice having a vim port id
323 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
324 vdu_iface
["mgmt-vnf"] = True
325 if iface
.get("mgmt-interface"):
326 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
328 # look for network where this interface is connected
329 if iface
.get("external-connection-point-ref"):
330 for nsd_vld
in get_iterable(nsd
.get("vld")):
331 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
332 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
333 iface
["external-connection-point-ref"] and \
334 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
335 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
340 elif iface
.get("internal-connection-point-ref"):
341 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
342 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
343 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
344 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
350 vdur
["interfaces"].append(vdu_iface
)
351 count
= vdu
.get("count", 1)
354 count
= int(count
) # TODO remove when descriptor serialized with payngbind
355 for index
in range(0, count
):
357 vdur
= deepcopy(vdur
)
358 vdur
["_id"] = str(uuid4())
359 vdur
["count-index"] = index
360 vnfr_descriptor
["vdur"].append(vdur
)
362 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
363 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
366 self
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
367 self
.db
.create("vnfrs", vnfr_descriptor
)
368 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
369 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
371 step
= "creating nsr at database"
372 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
373 self
.db
.create("nsrs", nsr_descriptor
)
374 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
376 step
= "creating nsr temporal folder"
377 self
.fs
.mkdir(nsr_id
)
380 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
381 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
382 except Exception as e
:
383 self
.logger
.exception("Exception {} at NsrTopic.new()".format(e
), exc_info
=True)
384 raise EngineException("Error {}: {}".format(step
, e
))
386 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
387 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
390 class VnfrTopic(BaseTopic
):
394 def __init__(self
, db
, fs
, msg
):
395 BaseTopic
.__init
__(self
, db
, fs
, msg
)
397 def delete(self
, session
, _id
, dry_run
=False):
398 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
400 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
401 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
403 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
404 # Not used because vnfrs are created and deleted by NsrTopic class directly
405 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
408 class NsLcmOpTopic(BaseTopic
):
411 operation_schema
= { # mapping between operation and jsonschema to validate
412 "instantiate": ns_instantiate
,
418 def __init__(self
, db
, fs
, msg
):
419 BaseTopic
.__init
__(self
, db
, fs
, msg
)
421 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
423 Check that user has enter right parameters for the operation
424 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
425 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
426 :param indata: descriptor with the parameters of the operation
434 def check_valid_vnf_member_index(member_vnf_index
):
435 # TODO change to vnfR
436 for vnf
in nsd
["constituent-vnfd"]:
437 if member_vnf_index
== vnf
["member-vnf-index"]:
438 vnfd_id
= vnf
["vnfd-id-ref"]
439 if vnfd_id
not in vnfds
:
440 vnfds
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
441 return vnfds
[vnfd_id
]
443 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
444 "nsd:constituent-vnfd".format(member_vnf_index
))
446 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
448 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
449 for vdu
in get_iterable(vnfd
.get("vdu")):
450 if in_vdu
["id"] == vdu
["id"]:
451 for volume
in get_iterable(in_vdu
.get("volume")):
452 for volumed
in get_iterable(vdu
.get("volumes")):
453 if volumed
["name"] == volume
["name"]:
456 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
457 "volume:name='{}' is not present at vnfd:vdu:volumes list".
458 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
460 for in_iface
in get_iterable(in_vdu
["interface"]):
461 for iface
in get_iterable(vdu
.get("interface")):
462 if in_iface
["name"] == iface
["name"]:
465 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
466 "interface[name='{}'] is not present at vnfd:vdu:interface"
467 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
471 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
472 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
474 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
475 for ivld
in get_iterable(vnfd
.get("internal-vld")):
476 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
477 for in_icp
in get_iterable(in_ivld
["internal-connection-point"]):
478 for icp
in ivld
["internal-connection-point"]:
479 if in_icp
["id-ref"] == icp
["id-ref"]:
482 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
483 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
484 "vnfd:internal-vld:name/id:internal-connection-point"
485 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
486 in_icp
["id-ref"], vnfd
["id"]))
489 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
490 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
491 in_ivld
["name"], vnfd
["id"]))
493 def check_valid_vim_account(vim_account
):
494 if vim_account
in vim_accounts
:
497 db_filter
= self
._get
_project
_filter
(session
)
498 db_filter
["_id"] = vim_account
499 self
.db
.get_one("vim_accounts", db_filter
)
501 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
502 vim_accounts
.append(vim_account
)
504 def check_valid_wim_account(wim_account
):
505 if not isinstance(wim_account
, str):
507 elif wim_account
in wim_accounts
:
510 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
511 db_filter
["_id"] = wim_account
512 self
.db
.get_one("wim_accounts", db_filter
)
514 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
515 wim_accounts
.append(wim_account
)
517 if operation
== "action":
518 # check vnf_member_index
519 if indata
.get("vnf_member_index"):
520 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
521 if indata
.get("member_vnf_index"):
522 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
523 descriptor_configuration
= vnfd
.get("vnf-configuration", {}).get("config-primitive")
525 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
527 for config_primitive
in get_iterable(descriptor_configuration
):
528 if indata
["primitive"] == config_primitive
["name"]:
529 # check needed primitive_params are provided
530 if indata
.get("primitive_params"):
531 in_primitive_params_copy
= copy(indata
["primitive_params"])
533 in_primitive_params_copy
= {}
534 for paramd
in get_iterable(config_primitive
.get("parameter")):
535 if paramd
["name"] in in_primitive_params_copy
:
536 del in_primitive_params_copy
[paramd
["name"]]
537 elif not paramd
.get("default-value"):
538 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
539 paramd
["name"], indata
["primitive"]))
540 # check no extra primitive params are provided
541 if in_primitive_params_copy
:
542 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
543 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
546 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
547 if operation
== "scale":
548 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
549 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
550 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
553 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
554 "present at vnfd:scaling-group-descriptor".format(
555 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
556 if operation
== "instantiate":
558 check_valid_vim_account(indata
["vimAccountId"])
559 check_valid_wim_account(indata
.get("wimAccountId"))
560 for in_vnf
in get_iterable(indata
.get("vnf")):
561 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
562 _check_vnf_instantiation_params(in_vnf
, vnfd
)
563 if in_vnf
.get("vimAccountId"):
564 check_valid_vim_account(in_vnf
["vimAccountId"])
566 for in_vld
in get_iterable(indata
.get("vld")):
567 check_valid_wim_account(in_vld
.get("wimAccountId"))
568 for vldd
in get_iterable(nsd
.get("vld")):
569 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
572 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
575 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
577 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
578 (ip_address, ...) information.
579 Modifies PDU _admin.usageState to 'IN_USE'
581 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
582 :param rollback: list with the database modifications to rollback if needed
583 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
584 :param vim_account: vim_account where this vnfr should be deployed
585 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
586 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
587 of the changed vnfr is needed
589 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
590 "vim-network-name": used at VIM
591 "name": interface name
592 "vnf-vld-id": internal VNFD vld where this interface is connected, or
593 "ns-vld-id": NSD vld where this interface is connected.
594 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
597 ifaces_forcing_vim_network
= []
598 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
599 if not vdur
.get("pdu-type"):
601 pdu_type
= vdur
.get("pdu-type")
602 pdu_filter
= self
._get
_project
_filter
(session
)
603 pdu_filter
["vim_accounts"] = vim_account
604 pdu_filter
["type"] = pdu_type
605 pdu_filter
["_admin.operationalState"] = "ENABLED"
606 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
607 # TODO feature 1417: "shared": True,
609 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
610 for pdu
in available_pdus
:
611 # step 1 check if this pdu contains needed interfaces:
612 match_interfaces
= True
613 for vdur_interface
in vdur
["interfaces"]:
614 for pdu_interface
in pdu
["interfaces"]:
615 if pdu_interface
["name"] == vdur_interface
["name"]:
616 # TODO feature 1417: match per mgmt type
618 else: # no interface found for name
619 match_interfaces
= False
624 raise EngineException(
625 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
626 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
630 "_admin.usageState": pdu
["_admin"]["usageState"],
631 "_admin.usage.vnfr_id": None,
632 "_admin.usage.nsr_id": None,
633 "_admin.usage.vdur": None,
635 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
636 {"_admin.usageState": "IN_USE",
637 "_admin.usage": {"vnfr_id": vnfr
["_id"],
638 "nsr_id": vnfr
["nsr-id-ref"],
639 "vdur": vdur
["vdu-id-ref"]}
641 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
643 # step 3. Fill vnfr info by filling vdur
644 vdu_text
= "vdur.{}".format(vdur_index
)
645 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
646 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
647 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
648 for pdu_interface
in pdu
["interfaces"]:
649 if pdu_interface
["name"] == vdur_interface
["name"]:
650 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
651 for k
, v
in pdu_interface
.items():
652 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
653 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
654 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
655 if pdu_interface
.get("ip-address"):
656 if vdur_interface
.get("mgmt-interface"):
657 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
658 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
659 if vdur_interface
.get("mgmt-vnf"):
660 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
661 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
662 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
663 ifaces_forcing_vim_network
.append({
664 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
665 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
666 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
667 if pdu_interface
.get("vim-network-id"):
668 ifaces_forcing_vim_network
.append({
669 "vim-network-id": pdu_interface
.get("vim-network-id")})
670 if pdu_interface
.get("vim-network-name"):
671 ifaces_forcing_vim_network
.append({
672 "vim-network-name": pdu_interface
.get("vim-network-name")})
675 return ifaces_forcing_vim_network
677 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
681 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
685 vnfr_update_rollback
= {}
686 member_vnf_index
= vnfr
["member-vnf-index-ref"]
687 # update vim-account-id
689 vim_account
= indata
["vimAccountId"]
690 # check instantiate parameters
691 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
692 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
694 if vnf_inst_params
.get("vimAccountId"):
695 vim_account
= vnf_inst_params
.get("vimAccountId")
697 vnfr_update
["vim-account-id"] = vim_account
698 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
701 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
702 vnfr_update_rollback
)
704 # updata database vnfr
705 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
706 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
708 # Update indada in case pdu forces to use a concrete vim-network-name
709 # TODO check if user has already insert a vim-network-name and raises an error
710 if not ifaces_forcing_vim_network
:
712 for iface_info
in ifaces_forcing_vim_network
:
713 if iface_info
.get("ns-vld-id"):
714 if "vld" not in indata
:
716 indata
["vld"].append({key
: iface_info
[key
] for key
in
717 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
719 elif iface_info
.get("vnf-vld-id"):
720 if "vnf" not in indata
:
722 indata
["vnf"].append({
723 "member-vnf-index": member_vnf_index
,
724 "internal-vld": [{key
: iface_info
[key
] for key
in
725 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
729 def _create_nslcmop(nsr_id
, operation
, params
):
731 Creates a ns-lcm-opp content to be stored at database.
732 :param nsr_id: internal id of the instance
733 :param operation: instantiate, terminate, scale, action, ...
734 :param params: user parameters for the operation
735 :return: dictionary following SOL005 format
742 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
743 "statusEnteredTime": now
,
744 "nsInstanceId": nsr_id
,
745 "lcmOperationType": operation
,
747 "isAutomaticInvocation": False,
748 "operationParams": params
,
749 "isCancelPending": False,
751 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
752 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
757 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
759 Performs a new operation over a ns
760 :param rollback: list to append created items at database in case a rollback must to be done
761 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
762 :param indata: descriptor with the parameters of the operation. It must contains among others
763 nsInstanceId: _id of the nsr to perform the operation
764 operation: it can be: instantiate, terminate, action, TODO: update, heal
765 :param kwargs: used to override the indata descriptor
766 :param headers: http request headers
767 :return: id of the nslcmops
769 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
771 db_filter
= self
._get
_project
_filter
(session
)
772 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
773 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
775 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
776 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
779 # Override descriptor with query string kwargs
780 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
781 operation
= indata
["lcmOperationType"]
782 nsInstanceId
= indata
["nsInstanceId"]
784 validate_input(indata
, self
.operation_schema
[operation
])
786 _filter
= BaseTopic
._get
_project
_filter
(session
)
787 _filter
["_id"] = nsInstanceId
788 nsr
= self
.db
.get_one("nsrs", _filter
)
791 if operation
== "terminate" and slice_object
is False:
792 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
793 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
794 if operation
== "terminate" and indata
.get("autoremove"):
795 # NSR must be deleted
796 return None # a none in this case is used to indicate not instantiated. It can be removed
797 if operation
!= "instantiate":
798 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
799 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
801 if operation
== "instantiate" and not session
["force"]:
802 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
803 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
804 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
806 if operation
== "instantiate":
807 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
809 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
810 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
811 _id
= self
.db
.create("nslcmops", nslcmop_desc
)
812 rollback
.append({"topic": "nslcmops", "_id": _id
})
814 self
.msg
.write("ns", operation
, nslcmop_desc
)
816 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
817 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
818 # except DbException as e:
819 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
821 def delete(self
, session
, _id
, dry_run
=False):
822 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
824 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
825 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
828 class NsiTopic(BaseTopic
):
832 def __init__(self
, db
, fs
, msg
):
833 BaseTopic
.__init
__(self
, db
, fs
, msg
)
834 self
.nsrTopic
= NsrTopic(db
, fs
, msg
)
837 def _format_ns_request(ns_request
):
838 formated_request
= copy(ns_request
)
839 # TODO: Add request params
840 return formated_request
843 def _format_addional_params(slice_request
):
845 Get and format user additional params for NS or VNF
846 :param slice_request: User instantiation additional parameters
847 :return: a formatted copy of additional params or None if not supplied
849 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
850 if additional_params
:
851 for k
, v
in additional_params
.items():
852 if not isinstance(k
, str):
853 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
855 if "." in k
or "$" in k
:
856 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
858 if isinstance(v
, (dict, tuple, list)):
859 additional_params
[k
] = "!!yaml " + safe_dump(v
)
860 return additional_params
862 def _check_descriptor_dependencies(self
, session
, descriptor
):
864 Check that the dependent descriptors exist on a new descriptor or edition
865 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
866 :param descriptor: descriptor to be inserted or edit
867 :return: None or raises exception
869 if not descriptor
.get("nst-ref"):
871 nstd_id
= descriptor
["nst-ref"]
872 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
873 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
874 http_code
=HTTPStatus
.CONFLICT
)
876 def check_conflict_on_del(self
, session
, _id
, db_content
):
878 Check that NSI is not instantiated
879 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
880 :param _id: nsi internal id
881 :param db_content: The database content of the _id
882 :return: None or raises EngineException with the conflict
887 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
888 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
889 "Launch 'terminate' operation first; or force deletion".format(_id
),
890 http_code
=HTTPStatus
.CONFLICT
)
892 def delete_extra(self
, session
, _id
, db_content
):
894 Deletes associated nsilcmops from database. Deletes associated filesystem.
895 Set usageState of nst
896 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
897 :param _id: server internal id
898 :param db_content: The database content of the descriptor
899 :return: None if ok or raises EngineException with the problem
902 # Deleting the nsrs belonging to nsir
904 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
905 nsr_id
= nsrs_detailed_item
["nsrId"]
906 if nsrs_detailed_item
.get("shared"):
907 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
908 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
909 "_id.ne": nsir
["_id"]}
910 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
911 if nsi
: # last one using nsr
914 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False)
915 except (DbException
, EngineException
) as e
:
916 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
921 # delete related nsilcmops database entries
922 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
924 # Check and set used NST usage state
925 nsir_admin
= nsir
.get("_admin")
926 if nsir_admin
and nsir_admin
.get("nst-id"):
927 # check if used by another NSI
928 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
929 fail_on_empty
=False, fail_on_more
=False)
931 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
933 # def delete(self, session, _id, dry_run=False):
935 # Delete item by its internal _id
936 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
937 # :param _id: server internal id
938 # :param dry_run: make checking but do not delete
939 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
941 # # TODO add admin to filter, validate rights
942 # BaseTopic.delete(self, session, _id, dry_run=True)
946 # # Deleting the nsrs belonging to nsir
947 # nsir = self.db.get_one("nsis", {"_id": _id})
948 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
949 # nsr_id = nsrs_detailed_item["nsrId"]
950 # if nsrs_detailed_item.get("shared"):
951 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
952 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
953 # "_id.ne": nsir["_id"]}
954 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
955 # if nsi: # last one using nsr
958 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
959 # except (DbException, EngineException) as e:
960 # if e.http_code == HTTPStatus.NOT_FOUND:
964 # # deletes NetSlice instance object
965 # v = self.db.del_one("nsis", {"_id": _id})
967 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
968 # _filter = {"netsliceInstanceId": _id}
969 # self.db.del_list("nsilcmops", _filter)
971 # # Search if nst is being used by other nsi
972 # nsir_admin = nsir.get("_admin")
974 # if nsir_admin.get("nst-id"):
975 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
976 # fail_on_empty=False, fail_on_more=False)
978 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
981 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
983 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
984 :param rollback: list to append the created items at database in case a rollback must be done
985 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
986 :param indata: params to be used for the nsir
987 :param kwargs: used to override the indata descriptor
988 :param headers: http request headers
989 :return: the _id of nsi descriptor created at database
994 slice_request
= self
._remove
_envelop
(indata
)
995 # Override descriptor with query string kwargs
996 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
997 self
._validate
_input
_new
(slice_request
, session
["force"])
1000 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1001 _filter
= self
._get
_project
_filter
(session
)
1002 _filter
["_id"] = slice_request
["nstId"]
1003 nstd
= self
.db
.get_one("nsts", _filter
)
1006 nstd
.pop("_admin", None)
1007 nstd_id
= nstd
.pop("_id", None)
1008 nsi_id
= str(uuid4())
1009 step
= "filling nsi_descriptor with input data"
1014 "name": slice_request
["nsiName"],
1015 "description": slice_request
.get("nsiDescription", ""),
1016 "datacenter": slice_request
["vimAccountId"],
1017 "nst-ref": nstd
["id"],
1018 "instantiation_parameters": slice_request
,
1019 "network-slice-template": nstd
,
1023 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1026 step
= "creating nsi at database"
1027 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1028 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1029 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1030 nsi_descriptor
["_admin"]["deployed"] = {}
1031 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1032 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1034 # Creating netslice-vld for the RO.
1035 step
= "creating netslice-vld at database"
1037 # Building the vlds list to be deployed
1038 # From netslice descriptors, creating the initial list
1041 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1042 # Getting template Instantiation parameters from NST
1043 nsi_vld
= deepcopy(netslice_vlds
)
1044 nsi_vld
["shared-nsrs-list"] = []
1045 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1046 nsi_vlds
.append(nsi_vld
)
1048 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1049 # Creating netslice-subnet_record.
1053 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1054 for member_ns
in nstd
["netslice-subnet"]:
1055 nsd_id
= member_ns
["nsd-ref"]
1056 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1057 member_ns
["nsd-ref"], member_ns
["id"])
1058 if nsd_id
not in needed_nsds
:
1060 _filter
["id"] = nsd_id
1061 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1064 needed_nsds
[nsd_id
] = nsd
1066 nsd
= needed_nsds
[nsd_id
]
1067 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1068 services
.append(member_ns
)
1070 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1071 member_ns
["nsd-ref"], member_ns
["id"])
1073 # creates Network Services records (NSRs)
1074 step
= "creating nsrs at database using NsrTopic.new()"
1075 ns_params
= slice_request
.get("netslice-subnet")
1077 nsi_netslice_subnet
= []
1078 for service
in services
:
1079 # Check if the netslice-subnet is shared and if it is share if the nss exists
1082 # Is the nss shared and instantiated?
1083 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1084 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1085 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1086 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1087 if nsi
and service
.get("is-shared-nss"):
1088 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1089 for nsrs_detailed_item
in nsrs_detailed_list
:
1090 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1091 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1092 _id_nsr
= nsrs_detailed_item
["nsrId"]
1094 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1095 if netslice_subnet
["nss-id"] == service
["id"]:
1096 indata_ns
= netslice_subnet
1100 if service
.get("instantiation-parameters"):
1101 indata_ns
= deepcopy(service
["instantiation-parameters"])
1102 # del service["instantiation-parameters"]
1104 indata_ns
["nsdId"] = service
["_id"]
1105 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1106 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1107 indata_ns
["nsDescription"] = service
["description"]
1108 if slice_request
.get("ssh_keys"):
1109 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1112 for ns_param
in ns_params
:
1113 if ns_param
.get("id") == service
["id"]:
1114 copy_ns_param
= deepcopy(ns_param
)
1115 del copy_ns_param
["id"]
1116 indata_ns
.update(copy_ns_param
)
1119 # Creates Nsr objects
1120 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1121 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1122 "nss-id": service
["id"], "nslcmop_instantiate": None}
1123 indata_ns
["nss-id"] = service
["id"]
1124 nsrs_list
.append(nsrs_item
)
1125 nsi_netslice_subnet
.append(indata_ns
)
1126 nsr_ref
= {"nsr-ref": _id_nsr
}
1127 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1129 # Adding the nsrs list to the nsi
1130 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1131 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1132 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1134 # Creating the entry in the database
1135 self
.db
.create("nsis", nsi_descriptor
)
1136 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1138 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1139 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1140 raise EngineException("Error {}: {}".format(step
, e
))
1141 except ValidationError
as e
:
1142 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1144 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1145 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1148 class NsiLcmOpTopic(BaseTopic
):
1151 operation_schema
= { # mapping between operation and jsonschema to validate
1152 "instantiate": nsi_instantiate
,
1156 def __init__(self
, db
, fs
, msg
):
1157 BaseTopic
.__init
__(self
, db
, fs
, msg
)
1158 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
)
1160 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1162 Check that user has enter right parameters for the operation
1163 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1164 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1165 :param indata: descriptor with the parameters of the operation
1169 nstd
= nsir
["network-slice-template"]
1171 def check_valid_netslice_subnet_id(nstId
):
1172 # TODO change to vnfR (??)
1173 for netslice_subnet
in nstd
["netslice-subnet"]:
1174 if nstId
== netslice_subnet
["id"]:
1175 nsd_id
= netslice_subnet
["nsd-ref"]
1176 if nsd_id
not in nsds
:
1177 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1180 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1181 "nst:netslice-subnet".format(nstId
))
1182 if operation
== "instantiate":
1183 # check the existance of netslice-subnet items
1184 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1185 check_valid_netslice_subnet_id(in_nst
["id"])
1187 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1193 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1194 "statusEnteredTime": now
,
1195 "netsliceInstanceId": netsliceInstanceId
,
1196 "lcmOperationType": operation
,
1198 "isAutomaticInvocation": False,
1199 "operationParams": params
,
1200 "isCancelPending": False,
1202 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1203 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1208 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1209 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1210 if nst_sb_item
.get("is-shared-nss"):
1211 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1212 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1213 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1214 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1215 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1216 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1217 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1219 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1220 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1222 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1224 Performs a new operation over a ns
1225 :param rollback: list to append created items at database in case a rollback must to be done
1226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1227 :param indata: descriptor with the parameters of the operation. It must contains among others
1228 netsliceInstanceId: _id of the nsir to perform the operation
1229 operation: it can be: instantiate, terminate, action, TODO: update, heal
1230 :param kwargs: used to override the indata descriptor
1231 :param headers: http request headers
1232 :return: id of the nslcmops
1235 # Override descriptor with query string kwargs
1236 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1237 operation
= indata
["lcmOperationType"]
1238 netsliceInstanceId
= indata
["netsliceInstanceId"]
1239 validate_input(indata
, self
.operation_schema
[operation
])
1241 # get nsi from netsliceInstanceId
1242 _filter
= self
._get
_project
_filter
(session
)
1243 _filter
["_id"] = netsliceInstanceId
1244 nsir
= self
.db
.get_one("nsis", _filter
)
1248 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1249 if operation
== "terminate" and indata
.get("autoremove"):
1250 # NSIR must be deleted
1251 return None # a none in this case is used to indicate not instantiated. It can be removed
1252 if operation
!= "instantiate":
1253 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1254 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1256 if operation
== "instantiate" and not session
["force"]:
1257 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1258 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1260 # Creating all the NS_operation (nslcmop)
1261 # Get service list from db
1262 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1264 # nslcmops_item = None
1265 for index
, nsr_item
in enumerate(nsrs_list
):
1267 if nsr_item
.get("shared"):
1268 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1269 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item
["nsrId"]
1270 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1271 _filter
["_id.ne"] = netsliceInstanceId
1272 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1273 if operation
== "terminate":
1274 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1275 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1277 # looks the first nsi fulfilling the conditions but not being the current NSIR
1279 nsi_admin_shared
= nsi
["_admin"]["nsrs-detailed-list"]
1280 for nsi_nsr_item
in nsi_admin_shared
:
1281 if nsi_nsr_item
["nsd-id"] == nsr_item
["nsd-id"] and nsi_nsr_item
["shared"]:
1282 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1283 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1284 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1285 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1287 # continue to not create nslcmop since nsrs is shared and nsrs was created
1290 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1293 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1295 indata_ns
= service
["instantiate_params"]
1296 indata_ns
["lcmOperationType"] = operation
1297 indata_ns
["nsInstanceId"] = service
["_id"]
1298 # Including netslice_id in the ns instantiate Operation
1299 indata_ns
["netsliceInstanceId"] = netsliceInstanceId
1300 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1301 # message via kafka bus
1302 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
,
1304 nslcmops
.append(nslcmop
)
1305 if operation
== "terminate":
1307 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1308 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1309 except (DbException
, EngineException
) as e
:
1310 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1311 self
.logger
.info("HTTPStatus.NOT_FOUND")
1317 indata
["nslcmops_ids"] = nslcmops
1318 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1320 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1321 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1322 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1323 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1324 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1326 except ValidationError
as e
:
1327 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1329 def delete(self
, session
, _id
, dry_run
=False):
1330 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1332 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1333 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)