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