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