Fixing bug 732
[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 try:
767 # Override descriptor with query string kwargs
768 self._update_input_with_kwargs(indata, kwargs)
769 operation = indata["lcmOperationType"]
770 nsInstanceId = indata["nsInstanceId"]
771
772 validate_input(indata, self.operation_schema[operation])
773 # get ns from nsr_id
774 _filter = BaseTopic._get_project_filter(session)
775 _filter["_id"] = nsInstanceId
776 nsr = self.db.get_one("nsrs", _filter)
777
778 # initial checking
779 if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
780 if operation == "terminate" and indata.get("autoremove"):
781 # NSR must be deleted
782 return None # a none in this case is used to indicate not instantiated. It can be removed
783 if operation != "instantiate":
784 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
785 nsInstanceId, operation), HTTPStatus.CONFLICT)
786 else:
787 if operation == "instantiate" and not session["force"]:
788 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
789 nsInstanceId, operation), HTTPStatus.CONFLICT)
790 self._check_ns_operation(session, nsr, operation, indata)
791
792 if operation == "instantiate":
793 self._update_vnfrs(session, rollback, nsr, indata)
794
795 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
796 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
797 _id = self.db.create("nslcmops", nslcmop_desc)
798 rollback.append({"topic": "nslcmops", "_id": _id})
799 if not slice_object:
800 self.msg.write("ns", operation, nslcmop_desc)
801 return _id
802 except ValidationError as e:
803 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
804 # except DbException as e:
805 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
806
807 def delete(self, session, _id, dry_run=False):
808 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
809
810 def edit(self, session, _id, indata=None, kwargs=None, content=None):
811 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
812
813
814 class NsiTopic(BaseTopic):
815 topic = "nsis"
816 topic_msg = "nsi"
817
818 def __init__(self, db, fs, msg):
819 BaseTopic.__init__(self, db, fs, msg)
820 self.nsrTopic = NsrTopic(db, fs, msg)
821
822 @staticmethod
823 def _format_ns_request(ns_request):
824 formated_request = copy(ns_request)
825 # TODO: Add request params
826 return formated_request
827
828 @staticmethod
829 def _format_addional_params(slice_request):
830 """
831 Get and format user additional params for NS or VNF
832 :param slice_request: User instantiation additional parameters
833 :return: a formatted copy of additional params or None if not supplied
834 """
835 additional_params = copy(slice_request.get("additionalParamsForNsi"))
836 if additional_params:
837 for k, v in additional_params.items():
838 if not isinstance(k, str):
839 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
840 format(k))
841 if "." in k or "$" in k:
842 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
843 format(k))
844 if isinstance(v, (dict, tuple, list)):
845 additional_params[k] = "!!yaml " + safe_dump(v)
846 return additional_params
847
848 def _check_descriptor_dependencies(self, session, descriptor):
849 """
850 Check that the dependent descriptors exist on a new descriptor or edition
851 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
852 :param descriptor: descriptor to be inserted or edit
853 :return: None or raises exception
854 """
855 if not descriptor.get("nst-ref"):
856 return
857 nstd_id = descriptor["nst-ref"]
858 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
859 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id),
860 http_code=HTTPStatus.CONFLICT)
861
862 def check_conflict_on_del(self, session, _id, db_content):
863 """
864 Check that NSI is not instantiated
865 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
866 :param _id: nsi internal id
867 :param db_content: The database content of the _id
868 :return: None or raises EngineException with the conflict
869 """
870 if session["force"]:
871 return
872 nsi = db_content
873 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
874 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
875 "Launch 'terminate' operation first; or force deletion".format(_id),
876 http_code=HTTPStatus.CONFLICT)
877
878 def delete_extra(self, session, _id, db_content):
879 """
880 Deletes associated nsilcmops from database. Deletes associated filesystem.
881 Set usageState of nst
882 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
883 :param _id: server internal id
884 :param db_content: The database content of the descriptor
885 :return: None if ok or raises EngineException with the problem
886 """
887
888 # Deleting the nsrs belonging to nsir
889 nsir = db_content
890 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
891 nsr_id = nsrs_detailed_item["nsrId"]
892 if nsrs_detailed_item.get("shared"):
893 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
894 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
895 "_id.ne": nsir["_id"]}
896 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
897 if nsi: # last one using nsr
898 continue
899 try:
900 self.nsrTopic.delete(session, nsr_id, dry_run=False)
901 except (DbException, EngineException) as e:
902 if e.http_code == HTTPStatus.NOT_FOUND:
903 pass
904 else:
905 raise
906
907 # delete related nsilcmops database entries
908 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
909
910 # Check and set used NST usage state
911 nsir_admin = nsir.get("_admin")
912 if nsir_admin and nsir_admin.get("nst-id"):
913 # check if used by another NSI
914 nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
915 fail_on_empty=False, fail_on_more=False)
916 if not nsis_list:
917 self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
918
919 # def delete(self, session, _id, dry_run=False):
920 # """
921 # Delete item by its internal _id
922 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
923 # :param _id: server internal id
924 # :param dry_run: make checking but do not delete
925 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
926 # """
927 # # TODO add admin to filter, validate rights
928 # BaseTopic.delete(self, session, _id, dry_run=True)
929 # if dry_run:
930 # return
931 #
932 # # Deleting the nsrs belonging to nsir
933 # nsir = self.db.get_one("nsis", {"_id": _id})
934 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
935 # nsr_id = nsrs_detailed_item["nsrId"]
936 # if nsrs_detailed_item.get("shared"):
937 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
938 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
939 # "_id.ne": nsir["_id"]}
940 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
941 # if nsi: # last one using nsr
942 # continue
943 # try:
944 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
945 # except (DbException, EngineException) as e:
946 # if e.http_code == HTTPStatus.NOT_FOUND:
947 # pass
948 # else:
949 # raise
950 # # deletes NetSlice instance object
951 # v = self.db.del_one("nsis", {"_id": _id})
952 #
953 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
954 # _filter = {"netsliceInstanceId": _id}
955 # self.db.del_list("nsilcmops", _filter)
956 #
957 # # Search if nst is being used by other nsi
958 # nsir_admin = nsir.get("_admin")
959 # if nsir_admin:
960 # if nsir_admin.get("nst-id"):
961 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
962 # fail_on_empty=False, fail_on_more=False)
963 # if not nsis_list:
964 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
965 # return v
966
967 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
968 """
969 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
970 :param rollback: list to append the created items at database in case a rollback must be done
971 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
972 :param indata: params to be used for the nsir
973 :param kwargs: used to override the indata descriptor
974 :param headers: http request headers
975 :return: the _id of nsi descriptor created at database
976 """
977
978 try:
979 slice_request = self._remove_envelop(indata)
980 # Override descriptor with query string kwargs
981 self._update_input_with_kwargs(slice_request, kwargs)
982 self._validate_input_new(slice_request, session["force"])
983
984 step = ""
985 # look for nstd
986 step = "getting nstd id='{}' from database".format(slice_request.get("nstId"))
987 _filter = self._get_project_filter(session)
988 _filter["_id"] = slice_request["nstId"]
989 nstd = self.db.get_one("nsts", _filter)
990 del _filter["_id"]
991
992 nstd.pop("_admin", None)
993 nstd_id = nstd.pop("_id", None)
994 nsi_id = str(uuid4())
995 step = "filling nsi_descriptor with input data"
996
997 # Creating the NSIR
998 nsi_descriptor = {
999 "id": nsi_id,
1000 "name": slice_request["nsiName"],
1001 "description": slice_request.get("nsiDescription", ""),
1002 "datacenter": slice_request["vimAccountId"],
1003 "nst-ref": nstd["id"],
1004 "instantiation_parameters": slice_request,
1005 "network-slice-template": nstd,
1006 "nsr-ref-list": [],
1007 "vlr-list": [],
1008 "_id": nsi_id,
1009 "additionalParamsForNsi": self._format_addional_params(slice_request)
1010 }
1011
1012 step = "creating nsi at database"
1013 self.format_on_new(nsi_descriptor, session["project_id"], make_public=session["public"])
1014 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1015 nsi_descriptor["_admin"]["netslice-subnet"] = None
1016 nsi_descriptor["_admin"]["deployed"] = {}
1017 nsi_descriptor["_admin"]["deployed"]["RO"] = []
1018 nsi_descriptor["_admin"]["nst-id"] = nstd_id
1019
1020 # Creating netslice-vld for the RO.
1021 step = "creating netslice-vld at database"
1022
1023 # Building the vlds list to be deployed
1024 # From netslice descriptors, creating the initial list
1025 nsi_vlds = []
1026
1027 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
1028 # Getting template Instantiation parameters from NST
1029 nsi_vld = deepcopy(netslice_vlds)
1030 nsi_vld["shared-nsrs-list"] = []
1031 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
1032 nsi_vlds.append(nsi_vld)
1033
1034 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
1035 # Creating netslice-subnet_record.
1036 needed_nsds = {}
1037 services = []
1038
1039 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1040 for member_ns in nstd["netslice-subnet"]:
1041 nsd_id = member_ns["nsd-ref"]
1042 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
1043 member_ns["nsd-ref"], member_ns["id"])
1044 if nsd_id not in needed_nsds:
1045 # Obtain nsd
1046 _filter["id"] = nsd_id
1047 nsd = self.db.get_one("nsds", _filter, fail_on_empty=True, fail_on_more=True)
1048 del _filter["id"]
1049 nsd.pop("_admin")
1050 needed_nsds[nsd_id] = nsd
1051 else:
1052 nsd = needed_nsds[nsd_id]
1053 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
1054 services.append(member_ns)
1055
1056 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1057 member_ns["nsd-ref"], member_ns["id"])
1058
1059 # creates Network Services records (NSRs)
1060 step = "creating nsrs at database using NsrTopic.new()"
1061 ns_params = slice_request.get("netslice-subnet")
1062 nsrs_list = []
1063 nsi_netslice_subnet = []
1064 for service in services:
1065 # Check if the netslice-subnet is shared and if it is share if the nss exists
1066 _id_nsr = None
1067 indata_ns = {}
1068 # Is the nss shared and instantiated?
1069 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1070 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service["nsd-ref"]
1071 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1072
1073 if nsi and service.get("is-shared-nss"):
1074 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
1075 for nsrs_detailed_item in nsrs_detailed_list:
1076 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
1077 _id_nsr = nsrs_detailed_item["nsrId"]
1078 break
1079 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
1080 if netslice_subnet["nss-id"] == service["id"]:
1081 indata_ns = netslice_subnet
1082 break
1083 else:
1084 indata_ns = {}
1085 if service.get("instantiation-parameters"):
1086 indata_ns = deepcopy(service["instantiation-parameters"])
1087 # del service["instantiation-parameters"]
1088
1089 indata_ns["nsdId"] = service["_id"]
1090 indata_ns["nsName"] = slice_request.get("nsiName") + "." + service["id"]
1091 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
1092 indata_ns["nsDescription"] = service["description"]
1093 indata_ns["key-pair-ref"] = slice_request.get("key-pair-ref")
1094
1095 if ns_params:
1096 for ns_param in ns_params:
1097 if ns_param.get("id") == service["id"]:
1098 copy_ns_param = deepcopy(ns_param)
1099 del copy_ns_param["id"]
1100 indata_ns.update(copy_ns_param)
1101 break
1102
1103 # Creates Nsr objects
1104 _id_nsr = self.nsrTopic.new(rollback, session, indata_ns, kwargs, headers)
1105 nsrs_item = {"nsrId": _id_nsr, "shared": service.get("is-shared-nss"), "nsd-id": service["nsd-ref"],
1106 "nslcmop_instantiate": None}
1107 indata_ns["nss-id"] = service["id"]
1108 nsrs_list.append(nsrs_item)
1109 nsi_netslice_subnet.append(indata_ns)
1110 nsr_ref = {"nsr-ref": _id_nsr}
1111 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
1112
1113 # Adding the nsrs list to the nsi
1114 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
1115 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1116 self.db.set_one("nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"})
1117
1118 # Creating the entry in the database
1119 self.db.create("nsis", nsi_descriptor)
1120 rollback.append({"topic": "nsis", "_id": nsi_id})
1121 return nsi_id
1122 except Exception as e:
1123 self.logger.exception("Exception {} at NsiTopic.new()".format(e), exc_info=True)
1124 raise EngineException("Error {}: {}".format(step, e))
1125 except ValidationError as e:
1126 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1127
1128 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1129 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1130
1131
1132 class NsiLcmOpTopic(BaseTopic):
1133 topic = "nsilcmops"
1134 topic_msg = "nsi"
1135 operation_schema = { # mapping between operation and jsonschema to validate
1136 "instantiate": nsi_instantiate,
1137 "terminate": None
1138 }
1139
1140 def __init__(self, db, fs, msg):
1141 BaseTopic.__init__(self, db, fs, msg)
1142 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg)
1143
1144 def _check_nsi_operation(self, session, nsir, operation, indata):
1145 """
1146 Check that user has enter right parameters for the operation
1147 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1148 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1149 :param indata: descriptor with the parameters of the operation
1150 :return: None
1151 """
1152 nsds = {}
1153 nstd = nsir["network-slice-template"]
1154
1155 def check_valid_netslice_subnet_id(nstId):
1156 # TODO change to vnfR (??)
1157 for netslice_subnet in nstd["netslice-subnet"]:
1158 if nstId == netslice_subnet["id"]:
1159 nsd_id = netslice_subnet["nsd-ref"]
1160 if nsd_id not in nsds:
1161 nsds[nsd_id] = self.db.get_one("nsds", {"id": nsd_id})
1162 return nsds[nsd_id]
1163 else:
1164 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1165 "nst:netslice-subnet".format(nstId))
1166 if operation == "instantiate":
1167 # check the existance of netslice-subnet items
1168 for in_nst in get_iterable(indata.get("netslice-subnet")):
1169 check_valid_netslice_subnet_id(in_nst["id"])
1170
1171 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
1172 now = time()
1173 _id = str(uuid4())
1174 nsilcmop = {
1175 "id": _id,
1176 "_id": _id,
1177 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1178 "statusEnteredTime": now,
1179 "netsliceInstanceId": netsliceInstanceId,
1180 "lcmOperationType": operation,
1181 "startTime": now,
1182 "isAutomaticInvocation": False,
1183 "operationParams": params,
1184 "isCancelPending": False,
1185 "links": {
1186 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
1187 "nsInstance": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId,
1188 }
1189 }
1190 return nsilcmop
1191
1192 def add_shared_nsr_2vld(self, nsir, nsr_item):
1193 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
1194 if nst_sb_item.get("is-shared-nss"):
1195 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
1196 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
1197 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
1198 for admin_vld_nss_cp_ref_item in admin_vld_item["nss-connection-point-ref"]:
1199 if admin_subnet_item["nss-id"] == admin_vld_nss_cp_ref_item["nss-ref"]:
1200 if not nsr_item["nsrId"] in admin_vld_item["shared-nsrs-list"]:
1201 admin_vld_item["shared-nsrs-list"].append(nsr_item["nsrId"])
1202 break
1203 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1204 self.db.set_one("nsis", {"_id": nsir["_id"]}, {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")})
1205
1206 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1207 """
1208 Performs a new operation over a ns
1209 :param rollback: list to append created items at database in case a rollback must to be done
1210 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1211 :param indata: descriptor with the parameters of the operation. It must contains among others
1212 nsiInstanceId: _id of the nsir to perform the operation
1213 operation: it can be: instantiate, terminate, action, TODO: update, heal
1214 :param kwargs: used to override the indata descriptor
1215 :param headers: http request headers
1216 :return: id of the nslcmops
1217 """
1218 try:
1219 # Override descriptor with query string kwargs
1220 self._update_input_with_kwargs(indata, kwargs)
1221 operation = indata["lcmOperationType"]
1222 nsiInstanceId = indata["nsiInstanceId"]
1223 validate_input(indata, self.operation_schema[operation])
1224
1225 # get nsi from nsiInstanceId
1226 _filter = self._get_project_filter(session)
1227 _filter["_id"] = nsiInstanceId
1228 nsir = self.db.get_one("nsis", _filter)
1229 del _filter["_id"]
1230
1231 # initial checking
1232 if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1233 if operation == "terminate" and indata.get("autoremove"):
1234 # NSIR must be deleted
1235 return None # a none in this case is used to indicate not instantiated. It can be removed
1236 if operation != "instantiate":
1237 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1238 nsiInstanceId, operation), HTTPStatus.CONFLICT)
1239 else:
1240 if operation == "instantiate" and not session["force"]:
1241 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1242 format(nsiInstanceId, operation), HTTPStatus.CONFLICT)
1243
1244 # Creating all the NS_operation (nslcmop)
1245 # Get service list from db
1246 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
1247 nslcmops = []
1248 # nslcmops_item = None
1249 for index, nsr_item in enumerate(nsrs_list):
1250 nsi = None
1251 if nsr_item.get("shared"):
1252 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1253 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_item["nsrId"]
1254 _filter["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1255 _filter["_id.ne"] = nsiInstanceId
1256 nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1257 if operation == "terminate":
1258 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): None}
1259 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1260
1261 # looks the first nsi fulfilling the conditions but not being the current NSIR
1262 if nsi:
1263 nsi_admin_shared = nsi["_admin"]["nsrs-detailed-list"]
1264 for nsi_nsr_item in nsi_admin_shared:
1265 if nsi_nsr_item["nsd-id"] == nsr_item["nsd-id"] and nsi_nsr_item["shared"]:
1266 self.add_shared_nsr_2vld(nsir, nsr_item)
1267 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
1268 _update = {"_admin.nsrs-detailed-list.{}".format(index): nsi_nsr_item}
1269 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1270 break
1271 # continue to not create nslcmop since nsrs is shared and nsrs was created
1272 continue
1273 else:
1274 self.add_shared_nsr_2vld(nsir, nsr_item)
1275
1276 try:
1277 service = self.db.get_one("nsrs", {"_id": nsr_item["nsrId"]})
1278 indata_ns = {}
1279 indata_ns = service["instantiate_params"]
1280 indata_ns["lcmOperationType"] = operation
1281 indata_ns["nsInstanceId"] = service["_id"]
1282 # Including netslice_id in the ns instantiate Operation
1283 indata_ns["netsliceInstanceId"] = nsiInstanceId
1284 del indata_ns["key-pair-ref"]
1285 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1286 # message via kafka bus
1287 nslcmop = self.nsi_NsLcmOpTopic.new(rollback, session, indata_ns, kwargs, headers,
1288 slice_object=True)
1289 nslcmops.append(nslcmop)
1290 if operation == "terminate":
1291 nslcmop = None
1292 _update = {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index): nslcmop}
1293 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
1294 except (DbException, EngineException) as e:
1295 if e.http_code == HTTPStatus.NOT_FOUND:
1296 self.logger.info("HTTPStatus.NOT_FOUND")
1297 pass
1298 else:
1299 raise
1300
1301 # Creates nsilcmop
1302 indata["nslcmops_ids"] = nslcmops
1303 self._check_nsi_operation(session, nsir, operation, indata)
1304
1305 nsilcmop_desc = self._create_nsilcmop(session, nsiInstanceId, operation, indata)
1306 self.format_on_new(nsilcmop_desc, session["project_id"], make_public=session["public"])
1307 _id = self.db.create("nsilcmops", nsilcmop_desc)
1308 rollback.append({"topic": "nsilcmops", "_id": _id})
1309 self.msg.write("nsi", operation, nsilcmop_desc)
1310 return _id
1311 except ValidationError as e:
1312 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1313
1314 def delete(self, session, _id, dry_run=False):
1315 raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
1316
1317 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1318 raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)