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
, auth
):
37 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
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
= "checking quotas"
186 self
.check_quota(session
)
188 step
= "validating input parameters"
189 ns_request
= self
._remove
_envelop
(indata
)
190 # Override descriptor with query string kwargs
191 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
192 self
._validate
_input
_new
(ns_request
, session
["force"])
195 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
196 _filter
= self
._get
_project
_filter
(session
)
197 _filter
["_id"] = ns_request
["nsdId"]
198 nsd
= self
.db
.get_one("nsds", _filter
)
201 nsr_id
= str(uuid4())
204 step
= "filling nsr from input data"
206 "name": ns_request
["nsName"],
207 "name-ref": ns_request
["nsName"],
208 "short-name": ns_request
["nsName"],
209 "admin-status": "ENABLED",
211 "datacenter": ns_request
["vimAccountId"],
212 "resource-orchestrator": "osmopenmano",
213 "description": ns_request
.get("nsDescription", ""),
214 "constituent-vnfr-ref": [],
216 "operational-status": "init", # typedef ns-operational-
217 "config-status": "init", # typedef config-states
218 "detailed-status": "scheduled",
220 "orchestration-progress": {},
221 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
224 "nsd-name-ref": nsd
["name"],
225 "operational-events": [], # "id", "timestamp", "description", "event",
226 "nsd-ref": nsd
["id"],
227 "nsd-id": nsd
["_id"],
229 "instantiate_params": self
._format
_ns
_request
(ns_request
),
230 "additionalParamsForNs": self
._format
_addional
_params
(ns_request
),
231 "ns-instance-config-ref": nsr_id
,
234 # "input-parameter": xpath, value,
235 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
237 ns_request
["nsr_id"] = nsr_id
240 nsr_descriptor
["vld"] = []
241 for nsd_vld
in nsd
.get("vld"):
242 nsr_descriptor
["vld"].append(
243 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in nsd_vld
})
247 for member_vnf
in nsd
.get("constituent-vnfd", ()):
248 vnfd_id
= member_vnf
["vnfd-id-ref"]
249 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
250 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
251 if vnfd_id
not in needed_vnfds
:
253 _filter
["id"] = vnfd_id
254 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
257 needed_vnfds
[vnfd_id
] = vnfd
258 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
260 vnfd
= needed_vnfds
[vnfd_id
]
261 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
262 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
263 vnfr_id
= str(uuid4())
267 "nsr-id-ref": nsr_id
,
268 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
269 "additionalParamsForVnf": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
272 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
274 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
275 "vim-account-id": None,
277 "connection-point": [],
278 "ip-address": None, # mgmt-interface filled by LCM
282 if vnfd
.get("internal-vld"):
283 vnfr_descriptor
["vld"] = []
284 for vnfd_vld
in vnfd
.get("internal-vld"):
285 vnfr_descriptor
["vld"].append(
286 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
289 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
290 for cp
in vnfd
.get("connection-point", ()):
293 "connection-point-id": cp
.get("id"),
295 # "ip-address", "mac-address" # filled by LCM
296 # vim-id # TODO it would be nice having a vim port id
298 vnfr_descriptor
["connection-point"].append(vnf_cp
)
299 for vdu
in vnfd
.get("vdu", ()):
301 "vdu-id-ref": vdu
["id"],
302 # TODO "name": "" Name of the VDU in the VIM
303 "ip-address": None, # mgmt-interface filled by LCM
304 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
305 "internal-connection-point": [],
308 if vdu
.get("pdu-type"):
309 vdur
["pdu-type"] = vdu
["pdu-type"]
310 # TODO volumes: name, volume-id
311 for icp
in vdu
.get("internal-connection-point", ()):
314 "connection-point-id": icp
["id"],
315 "name": icp
.get("name"),
316 # "ip-address", "mac-address" # filled by LCM
317 # vim-id # TODO it would be nice having a vim port id
319 vdur
["internal-connection-point"].append(vdu_icp
)
320 for iface
in vdu
.get("interface", ()):
322 "name": iface
.get("name"),
323 # "ip-address", "mac-address" # filled by LCM
324 # vim-id # TODO it would be nice having a vim port id
326 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
327 vdu_iface
["mgmt-vnf"] = True
328 if iface
.get("mgmt-interface"):
329 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
331 # look for network where this interface is connected
332 if iface
.get("external-connection-point-ref"):
333 for nsd_vld
in get_iterable(nsd
.get("vld")):
334 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
335 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
336 iface
["external-connection-point-ref"] and \
337 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
338 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
343 elif iface
.get("internal-connection-point-ref"):
344 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
345 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
346 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
347 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
353 vdur
["interfaces"].append(vdu_iface
)
354 count
= vdu
.get("count", 1)
357 count
= int(count
) # TODO remove when descriptor serialized with payngbind
358 for index
in range(0, count
):
360 vdur
= deepcopy(vdur
)
361 vdur
["_id"] = str(uuid4())
362 vdur
["count-index"] = index
363 vnfr_descriptor
["vdur"].append(vdur
)
365 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
366 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
369 self
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
370 self
.db
.create("vnfrs", vnfr_descriptor
)
371 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
372 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
374 step
= "creating nsr at database"
375 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
376 self
.db
.create("nsrs", nsr_descriptor
)
377 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
379 step
= "creating nsr temporal folder"
380 self
.fs
.mkdir(nsr_id
)
383 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
384 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
385 except Exception as e
:
386 self
.logger
.exception("Exception {} at NsrTopic.new()".format(e
), exc_info
=True)
387 raise EngineException("Error {}: {}".format(step
, e
))
389 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
390 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
393 class VnfrTopic(BaseTopic
):
397 def __init__(self
, db
, fs
, msg
, auth
):
398 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
400 def delete(self
, session
, _id
, dry_run
=False):
401 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
403 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
404 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
406 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
407 # Not used because vnfrs are created and deleted by NsrTopic class directly
408 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
411 class NsLcmOpTopic(BaseTopic
):
414 operation_schema
= { # mapping between operation and jsonschema to validate
415 "instantiate": ns_instantiate
,
421 def __init__(self
, db
, fs
, msg
, auth
):
422 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
424 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
426 Check that user has enter right parameters for the operation
427 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
428 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
429 :param indata: descriptor with the parameters of the operation
432 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
437 def check_valid_vnf_member_index(member_vnf_index
):
438 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
439 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
440 return vnf_member_index_to_vnfd
[member_vnf_index
]
441 vnfr
= self
.db
.get_one("vnfrs",
442 {"nsr-id-ref": nsr
["_id"], "member-vnf-index-ref": member_vnf_index
},
445 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
446 "nsd:constituent-vnfd".format(member_vnf_index
))
447 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
449 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
450 format(vnfr
["vnfd-id"]))
451 vnf_member_index_to_vnfd
[member_vnf_index
] = vnfd
# add to cache, avoiding a later look for
454 def check_valid_vdu(vnfd
, vdu_id
):
455 for vdud
in get_iterable(vnfd
.get("vdu")):
456 if vdud
["id"] == vdu_id
:
459 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id
))
461 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
463 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
464 for vdu
in get_iterable(vnfd
.get("vdu")):
465 if in_vdu
["id"] == vdu
["id"]:
466 for volume
in get_iterable(in_vdu
.get("volume")):
467 for volumed
in get_iterable(vdu
.get("volumes")):
468 if volumed
["name"] == volume
["name"]:
471 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
472 "volume:name='{}' is not present at vnfd:vdu:volumes list".
473 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
475 for in_iface
in get_iterable(in_vdu
["interface"]):
476 for iface
in get_iterable(vdu
.get("interface")):
477 if in_iface
["name"] == iface
["name"]:
480 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
481 "interface[name='{}'] is not present at vnfd:vdu:interface"
482 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
486 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
487 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
489 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
490 for ivld
in get_iterable(vnfd
.get("internal-vld")):
491 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
492 for in_icp
in get_iterable(in_ivld
["internal-connection-point"]):
493 for icp
in ivld
["internal-connection-point"]:
494 if in_icp
["id-ref"] == icp
["id-ref"]:
497 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
498 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
499 "vnfd:internal-vld:name/id:internal-connection-point"
500 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
501 in_icp
["id-ref"], vnfd
["id"]))
504 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
505 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
506 in_ivld
["name"], vnfd
["id"]))
508 def check_valid_vim_account(vim_account
):
509 if vim_account
in vim_accounts
:
512 db_filter
= self
._get
_project
_filter
(session
)
513 db_filter
["_id"] = vim_account
514 self
.db
.get_one("vim_accounts", db_filter
)
516 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
517 vim_accounts
.append(vim_account
)
519 def check_valid_wim_account(wim_account
):
520 if not isinstance(wim_account
, str):
522 elif wim_account
in wim_accounts
:
525 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
526 db_filter
["_id"] = wim_account
527 self
.db
.get_one("wim_accounts", db_filter
)
529 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
530 wim_accounts
.append(wim_account
)
532 if operation
== "action":
533 # check vnf_member_index
534 if indata
.get("vnf_member_index"):
535 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
536 if indata
.get("member_vnf_index"):
537 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
538 if indata
.get("vdu_id"):
539 vdud
= check_valid_vdu(vnfd
, indata
["vdu_id"])
540 descriptor_configuration
= vdud
.get("vdu-configuration", {}).get("config-primitive")
542 descriptor_configuration
= vnfd
.get("vnf-configuration", {}).get("config-primitive")
544 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
546 for config_primitive
in get_iterable(descriptor_configuration
):
547 if indata
["primitive"] == config_primitive
["name"]:
548 # check needed primitive_params are provided
549 if indata
.get("primitive_params"):
550 in_primitive_params_copy
= copy(indata
["primitive_params"])
552 in_primitive_params_copy
= {}
553 for paramd
in get_iterable(config_primitive
.get("parameter")):
554 if paramd
["name"] in in_primitive_params_copy
:
555 del in_primitive_params_copy
[paramd
["name"]]
556 elif not paramd
.get("default-value"):
557 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
558 paramd
["name"], indata
["primitive"]))
559 # check no extra primitive params are provided
560 if in_primitive_params_copy
:
561 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
562 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
565 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
566 if operation
== "scale":
567 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
568 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
569 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
572 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
573 "present at vnfd:scaling-group-descriptor".format(
574 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
575 if operation
== "instantiate":
577 check_valid_vim_account(indata
["vimAccountId"])
578 check_valid_wim_account(indata
.get("wimAccountId"))
579 for in_vnf
in get_iterable(indata
.get("vnf")):
580 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
581 _check_vnf_instantiation_params(in_vnf
, vnfd
)
582 if in_vnf
.get("vimAccountId"):
583 check_valid_vim_account(in_vnf
["vimAccountId"])
585 for in_vld
in get_iterable(indata
.get("vld")):
586 check_valid_wim_account(in_vld
.get("wimAccountId"))
587 for vldd
in get_iterable(nsd
.get("vld")):
588 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
591 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
594 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
596 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
597 (ip_address, ...) information.
598 Modifies PDU _admin.usageState to 'IN_USE'
600 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
601 :param rollback: list with the database modifications to rollback if needed
602 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
603 :param vim_account: vim_account where this vnfr should be deployed
604 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
605 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
606 of the changed vnfr is needed
608 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
609 "vim-network-name": used at VIM
610 "name": interface name
611 "vnf-vld-id": internal VNFD vld where this interface is connected, or
612 "ns-vld-id": NSD vld where this interface is connected.
613 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
616 ifaces_forcing_vim_network
= []
617 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
618 if not vdur
.get("pdu-type"):
620 pdu_type
= vdur
.get("pdu-type")
621 pdu_filter
= self
._get
_project
_filter
(session
)
622 pdu_filter
["vim_accounts"] = vim_account
623 pdu_filter
["type"] = pdu_type
624 pdu_filter
["_admin.operationalState"] = "ENABLED"
625 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
626 # TODO feature 1417: "shared": True,
628 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
629 for pdu
in available_pdus
:
630 # step 1 check if this pdu contains needed interfaces:
631 match_interfaces
= True
632 for vdur_interface
in vdur
["interfaces"]:
633 for pdu_interface
in pdu
["interfaces"]:
634 if pdu_interface
["name"] == vdur_interface
["name"]:
635 # TODO feature 1417: match per mgmt type
637 else: # no interface found for name
638 match_interfaces
= False
643 raise EngineException(
644 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
645 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
649 "_admin.usageState": pdu
["_admin"]["usageState"],
650 "_admin.usage.vnfr_id": None,
651 "_admin.usage.nsr_id": None,
652 "_admin.usage.vdur": None,
654 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
655 {"_admin.usageState": "IN_USE",
656 "_admin.usage": {"vnfr_id": vnfr
["_id"],
657 "nsr_id": vnfr
["nsr-id-ref"],
658 "vdur": vdur
["vdu-id-ref"]}
660 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
662 # step 3. Fill vnfr info by filling vdur
663 vdu_text
= "vdur.{}".format(vdur_index
)
664 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
665 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
666 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
667 for pdu_interface
in pdu
["interfaces"]:
668 if pdu_interface
["name"] == vdur_interface
["name"]:
669 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
670 for k
, v
in pdu_interface
.items():
671 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
672 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
673 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
674 if pdu_interface
.get("ip-address"):
675 if vdur_interface
.get("mgmt-interface"):
676 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
677 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
678 if vdur_interface
.get("mgmt-vnf"):
679 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
680 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
681 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
682 ifaces_forcing_vim_network
.append({
683 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
684 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
685 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
686 if pdu_interface
.get("vim-network-id"):
687 ifaces_forcing_vim_network
.append({
688 "vim-network-id": pdu_interface
.get("vim-network-id")})
689 if pdu_interface
.get("vim-network-name"):
690 ifaces_forcing_vim_network
.append({
691 "vim-network-name": pdu_interface
.get("vim-network-name")})
694 return ifaces_forcing_vim_network
696 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
700 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
704 vnfr_update_rollback
= {}
705 member_vnf_index
= vnfr
["member-vnf-index-ref"]
706 # update vim-account-id
708 vim_account
= indata
["vimAccountId"]
709 # check instantiate parameters
710 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
711 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
713 if vnf_inst_params
.get("vimAccountId"):
714 vim_account
= vnf_inst_params
.get("vimAccountId")
716 vnfr_update
["vim-account-id"] = vim_account
717 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
720 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
721 vnfr_update_rollback
)
723 # updata database vnfr
724 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
725 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
727 # Update indada in case pdu forces to use a concrete vim-network-name
728 # TODO check if user has already insert a vim-network-name and raises an error
729 if not ifaces_forcing_vim_network
:
731 for iface_info
in ifaces_forcing_vim_network
:
732 if iface_info
.get("ns-vld-id"):
733 if "vld" not in indata
:
735 indata
["vld"].append({key
: iface_info
[key
] for key
in
736 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
738 elif iface_info
.get("vnf-vld-id"):
739 if "vnf" not in indata
:
741 indata
["vnf"].append({
742 "member-vnf-index": member_vnf_index
,
743 "internal-vld": [{key
: iface_info
[key
] for key
in
744 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
748 def _create_nslcmop(nsr_id
, operation
, params
):
750 Creates a ns-lcm-opp content to be stored at database.
751 :param nsr_id: internal id of the instance
752 :param operation: instantiate, terminate, scale, action, ...
753 :param params: user parameters for the operation
754 :return: dictionary following SOL005 format
761 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
762 "statusEnteredTime": now
,
763 "nsInstanceId": nsr_id
,
764 "lcmOperationType": operation
,
766 "isAutomaticInvocation": False,
767 "operationParams": params
,
768 "isCancelPending": False,
770 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
771 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
776 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
778 Performs a new operation over a ns
779 :param rollback: list to append created items at database in case a rollback must to be done
780 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
781 :param indata: descriptor with the parameters of the operation. It must contains among others
782 nsInstanceId: _id of the nsr to perform the operation
783 operation: it can be: instantiate, terminate, action, TODO: update, heal
784 :param kwargs: used to override the indata descriptor
785 :param headers: http request headers
786 :return: id of the nslcmops
788 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
790 db_filter
= self
._get
_project
_filter
(session
)
791 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
792 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
794 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
795 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
798 # Override descriptor with query string kwargs
799 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
800 operation
= indata
["lcmOperationType"]
801 nsInstanceId
= indata
["nsInstanceId"]
803 validate_input(indata
, self
.operation_schema
[operation
])
805 _filter
= BaseTopic
._get
_project
_filter
(session
)
806 _filter
["_id"] = nsInstanceId
807 nsr
= self
.db
.get_one("nsrs", _filter
)
810 if operation
== "terminate" and slice_object
is False:
811 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
812 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
813 if operation
== "terminate" and indata
.get("autoremove"):
814 # NSR must be deleted
815 return None # a none in this case is used to indicate not instantiated. It can be removed
816 if operation
!= "instantiate":
817 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
818 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
820 if operation
== "instantiate" and not session
["force"]:
821 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
822 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
823 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
825 if operation
== "instantiate":
826 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
828 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
829 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
830 _id
= self
.db
.create("nslcmops", nslcmop_desc
)
831 rollback
.append({"topic": "nslcmops", "_id": _id
})
833 self
.msg
.write("ns", operation
, nslcmop_desc
)
835 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
836 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
837 # except DbException as e:
838 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
840 def delete(self
, session
, _id
, dry_run
=False):
841 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
843 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
844 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
847 class NsiTopic(BaseTopic
):
851 def __init__(self
, db
, fs
, msg
, auth
):
852 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
853 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
856 def _format_ns_request(ns_request
):
857 formated_request
= copy(ns_request
)
858 # TODO: Add request params
859 return formated_request
862 def _format_addional_params(slice_request
):
864 Get and format user additional params for NS or VNF
865 :param slice_request: User instantiation additional parameters
866 :return: a formatted copy of additional params or None if not supplied
868 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
869 if additional_params
:
870 for k
, v
in additional_params
.items():
871 if not isinstance(k
, str):
872 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
874 if "." in k
or "$" in k
:
875 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
877 if isinstance(v
, (dict, tuple, list)):
878 additional_params
[k
] = "!!yaml " + safe_dump(v
)
879 return additional_params
881 def _check_descriptor_dependencies(self
, session
, descriptor
):
883 Check that the dependent descriptors exist on a new descriptor or edition
884 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
885 :param descriptor: descriptor to be inserted or edit
886 :return: None or raises exception
888 if not descriptor
.get("nst-ref"):
890 nstd_id
= descriptor
["nst-ref"]
891 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
892 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
893 http_code
=HTTPStatus
.CONFLICT
)
895 def check_conflict_on_del(self
, session
, _id
, db_content
):
897 Check that NSI is not instantiated
898 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
899 :param _id: nsi internal id
900 :param db_content: The database content of the _id
901 :return: None or raises EngineException with the conflict
906 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
907 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
908 "Launch 'terminate' operation first; or force deletion".format(_id
),
909 http_code
=HTTPStatus
.CONFLICT
)
911 def delete_extra(self
, session
, _id
, db_content
):
913 Deletes associated nsilcmops from database. Deletes associated filesystem.
914 Set usageState of nst
915 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
916 :param _id: server internal id
917 :param db_content: The database content of the descriptor
918 :return: None if ok or raises EngineException with the problem
921 # Deleting the nsrs belonging to nsir
923 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
924 nsr_id
= nsrs_detailed_item
["nsrId"]
925 if nsrs_detailed_item
.get("shared"):
926 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
927 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
928 "_id.ne": nsir
["_id"]}
929 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
930 if nsi
: # last one using nsr
933 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False)
934 except (DbException
, EngineException
) as e
:
935 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
940 # delete related nsilcmops database entries
941 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
943 # Check and set used NST usage state
944 nsir_admin
= nsir
.get("_admin")
945 if nsir_admin
and nsir_admin
.get("nst-id"):
946 # check if used by another NSI
947 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
948 fail_on_empty
=False, fail_on_more
=False)
950 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
952 # def delete(self, session, _id, dry_run=False):
954 # Delete item by its internal _id
955 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
956 # :param _id: server internal id
957 # :param dry_run: make checking but do not delete
958 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
960 # # TODO add admin to filter, validate rights
961 # BaseTopic.delete(self, session, _id, dry_run=True)
965 # # Deleting the nsrs belonging to nsir
966 # nsir = self.db.get_one("nsis", {"_id": _id})
967 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
968 # nsr_id = nsrs_detailed_item["nsrId"]
969 # if nsrs_detailed_item.get("shared"):
970 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
971 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
972 # "_id.ne": nsir["_id"]}
973 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
974 # if nsi: # last one using nsr
977 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
978 # except (DbException, EngineException) as e:
979 # if e.http_code == HTTPStatus.NOT_FOUND:
983 # # deletes NetSlice instance object
984 # v = self.db.del_one("nsis", {"_id": _id})
986 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
987 # _filter = {"netsliceInstanceId": _id}
988 # self.db.del_list("nsilcmops", _filter)
990 # # Search if nst is being used by other nsi
991 # nsir_admin = nsir.get("_admin")
993 # if nsir_admin.get("nst-id"):
994 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
995 # fail_on_empty=False, fail_on_more=False)
997 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1000 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1002 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1003 :param rollback: list to append the created items at database in case a rollback must be done
1004 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1005 :param indata: params to be used for the nsir
1006 :param kwargs: used to override the indata descriptor
1007 :param headers: http request headers
1008 :return: the _id of nsi descriptor created at database
1012 step
= "checking quotas"
1013 self
.check_quota(session
)
1016 slice_request
= self
._remove
_envelop
(indata
)
1017 # Override descriptor with query string kwargs
1018 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
1019 self
._validate
_input
_new
(slice_request
, session
["force"])
1022 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1023 _filter
= self
._get
_project
_filter
(session
)
1024 _filter
["_id"] = slice_request
["nstId"]
1025 nstd
= self
.db
.get_one("nsts", _filter
)
1028 nstd
.pop("_admin", None)
1029 nstd_id
= nstd
.pop("_id", None)
1030 nsi_id
= str(uuid4())
1031 step
= "filling nsi_descriptor with input data"
1036 "name": slice_request
["nsiName"],
1037 "description": slice_request
.get("nsiDescription", ""),
1038 "datacenter": slice_request
["vimAccountId"],
1039 "nst-ref": nstd
["id"],
1040 "instantiation_parameters": slice_request
,
1041 "network-slice-template": nstd
,
1045 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1048 step
= "creating nsi at database"
1049 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1050 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1051 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1052 nsi_descriptor
["_admin"]["deployed"] = {}
1053 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1054 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1056 # Creating netslice-vld for the RO.
1057 step
= "creating netslice-vld at database"
1059 # Building the vlds list to be deployed
1060 # From netslice descriptors, creating the initial list
1063 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1064 # Getting template Instantiation parameters from NST
1065 nsi_vld
= deepcopy(netslice_vlds
)
1066 nsi_vld
["shared-nsrs-list"] = []
1067 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1068 nsi_vlds
.append(nsi_vld
)
1070 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1071 # Creating netslice-subnet_record.
1075 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1076 for member_ns
in nstd
["netslice-subnet"]:
1077 nsd_id
= member_ns
["nsd-ref"]
1078 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1079 member_ns
["nsd-ref"], member_ns
["id"])
1080 if nsd_id
not in needed_nsds
:
1082 _filter
["id"] = nsd_id
1083 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1086 needed_nsds
[nsd_id
] = nsd
1088 nsd
= needed_nsds
[nsd_id
]
1089 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1090 services
.append(member_ns
)
1092 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1093 member_ns
["nsd-ref"], member_ns
["id"])
1095 # creates Network Services records (NSRs)
1096 step
= "creating nsrs at database using NsrTopic.new()"
1097 ns_params
= slice_request
.get("netslice-subnet")
1099 nsi_netslice_subnet
= []
1100 for service
in services
:
1101 # Check if the netslice-subnet is shared and if it is share if the nss exists
1104 # Is the nss shared and instantiated?
1105 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1106 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1107 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1108 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1109 if nsi
and service
.get("is-shared-nss"):
1110 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1111 for nsrs_detailed_item
in nsrs_detailed_list
:
1112 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1113 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1114 _id_nsr
= nsrs_detailed_item
["nsrId"]
1116 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1117 if netslice_subnet
["nss-id"] == service
["id"]:
1118 indata_ns
= netslice_subnet
1122 if service
.get("instantiation-parameters"):
1123 indata_ns
= deepcopy(service
["instantiation-parameters"])
1124 # del service["instantiation-parameters"]
1126 indata_ns
["nsdId"] = service
["_id"]
1127 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1128 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1129 indata_ns
["nsDescription"] = service
["description"]
1130 if slice_request
.get("ssh_keys"):
1131 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1134 for ns_param
in ns_params
:
1135 if ns_param
.get("id") == service
["id"]:
1136 copy_ns_param
= deepcopy(ns_param
)
1137 del copy_ns_param
["id"]
1138 indata_ns
.update(copy_ns_param
)
1141 # Creates Nsr objects
1142 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1143 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1144 "nss-id": service
["id"], "nslcmop_instantiate": None}
1145 indata_ns
["nss-id"] = service
["id"]
1146 nsrs_list
.append(nsrs_item
)
1147 nsi_netslice_subnet
.append(indata_ns
)
1148 nsr_ref
= {"nsr-ref": _id_nsr
}
1149 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1151 # Adding the nsrs list to the nsi
1152 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1153 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1154 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1156 # Creating the entry in the database
1157 self
.db
.create("nsis", nsi_descriptor
)
1158 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1160 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1161 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1162 raise EngineException("Error {}: {}".format(step
, e
))
1163 except ValidationError
as e
:
1164 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1166 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1167 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1170 class NsiLcmOpTopic(BaseTopic
):
1173 operation_schema
= { # mapping between operation and jsonschema to validate
1174 "instantiate": nsi_instantiate
,
1178 def __init__(self
, db
, fs
, msg
, auth
):
1179 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1180 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
1182 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1184 Check that user has enter right parameters for the operation
1185 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1186 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1187 :param indata: descriptor with the parameters of the operation
1191 nstd
= nsir
["network-slice-template"]
1193 def check_valid_netslice_subnet_id(nstId
):
1194 # TODO change to vnfR (??)
1195 for netslice_subnet
in nstd
["netslice-subnet"]:
1196 if nstId
== netslice_subnet
["id"]:
1197 nsd_id
= netslice_subnet
["nsd-ref"]
1198 if nsd_id
not in nsds
:
1199 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1202 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1203 "nst:netslice-subnet".format(nstId
))
1204 if operation
== "instantiate":
1205 # check the existance of netslice-subnet items
1206 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1207 check_valid_netslice_subnet_id(in_nst
["id"])
1209 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1215 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1216 "statusEnteredTime": now
,
1217 "netsliceInstanceId": netsliceInstanceId
,
1218 "lcmOperationType": operation
,
1220 "isAutomaticInvocation": False,
1221 "operationParams": params
,
1222 "isCancelPending": False,
1224 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1225 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1230 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1231 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1232 if nst_sb_item
.get("is-shared-nss"):
1233 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1234 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1235 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1236 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1237 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1238 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1239 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1241 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1242 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1244 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1246 Performs a new operation over a ns
1247 :param rollback: list to append created items at database in case a rollback must to be done
1248 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1249 :param indata: descriptor with the parameters of the operation. It must contains among others
1250 netsliceInstanceId: _id of the nsir to perform the operation
1251 operation: it can be: instantiate, terminate, action, TODO: update, heal
1252 :param kwargs: used to override the indata descriptor
1253 :param headers: http request headers
1254 :return: id of the nslcmops
1257 # Override descriptor with query string kwargs
1258 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1259 operation
= indata
["lcmOperationType"]
1260 netsliceInstanceId
= indata
["netsliceInstanceId"]
1261 validate_input(indata
, self
.operation_schema
[operation
])
1263 # get nsi from netsliceInstanceId
1264 _filter
= self
._get
_project
_filter
(session
)
1265 _filter
["_id"] = netsliceInstanceId
1266 nsir
= self
.db
.get_one("nsis", _filter
)
1270 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1271 if operation
== "terminate" and indata
.get("autoremove"):
1272 # NSIR must be deleted
1273 return None # a none in this case is used to indicate not instantiated. It can be removed
1274 if operation
!= "instantiate":
1275 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1276 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1278 if operation
== "instantiate" and not session
["force"]:
1279 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1280 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1282 # Creating all the NS_operation (nslcmop)
1283 # Get service list from db
1284 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1286 # nslcmops_item = None
1287 for index
, nsr_item
in enumerate(nsrs_list
):
1289 if nsr_item
.get("shared"):
1290 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1291 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item
["nsrId"]
1292 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1293 _filter
["_id.ne"] = netsliceInstanceId
1294 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1295 if operation
== "terminate":
1296 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1297 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1299 # looks the first nsi fulfilling the conditions but not being the current NSIR
1301 nsi_admin_shared
= nsi
["_admin"]["nsrs-detailed-list"]
1302 for nsi_nsr_item
in nsi_admin_shared
:
1303 if nsi_nsr_item
["nsd-id"] == nsr_item
["nsd-id"] and nsi_nsr_item
["shared"]:
1304 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1305 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1306 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1307 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1309 # continue to not create nslcmop since nsrs is shared and nsrs was created
1312 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1315 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1317 indata_ns
= service
["instantiate_params"]
1318 indata_ns
["lcmOperationType"] = operation
1319 indata_ns
["nsInstanceId"] = service
["_id"]
1320 # Including netslice_id in the ns instantiate Operation
1321 indata_ns
["netsliceInstanceId"] = netsliceInstanceId
1322 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1323 # message via kafka bus
1324 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
,
1326 nslcmops
.append(nslcmop
)
1327 if operation
== "terminate":
1329 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1330 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1331 except (DbException
, EngineException
) as e
:
1332 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1333 self
.logger
.info("HTTPStatus.NOT_FOUND")
1339 indata
["nslcmops_ids"] = nslcmops
1340 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1342 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1343 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1344 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1345 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1346 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1348 except ValidationError
as e
:
1349 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1351 def delete(self
, session
, _id
, dry_run
=False):
1352 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1354 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1355 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)