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