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