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 osm_common
.msgbase
import MsgException
27 from osm_common
.fsbase
import FsException
28 from re
import match
# For checking that additional parameter names are valid Jinja2 identifiers
30 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
33 class NsrTopic(BaseTopic
):
36 schema_new
= ns_instantiate
38 def __init__(self
, db
, fs
, msg
, auth
):
39 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
41 def _check_descriptor_dependencies(self
, session
, descriptor
):
43 Check that the dependent descriptors exist on a new descriptor or edition
44 :param session: client session information
45 :param descriptor: descriptor to be inserted or edit
46 :return: None or raises exception
48 if not descriptor
.get("nsdId"):
50 nsd_id
= descriptor
["nsdId"]
51 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
52 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
53 http_code
=HTTPStatus
.CONFLICT
)
56 def format_on_new(content
, project_id
=None, make_public
=False):
57 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
58 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
61 def check_conflict_on_del(self
, session
, _id
, db_content
):
63 Check that NSR is not instantiated
64 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
65 :param _id: nsr internal id
66 :param db_content: The database content of the nsr
67 :return: None or raises EngineException with the conflict
72 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
73 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
74 "Launch 'terminate' operation first; or force deletion".format(_id
),
75 http_code
=HTTPStatus
.CONFLICT
)
77 def delete_extra(self
, session
, _id
, db_content
):
79 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
80 Set usageState of pdu, vnfd, nsd
81 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
82 :param _id: server internal id
83 :param db_content: The database content of the descriptor
84 :return: None if ok or raises EngineException with the problem
86 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
87 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
88 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
90 # set all used pdus as free
91 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
92 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
96 used_nsd_id
= nsr
.get("nsd-id")
98 # check if used by another NSR
99 nsrs_list
= self
.db
.get_one("nsrs", {"nsd-id": used_nsd_id
},
100 fail_on_empty
=False, fail_on_more
=False)
102 self
.db
.set_one("nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"})
104 # Set VNFD usageState
105 used_vnfd_id_list
= nsr
.get("vnfd-id")
106 if used_vnfd_id_list
:
107 for used_vnfd_id
in used_vnfd_id_list
:
108 # check if used by another NSR
109 nsrs_list
= self
.db
.get_one("nsrs", {"vnfd-id": used_vnfd_id
},
110 fail_on_empty
=False, fail_on_more
=False)
112 self
.db
.set_one("vnfds", {"_id": used_vnfd_id
}, {"_admin.usageState": "NOT_IN_USE"})
115 def _format_ns_request(ns_request
):
116 formated_request
= copy(ns_request
)
117 formated_request
.pop("additionalParamsForNs", None)
118 formated_request
.pop("additionalParamsForVnf", None)
119 return formated_request
122 def _format_addional_params(ns_request
, member_vnf_index
=None, descriptor
=None):
124 Get and format user additional params for NS or VNF
125 :param ns_request: User instantiation additional parameters
126 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
127 :param descriptor: If not None it check that needed parameters of descriptor are supplied
128 :return: a formated copy of additional params or None if not supplied
130 additional_params
= None
131 if not member_vnf_index
:
132 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
133 where_
= "additionalParamsForNs"
134 elif ns_request
.get("additionalParamsForVnf"):
135 for additionalParamsForVnf
in get_iterable(ns_request
.get("additionalParamsForVnf")):
136 if additionalParamsForVnf
["member-vnf-index"] == member_vnf_index
:
137 additional_params
= copy(additionalParamsForVnf
.get("additionalParams"))
138 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(
139 additionalParamsForVnf
["member-vnf-index"])
141 if additional_params
:
142 for k
, v
in additional_params
.items():
143 # BEGIN Check that additional parameter names are valid Jinja2 identifiers
144 if not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k
):
145 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
146 "and underscores, and cannot start with a digit"
148 # END Check that additional parameter names are valid Jinja2 identifiers
149 if not isinstance(k
, str):
150 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
151 if "." in k
or "$" in k
:
152 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
153 if isinstance(v
, (dict, tuple, list)):
154 additional_params
[k
] = "!!yaml " + safe_dump(v
)
157 # check that enough parameters are supplied for the initial-config-primitive
158 # TODO: check for cloud-init
160 if descriptor
.get("vnf-configuration"):
161 for initial_primitive
in get_iterable(
162 descriptor
["vnf-configuration"].get("initial-config-primitive")):
163 for param
in get_iterable(initial_primitive
.get("parameter")):
164 if param
["value"].startswith("<") and param
["value"].endswith(">"):
165 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>"):
167 if not additional_params
or param
["value"][1:-1] not in additional_params
:
168 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
169 "initial-config-primitive[name={}] not supplied".
170 format(param
["value"], descriptor
["id"],
171 initial_primitive
["name"]))
173 return additional_params
175 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
177 Creates a new nsr into database. It also creates needed vnfrs
178 :param rollback: list to append the created items at database in case a rollback must be done
179 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
180 :param indata: params to be used for the nsr
181 :param kwargs: used to override the indata descriptor
182 :param headers: http request headers
183 :return: the _id of nsr descriptor created at database. Or an exception of type
184 EngineException, ValidationError, DbException, FsException, MsgException.
185 Note: Exceptions are not captured on purpose. They should be captured at called
189 step
= "checking quotas"
190 self
.check_quota(session
)
192 step
= "validating input parameters"
193 ns_request
= self
._remove
_envelop
(indata
)
194 # Override descriptor with query string kwargs
195 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
196 self
._validate
_input
_new
(ns_request
, session
["force"])
199 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
200 _filter
= self
._get
_project
_filter
(session
)
201 _filter
["_id"] = ns_request
["nsdId"]
202 nsd
= self
.db
.get_one("nsds", _filter
)
205 nsr_id
= str(uuid4())
208 step
= "filling nsr from input data"
210 "name": ns_request
["nsName"],
211 "name-ref": ns_request
["nsName"],
212 "short-name": ns_request
["nsName"],
213 "admin-status": "ENABLED",
215 "datacenter": ns_request
["vimAccountId"],
216 "resource-orchestrator": "osmopenmano",
217 "description": ns_request
.get("nsDescription", ""),
218 "constituent-vnfr-ref": [],
220 "operational-status": "init", # typedef ns-operational-
221 "config-status": "init", # typedef config-states
222 "detailed-status": "scheduled",
224 "orchestration-progress": {},
225 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
228 "nsd-name-ref": nsd
["name"],
229 "operational-events": [], # "id", "timestamp", "description", "event",
230 "nsd-ref": nsd
["id"],
231 "nsd-id": nsd
["_id"],
233 "instantiate_params": self
._format
_ns
_request
(ns_request
),
234 "additionalParamsForNs": self
._format
_addional
_params
(ns_request
),
235 "ns-instance-config-ref": nsr_id
,
238 # "input-parameter": xpath, value,
239 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
241 ns_request
["nsr_id"] = nsr_id
244 nsr_descriptor
["vld"] = []
245 for nsd_vld
in nsd
.get("vld"):
246 nsr_descriptor
["vld"].append(
247 {key
: nsd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in nsd_vld
})
251 for member_vnf
in nsd
.get("constituent-vnfd", ()):
252 vnfd_id
= member_vnf
["vnfd-id-ref"]
253 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
254 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
255 if vnfd_id
not in needed_vnfds
:
257 _filter
["id"] = vnfd_id
258 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
261 needed_vnfds
[vnfd_id
] = vnfd
262 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
264 vnfd
= needed_vnfds
[vnfd_id
]
265 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
266 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
267 vnfr_id
= str(uuid4())
271 "nsr-id-ref": nsr_id
,
272 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
273 "additionalParamsForVnf": self
._format
_addional
_params
(ns_request
, member_vnf
["member-vnf-index"],
276 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
278 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
279 "vim-account-id": None,
281 "connection-point": [],
282 "ip-address": None, # mgmt-interface filled by LCM
286 if vnfd
.get("internal-vld"):
287 vnfr_descriptor
["vld"] = []
288 for vnfd_vld
in vnfd
.get("internal-vld"):
289 vnfr_descriptor
["vld"].append(
290 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
293 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
294 for cp
in vnfd
.get("connection-point", ()):
297 "connection-point-id": cp
.get("id"),
299 # "ip-address", "mac-address" # filled by LCM
300 # vim-id # TODO it would be nice having a vim port id
302 vnfr_descriptor
["connection-point"].append(vnf_cp
)
303 for vdu
in vnfd
.get("vdu", ()):
305 "vdu-id-ref": vdu
["id"],
306 # TODO "name": "" Name of the VDU in the VIM
307 "ip-address": None, # mgmt-interface filled by LCM
308 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
309 "internal-connection-point": [],
312 if vdu
.get("pdu-type"):
313 vdur
["pdu-type"] = vdu
["pdu-type"]
314 # TODO volumes: name, volume-id
315 for icp
in vdu
.get("internal-connection-point", ()):
318 "connection-point-id": icp
["id"],
319 "name": icp
.get("name"),
320 # "ip-address", "mac-address" # filled by LCM
321 # vim-id # TODO it would be nice having a vim port id
323 vdur
["internal-connection-point"].append(vdu_icp
)
324 for iface
in vdu
.get("interface", ()):
326 "name": iface
.get("name"),
327 # "ip-address", "mac-address" # filled by LCM
328 # vim-id # TODO it would be nice having a vim port id
330 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
331 vdu_iface
["mgmt-vnf"] = True
332 if iface
.get("mgmt-interface"):
333 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
335 # look for network where this interface is connected
336 if iface
.get("external-connection-point-ref"):
337 for nsd_vld
in get_iterable(nsd
.get("vld")):
338 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
339 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
340 iface
["external-connection-point-ref"] and \
341 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
342 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
347 elif iface
.get("internal-connection-point-ref"):
348 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
349 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
350 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
351 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
357 vdur
["interfaces"].append(vdu_iface
)
358 count
= vdu
.get("count", 1)
361 count
= int(count
) # TODO remove when descriptor serialized with payngbind
362 for index
in range(0, count
):
364 vdur
= deepcopy(vdur
)
365 vdur
["_id"] = str(uuid4())
366 vdur
["count-index"] = index
367 vnfr_descriptor
["vdur"].append(vdur
)
369 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
370 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
373 self
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
374 self
.db
.create("vnfrs", vnfr_descriptor
)
375 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
376 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
378 step
= "creating nsr at database"
379 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
380 self
.db
.create("nsrs", nsr_descriptor
)
381 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
383 step
= "creating nsr temporal folder"
384 self
.fs
.mkdir(nsr_id
)
387 except (ValidationError
, EngineException
, DbException
, MsgException
, FsException
) as e
:
388 raise type(e
)("{} while '{}".format(e
, step
), http_code
=e
.http_code
)
390 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
391 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
394 class VnfrTopic(BaseTopic
):
398 def __init__(self
, db
, fs
, msg
, auth
):
399 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
401 def delete(self
, session
, _id
, dry_run
=False):
402 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
404 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
405 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
407 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
408 # Not used because vnfrs are created and deleted by NsrTopic class directly
409 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
412 class NsLcmOpTopic(BaseTopic
):
415 operation_schema
= { # mapping between operation and jsonschema to validate
416 "instantiate": ns_instantiate
,
422 def __init__(self
, db
, fs
, msg
, auth
):
423 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
425 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
427 Check that user has enter right parameters for the operation
428 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
429 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
430 :param indata: descriptor with the parameters of the operation
433 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
438 def check_valid_vnf_member_index(member_vnf_index
):
439 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
440 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
441 return vnf_member_index_to_vnfd
[member_vnf_index
]
442 vnfr
= self
.db
.get_one("vnfrs",
443 {"nsr-id-ref": nsr
["_id"], "member-vnf-index-ref": member_vnf_index
},
446 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
447 "nsd:constituent-vnfd".format(member_vnf_index
))
448 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
450 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
451 format(vnfr
["vnfd-id"]))
452 vnf_member_index_to_vnfd
[member_vnf_index
] = vnfd
# add to cache, avoiding a later look for
455 def check_valid_vdu(vnfd
, vdu_id
):
456 for vdud
in get_iterable(vnfd
.get("vdu")):
457 if vdud
["id"] == vdu_id
:
460 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id
))
462 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
464 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
465 for vdu
in get_iterable(vnfd
.get("vdu")):
466 if in_vdu
["id"] == vdu
["id"]:
467 for volume
in get_iterable(in_vdu
.get("volume")):
468 for volumed
in get_iterable(vdu
.get("volumes")):
469 if volumed
["name"] == volume
["name"]:
472 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
473 "volume:name='{}' is not present at vnfd:vdu:volumes list".
474 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
476 for in_iface
in get_iterable(in_vdu
["interface"]):
477 for iface
in get_iterable(vdu
.get("interface")):
478 if in_iface
["name"] == iface
["name"]:
481 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
482 "interface[name='{}'] is not present at vnfd:vdu:interface"
483 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
487 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
488 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
490 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
491 for ivld
in get_iterable(vnfd
.get("internal-vld")):
492 if in_ivld
["name"] == ivld
["name"] or in_ivld
["name"] == ivld
["id"]:
493 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
494 for icp
in ivld
["internal-connection-point"]:
495 if in_icp
["id-ref"] == icp
["id-ref"]:
498 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
499 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
500 "vnfd:internal-vld:name/id:internal-connection-point"
501 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
502 in_icp
["id-ref"], vnfd
["id"]))
505 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
506 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
507 in_ivld
["name"], vnfd
["id"]))
509 def check_valid_vim_account(vim_account
):
510 if vim_account
in vim_accounts
:
513 db_filter
= self
._get
_project
_filter
(session
)
514 db_filter
["_id"] = vim_account
515 self
.db
.get_one("vim_accounts", db_filter
)
517 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
518 vim_accounts
.append(vim_account
)
520 def check_valid_wim_account(wim_account
):
521 if not isinstance(wim_account
, str):
523 elif wim_account
in wim_accounts
:
526 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
527 db_filter
["_id"] = wim_account
528 self
.db
.get_one("wim_accounts", db_filter
)
530 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
531 wim_accounts
.append(wim_account
)
533 if operation
== "action":
534 # check vnf_member_index
535 if indata
.get("vnf_member_index"):
536 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
537 if indata
.get("member_vnf_index"):
538 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
539 if indata
.get("vdu_id"):
540 vdud
= check_valid_vdu(vnfd
, indata
["vdu_id"])
541 descriptor_configuration
= vdud
.get("vdu-configuration", {}).get("config-primitive")
543 descriptor_configuration
= vnfd
.get("vnf-configuration", {}).get("config-primitive")
545 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
547 for config_primitive
in get_iterable(descriptor_configuration
):
548 if indata
["primitive"] == config_primitive
["name"]:
549 # check needed primitive_params are provided
550 if indata
.get("primitive_params"):
551 in_primitive_params_copy
= copy(indata
["primitive_params"])
553 in_primitive_params_copy
= {}
554 for paramd
in get_iterable(config_primitive
.get("parameter")):
555 if paramd
["name"] in in_primitive_params_copy
:
556 del in_primitive_params_copy
[paramd
["name"]]
557 elif not paramd
.get("default-value"):
558 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
559 paramd
["name"], indata
["primitive"]))
560 # check no extra primitive params are provided
561 if in_primitive_params_copy
:
562 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
563 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
566 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
567 if operation
== "scale":
568 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
569 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
570 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
573 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
574 "present at vnfd:scaling-group-descriptor".format(
575 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
576 if operation
== "instantiate":
578 check_valid_vim_account(indata
["vimAccountId"])
579 check_valid_wim_account(indata
.get("wimAccountId"))
580 for in_vnf
in get_iterable(indata
.get("vnf")):
581 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
582 _check_vnf_instantiation_params(in_vnf
, vnfd
)
583 if in_vnf
.get("vimAccountId"):
584 check_valid_vim_account(in_vnf
["vimAccountId"])
586 for in_vld
in get_iterable(indata
.get("vld")):
587 check_valid_wim_account(in_vld
.get("wimAccountId"))
588 for vldd
in get_iterable(nsd
.get("vld")):
589 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
592 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
595 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
597 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
598 (ip_address, ...) information.
599 Modifies PDU _admin.usageState to 'IN_USE'
601 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
602 :param rollback: list with the database modifications to rollback if needed
603 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
604 :param vim_account: vim_account where this vnfr should be deployed
605 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
606 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
607 of the changed vnfr is needed
609 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
610 "vim-network-name": used at VIM
611 "name": interface name
612 "vnf-vld-id": internal VNFD vld where this interface is connected, or
613 "ns-vld-id": NSD vld where this interface is connected.
614 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
617 ifaces_forcing_vim_network
= []
618 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
619 if not vdur
.get("pdu-type"):
621 pdu_type
= vdur
.get("pdu-type")
622 pdu_filter
= self
._get
_project
_filter
(session
)
623 pdu_filter
["vim_accounts"] = vim_account
624 pdu_filter
["type"] = pdu_type
625 pdu_filter
["_admin.operationalState"] = "ENABLED"
626 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
627 # TODO feature 1417: "shared": True,
629 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
630 for pdu
in available_pdus
:
631 # step 1 check if this pdu contains needed interfaces:
632 match_interfaces
= True
633 for vdur_interface
in vdur
["interfaces"]:
634 for pdu_interface
in pdu
["interfaces"]:
635 if pdu_interface
["name"] == vdur_interface
["name"]:
636 # TODO feature 1417: match per mgmt type
638 else: # no interface found for name
639 match_interfaces
= False
644 raise EngineException(
645 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
646 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
650 "_admin.usageState": pdu
["_admin"]["usageState"],
651 "_admin.usage.vnfr_id": None,
652 "_admin.usage.nsr_id": None,
653 "_admin.usage.vdur": None,
655 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
656 {"_admin.usageState": "IN_USE",
657 "_admin.usage": {"vnfr_id": vnfr
["_id"],
658 "nsr_id": vnfr
["nsr-id-ref"],
659 "vdur": vdur
["vdu-id-ref"]}
661 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
663 # step 3. Fill vnfr info by filling vdur
664 vdu_text
= "vdur.{}".format(vdur_index
)
665 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
666 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
667 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
668 for pdu_interface
in pdu
["interfaces"]:
669 if pdu_interface
["name"] == vdur_interface
["name"]:
670 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
671 for k
, v
in pdu_interface
.items():
672 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
673 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
674 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
675 if pdu_interface
.get("ip-address"):
676 if vdur_interface
.get("mgmt-interface"):
677 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
678 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
679 if vdur_interface
.get("mgmt-vnf"):
680 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
681 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
682 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
683 ifaces_forcing_vim_network
.append({
684 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
685 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
686 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
687 if pdu_interface
.get("vim-network-id"):
688 ifaces_forcing_vim_network
.append({
689 "vim-network-id": pdu_interface
.get("vim-network-id")})
690 if pdu_interface
.get("vim-network-name"):
691 ifaces_forcing_vim_network
.append({
692 "vim-network-name": pdu_interface
.get("vim-network-name")})
695 return ifaces_forcing_vim_network
697 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
701 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
705 vnfr_update_rollback
= {}
706 member_vnf_index
= vnfr
["member-vnf-index-ref"]
707 # update vim-account-id
709 vim_account
= indata
["vimAccountId"]
710 # check instantiate parameters
711 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
712 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
714 if vnf_inst_params
.get("vimAccountId"):
715 vim_account
= vnf_inst_params
.get("vimAccountId")
717 vnfr_update
["vim-account-id"] = vim_account
718 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
721 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
722 vnfr_update_rollback
)
724 # updata database vnfr
725 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
726 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
728 # Update indada in case pdu forces to use a concrete vim-network-name
729 # TODO check if user has already insert a vim-network-name and raises an error
730 if not ifaces_forcing_vim_network
:
732 for iface_info
in ifaces_forcing_vim_network
:
733 if iface_info
.get("ns-vld-id"):
734 if "vld" not in indata
:
736 indata
["vld"].append({key
: iface_info
[key
] for key
in
737 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
739 elif iface_info
.get("vnf-vld-id"):
740 if "vnf" not in indata
:
742 indata
["vnf"].append({
743 "member-vnf-index": member_vnf_index
,
744 "internal-vld": [{key
: iface_info
[key
] for key
in
745 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
749 def _create_nslcmop(nsr_id
, operation
, params
):
751 Creates a ns-lcm-opp content to be stored at database.
752 :param nsr_id: internal id of the instance
753 :param operation: instantiate, terminate, scale, action, ...
754 :param params: user parameters for the operation
755 :return: dictionary following SOL005 format
762 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
763 "statusEnteredTime": now
,
764 "nsInstanceId": nsr_id
,
765 "lcmOperationType": operation
,
767 "isAutomaticInvocation": False,
768 "operationParams": params
,
769 "isCancelPending": False,
771 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
772 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
777 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
779 Performs a new operation over a ns
780 :param rollback: list to append created items at database in case a rollback must to be done
781 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
782 :param indata: descriptor with the parameters of the operation. It must contains among others
783 nsInstanceId: _id of the nsr to perform the operation
784 operation: it can be: instantiate, terminate, action, TODO: update, heal
785 :param kwargs: used to override the indata descriptor
786 :param headers: http request headers
787 :return: id of the nslcmops
789 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
791 db_filter
= self
._get
_project
_filter
(session
)
792 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
793 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
795 raise EngineException("The NS instance {} cannot be terminate because is used by the slice {}".format(
796 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
799 # Override descriptor with query string kwargs
800 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
801 operation
= indata
["lcmOperationType"]
802 nsInstanceId
= indata
["nsInstanceId"]
804 validate_input(indata
, self
.operation_schema
[operation
])
806 _filter
= BaseTopic
._get
_project
_filter
(session
)
807 _filter
["_id"] = nsInstanceId
808 nsr
= self
.db
.get_one("nsrs", _filter
)
811 if operation
== "terminate" and slice_object
is False:
812 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
813 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
814 if operation
== "terminate" and indata
.get("autoremove"):
815 # NSR must be deleted
816 return None, None # a none in this case is used to indicate not instantiated. It can be removed
817 if operation
!= "instantiate":
818 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
819 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
821 if operation
== "instantiate" and not session
["force"]:
822 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
823 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
824 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
826 if operation
== "instantiate":
827 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
829 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
830 _id
= nslcmop_desc
["_id"]
831 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
832 self
.db
.create("nslcmops", nslcmop_desc
)
833 rollback
.append({"topic": "nslcmops", "_id": _id
})
835 self
.msg
.write("ns", operation
, nslcmop_desc
)
837 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
838 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
839 # except DbException as e:
840 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
842 def delete(self
, session
, _id
, dry_run
=False):
843 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
845 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
846 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
849 class NsiTopic(BaseTopic
):
853 def __init__(self
, db
, fs
, msg
, auth
):
854 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
855 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
858 def _format_ns_request(ns_request
):
859 formated_request
= copy(ns_request
)
860 # TODO: Add request params
861 return formated_request
864 def _format_addional_params(slice_request
):
866 Get and format user additional params for NS or VNF
867 :param slice_request: User instantiation additional parameters
868 :return: a formatted copy of additional params or None if not supplied
870 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
871 if additional_params
:
872 for k
, v
in additional_params
.items():
873 if not isinstance(k
, str):
874 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
876 if "." in k
or "$" in k
:
877 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
879 if isinstance(v
, (dict, tuple, list)):
880 additional_params
[k
] = "!!yaml " + safe_dump(v
)
881 return additional_params
883 def _check_descriptor_dependencies(self
, session
, descriptor
):
885 Check that the dependent descriptors exist on a new descriptor or edition
886 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
887 :param descriptor: descriptor to be inserted or edit
888 :return: None or raises exception
890 if not descriptor
.get("nst-ref"):
892 nstd_id
= descriptor
["nst-ref"]
893 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
894 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
895 http_code
=HTTPStatus
.CONFLICT
)
897 def check_conflict_on_del(self
, session
, _id
, db_content
):
899 Check that NSI is not instantiated
900 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
901 :param _id: nsi internal id
902 :param db_content: The database content of the _id
903 :return: None or raises EngineException with the conflict
908 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
909 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
910 "Launch 'terminate' operation first; or force deletion".format(_id
),
911 http_code
=HTTPStatus
.CONFLICT
)
913 def delete_extra(self
, session
, _id
, db_content
):
915 Deletes associated nsilcmops from database. Deletes associated filesystem.
916 Set usageState of nst
917 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
918 :param _id: server internal id
919 :param db_content: The database content of the descriptor
920 :return: None if ok or raises EngineException with the problem
923 # Deleting the nsrs belonging to nsir
925 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
926 nsr_id
= nsrs_detailed_item
["nsrId"]
927 if nsrs_detailed_item
.get("shared"):
928 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
929 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
930 "_id.ne": nsir
["_id"]}
931 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
932 if nsi
: # last one using nsr
935 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False)
936 except (DbException
, EngineException
) as e
:
937 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
942 # delete related nsilcmops database entries
943 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
945 # Check and set used NST usage state
946 nsir_admin
= nsir
.get("_admin")
947 if nsir_admin
and nsir_admin
.get("nst-id"):
948 # check if used by another NSI
949 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
950 fail_on_empty
=False, fail_on_more
=False)
952 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
954 # def delete(self, session, _id, dry_run=False):
956 # Delete item by its internal _id
957 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
958 # :param _id: server internal id
959 # :param dry_run: make checking but do not delete
960 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
962 # # TODO add admin to filter, validate rights
963 # BaseTopic.delete(self, session, _id, dry_run=True)
967 # # Deleting the nsrs belonging to nsir
968 # nsir = self.db.get_one("nsis", {"_id": _id})
969 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
970 # nsr_id = nsrs_detailed_item["nsrId"]
971 # if nsrs_detailed_item.get("shared"):
972 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
973 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
974 # "_id.ne": nsir["_id"]}
975 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
976 # if nsi: # last one using nsr
979 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
980 # except (DbException, EngineException) as e:
981 # if e.http_code == HTTPStatus.NOT_FOUND:
985 # # deletes NetSlice instance object
986 # v = self.db.del_one("nsis", {"_id": _id})
988 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
989 # _filter = {"netsliceInstanceId": _id}
990 # self.db.del_list("nsilcmops", _filter)
992 # # Search if nst is being used by other nsi
993 # nsir_admin = nsir.get("_admin")
995 # if nsir_admin.get("nst-id"):
996 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
997 # fail_on_empty=False, fail_on_more=False)
999 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1002 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1004 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1005 :param rollback: list to append the created items at database in case a rollback must be done
1006 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1007 :param indata: params to be used for the nsir
1008 :param kwargs: used to override the indata descriptor
1009 :param headers: http request headers
1010 :return: the _id of nsi descriptor created at database
1014 step
= "checking quotas"
1015 self
.check_quota(session
)
1018 slice_request
= self
._remove
_envelop
(indata
)
1019 # Override descriptor with query string kwargs
1020 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
1021 self
._validate
_input
_new
(slice_request
, session
["force"])
1024 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1025 _filter
= self
._get
_project
_filter
(session
)
1026 _filter
["_id"] = slice_request
["nstId"]
1027 nstd
= self
.db
.get_one("nsts", _filter
)
1030 nstd
.pop("_admin", None)
1031 nstd_id
= nstd
.pop("_id", None)
1032 nsi_id
= str(uuid4())
1033 step
= "filling nsi_descriptor with input data"
1038 "name": slice_request
["nsiName"],
1039 "description": slice_request
.get("nsiDescription", ""),
1040 "datacenter": slice_request
["vimAccountId"],
1041 "nst-ref": nstd
["id"],
1042 "instantiation_parameters": slice_request
,
1043 "network-slice-template": nstd
,
1047 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1050 step
= "creating nsi at database"
1051 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1052 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1053 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1054 nsi_descriptor
["_admin"]["deployed"] = {}
1055 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1056 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1058 # Creating netslice-vld for the RO.
1059 step
= "creating netslice-vld at database"
1061 # Building the vlds list to be deployed
1062 # From netslice descriptors, creating the initial list
1065 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1066 # Getting template Instantiation parameters from NST
1067 nsi_vld
= deepcopy(netslice_vlds
)
1068 nsi_vld
["shared-nsrs-list"] = []
1069 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1070 nsi_vlds
.append(nsi_vld
)
1072 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1073 # Creating netslice-subnet_record.
1077 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1078 for member_ns
in nstd
["netslice-subnet"]:
1079 nsd_id
= member_ns
["nsd-ref"]
1080 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1081 member_ns
["nsd-ref"], member_ns
["id"])
1082 if nsd_id
not in needed_nsds
:
1084 _filter
["id"] = nsd_id
1085 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1088 needed_nsds
[nsd_id
] = nsd
1090 nsd
= needed_nsds
[nsd_id
]
1091 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1092 services
.append(member_ns
)
1094 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1095 member_ns
["nsd-ref"], member_ns
["id"])
1097 # creates Network Services records (NSRs)
1098 step
= "creating nsrs at database using NsrTopic.new()"
1099 ns_params
= slice_request
.get("netslice-subnet")
1101 nsi_netslice_subnet
= []
1102 for service
in services
:
1103 # Check if the netslice-subnet is shared and if it is share if the nss exists
1106 # Is the nss shared and instantiated?
1107 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1108 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1109 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1110 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1111 if nsi
and service
.get("is-shared-nss"):
1112 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1113 for nsrs_detailed_item
in nsrs_detailed_list
:
1114 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1115 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1116 _id_nsr
= nsrs_detailed_item
["nsrId"]
1118 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1119 if netslice_subnet
["nss-id"] == service
["id"]:
1120 indata_ns
= netslice_subnet
1124 if service
.get("instantiation-parameters"):
1125 indata_ns
= deepcopy(service
["instantiation-parameters"])
1126 # del service["instantiation-parameters"]
1128 indata_ns
["nsdId"] = service
["_id"]
1129 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1130 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1131 indata_ns
["nsDescription"] = service
["description"]
1132 if slice_request
.get("ssh_keys"):
1133 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1136 for ns_param
in ns_params
:
1137 if ns_param
.get("id") == service
["id"]:
1138 copy_ns_param
= deepcopy(ns_param
)
1139 del copy_ns_param
["id"]
1140 indata_ns
.update(copy_ns_param
)
1143 # Creates Nsr objects
1144 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1145 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1146 "nss-id": service
["id"], "nslcmop_instantiate": None}
1147 indata_ns
["nss-id"] = service
["id"]
1148 nsrs_list
.append(nsrs_item
)
1149 nsi_netslice_subnet
.append(indata_ns
)
1150 nsr_ref
= {"nsr-ref": _id_nsr
}
1151 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1153 # Adding the nsrs list to the nsi
1154 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1155 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1156 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1158 # Creating the entry in the database
1159 self
.db
.create("nsis", nsi_descriptor
)
1160 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1162 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1163 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1164 raise EngineException("Error {}: {}".format(step
, e
))
1165 except ValidationError
as e
:
1166 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1168 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1169 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1172 class NsiLcmOpTopic(BaseTopic
):
1175 operation_schema
= { # mapping between operation and jsonschema to validate
1176 "instantiate": nsi_instantiate
,
1180 def __init__(self
, db
, fs
, msg
, auth
):
1181 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1182 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
1184 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1186 Check that user has enter right parameters for the operation
1187 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1188 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1189 :param indata: descriptor with the parameters of the operation
1193 nstd
= nsir
["network-slice-template"]
1195 def check_valid_netslice_subnet_id(nstId
):
1196 # TODO change to vnfR (??)
1197 for netslice_subnet
in nstd
["netslice-subnet"]:
1198 if nstId
== netslice_subnet
["id"]:
1199 nsd_id
= netslice_subnet
["nsd-ref"]
1200 if nsd_id
not in nsds
:
1201 nsds
[nsd_id
] = self
.db
.get_one("nsds", {"id": nsd_id
})
1204 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1205 "nst:netslice-subnet".format(nstId
))
1206 if operation
== "instantiate":
1207 # check the existance of netslice-subnet items
1208 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1209 check_valid_netslice_subnet_id(in_nst
["id"])
1211 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1217 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1218 "statusEnteredTime": now
,
1219 "netsliceInstanceId": netsliceInstanceId
,
1220 "lcmOperationType": operation
,
1222 "isAutomaticInvocation": False,
1223 "operationParams": params
,
1224 "isCancelPending": False,
1226 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1227 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1232 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1233 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1234 if nst_sb_item
.get("is-shared-nss"):
1235 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1236 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1237 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1238 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1239 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1240 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1241 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1243 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1244 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1246 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1248 Performs a new operation over a ns
1249 :param rollback: list to append created items at database in case a rollback must to be done
1250 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1251 :param indata: descriptor with the parameters of the operation. It must contains among others
1252 netsliceInstanceId: _id of the nsir to perform the operation
1253 operation: it can be: instantiate, terminate, action, TODO: update, heal
1254 :param kwargs: used to override the indata descriptor
1255 :param headers: http request headers
1256 :return: id of the nslcmops
1259 # Override descriptor with query string kwargs
1260 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1261 operation
= indata
["lcmOperationType"]
1262 netsliceInstanceId
= indata
["netsliceInstanceId"]
1263 validate_input(indata
, self
.operation_schema
[operation
])
1265 # get nsi from netsliceInstanceId
1266 _filter
= self
._get
_project
_filter
(session
)
1267 _filter
["_id"] = netsliceInstanceId
1268 nsir
= self
.db
.get_one("nsis", _filter
)
1272 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1273 if operation
== "terminate" and indata
.get("autoremove"):
1274 # NSIR must be deleted
1275 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1276 if operation
!= "instantiate":
1277 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1278 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1280 if operation
== "instantiate" and not session
["force"]:
1281 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1282 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1284 # Creating all the NS_operation (nslcmop)
1285 # Get service list from db
1286 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1288 # nslcmops_item = None
1289 for index
, nsr_item
in enumerate(nsrs_list
):
1291 if nsr_item
.get("shared"):
1292 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1293 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item
["nsrId"]
1294 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1295 _filter
["_id.ne"] = netsliceInstanceId
1296 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1297 if operation
== "terminate":
1298 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1299 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1301 # looks the first nsi fulfilling the conditions but not being the current NSIR
1303 nsi_admin_shared
= nsi
["_admin"]["nsrs-detailed-list"]
1304 for nsi_nsr_item
in nsi_admin_shared
:
1305 if nsi_nsr_item
["nsd-id"] == nsr_item
["nsd-id"] and nsi_nsr_item
["shared"]:
1306 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1307 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1308 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1309 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1311 # continue to not create nslcmop since nsrs is shared and nsrs was created
1314 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1317 service
= self
.db
.get_one("nsrs", {"_id": nsr_item
["nsrId"]})
1319 indata_ns
= service
["instantiate_params"]
1320 indata_ns
["lcmOperationType"] = operation
1321 indata_ns
["nsInstanceId"] = service
["_id"]
1322 # Including netslice_id in the ns instantiate Operation
1323 indata_ns
["netsliceInstanceId"] = netsliceInstanceId
1324 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1325 # message via kafka bus
1326 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
,
1328 nslcmops
.append(nslcmop
)
1329 if operation
== "terminate":
1331 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1332 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1333 except (DbException
, EngineException
) as e
:
1334 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1335 self
.logger
.info("HTTPStatus.NOT_FOUND")
1341 indata
["nslcmops_ids"] = nslcmops
1342 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1344 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1345 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1346 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1347 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1348 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1350 except ValidationError
as e
:
1351 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1353 def delete(self
, session
, _id
, dry_run
=False):
1354 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1356 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1357 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)