Fixing bug introduced in 35ef2f7832eb995b700a882262305a0dfedbc4c1
[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 not indata.get("member_vnf_index"):
519 raise EngineException("Missing 'member_vnf_index' parameter")
520 vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
521 # check primitive
522 for config_primitive in get_iterable(vnfd.get("vnf-configuration", {}).get("config-primitive")):
523 if indata["primitive"] == config_primitive["name"]:
524 # check needed primitive_params are provided
525 if indata.get("primitive_params"):
526 in_primitive_params_copy = copy(indata["primitive_params"])
527 else:
528 in_primitive_params_copy = {}
529 for paramd in get_iterable(config_primitive.get("parameter")):
530 if paramd["name"] in in_primitive_params_copy:
531 del in_primitive_params_copy[paramd["name"]]
532 elif not paramd.get("default-value"):
533 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
534 paramd["name"], indata["primitive"]))
535 # check no extra primitive params are provided
536 if in_primitive_params_copy:
537 raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
538 list(in_primitive_params_copy.keys()), indata["primitive"]))
539 break
540 else:
541 raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata["primitive"]))
542 if operation == "scale":
543 vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
544 for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
545 if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
546 break
547 else:
548 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
549 "present at vnfd:scaling-group-descriptor".format(
550 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
551 if operation == "instantiate":
552 # check vim_account
553 check_valid_vim_account(indata["vimAccountId"])
554 check_valid_wim_account(indata.get("wimAccountId"))
555 for in_vnf in get_iterable(indata.get("vnf")):
556 vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
557 _check_vnf_instantiation_params(in_vnf, vnfd)
558 if in_vnf.get("vimAccountId"):
559 check_valid_vim_account(in_vnf["vimAccountId"])
560
561 for in_vld in get_iterable(indata.get("vld")):
562 check_valid_wim_account(in_vld.get("wimAccountId"))
563 for vldd in get_iterable(nsd.get("vld")):
564 if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
565 break
566 else:
567 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
568 in_vld["name"]))
569
570 def _look_for_pdu(self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback):
571 """
572 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
573 (ip_address, ...) information.
574 Modifies PDU _admin.usageState to 'IN_USE'
575
576 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
577 :param rollback: list with the database modifications to rollback if needed
578 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
579 :param vim_account: vim_account where this vnfr should be deployed
580 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
581 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
582 of the changed vnfr is needed
583
584 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
585 "vim-network-name": used at VIM
586 "name": interface name
587 "vnf-vld-id": internal VNFD vld where this interface is connected, or
588 "ns-vld-id": NSD vld where this interface is connected.
589 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
590 """
591
592 ifaces_forcing_vim_network = []
593 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
594 if not vdur.get("pdu-type"):
595 continue
596 pdu_type = vdur.get("pdu-type")
597 pdu_filter = self._get_project_filter(session)
598 pdu_filter["vim_accounts"] = vim_account
599 pdu_filter["type"] = pdu_type
600 pdu_filter["_admin.operationalState"] = "ENABLED"
601 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
602 # TODO feature 1417: "shared": True,
603
604 available_pdus = self.db.get_list("pdus", pdu_filter)
605 for pdu in available_pdus:
606 # step 1 check if this pdu contains needed interfaces:
607 match_interfaces = True
608 for vdur_interface in vdur["interfaces"]:
609 for pdu_interface in pdu["interfaces"]:
610 if pdu_interface["name"] == vdur_interface["name"]:
611 # TODO feature 1417: match per mgmt type
612 break
613 else: # no interface found for name
614 match_interfaces = False
615 break
616 if match_interfaces:
617 break
618 else:
619 raise EngineException(
620 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
621 "names".format(pdu_type, vim_account, vnfr["member-vnf-index-ref"], vdur["vdu-id-ref"]))
622
623 # step 2. Update pdu
624 rollback_pdu = {
625 "_admin.usageState": pdu["_admin"]["usageState"],
626 "_admin.usage.vnfr_id": None,
627 "_admin.usage.nsr_id": None,
628 "_admin.usage.vdur": None,
629 }
630 self.db.set_one("pdus", {"_id": pdu["_id"]},
631 {"_admin.usageState": "IN_USE",
632 "_admin.usage": {"vnfr_id": vnfr["_id"],
633 "nsr_id": vnfr["nsr-id-ref"],
634 "vdur": vdur["vdu-id-ref"]}
635 })
636 rollback.append({"topic": "pdus", "_id": pdu["_id"], "operation": "set", "content": rollback_pdu})
637
638 # step 3. Fill vnfr info by filling vdur
639 vdu_text = "vdur.{}".format(vdur_index)
640 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
641 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
642 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
643 for pdu_interface in pdu["interfaces"]:
644 if pdu_interface["name"] == vdur_interface["name"]:
645 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
646 for k, v in pdu_interface.items():
647 if k in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
648 vnfr_update[iface_text + ".{}".format(k)] = v
649 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
650 if pdu_interface.get("ip-address"):
651 if vdur_interface.get("mgmt-interface"):
652 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
653 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
654 if vdur_interface.get("mgmt-vnf"):
655 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
656 vnfr_update["ip-address"] = pdu_interface["ip-address"]
657 if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
658 ifaces_forcing_vim_network.append({
659 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
660 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
661 "ns-vld-id": vdur_interface.get("ns-vld-id")})
662 if pdu_interface.get("vim-network-id"):
663 ifaces_forcing_vim_network.append({
664 "vim-network-id": pdu_interface.get("vim-network-id")})
665 if pdu_interface.get("vim-network-name"):
666 ifaces_forcing_vim_network.append({
667 "vim-network-name": pdu_interface.get("vim-network-name")})
668 break
669
670 return ifaces_forcing_vim_network
671
672 def _update_vnfrs(self, session, rollback, nsr, indata):
673 vnfrs = None
674 # get vnfr
675 nsr_id = nsr["_id"]
676 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
677
678 for vnfr in vnfrs:
679 vnfr_update = {}
680 vnfr_update_rollback = {}
681 member_vnf_index = vnfr["member-vnf-index-ref"]
682 # update vim-account-id
683
684 vim_account = indata["vimAccountId"]
685 # check instantiate parameters
686 for vnf_inst_params in get_iterable(indata.get("vnf")):
687 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
688 continue
689 if vnf_inst_params.get("vimAccountId"):
690 vim_account = vnf_inst_params.get("vimAccountId")
691
692 vnfr_update["vim-account-id"] = vim_account
693 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
694
695 # get pdu
696 ifaces_forcing_vim_network = self._look_for_pdu(session, rollback, vnfr, vim_account, vnfr_update,
697 vnfr_update_rollback)
698
699 # updata database vnfr
700 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
701 rollback.append({"topic": "vnfrs", "_id": vnfr["_id"], "operation": "set", "content": vnfr_update_rollback})
702
703 # Update indada in case pdu forces to use a concrete vim-network-name
704 # TODO check if user has already insert a vim-network-name and raises an error
705 if not ifaces_forcing_vim_network:
706 continue
707 for iface_info in ifaces_forcing_vim_network:
708 if iface_info.get("ns-vld-id"):
709 if "vld" not in indata:
710 indata["vld"] = []
711 indata["vld"].append({key: iface_info[key] for key in
712 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)})
713
714 elif iface_info.get("vnf-vld-id"):
715 if "vnf" not in indata:
716 indata["vnf"] = []
717 indata["vnf"].append({
718 "member-vnf-index": member_vnf_index,
719 "internal-vld": [{key: iface_info[key] for key in
720 ("name", "vim-network-name", "vim-network-id") if iface_info.get(key)}]
721 })
722
723 @staticmethod
724 def _create_nslcmop(nsr_id, operation, params):
725 """
726 Creates a ns-lcm-opp content to be stored at database.
727 :param nsr_id: internal id of the instance
728 :param operation: instantiate, terminate, scale, action, ...
729 :param params: user parameters for the operation
730 :return: dictionary following SOL005 format
731 """
732 now = time()
733 _id = str(uuid4())
734 nslcmop = {
735 "id": _id,
736 "_id": _id,
737 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
738 "statusEnteredTime": now,
739 "nsInstanceId": nsr_id,
740 "lcmOperationType": operation,
741 "startTime": now,
742 "isAutomaticInvocation": False,
743 "operationParams": params,
744 "isCancelPending": False,
745 "links": {
746 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
747 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
748 }
749 }
750 return nslcmop
751
752 def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
753 """
754 Performs a new operation over a ns
755 :param rollback: list to append created items at database in case a rollback must to be done
756 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
757 :param indata: descriptor with the parameters of the operation. It must contains among others
758 nsInstanceId: _id of the nsr to perform the operation
759 operation: it can be: instantiate, terminate, action, TODO: update, heal
760 :param kwargs: used to override the indata descriptor
761 :param headers: http request headers
762 :return: id of the nslcmops
763 """
764 try:
765 # Override descriptor with query string kwargs
766 self._update_input_with_kwargs(indata, kwargs)
767 operation = indata["lcmOperationType"]
768 nsInstanceId = indata["nsInstanceId"]
769
770 validate_input(indata, self.operation_schema[operation])
771 # get ns from nsr_id
772 _filter = BaseTopic._get_project_filter(session)
773 _filter["_id"] = nsInstanceId
774 nsr = self.db.get_one("nsrs", _filter)
775
776 # initial checking
777 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
778 if operation == "terminate" and indata.get("autoremove"):
779 # NSR must be deleted
780 return None # a none in this case is used to indicate not instantiated. It can be removed
781 if operation != "instantiate":
782 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
783 nsInstanceId, operation), HTTPStatus.CONFLICT)
784 else:
785 if operation == "instantiate" and not session["force"]:
786 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
787 nsInstanceId, operation), HTTPStatus.CONFLICT)
788 self._check_ns_operation(session, nsr, operation, indata)
789
790 if operation == "instantiate":
791 self._update_vnfrs(session, rollback, nsr, indata)
792
793 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
794 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
795 _id = self.db.create("nslcmops", nslcmop_desc)
796 rollback.append({"topic": "nslcmops", "_id": _id})
797 if not slice_object:
798 self.msg.write("ns", operation, nslcmop_desc)
799 return _id
800 except ValidationError as e:
801 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
802 # except DbException as e:
803 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
804
805 def delete(self, session, _id, dry_run=False):
806 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
807
808 def edit(self, session, _id, indata=None, kwargs=None, content=None):
809 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
810
811
812 class NsiTopic(BaseTopic):
813 topic = "nsis"
814 topic_msg = "nsi"
815
816 def __init__(self, db, fs, msg):
817 BaseTopic.__init__(self, db, fs, msg)
818 self.nsrTopic = NsrTopic(db, fs, msg)
819
820 @staticmethod
821 def _format_ns_request(ns_request):
822 formated_request = copy(ns_request)
823 # TODO: Add request params
824 return formated_request
825
826 @staticmethod
827 def _format_addional_params(slice_request):
828 """
829 Get and format user additional params for NS or VNF
830 :param slice_request: User instantiation additional parameters
831 :return: a formatted copy of additional params or None if not supplied
832 """
833 additional_params = copy(slice_request.get("additionalParamsForNsi"))
834 if additional_params:
835 for k, v in additional_params.items():
836 if not isinstance(k, str):
837 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
838 format(k))
839 if "." in k or "$" in k:
840 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
841 format(k))
842 if isinstance(v, (dict, tuple, list)):
843 additional_params[k] = "!!yaml " + safe_dump(v)
844 return additional_params
845
846 def _check_descriptor_dependencies(self, session, descriptor):
847 """
848 Check that the dependent descriptors exist on a new descriptor or edition
849 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
850 :param descriptor: descriptor to be inserted or edit
851 :return: None or raises exception
852 """
853 if not descriptor.get("nst-ref"):
854 return
855 nstd_id = descriptor["nst-ref"]
856 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
857 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
858 http_code=HTTPStatus.CONFLICT)
859
860 def check_conflict_on_del(self, session, _id, db_content):
861 """
862 Check that NSI is not instantiated
863 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
864 :param _id: nsi internal id
865 :param db_content: The database content of the _id
866 :return: None or raises EngineException with the conflict
867 """
868 if session["force"]:
869 return
870 nsi = db_content
871 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
872 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
873 "Launch 'terminate' operation first; or force deletion".format(_id),
874 http_code=HTTPStatus.CONFLICT)
875
876 def delete_extra(self, session, _id, db_content):
877 """
878 Deletes associated nsilcmops from database. Deletes associated filesystem.
879 Set usageState of nst
880 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
881 :param _id: server internal id
882 :param db_content: The database content of the descriptor
883 :return: None if ok or raises EngineException with the problem
884 """
885
886 # Deleting the nsrs belonging to nsir
887 nsir = db_content
888 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
889 nsr_id = nsrs_detailed_item["nsrId"]
890 if nsrs_detailed_item.get("shared"):
891 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
892 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
893 "_id.ne": nsir["_id"]}
894 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
895 if nsi: # last one using nsr
896 continue
897 try:
898 self.nsrTopic.delete(session, nsr_id, dry_run=False)
899 except (DbException, EngineException) as e:
900 if e.http_code == HTTPStatus.NOT_FOUND:
901 pass
902 else:
903 raise
904
905 # delete related nsilcmops database entries
906 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
907
908 # Check and set used NST usage state
909 nsir_admin = nsir.get("_admin")
910 if nsir_admin and nsir_admin.get("nst-id"):
911 # check if used by another NSI
912 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
913 fail_on_empty=False, fail_on_more=False)
914 if not nsis_list:
915 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
916
917 # def delete(self, session, _id, dry_run=False):
918 # """
919 # Delete item by its internal _id
920 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
921 # :param _id: server internal id
922 # :param dry_run: make checking but do not delete
923 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
924 # """
925 # # TODO add admin to filter, validate rights
926 # BaseTopic.delete(self, session, _id, dry_run=True)
927 # if dry_run:
928 # return
929 #
930 # # Deleting the nsrs belonging to nsir
931 # nsir = self.db.get_one("nsis", {"_id": _id})
932 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
933 # nsr_id = nsrs_detailed_item["nsrId"]
934 # if nsrs_detailed_item.get("shared"):
935 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
936 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
937 # "_id.ne": nsir["_id"]}
938 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
939 # if nsi: # last one using nsr
940 # continue
941 # try:
942 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
943 # except (DbException, EngineException) as e:
944 # if e.http_code == HTTPStatus.NOT_FOUND:
945 # pass
946 # else:
947 # raise
948 # # deletes NetSlice instance object
949 # v = self.db.del_one("nsis", {"_id": _id})
950 #
951 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
952 # _filter = {"netsliceInstanceId": _id}
953 # self.db.del_list("nsilcmops", _filter)
954 #
955 # # Search if nst is being used by other nsi
956 # nsir_admin = nsir.get("_admin")
957 # if nsir_admin:
958 # if nsir_admin.get("nst-id"):
959 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
960 # fail_on_empty=False, fail_on_more=False)
961 # if not nsis_list:
962 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
963 # return v
964
965 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
966 """
967 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
968 :param rollback: list to append the created items at database in case a rollback must be done
969 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
970 :param indata: params to be used for the nsir
971 :param kwargs: used to override the indata descriptor
972 :param headers: http request headers
973 :return: the _id of nsi descriptor created at database
974 """
975
976 try:
977 slice_request = self._remove_envelop(indata)
978 # Override descriptor with query string kwargs
979 self._update_input_with_kwargs(slice_request, kwargs)
980 self._validate_input_new(slice_request, session["force"])
981
982 step = ""
983 # look for nstd
984 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
985 _filter = self._get_project_filter(session)
986 _filter["_id"] = slice_request["nstId"]
987 nstd = self.db.get_one("nsts", _filter)
988 del _filter["_id"]
989
990 nstd.pop("_admin", None)
991 nstd_id = nstd.pop("_id", None)
992 nsi_id = str(uuid4())
993 step = "filling nsi_descriptor with input data"
994
995 # Creating the NSIR
996 nsi_descriptor = {
997 "id": nsi_id,
998 "name": slice_request["nsiName"],
999 "description": slice_request.get("nsiDescription", ""),
1000 "datacenter": slice_request["vimAccountId"],
1001 "nst-ref": nstd["id"],
1002 "instantiation_parameters": slice_request,
1003 "network-slice-template": nstd,
1004 "nsr-ref-list": [],
1005 "vlr-list": [],
1006 "_id": nsi_id,
1007 "additionalParamsForNsi": self._format_addional_params(slice_request)
1008 }
1009
1010 step = "creating nsi at database"
1011 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
1012 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1013 nsi_descriptor["_admin"]["netslice-subnet"] = None
1014 nsi_descriptor["_admin"]["deployed"] = {}
1015 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1016 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1017
1018 # Creating netslice-vld for the RO.
1019 step = "creating netslice-vld at database"
1020
1021 # Building the vlds list to be deployed
1022 # From netslice descriptors, creating the initial list
1023 nsi_vlds = []
1024
1025 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1026 # Getting template Instantiation parameters from NST
1027 nsi_vld = deepcopy(netslice_vlds)
1028 nsi_vld["shared-nsrs-list"] = []
1029 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1030 nsi_vlds.append(nsi_vld)
1031
1032 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
1033 # Creating netslice-subnet_record.
1034 needed_nsds = {}
1035 services = []
1036
1037 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1038 for member_ns in nstd["netslice-subnet"]:
1039 nsd_id = member_ns["nsd-ref"]
1040 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1041 member_ns["nsd-ref"], member_ns["id"])
1042 if nsd_id not in needed_nsds:
1043 # Obtain nsd
1044 _filter["id"] = nsd_id
1045 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1046 del _filter["id"]
1047 nsd.pop("_admin")
1048 needed_nsds[nsd_id] = nsd
1049 else:
1050 nsd = needed_nsds[nsd_id]
1051 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1052 services.append(member_ns)
1053
1054 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1055 member_ns["nsd-ref"], member_ns["id"])
1056
1057 # creates Network Services records (NSRs)
1058 step = "creating nsrs at database using NsrTopic.new()"
1059 ns_params = slice_request.get("netslice-subnet")
1060 nsrs_list = []
1061 nsi_netslice_subnet = []
1062 for service in services:
1063 # Check if the netslice-subnet is shared and if it is share if the nss exists
1064 _id_nsr = None
1065 indata_ns = {}
1066 # Is the nss shared and instantiated?
1067 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1068 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
1069 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1070
1071 if nsi and service.get("is-shared-nss"):
1072 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1073 for nsrs_detailed_item in nsrs_detailed_list:
1074 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
1075 _id_nsr = nsrs_detailed_item["nsrId"]
1076 break
1077 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1078 if netslice_subnet["nss-id"] == service["id"]:
1079 indata_ns = netslice_subnet
1080 break
1081 else:
1082 indata_ns = {}
1083 if service.get("instantiation-parameters"):
1084 indata_ns = deepcopy(service["instantiation-parameters"])
1085 # del service["instantiation-parameters"]
1086
1087 indata_ns["nsdId"] = service["_id"]
1088 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1089 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1090 indata_ns["nsDescription"] = service["description"]
1091 indata_ns["key-pair-ref"] = slice_request.get("key-pair-ref")
1092
1093 if ns_params:
1094 for ns_param in ns_params:
1095 if ns_param.get("id") == service["id"]:
1096 copy_ns_param = deepcopy(ns_param)
1097 del copy_ns_param["id"]
1098 indata_ns.update(copy_ns_param)
1099 break
1100
1101 # Creates Nsr objects
1102 _id_nsr = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
1103 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
1104 "nslcmop_instantiate": None}
1105 indata_ns["nss-id"] = service["id"]
1106 nsrs_list.append(nsrs_item)
1107 nsi_netslice_subnet.append(indata_ns)
1108 nsr_ref = {"nsr-ref": _id_nsr}
1109 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
1110
1111 # Adding the nsrs list to the nsi
1112 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
1113 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1114 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1115
1116 # Creating the entry in the database
1117 self.db.create("nsis", nsi_descriptor)
1118 rollback.append({"topic": "nsis", "_id": nsi_id})
1119 return nsi_id
1120 except Exception as e:
1121 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1122 raise EngineException("Error {}: {}".format(step, e))
1123 except ValidationError as e:
1124 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1125
1126 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1127 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1128
1129
1130 class NsiLcmOpTopic(BaseTopic):
1131 topic = "nsilcmops"
1132 topic_msg = "nsi"
1133 operation_schema = { # mapping between operation and jsonschema to validate
1134 "instantiate": nsi_instantiate,
1135 "terminate": None
1136 }
1137
1138 def __init__(self, db, fs, msg):
1139 BaseTopic.__init__(self, db, fs, msg)
1140 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg)
1141
1142 def _check_nsi_operation(self, session, nsir, operation, indata):
1143 """
1144 Check that user has enter right parameters for the operation
1145 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1146 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1147 :param indata: descriptor with the parameters of the operation
1148 :return: None
1149 """
1150 nsds = {}
1151 nstd = nsir["network-slice-template"]
1152
1153 def check_valid_netslice_subnet_id(nstId):
1154 # TODO change to vnfR (??)
1155 for netslice_subnet in nstd["netslice-subnet"]:
1156 if nstId == netslice_subnet["id"]:
1157 nsd_id = netslice_subnet["nsd-ref"]
1158 if nsd_id not in nsds:
1159 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1160 return nsds[nsd_id]
1161 else:
1162 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1163 "nst:netslice-subnet".format(nstId))
1164 if operation == "instantiate":
1165 # check the existance of netslice-subnet items
1166 for in_nst in get_iterable(indata.get("netslice-subnet")):
1167 check_valid_netslice_subnet_id(in_nst["id"])
1168
1169 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1170 now = time()
1171 _id = str(uuid4())
1172 nsilcmop = {
1173 "id": _id,
1174 "_id": _id,
1175 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1176 "statusEnteredTime": now,
1177 "netsliceInstanceId": netsliceInstanceId,
1178 "lcmOperationType": operation,
1179 "startTime": now,
1180 "isAutomaticInvocation": False,
1181 "operationParams": params,
1182 "isCancelPending": False,
1183 "links": {
1184 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
1185 "nsInstance": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
1186 }
1187 }
1188 return nsilcmop
1189
1190 def add_shared_nsr_2vld(self, nsir, nsr_item):
1191 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1192 if nst_sb_item.get("is-shared-nss"):
1193 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1194 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1195 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1196 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1197 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1198 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1199 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1200 break
1201 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1202 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1203
1204 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1205 """
1206 Performs a new operation over a ns
1207 :param rollback: list to append created items at database in case a rollback must to be done
1208 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1209 :param indata: descriptor with the parameters of the operation. It must contains among others
1210 nsiInstanceId: _id of the nsir to perform the operation
1211 operation: it can be: instantiate, terminate, action, TODO: update, heal
1212 :param kwargs: used to override the indata descriptor
1213 :param headers: http request headers
1214 :return: id of the nslcmops
1215 """
1216 try:
1217 # Override descriptor with query string kwargs
1218 self._update_input_with_kwargs(indata, kwargs)
1219 operation = indata["lcmOperationType"]
1220 nsiInstanceId = indata["nsiInstanceId"]
1221 validate_input(indata, self.operation_schema[operation])
1222
1223 # get nsi from nsiInstanceId
1224 _filter = self._get_project_filter(session)
1225 _filter["_id"] = nsiInstanceId
1226 nsir = self.db.get_one("nsis", _filter)
1227 del _filter["_id"]
1228
1229 # initial checking
1230 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1231 if operation == "terminate" and indata.get("autoremove"):
1232 # NSIR must be deleted
1233 return None # a none in this case is used to indicate not instantiated. It can be removed
1234 if operation != "instantiate":
1235 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1236 nsiInstanceId, operation), HTTPStatus.CONFLICT)
1237 else:
1238 if operation == "instantiate" and not session["force"]:
1239 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1240 format(nsiInstanceId, operation), HTTPStatus.CONFLICT)
1241
1242 # Creating all the NS_operation (nslcmop)
1243 # Get service list from db
1244 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1245 nslcmops = []
1246 # nslcmops_item = None
1247 for index, nsr_item in enumerate(nsrs_list):
1248 nsi = None
1249 if nsr_item.get("shared"):
1250 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True,
1251 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1252 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1253 _filter["_id.ne"] = nsiInstanceId
1254
1255 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1256 # looks the first nsi fulfilling the conditions but not being the current NSIR
1257 if nsi:
1258 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1259 for nsi_nsr_item in nsi_admin_shared:
1260 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1261 self.add_shared_nsr_2vld(nsir, nsr_item)
1262 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1263 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1264 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1265 break
1266 # continue to not create nslcmop since nsrs is shared and nsrs was created
1267 continue
1268 else:
1269 self.add_shared_nsr_2vld(nsir, nsr_item)
1270
1271 try:
1272 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1273 indata_ns = {}
1274 indata_ns = service["instantiate_params"]
1275 indata_ns["lcmOperationType"] = operation
1276 indata_ns["nsInstanceId"] = service["_id"]
1277 # Including netslice_id in the ns instantiate Operation
1278 indata_ns["netsliceInstanceId"] = nsiInstanceId
1279 del indata_ns["key-pair-ref"]
1280 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1281 # message via kafka bus
1282 nslcmop = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
1283 slice_object=True)
1284 nslcmops.append(nslcmop)
1285 if operation == "terminate":
1286 nslcmop = None
1287 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1288 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1289 except (DbException, EngineException) as e:
1290 if e.http_code == HTTPStatus.NOT_FOUND:
1291 self.logger.info("HTTPStatus.NOT_FOUND")
1292 pass
1293 else:
1294 raise
1295
1296 # Creates nsilcmop
1297 indata["nslcmops_ids"] = nslcmops
1298 self._check_nsi_operation(session, nsir, operation, indata)
1299
1300 nsilcmop_desc = self._create_nsilcmop(session, nsiInstanceId, operation, indata)
1301 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
1302 _id = self.db.create("nsilcmops", nsilcmop_desc)
1303 rollback.append({"topic": "nsilcmops", "_id": _id})
1304 self.msg.write("nsi", operation, nsilcmop_desc)
1305 return _id
1306 except ValidationError as e:
1307 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1308
1309 def delete(self, session, _id, dry_run=False):
1310 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1311
1312 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1313 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)