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