36b6a4218edb7100ab051d008760644fa6acabb7
[osm/NBI.git] / osm_nbi / instance_topics.py
1 # -*- coding: utf-8 -*-
2
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 # import logging
17 from uuid import uuid4
18 from http import HTTPStatus
19 from time import time
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
26 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
27
28
29 class NsrTopic(BaseTopic):
30 topic = "nsrs"
31 topic_msg = "ns"
32
33 def __init__(self, db, fs, msg):
34 BaseTopic.__init__(self, db, fs, msg)
35
36 def _check_descriptor_dependencies(self, session, descriptor):
37 """
38 Check that the dependent descriptors exist on a new descriptor or edition
39 :param session: client session information
40 :param descriptor: descriptor to be inserted or edit
41 :return: None or raises exception
42 """
43 if not descriptor.get("nsdId"):
44 return
45 nsd_id = descriptor["nsdId"]
46 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
47 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
48 http_code=HTTPStatus.CONFLICT)
49
50 @staticmethod
51 def format_on_new(content, project_id=None, make_public=False):
52 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
53 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
54
55 def check_conflict_on_del(self, session, _id, force=False):
56 if force:
57 return
58 nsr = self.db.get_one("nsrs", {"_id": _id})
59 if nsr["_admin"].get("nsState") == "INSTANTIATED":
60 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
61 "Launch 'terminate' operation first; or force deletion".format(_id),
62 http_code=HTTPStatus.CONFLICT)
63
64 def delete(self, session, _id, force=False, dry_run=False):
65 """
66 Delete item by its internal _id
67 :param session: contains the used login username, working project, and admin rights
68 :param _id: server internal id
69 :param force: indicates if deletion must be forced in case of conflict
70 :param dry_run: make checking but do not delete
71 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
72 """
73 # TODO add admin to filter, validate rights
74 BaseTopic.delete(self, session, _id, force, dry_run=True)
75 if dry_run:
76 return
77
78 self.fs.file_delete(_id, ignore_non_exist=True)
79 v = self.db.del_one("nsrs", {"_id": _id})
80 self.db.del_list("nslcmops", {"nsInstanceId": _id})
81 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
82 # set all used pdus as free
83 self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
84 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
85 self._send_msg("deleted", {"_id": _id})
86 return v
87
88 @staticmethod
89 def _format_ns_request(ns_request):
90 formated_request = copy(ns_request)
91 formated_request.pop("additionalParamsForNs", None)
92 formated_request.pop("additionalParamsForVnf", None)
93 return formated_request
94
95 @staticmethod
96 def _format_addional_params(ns_request, member_vnf_index=None, descriptor=None):
97 """
98 Get and format user additional params for NS or VNF
99 :param ns_request: User instantiation additional parameters
100 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
101 :param descriptor: If not None it check that needed parameters of descriptor are supplied
102 :return: a formated copy of additional params or None if not supplied
103 """
104 additional_params = None
105 if not member_vnf_index:
106 additional_params = copy(ns_request.get("additionalParamsForNs"))
107 where_ = "additionalParamsForNs"
108 elif ns_request.get("additionalParamsForVnf"):
109 for additionalParamsForVnf in get_iterable(ns_request.get("additionalParamsForVnf")):
110 if additionalParamsForVnf["member-vnf-index"] == member_vnf_index:
111 additional_params = copy(additionalParamsForVnf.get("additionalParams"))
112 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
113 additionalParamsForVnf["member-vnf-index"])
114 break
115 if additional_params:
116 for k, v in additional_params.items():
117 if not isinstance(k, str):
118 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_, k))
119 if "." in k or "$" in k:
120 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_, k))
121 if isinstance(v, (dict, tuple, list)):
122 additional_params[k] = "!!yaml " + safe_dump(v)
123
124 if descriptor:
125 # check that enough parameters are supplied for the initial-config-primitive
126 # TODO: check for cloud-init
127 if member_vnf_index:
128 if descriptor.get("vnf-configuration"):
129 for initial_primitive in get_iterable(
130 descriptor["vnf-configuration"].get("initial-config-primitive")):
131 for param in get_iterable(initial_primitive.get("parameter")):
132 if param["value"].startswith("<") and param["value"].endswith(">"):
133 if param["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>"):
134 continue
135 if not additional_params or param["value"][1:-1] not in additional_params:
136 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
137 "initial-config-primitive[name={}] not supplied".
138 format(param["value"], descriptor["id"],
139 initial_primitive["name"]))
140
141 return additional_params
142
143 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
144 """
145 Creates a new nsr into database. It also creates needed vnfrs
146 :param rollback: list to append the created items at database in case a rollback must be done
147 :param session: contains the used login username and working project
148 :param indata: params to be used for the nsr
149 :param kwargs: used to override the indata descriptor
150 :param headers: http request headers
151 :param force: If True avoid some dependence checks
152 :param make_public: Make the created item public to all projects
153 :return: the _id of nsr descriptor created at database
154 """
155
156 try:
157 ns_request = self._remove_envelop(indata)
158 # Override descriptor with query string kwargs
159 self._update_input_with_kwargs(ns_request, kwargs)
160 self._validate_input_new(ns_request, force)
161
162 step = ""
163 # look for nsr
164 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
165 _filter = {"_id": ns_request["nsdId"]}
166 _filter.update(BaseTopic._get_project_filter(session, write=False, show_all=True))
167 nsd = self.db.get_one("nsds", _filter)
168
169 nsr_id = str(uuid4())
170
171 now = time()
172 step = "filling nsr from input data"
173 nsr_descriptor = {
174 "name": ns_request["nsName"],
175 "name-ref": ns_request["nsName"],
176 "short-name": ns_request["nsName"],
177 "admin-status": "ENABLED",
178 "nsd": nsd,
179 "datacenter": ns_request["vimAccountId"],
180 "resource-orchestrator": "osmopenmano",
181 "description": ns_request.get("nsDescription", ""),
182 "constituent-vnfr-ref": [],
183
184 "operational-status": "init", # typedef ns-operational-
185 "config-status": "init", # typedef config-states
186 "detailed-status": "scheduled",
187
188 "orchestration-progress": {},
189 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
190
191 "crete-time": now,
192 "nsd-name-ref": nsd["name"],
193 "operational-events": [], # "id", "timestamp", "description", "event",
194 "nsd-ref": nsd["id"],
195 "instantiate_params": self._format_ns_request(ns_request),
196 "additionalParamsForNs": self._format_addional_params(ns_request),
197 "ns-instance-config-ref": nsr_id,
198 "id": nsr_id,
199 "_id": nsr_id,
200 # "input-parameter": xpath, value,
201 "ssh-authorized-key": ns_request.get("key-pair-ref"), # TODO remove
202 }
203 ns_request["nsr_id"] = nsr_id
204 # Create vld
205 if nsd.get("vld"):
206 nsr_descriptor["vld"] = []
207 for nsd_vld in nsd.get("vld"):
208 nsr_descriptor["vld"].append(
209 {key: nsd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in nsd_vld})
210
211 # Create VNFR
212 needed_vnfds = {}
213 for member_vnf in nsd.get("constituent-vnfd", ()):
214 vnfd_id = member_vnf["vnfd-id-ref"]
215 step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
216 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
217 if vnfd_id not in needed_vnfds:
218 # Obtain vnfd
219 vnfd = DescriptorTopic.get_one_by_id(self.db, session, "vnfds", vnfd_id)
220 vnfd.pop("_admin")
221 needed_vnfds[vnfd_id] = vnfd
222 else:
223 vnfd = needed_vnfds[vnfd_id]
224 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
225 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
226 vnfr_id = str(uuid4())
227 vnfr_descriptor = {
228 "id": vnfr_id,
229 "_id": vnfr_id,
230 "nsr-id-ref": nsr_id,
231 "member-vnf-index-ref": member_vnf["member-vnf-index"],
232 "additionalParamsForVnf": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
233 vnfd),
234 "created-time": now,
235 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
236 "vnfd-ref": vnfd_id,
237 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
238 "vim-account-id": None,
239 "vdur": [],
240 "connection-point": [],
241 "ip-address": None, # mgmt-interface filled by LCM
242 }
243
244 # Create vld
245 if vnfd.get("internal-vld"):
246 vnfr_descriptor["vld"] = []
247 for vnfd_vld in vnfd.get("internal-vld"):
248 vnfr_descriptor["vld"].append(
249 {key: vnfd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in
250 vnfd_vld})
251
252 vnfd_mgmt_cp = vnfd["mgmt-interface"].get("cp")
253 for cp in vnfd.get("connection-point", ()):
254 vnf_cp = {
255 "name": cp["name"],
256 "connection-point-id": cp.get("id"),
257 "id": cp.get("id"),
258 # "ip-address", "mac-address" # filled by LCM
259 # vim-id # TODO it would be nice having a vim port id
260 }
261 vnfr_descriptor["connection-point"].append(vnf_cp)
262 for vdu in vnfd.get("vdu", ()):
263 vdur = {
264 "vdu-id-ref": vdu["id"],
265 # TODO "name": "" Name of the VDU in the VIM
266 "ip-address": None, # mgmt-interface filled by LCM
267 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
268 "internal-connection-point": [],
269 "interfaces": [],
270 }
271 if vdu.get("pdu-type"):
272 vdur["pdu-type"] = vdu["pdu-type"]
273 # TODO volumes: name, volume-id
274 for icp in vdu.get("internal-connection-point", ()):
275 vdu_icp = {
276 "id": icp["id"],
277 "connection-point-id": icp["id"],
278 "name": icp.get("name"),
279 # "ip-address", "mac-address" # filled by LCM
280 # vim-id # TODO it would be nice having a vim port id
281 }
282 vdur["internal-connection-point"].append(vdu_icp)
283 for iface in vdu.get("interface", ()):
284 vdu_iface = {
285 "name": iface.get("name"),
286 # "ip-address", "mac-address" # filled by LCM
287 # vim-id # TODO it would be nice having a vim port id
288 }
289 if vnfd_mgmt_cp and iface.get("external-connection-point-ref") == vnfd_mgmt_cp:
290 vdu_iface["mgmt-vnf"] = True
291 if iface.get("mgmt-interface"):
292 vdu_iface["mgmt-interface"] = True # TODO change to mgmt-vdu
293
294 # look for network where this interface is connected
295 if iface.get("external-connection-point-ref"):
296 for nsd_vld in get_iterable(nsd.get("vld")):
297 for nsd_vld_cp in get_iterable(nsd_vld.get("vnfd-connection-point-ref")):
298 if nsd_vld_cp.get("vnfd-connection-point-ref") == \
299 iface["external-connection-point-ref"] and \
300 nsd_vld_cp.get("member-vnf-index-ref") == member_vnf["member-vnf-index"]:
301 vdu_iface["ns-vld-id"] = nsd_vld["id"]
302 break
303 else:
304 continue
305 break
306 elif iface.get("internal-connection-point-ref"):
307 for vnfd_ivld in get_iterable(vnfd.get("internal-vld")):
308 for vnfd_ivld_icp in get_iterable(vnfd_ivld.get("internal-connection-point")):
309 if vnfd_ivld_icp.get("id-ref") == iface["internal-connection-point-ref"]:
310 vdu_iface["vnf-vld-id"] = vnfd_ivld["id"]
311 break
312 else:
313 continue
314 break
315
316 vdur["interfaces"].append(vdu_iface)
317 count = vdu.get("count", 1)
318 if count is None:
319 count = 1
320 count = int(count) # TODO remove when descriptor serialized with payngbind
321 for index in range(0, count):
322 if index:
323 vdur = deepcopy(vdur)
324 vdur["_id"] = str(uuid4())
325 vdur["count-index"] = index
326 vnfr_descriptor["vdur"].append(vdur)
327
328 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
329 member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
330
331 # add at database
332 BaseTopic.format_on_new(vnfr_descriptor, session["project_id"], make_public=make_public)
333 self.db.create("vnfrs", vnfr_descriptor)
334 rollback.append({"topic": "vnfrs", "_id": vnfr_id})
335 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
336
337 step = "creating nsr at database"
338 self.format_on_new(nsr_descriptor, session["project_id"], make_public=make_public)
339 self.db.create("nsrs", nsr_descriptor)
340 rollback.append({"topic": "nsrs", "_id": nsr_id})
341
342 step = "creating nsr temporal folder"
343 self.fs.mkdir(nsr_id)
344
345 return nsr_id
346 except Exception as e:
347 self.logger.exception("Exception {} at NsrTopic.new()".format(e), exc_info=True)
348 raise EngineException("Error {}: {}".format(step, e))
349 except ValidationError as e:
350 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
351
352 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
353 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
354
355
356 class VnfrTopic(BaseTopic):
357 topic = "vnfrs"
358 topic_msg = None
359
360 def __init__(self, db, fs, msg):
361 BaseTopic.__init__(self, db, fs, msg)
362
363 def delete(self, session, _id, force=False, dry_run=False):
364 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
365
366 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
367 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
368
369 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
370 # Not used because vnfrs are created and deleted by NsrTopic class directly
371 raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
372
373
374 class NsLcmOpTopic(BaseTopic):
375 topic = "nslcmops"
376 topic_msg = "ns"
377 operation_schema = { # mapping between operation and jsonschema to validate
378 "instantiate": ns_instantiate,
379 "action": ns_action,
380 "scale": ns_scale,
381 "terminate": None,
382 }
383
384 def __init__(self, db, fs, msg):
385 BaseTopic.__init__(self, db, fs, msg)
386
387 def _check_ns_operation(self, session, nsr, operation, indata):
388 """
389 Check that user has enter right parameters for the operation
390 :param session:
391 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
392 :param indata: descriptor with the parameters of the operation
393 :return: None
394 """
395 vnfds = {}
396 vim_accounts = []
397 nsd = nsr["nsd"]
398
399 def check_valid_vnf_member_index(member_vnf_index):
400 # TODO change to vnfR
401 for vnf in nsd["constituent-vnfd"]:
402 if member_vnf_index == vnf["member-vnf-index"]:
403 vnfd_id = vnf["vnfd-id-ref"]
404 if vnfd_id not in vnfds:
405 vnfds[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
406 return vnfds[vnfd_id]
407 else:
408 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
409 "nsd:constituent-vnfd".format(member_vnf_index))
410
411 def _check_vnf_instantiation_params(in_vnfd, vnfd):
412
413 for in_vdu in get_iterable(in_vnfd.get("vdu")):
414 for vdu in get_iterable(vnfd.get("vdu")):
415 if in_vdu["id"] == vdu["id"]:
416 for volume in get_iterable(in_vdu.get("volume")):
417 for volumed in get_iterable(vdu.get("volumes")):
418 if volumed["name"] == volume["name"]:
419 break
420 else:
421 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
422 "volume:name='{}' is not present at vnfd:vdu:volumes list".
423 format(in_vnf["member-vnf-index"], in_vdu["id"],
424 volume["name"]))
425 for in_iface in get_iterable(in_vdu["interface"]):
426 for iface in get_iterable(vdu.get("interface")):
427 if in_iface["name"] == iface["name"]:
428 break
429 else:
430 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
431 "interface[name='{}'] is not present at vnfd:vdu:interface"
432 .format(in_vnf["member-vnf-index"], in_vdu["id"],
433 in_iface["name"]))
434 break
435 else:
436 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
437 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"]))
438
439 for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
440 for ivld in get_iterable(vnfd.get("internal-vld")):
441 if in_ivld["name"] == ivld["name"] or in_ivld["name"] == ivld["id"]:
442 for in_icp in get_iterable(in_ivld["internal-connection-point"]):
443 for icp in ivld["internal-connection-point"]:
444 if in_icp["id-ref"] == icp["id-ref"]:
445 break
446 else:
447 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
448 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
449 "vnfd:internal-vld:name/id:internal-connection-point"
450 .format(in_vnf["member-vnf-index"], in_ivld["name"],
451 in_icp["id-ref"], vnfd["id"]))
452 break
453 else:
454 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
455 " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
456 in_ivld["name"], vnfd["id"]))
457
458 def check_valid_vim_account(vim_account):
459 if vim_account in vim_accounts:
460 return
461 try:
462 db_filter = self._get_project_filter(session, write=False, show_all=True)
463 db_filter["_id"] = vim_account
464 self.db.get_one("vim_accounts", db_filter)
465 except Exception:
466 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account))
467 vim_accounts.append(vim_account)
468
469 if operation == "action":
470 # check vnf_member_index
471 if indata.get("vnf_member_index"):
472 indata["member_vnf_index"] = indata.pop("vnf_member_index") # for backward compatibility
473 if not indata.get("member_vnf_index"):
474 raise EngineException("Missing 'member_vnf_index' parameter")
475 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
476 # check primitive
477 for config_primitive in get_iterable(vnfd.get("vnf-configuration", {}).get("config-primitive")):
478 if indata["primitive"] == config_primitive["name"]:
479 # check needed primitive_params are provided
480 if indata.get("primitive_params"):
481 in_primitive_params_copy = copy(indata["primitive_params"])
482 else:
483 in_primitive_params_copy = {}
484 for paramd in get_iterable(config_primitive.get("parameter")):
485 if paramd["name"] in in_primitive_params_copy:
486 del in_primitive_params_copy[paramd["name"]]
487 elif not paramd.get("default-value"):
488 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
489 paramd["name"], indata["primitive"]))
490 # check no extra primitive params are provided
491 if in_primitive_params_copy:
492 raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
493 list(in_primitive_params_copy.keys()), indata["primitive"]))
494 break
495 else:
496 raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata["primitive"]))
497 if operation == "scale":
498 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
499 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
500 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
501 break
502 else:
503 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
504 "present at vnfd:scaling-group-descriptor".format(
505 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
506 if operation == "instantiate":
507 # check vim_account
508 check_valid_vim_account(indata["vimAccountId"])
509 for in_vnf in get_iterable(indata.get("vnf")):
510 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
511 _check_vnf_instantiation_params(in_vnf, vnfd)
512 if in_vnf.get("vimAccountId"):
513 check_valid_vim_account(in_vnf["vimAccountId"])
514
515 for in_vld in get_iterable(indata.get("vld")):
516 for vldd in get_iterable(nsd.get("vld")):
517 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
518 break
519 else:
520 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
521 in_vld["name"]))
522
523 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
524 """
525 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
526 (ip_address, ...) information.
527 Modifies PDU _admin.usageState to 'IN_USE'
528
529 :param session: client session information
530 :param rollback: list with the database modifications to rollback if needed
531 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
532 :param vim_account: vim_account where this vnfr should be deployed
533 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
534 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
535 of the changed vnfr is needed
536
537 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
538 "vim-network-name": used at VIM
539 "name": interface name
540 "vnf-vld-id": internal VNFD vld where this interface is connected, or
541 "ns-vld-id": NSD vld where this interface is connected.
542 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
543 """
544
545 ifaces_forcing_vim_network = []
546 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
547 if not vdur.get("pdu-type"):
548 continue
549 pdu_type = vdur.get("pdu-type")
550 pdu_filter = self._get_project_filter(session, write=True, show_all=True)
551 pdu_filter["vim_accounts"] = vim_account
552 pdu_filter["type"] = pdu_type
553 pdu_filter["_admin.operationalState"] = "ENABLED"
554 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
555 # TODO feature 1417: "shared": True,
556
557 available_pdus = self.db.get_list("pdus", pdu_filter)
558 for pdu in available_pdus:
559 # step 1 check if this pdu contains needed interfaces:
560 match_interfaces = True
561 for vdur_interface in vdur["interfaces"]:
562 for pdu_interface in pdu["interfaces"]:
563 if pdu_interface["name"] == vdur_interface["name"]:
564 # TODO feature 1417: match per mgmt type
565 break
566 else: # no interface found for name
567 match_interfaces = False
568 break
569 if match_interfaces:
570 break
571 else:
572 raise EngineException(
573 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
574 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
575
576 # step 2. Update pdu
577 rollback_pdu = {
578 "_admin.usageState": pdu["_admin"]["usageState"],
579 "_admin.usage.vnfr_id": None,
580 "_admin.usage.nsr_id": None,
581 "_admin.usage.vdur": None,
582 }
583 self.db.set_one("pdus", {"_id": pdu["_id"]},
584 {"_admin.usageState": "IN_USE",
585 "_admin.usage": {"vnfr_id": vnfr["_id"],
586 "nsr_id": vnfr["nsr-id-ref"],
587 "vdur": vdur["vdu-id-ref"]}
588 })
589 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
590
591 # step 3. Fill vnfr info by filling vdur
592 vdu_text = "vdur.{}".format(vdur_index)
593 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
594 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
595 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
596 for pdu_interface in pdu["interfaces"]:
597 if pdu_interface["name"] == vdur_interface["name"]:
598 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
599 for k, v in pdu_interface.items():
600 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
601 vnfr_update[iface_text + ".{}".format(k)] = v
602 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
603 if pdu_interface.get("ip-address"):
604 if vdur_interface.get("mgmt-interface"):
605 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
606 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
607 if vdur_interface.get("mgmt-vnf"):
608 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
609 vnfr_update["ip-address"] = pdu_interface["ip-address"]
610 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
611 ifaces_forcing_vim_network.append({
612 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
613 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
614 "ns-vld-id": vdur_interface.get("ns-vld-id")})
615 if pdu_interface.get("vim-network-id"):
616 ifaces_forcing_vim_network.append({
617 "vim-network-id": pdu_interface.get("vim-network-id")})
618 if pdu_interface.get("vim-network-name"):
619 ifaces_forcing_vim_network.append({
620 "vim-network-name": pdu_interface.get("vim-network-name")})
621 break
622
623 return ifaces_forcing_vim_network
624
625 def _update_vnfrs(self, session, rollback, nsr, indata):
626 vnfrs = None
627 # get vnfr
628 nsr_id = nsr["_id"]
629 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
630
631 for vnfr in vnfrs:
632 vnfr_update = {}
633 vnfr_update_rollback = {}
634 member_vnf_index = vnfr["member-vnf-index-ref"]
635 # update vim-account-id
636
637 vim_account = indata["vimAccountId"]
638 # check instantiate parameters
639 for vnf_inst_params in get_iterable(indata.get("vnf")):
640 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
641 continue
642 if vnf_inst_params.get("vimAccountId"):
643 vim_account = vnf_inst_params.get("vimAccountId")
644
645 vnfr_update["vim-account-id"] = vim_account
646 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
647
648 # get pdu
649 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
650 vnfr_update_rollback)
651
652 # updata database vnfr
653 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
654 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
655
656 # Update indada in case pdu forces to use a concrete vim-network-name
657 # TODO check if user has already insert a vim-network-name and raises an error
658 if not ifaces_forcing_vim_network:
659 continue
660 for iface_info in ifaces_forcing_vim_network:
661 if iface_info.get("ns-vld-id"):
662 if "vld" not in indata:
663 indata["vld"] = []
664 indata["vld"].append({key: iface_info[key] for key in
665 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
666
667 elif iface_info.get("vnf-vld-id"):
668 if "vnf" not in indata:
669 indata["vnf"] = []
670 indata["vnf"].append({
671 "member-vnf-index": member_vnf_index,
672 "internal-vld": [{key: iface_info[key] for key in
673 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
674 })
675
676 @staticmethod
677 def _create_nslcmop(nsr_id, operation, params):
678 """
679 Creates a ns-lcm-opp content to be stored at database.
680 :param nsr_id: internal id of the instance
681 :param operation: instantiate, terminate, scale, action, ...
682 :param params: user parameters for the operation
683 :return: dictionary following SOL005 format
684 """
685 now = time()
686 _id = str(uuid4())
687 nslcmop = {
688 "id": _id,
689 "_id": _id,
690 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
691 "statusEnteredTime": now,
692 "nsInstanceId": nsr_id,
693 "lcmOperationType": operation,
694 "startTime": now,
695 "isAutomaticInvocation": False,
696 "operationParams": params,
697 "isCancelPending": False,
698 "links": {
699 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
700 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
701 }
702 }
703 return nslcmop
704
705 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False,
706 slice_object=False):
707 """
708 Performs a new operation over a ns
709 :param rollback: list to append created items at database in case a rollback must to be done
710 :param session: contains the used login username and working project
711 :param indata: descriptor with the parameters of the operation. It must contains among others
712 nsInstanceId: _id of the nsr to perform the operation
713 operation: it can be: instantiate, terminate, action, TODO: update, heal
714 :param kwargs: used to override the indata descriptor
715 :param headers: http request headers
716 :param force: If True avoid some dependence checks
717 :param make_public: Make the created item public to all projects
718 :return: id of the nslcmops
719 """
720 try:
721 # Override descriptor with query string kwargs
722 self._update_input_with_kwargs(indata, kwargs)
723 operation = indata["lcmOperationType"]
724 nsInstanceId = indata["nsInstanceId"]
725
726 validate_input(indata, self.operation_schema[operation])
727 # get ns from nsr_id
728 _filter = BaseTopic._get_project_filter(session, write=True, show_all=False)
729 _filter["_id"] = nsInstanceId
730 nsr = self.db.get_one("nsrs", _filter)
731
732 # initial checking
733 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
734 if operation == "terminate" and indata.get("autoremove"):
735 # NSR must be deleted
736 return None # a none in this case is used to indicate not instantiated. It can be removed
737 if operation != "instantiate":
738 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
739 nsInstanceId, operation), HTTPStatus.CONFLICT)
740 else:
741 if operation == "instantiate" and not indata.get("force"):
742 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
743 nsInstanceId, operation), HTTPStatus.CONFLICT)
744 self._check_ns_operation(session, nsr, operation, indata)
745
746 if operation == "instantiate":
747 self._update_vnfrs(session, rollback, nsr, indata)
748
749 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
750 self.format_on_new(nslcmop_desc, session["project_id"], make_public=make_public)
751 _id = self.db.create("nslcmops", nslcmop_desc)
752 rollback.append({"topic": "nslcmops", "_id": _id})
753 if not slice_object:
754 self.msg.write("ns", operation, nslcmop_desc)
755 return _id
756 except ValidationError as e:
757 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
758 # except DbException as e:
759 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
760
761 def delete(self, session, _id, force=False, dry_run=False):
762 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
763
764 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
765 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
766
767
768 class NsiTopic(BaseTopic):
769 topic = "nsis"
770 topic_msg = "nsi"
771
772 def __init__(self, db, fs, msg):
773 BaseTopic.__init__(self, db, fs, msg)
774 self.nsrTopic = NsrTopic(db, fs, msg)
775
776 @staticmethod
777 def _format_ns_request(ns_request):
778 formated_request = copy(ns_request)
779 # TODO: Add request params
780 return formated_request
781
782 @staticmethod
783 def _format_addional_params(slice_request):
784 """
785 Get and format user additional params for NS or VNF
786 :param slice_request: User instantiation additional parameters
787 :return: a formatted copy of additional params or None if not supplied
788 """
789 additional_params = copy(slice_request.get("additionalParamsForNsi"))
790 if additional_params:
791 for k, v in additional_params.items():
792 if not isinstance(k, str):
793 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
794 format(k))
795 if "." in k or "$" in k:
796 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
797 format(k))
798 if isinstance(v, (dict, tuple, list)):
799 additional_params[k] = "!!yaml " + safe_dump(v)
800 return additional_params
801
802 def _check_descriptor_dependencies(self, session, descriptor):
803 """
804 Check that the dependent descriptors exist on a new descriptor or edition
805 :param session: client session information
806 :param descriptor: descriptor to be inserted or edit
807 :return: None or raises exception
808 """
809 if not descriptor.get("nst-ref"):
810 return
811 nstd_id = descriptor["nst-ref"]
812 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
813 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
814 http_code=HTTPStatus.CONFLICT)
815
816 @staticmethod
817 def format_on_new(content, project_id=None, make_public=False):
818 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
819
820 def check_conflict_on_del(self, session, _id, force=False):
821 if force:
822 return
823 nsi = self.db.get_one("nsis", {"_id": _id})
824 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
825 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
826 "Launch 'terminate' operation first; or force deletion".format(_id),
827 http_code=HTTPStatus.CONFLICT)
828
829 def delete(self, session, _id, force=False, dry_run=False):
830 """
831 Delete item by its internal _id
832 :param session: contains the used login username, working project, and admin rights
833 :param _id: server internal id
834 :param force: indicates if deletion must be forced in case of conflict
835 :param dry_run: make checking but do not delete
836 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
837 """
838 # TODO add admin to filter, validate rights
839 BaseTopic.delete(self, session, _id, force, dry_run=True)
840 if dry_run:
841 return
842
843 # deletes NetSlice instance object
844 v = self.db.del_one("nsis", {"_id": _id})
845
846 # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
847 _filter = {"netsliceInstanceId": _id}
848 self.db.del_list("nsilcmops", _filter)
849
850 _filter = {"operationParams.netsliceInstanceId": _id}
851 nslcmops_list = self.db.get_list("nslcmops", _filter)
852
853 for id_item in nslcmops_list:
854 _filter = {"_id": id_item}
855 nslcmop = self.db.get_one("nslcmops", _filter)
856 nsr_id = nslcmop["operationParams"]["nsr_id"]
857 self.nsrTopic.delete(session, nsr_id, force=False, dry_run=False)
858 self._send_msg("deleted", {"_id": _id})
859 return v
860
861 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
862 """
863 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
864 :param rollback: list to append the created items at database in case a rollback must be done
865 :param session: contains the used login username and working project
866 :param indata: params to be used for the nsir
867 :param kwargs: used to override the indata descriptor
868 :param headers: http request headers
869 :param force: If True avoid some dependence checks
870 :param make_public: Make the created item public to all projects
871 :return: the _id of nsi descriptor created at database
872 """
873
874 try:
875 slice_request = self._remove_envelop(indata)
876 # Override descriptor with query string kwargs
877 self._update_input_with_kwargs(slice_request, kwargs)
878 self._validate_input_new(slice_request, force)
879
880 step = ""
881 # look for nstd
882 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
883 _filter = {"_id": slice_request["nstId"]}
884 _filter.update(BaseTopic._get_project_filter(session, write=False, show_all=True))
885 nstd = self.db.get_one("nsts", _filter)
886 nstd.pop("_admin", None)
887 nstd.pop("_id", None)
888 nsi_id = str(uuid4())
889 step = "filling nsi_descriptor with input data"
890
891 # Creating the NSIR
892 nsi_descriptor = {
893 "id": nsi_id,
894 "name": slice_request["nsiName"],
895 "description": slice_request.get("nsiDescription", ""),
896 "datacenter": slice_request["vimAccountId"],
897 "nst-ref": nstd["id"],
898 "instantiation_parameters": slice_request,
899 "network-slice-template": nstd,
900 "nsr-ref-list": [],
901 "vlr-list": [],
902 "_id": nsi_id,
903 "additionalParamsForNsi": self._format_addional_params(slice_request)
904 }
905
906 step = "creating nsi at database"
907 self.format_on_new(nsi_descriptor, session["project_id"], make_public=make_public)
908 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
909 nsi_descriptor["_admin"]["netslice-subnet"] = None
910
911 # Creating netslice-vld for the RO.
912 step = "creating netslice-vld at database"
913 instantiation_parameters = slice_request
914
915 # Building the vlds list to be deployed
916 # From netslice descriptors, creating the initial list
917 nsi_vlds = []
918 if nstd.get("netslice-vld"):
919 # Building VLDs from NST
920 for netslice_vlds in nstd["netslice-vld"]:
921 nsi_vld = {}
922 # Adding nst vld name and global vimAccountId for netslice vld creation
923 nsi_vld["name"] = netslice_vlds["name"]
924 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
925 # Getting template Instantiation parameters from NST
926 for netslice_vld in netslice_vlds["nss-connection-point-ref"]:
927 for netslice_subnet in nstd["netslice-subnet"]:
928 nsi_vld["nsd-ref"] = netslice_subnet["nsd-ref"]
929 nsi_vld["nsd-connection-point-ref"] = netslice_vld["nsd-connection-point-ref"]
930 # Obtaining the vimAccountId from template instantiation parameter
931 if netslice_subnet.get("instantiation-parameters"):
932 # Taking the vimAccountId from NST netslice-subnet instantiation parameters
933 if netslice_subnet["instantiation-parameters"].get("vimAccountId"):
934 netsn = netslice_subnet["instantiation-parameters"]["vimAccountId"]
935 nsi_vld["vimAccountId"] = netsn
936 # Obtaining the vimAccountId from user instantiation parameter
937 if instantiation_parameters.get("netslice-subnet"):
938 for ins_param in instantiation_parameters["netslice-subnet"]:
939 if ins_param.get("id") == netslice_vld["nss-ref"]:
940 if ins_param.get("vimAccountId"):
941 nsi_vld["vimAccountId"] = ins_param["vimAccountId"]
942 # Adding vim-network-name / vim-network-id defined by the user to vld
943 if instantiation_parameters.get("netslice-vld"):
944 for ins_param in instantiation_parameters["netslice-vld"]:
945 if ins_param["name"] == netslice_vlds["name"]:
946 if ins_param.get("vim-network-name"):
947 nsi_vld["vim-network-name"] = ins_param.get("vim-network-name")
948 if ins_param.get("vim-network-id"):
949 nsi_vld["vim-network-id"] = ins_param.get("vim-network-id")
950 if netslice_vlds.get("mgmt-network"):
951 nsi_vld["mgmt-network"] = netslice_vlds.get("mgmt-network")
952 nsi_vlds.append(nsi_vld)
953
954 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
955 # Creating netslice-subnet_record.
956 needed_nsds = {}
957 services = []
958
959 for member_ns in nstd["netslice-subnet"]:
960 nsd_id = member_ns["nsd-ref"]
961 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
962 member_ns["nsd-ref"], member_ns["id"])
963 if nsd_id not in needed_nsds:
964 # Obtain nsd
965 nsd = DescriptorTopic.get_one_by_id(self.db, session, "nsds", nsd_id)
966 nsd.pop("_admin")
967 needed_nsds[nsd_id] = nsd
968 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
969 services.append(member_ns)
970 else:
971 nsd = needed_nsds[nsd_id]
972 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
973 services.append(member_ns)
974
975 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
976 member_ns["nsd-ref"], member_ns["id"])
977
978 # check additionalParamsForSubnet contains a valid id
979 if slice_request.get("additionalParamsForSubnet"):
980 for additional_params_subnet in get_iterable(slice_request.get("additionalParamsForSubnet")):
981 for service in services:
982 if additional_params_subnet["id"] == service["id"]:
983 break
984 else:
985 raise EngineException("Error at additionalParamsForSubnet:id='{}' not match any "
986 "netslice-subnet:id".format(additional_params_subnet["id"]))
987
988 # creates Network Services records (NSRs)
989 step = "creating nsrs at database using NsrTopic.new()"
990 ns_params = slice_request.get("netslice-subnet")
991
992 nsrs_list = []
993 nsi_netslice_subnet = []
994 for service in services:
995 indata_ns = {}
996 indata_ns["nsdId"] = service["_id"]
997 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
998 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
999 indata_ns["nsDescription"] = service["description"]
1000 indata_ns["key-pair-ref"] = None
1001 for additional_params_subnet in get_iterable(slice_request.get("additionalParamsForSubnet")):
1002 if additional_params_subnet["id"] == service["id"]:
1003 if additional_params_subnet.get("additionalParamsForNs"):
1004 indata_ns["additionalParamsForNs"] = additional_params_subnet["additionalParamsForNs"]
1005 if additional_params_subnet.get("additionalParamsForVnf"):
1006 indata_ns["additionalParamsForVnf"] = additional_params_subnet["additionalParamsForVnf"]
1007 break
1008
1009 # NsrTopic(rollback, session, indata_ns, kwargs, headers, force)
1010 # Overwriting ns_params filtering by nsName == netslice-subnet.id
1011
1012 if ns_params:
1013 for ns_param in ns_params:
1014 if ns_param.get("id") == service["id"]:
1015 copy_ns_param = deepcopy(ns_param)
1016 del copy_ns_param["id"]
1017 indata_ns.update(copy_ns_param)
1018 # TODO: Improve network selection via networkID
1019 # Override the instantiation parameters for netslice-vld provided by user
1020 if nsi_vlds:
1021 indata_ns_list = []
1022 for nsi_vld in nsi_vlds:
1023 nsd = self.db.get_one("nsds", {"id": nsi_vld["nsd-ref"]})
1024 if nsd["connection-point"]:
1025 for cp_item in nsd["connection-point"]:
1026 if cp_item["name"] == nsi_vld["nsd-connection-point-ref"]:
1027 vld_id_ref = cp_item["vld-id-ref"]
1028 # Mapping the vim-network-name or vim-network-id instantiation parameters
1029 if nsi_vld.get("vim-network-id"):
1030 vnid = nsi_vld.get("vim-network-id")
1031 if type(vnid) is not dict:
1032 vim_network_id = {slice_request.get("vimAccountId"): vnid}
1033 else: # is string
1034 vim_network_id = vnid
1035 indata_ns_list.append({"name": vld_id_ref, "vim-network-id": vim_network_id})
1036 # Case not vim-network-name instantiation parameter
1037 elif nsi_vld.get("vim-network-name"):
1038 vnm = nsi_vld.get("vim-network-name")
1039 if type(vnm) is not dict:
1040 vim_network_name = {slice_request.get("vimAccountId"): vnm}
1041 else: # is string
1042 vim_network_name = vnm
1043 indata_ns_list.append({"name": vld_id_ref,
1044 "vim-network-name": vim_network_name})
1045 # Case neither vim-network-name nor vim-network-id provided
1046 else:
1047 indata_ns_list.append({"name": vld_id_ref})
1048 if indata_ns_list:
1049 indata_ns["vld"] = indata_ns_list
1050
1051 # Creates Nsr objects
1052 _id_nsr = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers, force)
1053 nsrs_item = {"nsrId": _id_nsr}
1054 nsrs_list.append(nsrs_item)
1055 nsi_netslice_subnet.append(indata_ns)
1056 nsr_ref = {"nsr-ref": _id_nsr}
1057 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
1058
1059 # Adding the nsrs list to the nsi
1060 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
1061 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1062 # Creating the entry in the database
1063 self.db.create("nsis", nsi_descriptor)
1064 rollback.append({"topic": "nsis", "_id": nsi_id})
1065 return nsi_id
1066 except Exception as e:
1067 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1068 raise EngineException("Error {}: {}".format(step, e))
1069 except ValidationError as e:
1070 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1071
1072 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
1073 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1074
1075
1076 class NsiLcmOpTopic(BaseTopic):
1077 topic = "nsilcmops"
1078 topic_msg = "nsi"
1079 operation_schema = { # mapping between operation and jsonschema to validate
1080 "instantiate": nsi_instantiate,
1081 "terminate": None
1082 }
1083
1084 def __init__(self, db, fs, msg):
1085 BaseTopic.__init__(self, db, fs, msg)
1086
1087 def _check_nsi_operation(self, session, nsir, operation, indata):
1088 """
1089 Check that user has enter right parameters for the operation
1090 :param session:
1091 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1092 :param indata: descriptor with the parameters of the operation
1093 :return: None
1094 """
1095 nsds = {}
1096 nstd = nsir["network-slice-template"]
1097
1098 def check_valid_netslice_subnet_id(nstId):
1099 # TODO change to vnfR (??)
1100 for netslice_subnet in nstd["netslice-subnet"]:
1101 if nstId == netslice_subnet["id"]:
1102 nsd_id = netslice_subnet["nsd-ref"]
1103 if nsd_id not in nsds:
1104 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1105 return nsds[nsd_id]
1106 else:
1107 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1108 "nst:netslice-subnet".format(nstId))
1109 if operation == "instantiate":
1110 # check the existance of netslice-subnet items
1111 for in_nst in get_iterable(indata.get("netslice-subnet")):
1112 check_valid_netslice_subnet_id(in_nst["id"])
1113
1114 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1115 now = time()
1116 _id = str(uuid4())
1117 nsilcmop = {
1118 "id": _id,
1119 "_id": _id,
1120 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1121 "statusEnteredTime": now,
1122 "netsliceInstanceId": netsliceInstanceId,
1123 "lcmOperationType": operation,
1124 "startTime": now,
1125 "isAutomaticInvocation": False,
1126 "operationParams": params,
1127 "isCancelPending": False,
1128 "links": {
1129 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
1130 "nsInstance": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
1131 }
1132 }
1133 return nsilcmop
1134
1135 def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
1136 """
1137 Performs a new operation over a ns
1138 :param rollback: list to append created items at database in case a rollback must to be done
1139 :param session: contains the used login username and working project
1140 :param indata: descriptor with the parameters of the operation. It must contains among others
1141 nsiInstanceId: _id of the nsir to perform the operation
1142 operation: it can be: instantiate, terminate, action, TODO: update, heal
1143 :param kwargs: used to override the indata descriptor
1144 :param headers: http request headers
1145 :param force: If True avoid some dependence checks
1146 :param make_public: Make the created item public to all projects
1147 :return: id of the nslcmops
1148 """
1149 try:
1150 # Override descriptor with query string kwargs
1151 self._update_input_with_kwargs(indata, kwargs)
1152 operation = indata["lcmOperationType"]
1153 nsiInstanceId = indata["nsiInstanceId"]
1154 validate_input(indata, self.operation_schema[operation])
1155
1156 # get nsi from nsiInstanceId
1157 _filter = BaseTopic._get_project_filter(session, write=True, show_all=False)
1158 _filter["_id"] = nsiInstanceId
1159 nsir = self.db.get_one("nsis", _filter)
1160
1161 # initial checking
1162 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1163 if operation == "terminate" and indata.get("autoremove"):
1164 # NSIR must be deleted
1165 return None # a none in this case is used to indicate not instantiated. It can be removed
1166 if operation != "instantiate":
1167 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1168 nsiInstanceId, operation), HTTPStatus.CONFLICT)
1169 else:
1170 if operation == "instantiate" and not indata.get("force"):
1171 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1172 format(nsiInstanceId, operation), HTTPStatus.CONFLICT)
1173
1174 # Creating all the NS_operation (nslcmop)
1175 # Get service list from db
1176 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1177 nslcmops = []
1178 for nsr_item in nsrs_list:
1179 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1180 indata_ns = {}
1181 indata_ns = service["instantiate_params"]
1182 indata_ns["lcmOperationType"] = operation
1183 indata_ns["nsInstanceId"] = service["_id"]
1184 # Including netslice_id in the ns instantiate Operation
1185 indata_ns["netsliceInstanceId"] = nsiInstanceId
1186 del indata_ns["key-pair-ref"]
1187 nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg)
1188 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1189 # message via kafka bus
1190 nslcmop = nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers, force, slice_object=True)
1191 nslcmops.append(nslcmop)
1192
1193 # Creates nsilcmop
1194 indata["nslcmops_ids"] = nslcmops
1195 self._check_nsi_operation(session, nsir, operation, indata)
1196 nsilcmop_desc = self._create_nsilcmop(session, nsiInstanceId, operation, indata)
1197 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=make_public)
1198 _id = self.db.create("nsilcmops", nsilcmop_desc)
1199 rollback.append({"topic": "nsilcmops", "_id": _id})
1200 self.msg.write("nsi", operation, nsilcmop_desc)
1201 return _id
1202 except ValidationError as e:
1203 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1204 # except DbException as e:
1205 # raise EngineException("Cannot get nsi_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1206
1207 def delete(self, session, _id, force=False, dry_run=False):
1208 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1209
1210 def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
1211 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)