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