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