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