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