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