1 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 from uuid
import uuid4
18 from http
import HTTPStatus
20 from copy
import copy
, deepcopy
21 from validation
import validate_input
, ValidationError
, ns_instantiate
, ns_action
, ns_scale
, nsi_instantiate
22 from base_topic
import BaseTopic
, EngineException
, get_iterable
23 # from descriptor_topics import DescriptorTopic
24 from yaml
import safe_dump
25 from osm_common
.dbbase
import DbException
26 from re
import match
# For checking that additional parameter names are valid Jinja2 identifiers
28 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
31 class NsrTopic(BaseTopic
):
35 def __init__(self
, db
, fs
, msg
):
36 BaseTopic
.__init
__(self
, db
, fs
, msg
)
38 def _check_descriptor_dependencies(self
, session
, descriptor
):
40 Check that the dependent descriptors exist on a new descriptor or edition
41 :param session: client session information
42 :param descriptor: descriptor to be inserted or edit
43 :return: None or raises exception
45 if not descriptor
.get("nsdId"):
47 nsd_id
= descriptor
["nsdId"]
48 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
49 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
50 http_code
=HTTPStatus
.CONFLICT
)
53 def format_on_new(content
, project_id
=None, make_public
=False):
54 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
55 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
57 def check_conflict_on_del(self
, session
, _id
, db_content
):
59 Check that NSR is not instantiated
60 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
61 :param _id: nsr internal id
62 :param db_content: The database content of the nsr
63 :return: None or raises EngineException with the conflict
68 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
69 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
70 "Launch 'terminate' operation first; or force deletion".format(_id
),
71 http_code
=HTTPStatus
.CONFLICT
)
73 def delete_extra(self
, session
, _id
, db_content
):
75 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
76 Set usageState of pdu, vnfd, nsd
77 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
78 :param _id: server internal id
79 :param db_content: The database content of the descriptor
80 :return: None if ok or raises EngineException with the problem
82 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
83 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
84 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
86 # set all used pdus as free
87 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
88 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
92 used_nsd_id
= nsr
.get("nsd-id")
94 # check if used by another NSR
95 nsrs_list
= self
.db
.get_one("nsrs", {"nsd-id": used_nsd_id
},
96 fail_on_empty
=False, fail_on_more
=False)
98 self
.db
.set_one("nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"})
100 # Set VNFD usageState
101 used_vnfd_id_list
= nsr
.get("vnfd-id")
102 if used_vnfd_id_list
:
103 for used_vnfd_id
in used_vnfd_id_list
:
104 # check if used by another NSR
105 nsrs_list
= self
.db
.get_one("nsrs", {"vnfd-id": used_vnfd_id
},
106 fail_on_empty
=False, fail_on_more
=False)
108 self
.db
.set_one("vnfds", {"_id": used_vnfd_id
}, {"_admin.usageState": "NOT_IN_USE"})
111 def _format_ns_request(ns_request
):
112 formated_request
= copy(ns_request
)
113 formated_request
.pop("additionalParamsForNs", None)
114 formated_request
.pop("additionalParamsForVnf", None)
115 return formated_request
118 def _format_addional_params(ns_request
, member_vnf_index
=None, descriptor
=None):
120 Get and format user additional params for NS or VNF
121 :param ns_request: User instantiation additional parameters
122 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
123 :param descriptor: If not None it check that needed parameters of descriptor are supplied
124 :return: a formated copy of additional params or None if not supplied
126 additional_params
= None
127 if not member_vnf_index
:
128 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
129 where_
= "additionalParamsForNs"
130 elif ns_request
.get("additionalParamsForVnf"):
131 for additionalParamsForVnf
in get_iterable(ns_request
.get("additionalParamsForVnf")):
132 if additionalParamsForVnf
["member-vnf-index"] == member_vnf_index
:
133 additional_params
= copy(additionalParamsForVnf
.get("additionalParams"))
134 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
135 additionalParamsForVnf
["member-vnf-index"])
137 if additional_params
:
138 for k
, v
in additional_params
.items():
139 # BEGIN Check that additional parameter names are valid Jinja2 identifiers
140 if not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k
):
141 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
142 "and underscores, and cannot start with a digit"
144 # END Check that additional parameter names are valid Jinja2 identifiers
145 if not isinstance(k
, str):
146 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
147 if "." in k
or "$" in k
:
148 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
149 if isinstance(v
, (dict, tuple, list)):
150 additional_params
[k
] = "!!yaml " + safe_dump(v
)
153 # check that enough parameters are supplied for the initial-config-primitive
154 # TODO: check for cloud-init
156 if descriptor
.get("vnf-configuration"):
157 for initial_primitive
in get_iterable(
158 descriptor
["vnf-configuration"].get("initial-config-primitive")):
159 for param
in get_iterable(initial_primitive
.get("parameter")):
160 if param
["value"].startswith("<") and param
["value"].endswith(">"):
161 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>"):
163 if not additional_params
or param
["value"][1:-1] not in additional_params
:
164 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
165 "initial-config-primitive[name={}] not supplied".
166 format(param
["value"], descriptor
["id"],
167 initial_primitive
["name"]))
169 return additional_params
171 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
173 Creates a new nsr into database. It also creates needed vnfrs
174 :param rollback: list to append the created items at database in case a rollback must be done
175 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
176 :param indata: params to be used for the nsr
177 :param kwargs: used to override the indata descriptor
178 :param headers: http request headers
179 :return: the _id of nsr descriptor created at database
183 ns_request
= self
._remove
_envelop
(indata
)
184 # Override descriptor with query string kwargs
185 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
186 self
._validate
_input
_new
(ns_request
, session
["force"])
189 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
190 _filter
= self
._get
_project
_filter
(session
)
191 _filter
["_id"] = ns_request
["nsdId"]
192 nsd
= self
.db
.get_one("nsds", _filter
)
195 nsr_id
= str(uuid4())
198 step
= "filling nsr from input data"
200 "name": ns_request
["nsName"],
201 "name-ref": ns_request
["nsName"],
202 "short-name": ns_request
["nsName"],
203 "admin-status": "ENABLED",
205 "datacenter": ns_request
["vimAccountId"],
206 "resource-orchestrator": "osmopenmano",
207 "description": ns_request
.get("nsDescription", ""),
208 "constituent-vnfr-ref": [],
210 "operational-status": "init", # typedef ns-operational-
211 "config-status": "init", # typedef config-states
212 "detailed-status": "scheduled",
214 "orchestration-progress": {},
215 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
218 "nsd-name-ref": nsd
["name"],
219 "operational-events": [], # "id", "timestamp", "description", "event",
220 "nsd-ref": nsd
["id"],
221 "nsd-id": nsd
["_id"],
223 "instantiate_params": self
._format
_ns
_request
(ns_request
),
224 "additionalParamsForNs": self
._format
_addional
_params
(ns_request
),
225 "ns-instance-config-ref": nsr_id
,
228 # "input-parameter": xpath, value,
229 "ssh-authorized-key": ns_request
.get("key-pair-ref"), # TODO remove
231 ns_request
["nsr_id"] = nsr_id
234 nsr_descriptor
["vld"] = []
235 for nsd_vld
in nsd
.get("vld"):
236 nsr_descriptor
["vld"].append(
237 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in nsd_vld
})
241 for member_vnf
in nsd
.get("constituent-vnfd", ()):
242 vnfd_id
= member_vnf
["vnfd-id-ref"]
243 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
244 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
245 if vnfd_id
not in needed_vnfds
:
247 _filter
["id"] = vnfd_id
248 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
251 needed_vnfds
[vnfd_id
] = vnfd
252 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
254 vnfd
= needed_vnfds
[vnfd_id
]
255 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
256 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
257 vnfr_id
= str(uuid4())
261 "nsr-id-ref": nsr_id
,
262 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
263 "additionalParamsForVnf": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
266 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
268 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
269 "vim-account-id": None,
271 "connection-point": [],
272 "ip-address": None, # mgmt-interface filled by LCM
276 if vnfd
.get("internal-vld"):
277 vnfr_descriptor
["vld"] = []
278 for vnfd_vld
in vnfd
.get("internal-vld"):
279 vnfr_descriptor
["vld"].append(
280 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
283 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
284 for cp
in vnfd
.get("connection-point", ()):
287 "connection-point-id": cp
.get("id"),
289 # "ip-address", "mac-address" # filled by LCM
290 # vim-id # TODO it would be nice having a vim port id
292 vnfr_descriptor
["connection-point"].append(vnf_cp
)
293 for vdu
in vnfd
.get("vdu", ()):
295 "vdu-id-ref": vdu
["id"],
296 # TODO "name": "" Name of the VDU in the VIM
297 "ip-address": None, # mgmt-interface filled by LCM
298 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
299 "internal-connection-point": [],
302 if vdu
.get("pdu-type"):
303 vdur
["pdu-type"] = vdu
["pdu-type"]
304 # TODO volumes: name, volume-id
305 for icp
in vdu
.get("internal-connection-point", ()):
308 "connection-point-id": icp
["id"],
309 "name": icp
.get("name"),
310 # "ip-address", "mac-address" # filled by LCM
311 # vim-id # TODO it would be nice having a vim port id
313 vdur
["internal-connection-point"].append(vdu_icp
)
314 for iface
in vdu
.get("interface", ()):
316 "name": iface
.get("name"),
317 # "ip-address", "mac-address" # filled by LCM
318 # vim-id # TODO it would be nice having a vim port id
320 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
321 vdu_iface
["mgmt-vnf"] = True
322 if iface
.get("mgmt-interface"):
323 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
325 # look for network where this interface is connected
326 if iface
.get("external-connection-point-ref"):
327 for nsd_vld
in get_iterable(nsd
.get("vld")):
328 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
329 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
330 iface
["external-connection-point-ref"] and \
331 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
332 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
337 elif iface
.get("internal-connection-point-ref"):
338 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
339 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
340 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
341 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
347 vdur
["interfaces"].append(vdu_iface
)
348 count
= vdu
.get("count", 1)
351 count
= int(count
) # TODO remove when descriptor serialized with payngbind
352 for index
in range(0, count
):
354 vdur
= deepcopy(vdur
)
355 vdur
["_id"] = str(uuid4())
356 vdur
["count-index"] = index
357 vnfr_descriptor
["vdur"].append(vdur
)
359 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
360 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
363 BaseTopic
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
364 self
.db
.create("vnfrs", vnfr_descriptor
)
365 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
366 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
368 step
= "creating nsr at database"
369 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
370 self
.db
.create("nsrs", nsr_descriptor
)
371 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
373 step
= "creating nsr temporal folder"
374 self
.fs
.mkdir(nsr_id
)
377 except Exception as e
:
378 self
.logger
.exception("Exception {} at NsrTopic.new()".format(e
), exc_info
=True)
379 raise EngineException("Error {}: {}".format(step
, e
))
380 except ValidationError
as e
:
381 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
383 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
384 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
387 class VnfrTopic(BaseTopic
):
391 def __init__(self
, db
, fs
, msg
):
392 BaseTopic
.__init
__(self
, db
, fs
, msg
)
394 def delete(self
, session
, _id
, dry_run
=False):
395 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
397 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
398 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
400 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
401 # Not used because vnfrs are created and deleted by NsrTopic class directly
402 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
405 class NsLcmOpTopic(BaseTopic
):
408 operation_schema
= { # mapping between operation and jsonschema to validate
409 "instantiate": ns_instantiate
,
415 def __init__(self
, db
, fs
, msg
):
416 BaseTopic
.__init
__(self
, db
, fs
, msg
)
418 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
420 Check that user has enter right parameters for the operation
421 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
422 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
423 :param indata: descriptor with the parameters of the operation
431 def check_valid_vnf_member_index(member_vnf_index
):
432 # TODO change to vnfR
433 for vnf
in nsd
["constituent-vnfd"]:
434 if member_vnf_index
== vnf
["member-vnf-index"]:
435 vnfd_id
= vnf
["vnfd-id-ref"]
436 if vnfd_id
not in vnfds
:
437 vnfds
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
438 return vnfds
[vnfd_id
]
440 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
441 "nsd:constituent-vnfd".format(member_vnf_index
))
443 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
445 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
446 for vdu
in get_iterable(vnfd
.get("vdu")):
447 if in_vdu
["id"] == vdu
["id"]:
448 for volume
in get_iterable(in_vdu
.get("volume")):
449 for volumed
in get_iterable(vdu
.get("volumes")):
450 if volumed
["name"] == volume
["name"]:
453 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
454 "volume:name='{}' is not present at vnfd:vdu:volumes list".
455 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
457 for in_iface
in get_iterable(in_vdu
["interface"]):
458 for iface
in get_iterable(vdu
.get("interface")):
459 if in_iface
["name"] == iface
["name"]:
462 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
463 "interface[name='{}'] is not present at vnfd:vdu:interface"
464 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
468 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
469 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
471 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
472 for ivld
in get_iterable(vnfd
.get("internal-vld")):
473 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
474 for in_icp
in get_iterable(in_ivld
["internal-connection-point"]):
475 for icp
in ivld
["internal-connection-point"]:
476 if in_icp
["id-ref"] == icp
["id-ref"]:
479 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
480 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
481 "vnfd:internal-vld:name/id:internal-connection-point"
482 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
483 in_icp
["id-ref"], vnfd
["id"]))
486 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
487 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
488 in_ivld
["name"], vnfd
["id"]))
490 def check_valid_vim_account(vim_account
):
491 if vim_account
in vim_accounts
:
494 db_filter
= self
._get
_project
_filter
(session
)
495 db_filter
["_id"] = vim_account
496 self
.db
.get_one("vim_accounts", db_filter
)
498 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
499 vim_accounts
.append(vim_account
)
501 def check_valid_wim_account(wim_account
):
502 if not isinstance(wim_account
, str):
504 elif wim_account
in wim_accounts
:
507 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
508 db_filter
["_id"] = wim_account
509 self
.db
.get_one("wim_accounts", db_filter
)
511 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
512 wim_accounts
.append(wim_account
)
514 if operation
== "action":
515 # check vnf_member_index
516 if indata
.get("vnf_member_index"):
517 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
518 if not indata
.get("member_vnf_index"):
519 raise EngineException("Missing 'member_vnf_index' parameter")
520 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
522 for config_primitive
in get_iterable(vnfd
.get("vnf-configuration", {}).get("config-primitive")):
523 if indata
["primitive"] == config_primitive
["name"]:
524 # check needed primitive_params are provided
525 if indata
.get("primitive_params"):
526 in_primitive_params_copy
= copy(indata
["primitive_params"])
528 in_primitive_params_copy
= {}
529 for paramd
in get_iterable(config_primitive
.get("parameter")):
530 if paramd
["name"] in in_primitive_params_copy
:
531 del in_primitive_params_copy
[paramd
["name"]]
532 elif not paramd
.get("default-value"):
533 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
534 paramd
["name"], indata
["primitive"]))
535 # check no extra primitive params are provided
536 if in_primitive_params_copy
:
537 raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
538 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
541 raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata
["primitive"]))
542 if operation
== "scale":
543 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
544 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
545 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
548 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
549 "present at vnfd:scaling-group-descriptor".format(
550 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
551 if operation
== "instantiate":
553 check_valid_vim_account(indata
["vimAccountId"])
554 check_valid_wim_account(indata
.get("wimAccountId"))
555 for in_vnf
in get_iterable(indata
.get("vnf")):
556 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
557 _check_vnf_instantiation_params(in_vnf
, vnfd
)
558 if in_vnf
.get("vimAccountId"):
559 check_valid_vim_account(in_vnf
["vimAccountId"])
561 for in_vld
in get_iterable(indata
.get("vld")):
562 check_valid_wim_account(in_vld
.get("wimAccountId"))
563 for vldd
in get_iterable(nsd
.get("vld")):
564 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
567 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
570 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
572 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
573 (ip_address, ...) information.
574 Modifies PDU _admin.usageState to 'IN_USE'
576 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
577 :param rollback: list with the database modifications to rollback if needed
578 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
579 :param vim_account: vim_account where this vnfr should be deployed
580 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
581 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
582 of the changed vnfr is needed
584 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
585 "vim-network-name": used at VIM
586 "name": interface name
587 "vnf-vld-id": internal VNFD vld where this interface is connected, or
588 "ns-vld-id": NSD vld where this interface is connected.
589 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
592 ifaces_forcing_vim_network
= []
593 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
594 if not vdur
.get("pdu-type"):
596 pdu_type
= vdur
.get("pdu-type")
597 pdu_filter
= self
._get
_project
_filter
(session
)
598 pdu_filter
["vim_accounts"] = vim_account
599 pdu_filter
["type"] = pdu_type
600 pdu_filter
["_admin.operationalState"] = "ENABLED"
601 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
602 # TODO feature 1417: "shared": True,
604 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
605 for pdu
in available_pdus
:
606 # step 1 check if this pdu contains needed interfaces:
607 match_interfaces
= True
608 for vdur_interface
in vdur
["interfaces"]:
609 for pdu_interface
in pdu
["interfaces"]:
610 if pdu_interface
["name"] == vdur_interface
["name"]:
611 # TODO feature 1417: match per mgmt type
613 else: # no interface found for name
614 match_interfaces
= False
619 raise EngineException(
620 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
621 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
625 "_admin.usageState": pdu
["_admin"]["usageState"],
626 "_admin.usage.vnfr_id": None,
627 "_admin.usage.nsr_id": None,
628 "_admin.usage.vdur": None,
630 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
631 {"_admin.usageState": "IN_USE",
632 "_admin.usage": {"vnfr_id": vnfr
["_id"],
633 "nsr_id": vnfr
["nsr-id-ref"],
634 "vdur": vdur
["vdu-id-ref"]}
636 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
638 # step 3. Fill vnfr info by filling vdur
639 vdu_text
= "vdur.{}".format(vdur_index
)
640 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
641 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
642 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
643 for pdu_interface
in pdu
["interfaces"]:
644 if pdu_interface
["name"] == vdur_interface
["name"]:
645 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
646 for k
, v
in pdu_interface
.items():
647 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
648 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
649 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
650 if pdu_interface
.get("ip-address"):
651 if vdur_interface
.get("mgmt-interface"):
652 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
653 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
654 if vdur_interface
.get("mgmt-vnf"):
655 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
656 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
657 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
658 ifaces_forcing_vim_network
.append({
659 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
660 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
661 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
662 if pdu_interface
.get("vim-network-id"):
663 ifaces_forcing_vim_network
.append({
664 "vim-network-id": pdu_interface
.get("vim-network-id")})
665 if pdu_interface
.get("vim-network-name"):
666 ifaces_forcing_vim_network
.append({
667 "vim-network-name": pdu_interface
.get("vim-network-name")})
670 return ifaces_forcing_vim_network
672 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
676 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
680 vnfr_update_rollback
= {}
681 member_vnf_index
= vnfr
["member-vnf-index-ref"]
682 # update vim-account-id
684 vim_account
= indata
["vimAccountId"]
685 # check instantiate parameters
686 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
687 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
689 if vnf_inst_params
.get("vimAccountId"):
690 vim_account
= vnf_inst_params
.get("vimAccountId")
692 vnfr_update
["vim-account-id"] = vim_account
693 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
696 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
697 vnfr_update_rollback
)
699 # updata database vnfr
700 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
701 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
703 # Update indada in case pdu forces to use a concrete vim-network-name
704 # TODO check if user has already insert a vim-network-name and raises an error
705 if not ifaces_forcing_vim_network
:
707 for iface_info
in ifaces_forcing_vim_network
:
708 if iface_info
.get("ns-vld-id"):
709 if "vld" not in indata
:
711 indata
["vld"].append({key
: iface_info
[key
] for key
in
712 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
714 elif iface_info
.get("vnf-vld-id"):
715 if "vnf" not in indata
:
717 indata
["vnf"].append({
718 "member-vnf-index": member_vnf_index
,
719 "internal-vld": [{key
: iface_info
[key
] for key
in
720 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
724 def _create_nslcmop(nsr_id
, operation
, params
):
726 Creates a ns-lcm-opp content to be stored at database.
727 :param nsr_id: internal id of the instance
728 :param operation: instantiate, terminate, scale, action, ...
729 :param params: user parameters for the operation
730 :return: dictionary following SOL005 format
737 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
738 "statusEnteredTime": now
,
739 "nsInstanceId": nsr_id
,
740 "lcmOperationType": operation
,
742 "isAutomaticInvocation": False,
743 "operationParams": params
,
744 "isCancelPending": False,
746 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
747 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
752 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
754 Performs a new operation over a ns
755 :param rollback: list to append created items at database in case a rollback must to be done
756 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
757 :param indata: descriptor with the parameters of the operation. It must contains among others
758 nsInstanceId: _id of the nsr to perform the operation
759 operation: it can be: instantiate, terminate, action, TODO: update, heal
760 :param kwargs: used to override the indata descriptor
761 :param headers: http request headers
762 :return: id of the nslcmops
765 # Override descriptor with query string kwargs
766 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
767 operation
= indata
["lcmOperationType"]
768 nsInstanceId
= indata
["nsInstanceId"]
770 validate_input(indata
, self
.operation_schema
[operation
])
772 _filter
= BaseTopic
._get
_project
_filter
(session
)
773 _filter
["_id"] = nsInstanceId
774 nsr
= self
.db
.get_one("nsrs", _filter
)
777 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
778 if operation
== "terminate" and indata
.get("autoremove"):
779 # NSR must be deleted
780 return None # a none in this case is used to indicate not instantiated. It can be removed
781 if operation
!= "instantiate":
782 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
783 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
785 if operation
== "instantiate" and not session
["force"]:
786 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
787 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
788 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
790 if operation
== "instantiate":
791 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
793 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
794 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
795 _id
= self
.db
.create("nslcmops", nslcmop_desc
)
796 rollback
.append({"topic": "nslcmops", "_id": _id
})
798 self
.msg
.write("ns", operation
, nslcmop_desc
)
800 except ValidationError
as e
:
801 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
802 # except DbException as e:
803 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
805 def delete(self
, session
, _id
, dry_run
=False):
806 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
808 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
809 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
812 class NsiTopic(BaseTopic
):
816 def __init__(self
, db
, fs
, msg
):
817 BaseTopic
.__init
__(self
, db
, fs
, msg
)
818 self
.nsrTopic
= NsrTopic(db
, fs
, msg
)
821 def _format_ns_request(ns_request
):
822 formated_request
= copy(ns_request
)
823 # TODO: Add request params
824 return formated_request
827 def _format_addional_params(slice_request
):
829 Get and format user additional params for NS or VNF
830 :param slice_request: User instantiation additional parameters
831 :return: a formatted copy of additional params or None if not supplied
833 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
834 if additional_params
:
835 for k
, v
in additional_params
.items():
836 if not isinstance(k
, str):
837 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
839 if "." in k
or "$" in k
:
840 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
842 if isinstance(v
, (dict, tuple, list)):
843 additional_params
[k
] = "!!yaml " + safe_dump(v
)
844 return additional_params
846 def _check_descriptor_dependencies(self
, session
, descriptor
):
848 Check that the dependent descriptors exist on a new descriptor or edition
849 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
850 :param descriptor: descriptor to be inserted or edit
851 :return: None or raises exception
853 if not descriptor
.get("nst-ref"):
855 nstd_id
= descriptor
["nst-ref"]
856 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
857 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
858 http_code
=HTTPStatus
.CONFLICT
)
860 def check_conflict_on_del(self
, session
, _id
, db_content
):
862 Check that NSI is not instantiated
863 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
864 :param _id: nsi internal id
865 :param db_content: The database content of the _id
866 :return: None or raises EngineException with the conflict
871 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
872 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
873 "Launch 'terminate' operation first; or force deletion".format(_id
),
874 http_code
=HTTPStatus
.CONFLICT
)
876 def delete_extra(self
, session
, _id
, db_content
):
878 Deletes associated nsilcmops from database. Deletes associated filesystem.
879 Set usageState of nst
880 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
881 :param _id: server internal id
882 :param db_content: The database content of the descriptor
883 :return: None if ok or raises EngineException with the problem
886 # Deleting the nsrs belonging to nsir
888 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
889 nsr_id
= nsrs_detailed_item
["nsrId"]
890 if nsrs_detailed_item
.get("shared"):
891 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
892 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
893 "_id.ne": nsir
["_id"]}
894 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
895 if nsi
: # last one using nsr
898 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False)
899 except (DbException
, EngineException
) as e
:
900 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
905 # delete related nsilcmops database entries
906 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
908 # Check and set used NST usage state
909 nsir_admin
= nsir
.get("_admin")
910 if nsir_admin
and nsir_admin
.get("nst-id"):
911 # check if used by another NSI
912 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
913 fail_on_empty
=False, fail_on_more
=False)
915 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
917 # def delete(self, session, _id, dry_run=False):
919 # Delete item by its internal _id
920 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
921 # :param _id: server internal id
922 # :param dry_run: make checking but do not delete
923 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
925 # # TODO add admin to filter, validate rights
926 # BaseTopic.delete(self, session, _id, dry_run=True)
930 # # Deleting the nsrs belonging to nsir
931 # nsir = self.db.get_one("nsis", {"_id": _id})
932 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
933 # nsr_id = nsrs_detailed_item["nsrId"]
934 # if nsrs_detailed_item.get("shared"):
935 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
936 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
937 # "_id.ne": nsir["_id"]}
938 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
939 # if nsi: # last one using nsr
942 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
943 # except (DbException, EngineException) as e:
944 # if e.http_code == HTTPStatus.NOT_FOUND:
948 # # deletes NetSlice instance object
949 # v = self.db.del_one("nsis", {"_id": _id})
951 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
952 # _filter = {"netsliceInstanceId": _id}
953 # self.db.del_list("nsilcmops", _filter)
955 # # Search if nst is being used by other nsi
956 # nsir_admin = nsir.get("_admin")
958 # if nsir_admin.get("nst-id"):
959 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
960 # fail_on_empty=False, fail_on_more=False)
962 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
965 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
967 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
968 :param rollback: list to append the created items at database in case a rollback must be done
969 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
970 :param indata: params to be used for the nsir
971 :param kwargs: used to override the indata descriptor
972 :param headers: http request headers
973 :return: the _id of nsi descriptor created at database
977 slice_request
= self
._remove
_envelop
(indata
)
978 # Override descriptor with query string kwargs
979 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
980 self
._validate
_input
_new
(slice_request
, session
["force"])
984 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
985 _filter
= self
._get
_project
_filter
(session
)
986 _filter
["_id"] = slice_request
["nstId"]
987 nstd
= self
.db
.get_one("nsts", _filter
)
990 nstd
.pop("_admin", None)
991 nstd_id
= nstd
.pop("_id", None)
992 nsi_id
= str(uuid4())
993 step
= "filling nsi_descriptor with input data"
998 "name": slice_request
["nsiName"],
999 "description": slice_request
.get("nsiDescription", ""),
1000 "datacenter": slice_request
["vimAccountId"],
1001 "nst-ref": nstd
["id"],
1002 "instantiation_parameters": slice_request
,
1003 "network-slice-template": nstd
,
1007 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1010 step
= "creating nsi at database"
1011 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1012 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1013 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1014 nsi_descriptor
["_admin"]["deployed"] = {}
1015 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1016 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1018 # Creating netslice-vld for the RO.
1019 step
= "creating netslice-vld at database"
1021 # Building the vlds list to be deployed
1022 # From netslice descriptors, creating the initial list
1025 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1026 # Getting template Instantiation parameters from NST
1027 nsi_vld
= deepcopy(netslice_vlds
)
1028 nsi_vld
["shared-nsrs-list"] = []
1029 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1030 nsi_vlds
.append(nsi_vld
)
1032 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1033 # Creating netslice-subnet_record.
1037 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1038 for member_ns
in nstd
["netslice-subnet"]:
1039 nsd_id
= member_ns
["nsd-ref"]
1040 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1041 member_ns
["nsd-ref"], member_ns
["id"])
1042 if nsd_id
not in needed_nsds
:
1044 _filter
["id"] = nsd_id
1045 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1048 needed_nsds
[nsd_id
] = nsd
1050 nsd
= needed_nsds
[nsd_id
]
1051 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1052 services
.append(member_ns
)
1054 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1055 member_ns
["nsd-ref"], member_ns
["id"])
1057 # creates Network Services records (NSRs)
1058 step
= "creating nsrs at database using NsrTopic.new()"
1059 ns_params
= slice_request
.get("netslice-subnet")
1061 nsi_netslice_subnet
= []
1062 for service
in services
:
1063 # Check if the netslice-subnet is shared and if it is share if the nss exists
1066 # Is the nss shared and instantiated?
1067 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1068 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1069 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1071 if nsi
and service
.get("is-shared-nss"):
1072 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1073 for nsrs_detailed_item
in nsrs_detailed_list
:
1074 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1075 _id_nsr
= nsrs_detailed_item
["nsrId"]
1077 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1078 if netslice_subnet
["nss-id"] == service
["id"]:
1079 indata_ns
= netslice_subnet
1083 if service
.get("instantiation-parameters"):
1084 indata_ns
= deepcopy(service
["instantiation-parameters"])
1085 # del service["instantiation-parameters"]
1087 indata_ns
["nsdId"] = service
["_id"]
1088 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1089 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1090 indata_ns
["nsDescription"] = service
["description"]
1091 indata_ns
["key-pair-ref"] = slice_request
.get("key-pair-ref")
1094 for ns_param
in ns_params
:
1095 if ns_param
.get("id") == service
["id"]:
1096 copy_ns_param
= deepcopy(ns_param
)
1097 del copy_ns_param
["id"]
1098 indata_ns
.update(copy_ns_param
)
1101 # Creates Nsr objects
1102 _id_nsr
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1103 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1104 "nslcmop_instantiate": None}
1105 indata_ns
["nss-id"] = service
["id"]
1106 nsrs_list
.append(nsrs_item
)
1107 nsi_netslice_subnet
.append(indata_ns
)
1108 nsr_ref
= {"nsr-ref": _id_nsr
}
1109 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1111 # Adding the nsrs list to the nsi
1112 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1113 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1114 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1116 # Creating the entry in the database
1117 self
.db
.create("nsis", nsi_descriptor
)
1118 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1120 except Exception as e
:
1121 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1122 raise EngineException("Error {}: {}".format(step
, e
))
1123 except ValidationError
as e
:
1124 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1126 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1127 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1130 class NsiLcmOpTopic(BaseTopic
):
1133 operation_schema
= { # mapping between operation and jsonschema to validate
1134 "instantiate": nsi_instantiate
,
1138 def __init__(self
, db
, fs
, msg
):
1139 BaseTopic
.__init
__(self
, db
, fs
, msg
)
1140 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
)
1142 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1144 Check that user has enter right parameters for the operation
1145 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1146 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1147 :param indata: descriptor with the parameters of the operation
1151 nstd
= nsir
["network-slice-template"]
1153 def check_valid_netslice_subnet_id(nstId
):
1154 # TODO change to vnfR (??)
1155 for netslice_subnet
in nstd
["netslice-subnet"]:
1156 if nstId
== netslice_subnet
["id"]:
1157 nsd_id
= netslice_subnet
["nsd-ref"]
1158 if nsd_id
not in nsds
:
1159 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1162 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1163 "nst:netslice-subnet".format(nstId
))
1164 if operation
== "instantiate":
1165 # check the existance of netslice-subnet items
1166 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1167 check_valid_netslice_subnet_id(in_nst
["id"])
1169 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1175 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1176 "statusEnteredTime": now
,
1177 "netsliceInstanceId": netsliceInstanceId
,
1178 "lcmOperationType": operation
,
1180 "isAutomaticInvocation": False,
1181 "operationParams": params
,
1182 "isCancelPending": False,
1184 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1185 "nsInstance": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1190 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1191 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1192 if nst_sb_item
.get("is-shared-nss"):
1193 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1194 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1195 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1196 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1197 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1198 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1199 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1201 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1202 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1204 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1206 Performs a new operation over a ns
1207 :param rollback: list to append created items at database in case a rollback must to be done
1208 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1209 :param indata: descriptor with the parameters of the operation. It must contains among others
1210 nsiInstanceId: _id of the nsir to perform the operation
1211 operation: it can be: instantiate, terminate, action, TODO: update, heal
1212 :param kwargs: used to override the indata descriptor
1213 :param headers: http request headers
1214 :return: id of the nslcmops
1217 # Override descriptor with query string kwargs
1218 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1219 operation
= indata
["lcmOperationType"]
1220 nsiInstanceId
= indata
["nsiInstanceId"]
1221 validate_input(indata
, self
.operation_schema
[operation
])
1223 # get nsi from nsiInstanceId
1224 _filter
= self
._get
_project
_filter
(session
)
1225 _filter
["_id"] = nsiInstanceId
1226 nsir
= self
.db
.get_one("nsis", _filter
)
1230 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1231 if operation
== "terminate" and indata
.get("autoremove"):
1232 # NSIR must be deleted
1233 return None # a none in this case is used to indicate not instantiated. It can be removed
1234 if operation
!= "instantiate":
1235 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1236 nsiInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1238 if operation
== "instantiate" and not session
["force"]:
1239 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1240 format(nsiInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1242 # Creating all the NS_operation (nslcmop)
1243 # Get service list from db
1244 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1246 # nslcmops_item = None
1247 for index
, nsr_item
in enumerate(nsrs_list
):
1249 if nsr_item
.get("shared"):
1250 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1251 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item
["nsrId"]
1252 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1253 _filter
["_id.ne"] = nsiInstanceId
1254 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1255 if operation
== "terminate":
1256 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1257 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1259 # looks the first nsi fulfilling the conditions but not being the current NSIR
1261 nsi_admin_shared
= nsi
["_admin"]["nsrs-detailed-list"]
1262 for nsi_nsr_item
in nsi_admin_shared
:
1263 if nsi_nsr_item
["nsd-id"] == nsr_item
["nsd-id"] and nsi_nsr_item
["shared"]:
1264 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1265 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1266 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1267 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1269 # continue to not create nslcmop since nsrs is shared and nsrs was created
1272 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1275 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1277 indata_ns
= service
["instantiate_params"]
1278 indata_ns
["lcmOperationType"] = operation
1279 indata_ns
["nsInstanceId"] = service
["_id"]
1280 # Including netslice_id in the ns instantiate Operation
1281 indata_ns
["netsliceInstanceId"] = nsiInstanceId
1282 del indata_ns
["key-pair-ref"]
1283 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1284 # message via kafka bus
1285 nslcmop
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
,
1287 nslcmops
.append(nslcmop
)
1288 if operation
== "terminate":
1290 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1291 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1292 except (DbException
, EngineException
) as e
:
1293 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1294 self
.logger
.info("HTTPStatus.NOT_FOUND")
1300 indata
["nslcmops_ids"] = nslcmops
1301 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1303 nsilcmop_desc
= self
._create
_nsilcmop
(session
, nsiInstanceId
, operation
, indata
)
1304 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1305 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1306 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1307 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1309 except ValidationError
as e
:
1310 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1312 def delete(self
, session
, _id
, dry_run
=False):
1313 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1315 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1316 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)