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