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