blob: 3afa3965e9f6a9a2686212abc77a2f88304d10ee [file] [log] [blame]
tierno1d213f42020-04-24 14:02:51 +00001# -*- coding: utf-8 -*-
2
3##
4# Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14# implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17##
18
Lovejeet Singhdf486552023-05-09 22:41:09 +053019from copy import deepcopy
sousaedu049cbb12022-01-05 11:39:35 +000020from http import HTTPStatus
aticigcf14bb12022-05-19 13:03:17 +030021from itertools import product
sousaedu80135b92021-02-17 15:05:18 +010022import logging
sousaedu049cbb12022-01-05 11:39:35 +000023from random import choice as random_choice
24from threading import Lock
25from time import time
tierno1d213f42020-04-24 14:02:51 +000026from traceback import format_exc as traceback_format_exc
Gulsum Atici4bc8eb92022-11-21 14:11:02 +030027from typing import Any, Dict, List, Optional, Tuple, Type
sousaedu049cbb12022-01-05 11:39:35 +000028from uuid import uuid4
29
30from cryptography.hazmat.backends import default_backend as crypto_default_backend
31from cryptography.hazmat.primitives import serialization as crypto_serialization
32from cryptography.hazmat.primitives.asymmetric import rsa
33from jinja2 import (
34 Environment,
aticig7b521f72022-07-15 00:43:09 +030035 select_autoescape,
sousaedu049cbb12022-01-05 11:39:35 +000036 StrictUndefined,
37 TemplateError,
38 TemplateNotFound,
39 UndefinedError,
40)
sousaedu80135b92021-02-17 15:05:18 +010041from osm_common import (
sousaedu80135b92021-02-17 15:05:18 +010042 dbmemory,
sousaedu049cbb12022-01-05 11:39:35 +000043 dbmongo,
sousaedu80135b92021-02-17 15:05:18 +010044 fslocal,
45 fsmongo,
sousaedu80135b92021-02-17 15:05:18 +010046 msgkafka,
sousaedu049cbb12022-01-05 11:39:35 +000047 msglocal,
sousaedu80135b92021-02-17 15:05:18 +010048 version as common_version,
49)
sousaedu0b1e7342021-12-07 15:33:46 +000050from osm_common.dbbase import DbBase, DbException
51from osm_common.fsbase import FsBase, FsException
tierno1d213f42020-04-24 14:02:51 +000052from osm_common.msgbase import MsgException
sousaedu049cbb12022-01-05 11:39:35 +000053from osm_ng_ro.ns_thread import deep_get, NsWorker, NsWorkerException
54from osm_ng_ro.validation import deploy_schema, validate_input
aticig285185e2022-05-02 21:23:48 +030055import yaml
tierno1d213f42020-04-24 14:02:51 +000056
57__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
58min_common_version = "0.1.16"
59
60
61class NsException(Exception):
tierno1d213f42020-04-24 14:02:51 +000062 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
63 self.http_code = http_code
64 super(Exception, self).__init__(message)
65
66
67def get_process_id():
68 """
69 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
70 will provide a random one
71 :return: Obtained ID
72 """
73 # Try getting docker id. If fails, get pid
74 try:
75 with open("/proc/self/cgroup", "r") as f:
76 text_id_ = f.readline()
77 _, _, text_id = text_id_.rpartition("/")
78 text_id = text_id.replace("\n", "")[:12]
sousaedu80135b92021-02-17 15:05:18 +010079
tierno1d213f42020-04-24 14:02:51 +000080 if text_id:
81 return text_id
aticig7b521f72022-07-15 00:43:09 +030082 except Exception as error:
83 logging.exception(f"{error} occured while getting process id")
sousaedu80135b92021-02-17 15:05:18 +010084
tierno1d213f42020-04-24 14:02:51 +000085 # Return a random id
86 return "".join(random_choice("0123456789abcdef") for _ in range(12))
87
88
89def versiontuple(v):
90 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
91 filled = []
sousaedu80135b92021-02-17 15:05:18 +010092
tierno1d213f42020-04-24 14:02:51 +000093 for point in v.split("."):
94 filled.append(point.zfill(8))
sousaedu80135b92021-02-17 15:05:18 +010095
tierno1d213f42020-04-24 14:02:51 +000096 return tuple(filled)
97
98
99class Ns(object):
tierno1d213f42020-04-24 14:02:51 +0000100 def __init__(self):
101 self.db = None
102 self.fs = None
103 self.msg = None
104 self.config = None
105 # self.operations = None
tierno70eeb182020-10-19 16:38:00 +0000106 self.logger = None
107 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
108 # If done now it will not be linked to parent not getting its handler and level
tierno1d213f42020-04-24 14:02:51 +0000109 self.map_topic = {}
110 self.write_lock = None
tierno86153522020-12-06 18:27:16 +0000111 self.vims_assigned = {}
tierno1d213f42020-04-24 14:02:51 +0000112 self.next_worker = 0
113 self.plugins = {}
114 self.workers = []
gallardoa1c2b402022-02-11 12:41:59 +0000115 self.process_params_function_map = {
116 "net": Ns._process_net_params,
117 "image": Ns._process_image_params,
118 "flavor": Ns._process_flavor_params,
119 "vdu": Ns._process_vdu_params,
Lovejeet Singhdf486552023-05-09 22:41:09 +0530120 "classification": Ns._process_classification_params,
121 "sfi": Ns._process_sfi_params,
122 "sf": Ns._process_sf_params,
123 "sfp": Ns._process_sfp_params,
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100124 "affinity-or-anti-affinity-group": Ns._process_affinity_group_params,
vegall364627c2023-03-17 15:09:50 +0000125 "shared-volumes": Ns._process_shared_volumes_params,
gallardoa1c2b402022-02-11 12:41:59 +0000126 }
127 self.db_path_map = {
128 "net": "vld",
129 "image": "image",
130 "flavor": "flavor",
131 "vdu": "vdur",
Lovejeet Singhdf486552023-05-09 22:41:09 +0530132 "classification": "classification",
133 "sfi": "sfi",
134 "sf": "sf",
135 "sfp": "sfp",
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100136 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
vegall364627c2023-03-17 15:09:50 +0000137 "shared-volumes": "shared-volumes",
gallardoa1c2b402022-02-11 12:41:59 +0000138 }
tierno1d213f42020-04-24 14:02:51 +0000139
140 def init_db(self, target_version):
141 pass
142
143 def start(self, config):
144 """
145 Connect to database, filesystem storage, and messaging
146 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
147 :param config: Configuration of db, storage, etc
148 :return: None
149 """
150 self.config = config
151 self.config["process_id"] = get_process_id() # used for HA identity
tierno70eeb182020-10-19 16:38:00 +0000152 self.logger = logging.getLogger("ro.ns")
sousaedu80135b92021-02-17 15:05:18 +0100153
tierno1d213f42020-04-24 14:02:51 +0000154 # check right version of common
155 if versiontuple(common_version) < versiontuple(min_common_version):
sousaedu80135b92021-02-17 15:05:18 +0100156 raise NsException(
157 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
158 common_version, min_common_version
159 )
160 )
tierno1d213f42020-04-24 14:02:51 +0000161
162 try:
163 if not self.db:
164 if config["database"]["driver"] == "mongo":
165 self.db = dbmongo.DbMongo()
166 self.db.db_connect(config["database"])
167 elif config["database"]["driver"] == "memory":
168 self.db = dbmemory.DbMemory()
169 self.db.db_connect(config["database"])
170 else:
sousaedu80135b92021-02-17 15:05:18 +0100171 raise NsException(
172 "Invalid configuration param '{}' at '[database]':'driver'".format(
173 config["database"]["driver"]
174 )
175 )
176
tierno1d213f42020-04-24 14:02:51 +0000177 if not self.fs:
178 if config["storage"]["driver"] == "local":
179 self.fs = fslocal.FsLocal()
180 self.fs.fs_connect(config["storage"])
181 elif config["storage"]["driver"] == "mongo":
182 self.fs = fsmongo.FsMongo()
183 self.fs.fs_connect(config["storage"])
tierno70eeb182020-10-19 16:38:00 +0000184 elif config["storage"]["driver"] is None:
185 pass
tierno1d213f42020-04-24 14:02:51 +0000186 else:
sousaedu80135b92021-02-17 15:05:18 +0100187 raise NsException(
188 "Invalid configuration param '{}' at '[storage]':'driver'".format(
189 config["storage"]["driver"]
190 )
191 )
192
tierno1d213f42020-04-24 14:02:51 +0000193 if not self.msg:
194 if config["message"]["driver"] == "local":
195 self.msg = msglocal.MsgLocal()
196 self.msg.connect(config["message"])
197 elif config["message"]["driver"] == "kafka":
198 self.msg = msgkafka.MsgKafka()
199 self.msg.connect(config["message"])
200 else:
sousaedu80135b92021-02-17 15:05:18 +0100201 raise NsException(
202 "Invalid configuration param '{}' at '[message]':'driver'".format(
203 config["message"]["driver"]
204 )
205 )
tierno1d213f42020-04-24 14:02:51 +0000206
207 # TODO load workers to deal with exising database tasks
208
209 self.write_lock = Lock()
210 except (DbException, FsException, MsgException) as e:
211 raise NsException(str(e), http_code=e.http_code)
sousaedu80135b92021-02-17 15:05:18 +0100212
tierno86153522020-12-06 18:27:16 +0000213 def get_assigned_vims(self):
214 return list(self.vims_assigned.keys())
tierno1d213f42020-04-24 14:02:51 +0000215
216 def stop(self):
217 try:
218 if self.db:
219 self.db.db_disconnect()
sousaedu80135b92021-02-17 15:05:18 +0100220
tierno1d213f42020-04-24 14:02:51 +0000221 if self.fs:
222 self.fs.fs_disconnect()
sousaedu80135b92021-02-17 15:05:18 +0100223
tierno1d213f42020-04-24 14:02:51 +0000224 if self.msg:
225 self.msg.disconnect()
sousaedu80135b92021-02-17 15:05:18 +0100226
tierno1d213f42020-04-24 14:02:51 +0000227 self.write_lock = None
228 except (DbException, FsException, MsgException) as e:
229 raise NsException(str(e), http_code=e.http_code)
sousaedu80135b92021-02-17 15:05:18 +0100230
tierno1d213f42020-04-24 14:02:51 +0000231 for worker in self.workers:
232 worker.insert_task(("terminate",))
233
tierno86153522020-12-06 18:27:16 +0000234 def _create_worker(self):
235 """
236 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
237 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
238 return the index of the assigned worker thread. Worker threads are storead at self.workers
239 """
240 # Look for a thread in idle status
sousaedu80135b92021-02-17 15:05:18 +0100241 worker_id = next(
242 (
243 i
244 for i in range(len(self.workers))
245 if self.workers[i] and self.workers[i].idle
246 ),
247 None,
248 )
249
tierno86153522020-12-06 18:27:16 +0000250 if worker_id is not None:
251 # unset idle status to avoid race conditions
252 self.workers[worker_id].idle = False
tierno70eeb182020-10-19 16:38:00 +0000253 else:
254 worker_id = len(self.workers)
sousaedu80135b92021-02-17 15:05:18 +0100255
tierno70eeb182020-10-19 16:38:00 +0000256 if worker_id < self.config["global"]["server.ns_threads"]:
257 # create a new worker
sousaedu80135b92021-02-17 15:05:18 +0100258 self.workers.append(
259 NsWorker(worker_id, self.config, self.plugins, self.db)
260 )
tierno70eeb182020-10-19 16:38:00 +0000261 self.workers[worker_id].start()
262 else:
263 # reached maximum number of threads, assign VIM to an existing one
264 worker_id = self.next_worker
sousaedu80135b92021-02-17 15:05:18 +0100265 self.next_worker = (self.next_worker + 1) % self.config["global"][
266 "server.ns_threads"
267 ]
268
tierno1d213f42020-04-24 14:02:51 +0000269 return worker_id
270
tierno70eeb182020-10-19 16:38:00 +0000271 def assign_vim(self, target_id):
tierno86153522020-12-06 18:27:16 +0000272 with self.write_lock:
273 return self._assign_vim(target_id)
274
275 def _assign_vim(self, target_id):
276 if target_id not in self.vims_assigned:
277 worker_id = self.vims_assigned[target_id] = self._create_worker()
278 self.workers[worker_id].insert_task(("load_vim", target_id))
tierno70eeb182020-10-19 16:38:00 +0000279
280 def reload_vim(self, target_id):
281 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
282 # this is because database VIM information is cached for threads working with SDN
tierno86153522020-12-06 18:27:16 +0000283 with self.write_lock:
284 for worker in self.workers:
285 if worker and not worker.idle:
286 worker.insert_task(("reload_vim", target_id))
tierno70eeb182020-10-19 16:38:00 +0000287
288 def unload_vim(self, target_id):
tierno86153522020-12-06 18:27:16 +0000289 with self.write_lock:
290 return self._unload_vim(target_id)
291
292 def _unload_vim(self, target_id):
293 if target_id in self.vims_assigned:
294 worker_id = self.vims_assigned[target_id]
tierno70eeb182020-10-19 16:38:00 +0000295 self.workers[worker_id].insert_task(("unload_vim", target_id))
tierno86153522020-12-06 18:27:16 +0000296 del self.vims_assigned[target_id]
tierno70eeb182020-10-19 16:38:00 +0000297
298 def check_vim(self, target_id):
tierno86153522020-12-06 18:27:16 +0000299 with self.write_lock:
300 if target_id in self.vims_assigned:
301 worker_id = self.vims_assigned[target_id]
302 else:
303 worker_id = self._create_worker()
tierno70eeb182020-10-19 16:38:00 +0000304
305 worker = self.workers[worker_id]
306 worker.insert_task(("check_vim", target_id))
tierno1d213f42020-04-24 14:02:51 +0000307
tierno86153522020-12-06 18:27:16 +0000308 def unload_unused_vims(self):
309 with self.write_lock:
310 vims_to_unload = []
sousaedu80135b92021-02-17 15:05:18 +0100311
tierno86153522020-12-06 18:27:16 +0000312 for target_id in self.vims_assigned:
sousaedu80135b92021-02-17 15:05:18 +0100313 if not self.db.get_one(
314 "ro_tasks",
315 q_filter={
316 "target_id": target_id,
317 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
318 },
319 fail_on_empty=False,
320 ):
tierno86153522020-12-06 18:27:16 +0000321 vims_to_unload.append(target_id)
sousaedu80135b92021-02-17 15:05:18 +0100322
tierno86153522020-12-06 18:27:16 +0000323 for target_id in vims_to_unload:
324 self._unload_vim(target_id)
325
sousaedu0b1e7342021-12-07 15:33:46 +0000326 @staticmethod
327 def _get_cloud_init(
328 db: Type[DbBase],
329 fs: Type[FsBase],
330 location: str,
331 ) -> str:
332 """This method reads cloud init from a file.
333
334 Note: Not used as cloud init content is provided in the http body.
335
336 Args:
337 db (Type[DbBase]): [description]
338 fs (Type[FsBase]): [description]
339 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
340
341 Raises:
342 NsException: [description]
343 NsException: [description]
344
345 Returns:
346 str: [description]
tierno1d213f42020-04-24 14:02:51 +0000347 """
sousaedu0b1e7342021-12-07 15:33:46 +0000348 vnfd_id, _, other = location.partition(":")
tierno1d213f42020-04-24 14:02:51 +0000349 _type, _, name = other.partition(":")
sousaedu0b1e7342021-12-07 15:33:46 +0000350 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
sousaedu80135b92021-02-17 15:05:18 +0100351
tierno1d213f42020-04-24 14:02:51 +0000352 if _type == "file":
353 base_folder = vnfd["_admin"]["storage"]
sousaedu80135b92021-02-17 15:05:18 +0100354 cloud_init_file = "{}/{}/cloud_init/{}".format(
355 base_folder["folder"], base_folder["pkg-dir"], name
356 )
357
sousaedu0b1e7342021-12-07 15:33:46 +0000358 if not fs:
sousaedu80135b92021-02-17 15:05:18 +0100359 raise NsException(
360 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
361 cloud_init_file
362 )
363 )
364
sousaedu0b1e7342021-12-07 15:33:46 +0000365 with fs.file_open(cloud_init_file, "r") as ci_file:
tierno1d213f42020-04-24 14:02:51 +0000366 cloud_init_content = ci_file.read()
367 elif _type == "vdu":
368 cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
369 else:
sousaedu0b1e7342021-12-07 15:33:46 +0000370 raise NsException("Mismatch descriptor for cloud init: {}".format(location))
sousaedu80135b92021-02-17 15:05:18 +0100371
tierno1d213f42020-04-24 14:02:51 +0000372 return cloud_init_content
373
sousaedu0b1e7342021-12-07 15:33:46 +0000374 @staticmethod
375 def _parse_jinja2(
376 cloud_init_content: str,
377 params: Dict[str, Any],
378 context: str,
379 ) -> str:
380 """Function that processes the cloud init to replace Jinja2 encoded parameters.
381
382 Args:
383 cloud_init_content (str): [description]
384 params (Dict[str, Any]): [description]
385 context (str): [description]
386
387 Raises:
388 NsException: [description]
389 NsException: [description]
390
391 Returns:
392 str: [description]
393 """
tierno70eeb182020-10-19 16:38:00 +0000394 try:
aticig7b521f72022-07-15 00:43:09 +0300395 env = Environment(
396 undefined=StrictUndefined,
397 autoescape=select_autoescape(default_for_string=True, default=True),
398 )
tierno70eeb182020-10-19 16:38:00 +0000399 template = env.from_string(cloud_init_content)
sousaedu80135b92021-02-17 15:05:18 +0100400
tierno70eeb182020-10-19 16:38:00 +0000401 return template.render(params or {})
402 except UndefinedError as e:
403 raise NsException(
404 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
sousaedu80135b92021-02-17 15:05:18 +0100405 "inside the 'additionalParamsForVnf' block".format(e, context)
406 )
tierno70eeb182020-10-19 16:38:00 +0000407 except (TemplateError, TemplateNotFound) as e:
sousaedu80135b92021-02-17 15:05:18 +0100408 raise NsException(
409 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
410 context, e
411 )
412 )
tierno1d213f42020-04-24 14:02:51 +0000413
414 def _create_db_ro_nsrs(self, nsr_id, now):
415 try:
416 key = rsa.generate_private_key(
sousaedu80135b92021-02-17 15:05:18 +0100417 backend=crypto_default_backend(), public_exponent=65537, key_size=2048
tierno1d213f42020-04-24 14:02:51 +0000418 )
419 private_key = key.private_bytes(
420 crypto_serialization.Encoding.PEM,
421 crypto_serialization.PrivateFormat.PKCS8,
sousaedu80135b92021-02-17 15:05:18 +0100422 crypto_serialization.NoEncryption(),
423 )
tierno1d213f42020-04-24 14:02:51 +0000424 public_key = key.public_key().public_bytes(
425 crypto_serialization.Encoding.OpenSSH,
sousaedu80135b92021-02-17 15:05:18 +0100426 crypto_serialization.PublicFormat.OpenSSH,
tierno1d213f42020-04-24 14:02:51 +0000427 )
sousaedu80135b92021-02-17 15:05:18 +0100428 private_key = private_key.decode("utf8")
tierno70eeb182020-10-19 16:38:00 +0000429 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
430 i = private_key.find("\n")
431 private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:]
sousaedu80135b92021-02-17 15:05:18 +0100432 public_key = public_key.decode("utf8")
tierno1d213f42020-04-24 14:02:51 +0000433 except Exception as e:
434 raise NsException("Cannot create ssh-keys: {}".format(e))
435
436 schema_version = "1.1"
sousaedu80135b92021-02-17 15:05:18 +0100437 private_key_encrypted = self.db.encrypt(
438 private_key, schema_version=schema_version, salt=nsr_id
439 )
tierno1d213f42020-04-24 14:02:51 +0000440 db_content = {
441 "_id": nsr_id,
442 "_admin": {
443 "created": now,
444 "modified": now,
sousaedu80135b92021-02-17 15:05:18 +0100445 "schema_version": schema_version,
tierno1d213f42020-04-24 14:02:51 +0000446 },
447 "public_key": public_key,
448 "private_key": private_key_encrypted,
sousaedu80135b92021-02-17 15:05:18 +0100449 "actions": [],
tierno1d213f42020-04-24 14:02:51 +0000450 }
451 self.db.create("ro_nsrs", db_content)
sousaedu80135b92021-02-17 15:05:18 +0100452
tierno1d213f42020-04-24 14:02:51 +0000453 return db_content
454
sousaedu89278b82021-11-19 01:01:32 +0000455 @staticmethod
456 def _create_task(
457 deployment_info: Dict[str, Any],
458 target_id: str,
459 item: str,
460 action: str,
461 target_record: str,
462 target_record_id: str,
463 extra_dict: Dict[str, Any] = None,
464 ) -> Dict[str, Any]:
465 """Function to create task dict from deployment information.
466
467 Args:
468 deployment_info (Dict[str, Any]): [description]
469 target_id (str): [description]
470 item (str): [description]
471 action (str): [description]
472 target_record (str): [description]
473 target_record_id (str): [description]
474 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
475
476 Returns:
477 Dict[str, Any]: [description]
478 """
479 task = {
480 "target_id": target_id, # it will be removed before pushing at database
481 "action_id": deployment_info.get("action_id"),
482 "nsr_id": deployment_info.get("nsr_id"),
483 "task_id": f"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
484 "status": "SCHEDULED",
485 "action": action,
486 "item": item,
487 "target_record": target_record,
488 "target_record_id": target_record_id,
489 }
490
491 if extra_dict:
492 task.update(extra_dict) # params, find_params, depends_on
493
494 deployment_info["task_index"] = deployment_info.get("task_index", 0) + 1
495
496 return task
497
sousaedu839e5ca2021-11-19 16:41:38 +0000498 @staticmethod
499 def _create_ro_task(
500 target_id: str,
501 task: Dict[str, Any],
502 ) -> Dict[str, Any]:
503 """Function to create an RO task from task information.
504
505 Args:
506 target_id (str): [description]
507 task (Dict[str, Any]): [description]
508
509 Returns:
510 Dict[str, Any]: [description]
511 """
512 now = time()
513
514 _id = task.get("task_id")
515 db_ro_task = {
516 "_id": _id,
517 "locked_by": None,
518 "locked_at": 0.0,
519 "target_id": target_id,
520 "vim_info": {
521 "created": False,
522 "created_items": None,
523 "vim_id": None,
524 "vim_name": None,
525 "vim_status": None,
526 "vim_details": None,
aticig79ac6df2022-05-06 16:09:52 +0300527 "vim_message": None,
sousaedu839e5ca2021-11-19 16:41:38 +0000528 "refresh_at": None,
529 },
530 "modified_at": now,
531 "created_at": now,
532 "to_check_at": now,
533 "tasks": [task],
534 }
535
536 return db_ro_task
537
sousaedua0a33302021-11-21 16:21:13 +0000538 @staticmethod
539 def _process_image_params(
540 target_image: Dict[str, Any],
sousaedu686720b2021-11-24 02:16:11 +0000541 indata: Dict[str, Any],
sousaedua0a33302021-11-21 16:21:13 +0000542 vim_info: Dict[str, Any],
543 target_record_id: str,
sousaedu0b1e7342021-12-07 15:33:46 +0000544 **kwargs: Dict[str, Any],
sousaedua0a33302021-11-21 16:21:13 +0000545 ) -> Dict[str, Any]:
546 """Function to process VDU image parameters.
547
548 Args:
549 target_image (Dict[str, Any]): [description]
sousaedu686720b2021-11-24 02:16:11 +0000550 indata (Dict[str, Any]): [description]
sousaedua0a33302021-11-21 16:21:13 +0000551 vim_info (Dict[str, Any]): [description]
552 target_record_id (str): [description]
553
554 Returns:
555 Dict[str, Any]: [description]
556 """
557 find_params = {}
558
559 if target_image.get("image"):
560 find_params["filter_dict"] = {"name": target_image.get("image")}
561
562 if target_image.get("vim_image_id"):
563 find_params["filter_dict"] = {"id": target_image.get("vim_image_id")}
564
565 if target_image.get("image_checksum"):
566 find_params["filter_dict"] = {
567 "checksum": target_image.get("image_checksum")
568 }
569
570 return {"find_params": find_params}
571
sousaeduabdfe782021-11-22 23:56:28 +0000572 @staticmethod
573 def _get_resource_allocation_params(
574 quota_descriptor: Dict[str, Any],
575 ) -> Dict[str, Any]:
576 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
577 descriptor object.
578
579 Args:
580 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
581
582 Returns:
583 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
584 """
585 quota = {}
586
587 if quota_descriptor.get("limit"):
588 quota["limit"] = int(quota_descriptor["limit"])
589
590 if quota_descriptor.get("reserve"):
591 quota["reserve"] = int(quota_descriptor["reserve"])
592
593 if quota_descriptor.get("shares"):
594 quota["shares"] = int(quota_descriptor["shares"])
595
596 return quota
597
sousaedu686720b2021-11-24 02:16:11 +0000598 @staticmethod
599 def _process_guest_epa_quota_params(
600 guest_epa_quota: Dict[str, Any],
601 epa_vcpu_set: bool,
602 ) -> Dict[str, Any]:
603 """Function to extract the guest epa quota parameters.
604
605 Args:
606 guest_epa_quota (Dict[str, Any]): [description]
607 epa_vcpu_set (bool): [description]
608
609 Returns:
610 Dict[str, Any]: [description]
611 """
612 result = {}
613
614 if guest_epa_quota.get("cpu-quota") and not epa_vcpu_set:
615 cpuquota = Ns._get_resource_allocation_params(
616 guest_epa_quota.get("cpu-quota")
617 )
618
619 if cpuquota:
620 result["cpu-quota"] = cpuquota
621
622 if guest_epa_quota.get("mem-quota"):
623 vduquota = Ns._get_resource_allocation_params(
624 guest_epa_quota.get("mem-quota")
625 )
626
627 if vduquota:
628 result["mem-quota"] = vduquota
629
630 if guest_epa_quota.get("disk-io-quota"):
631 diskioquota = Ns._get_resource_allocation_params(
632 guest_epa_quota.get("disk-io-quota")
633 )
634
635 if diskioquota:
636 result["disk-io-quota"] = diskioquota
637
638 if guest_epa_quota.get("vif-quota"):
639 vifquota = Ns._get_resource_allocation_params(
640 guest_epa_quota.get("vif-quota")
641 )
642
643 if vifquota:
644 result["vif-quota"] = vifquota
645
646 return result
647
648 @staticmethod
649 def _process_guest_epa_numa_params(
650 guest_epa_quota: Dict[str, Any],
651 ) -> Tuple[Dict[str, Any], bool]:
652 """[summary]
653
654 Args:
655 guest_epa_quota (Dict[str, Any]): [description]
656
657 Returns:
658 Tuple[Dict[str, Any], bool]: [description]
659 """
660 numa = {}
sritharan09dcc582022-10-13 05:43:13 +0000661 numa_list = []
sousaedu686720b2021-11-24 02:16:11 +0000662 epa_vcpu_set = False
663
664 if guest_epa_quota.get("numa-node-policy"):
665 numa_node_policy = guest_epa_quota.get("numa-node-policy")
666
667 if numa_node_policy.get("node"):
sritharan09dcc582022-10-13 05:43:13 +0000668 for numa_node in numa_node_policy["node"]:
669 vcpu_list = []
670 if numa_node.get("id"):
671 numa["id"] = int(numa_node["id"])
sousaedu686720b2021-11-24 02:16:11 +0000672
sritharan09dcc582022-10-13 05:43:13 +0000673 if numa_node.get("vcpu"):
674 for vcpu in numa_node.get("vcpu"):
675 vcpu_id = int(vcpu.get("id"))
676 vcpu_list.append(vcpu_id)
677 numa["vcpu"] = vcpu_list
sousaedu686720b2021-11-24 02:16:11 +0000678
sritharan09dcc582022-10-13 05:43:13 +0000679 if numa_node.get("num-cores"):
680 numa["cores"] = numa_node["num-cores"]
681 epa_vcpu_set = True
sousaedu686720b2021-11-24 02:16:11 +0000682
sritharan09dcc582022-10-13 05:43:13 +0000683 paired_threads = numa_node.get("paired-threads", {})
684 if paired_threads.get("num-paired-threads"):
685 numa["paired_threads"] = int(
686 numa_node["paired-threads"]["num-paired-threads"]
sousaedu686720b2021-11-24 02:16:11 +0000687 )
sritharan09dcc582022-10-13 05:43:13 +0000688 epa_vcpu_set = True
sousaedu686720b2021-11-24 02:16:11 +0000689
sritharan09dcc582022-10-13 05:43:13 +0000690 if paired_threads.get("paired-thread-ids"):
691 numa["paired-threads-id"] = []
sousaedu686720b2021-11-24 02:16:11 +0000692
sritharan09dcc582022-10-13 05:43:13 +0000693 for pair in paired_threads["paired-thread-ids"]:
694 numa["paired-threads-id"].append(
695 (
696 str(pair["thread-a"]),
697 str(pair["thread-b"]),
698 )
699 )
sousaedu686720b2021-11-24 02:16:11 +0000700
sritharan09dcc582022-10-13 05:43:13 +0000701 if numa_node.get("num-threads"):
702 numa["threads"] = int(numa_node["num-threads"])
703 epa_vcpu_set = True
704
705 if numa_node.get("memory-mb"):
706 numa["memory"] = max(int(int(numa_node["memory-mb"]) / 1024), 1)
707
708 numa_list.append(numa)
709 numa = {}
710
711 return numa_list, epa_vcpu_set
sousaedu686720b2021-11-24 02:16:11 +0000712
713 @staticmethod
714 def _process_guest_epa_cpu_pinning_params(
715 guest_epa_quota: Dict[str, Any],
716 vcpu_count: int,
717 epa_vcpu_set: bool,
718 ) -> Tuple[Dict[str, Any], bool]:
719 """[summary]
720
721 Args:
722 guest_epa_quota (Dict[str, Any]): [description]
723 vcpu_count (int): [description]
724 epa_vcpu_set (bool): [description]
725
726 Returns:
727 Tuple[Dict[str, Any], bool]: [description]
728 """
729 numa = {}
730 local_epa_vcpu_set = epa_vcpu_set
731
732 if (
733 guest_epa_quota.get("cpu-pinning-policy") == "DEDICATED"
734 and not epa_vcpu_set
735 ):
Gulsum Atici6a6e3342023-01-23 16:22:59 +0300736 # Pinning policy "REQUIRE" uses threads as host should support SMT architecture
737 # Pinning policy "ISOLATE" uses cores as host should not support SMT architecture
738 # Pinning policy "PREFER" uses threads in case host supports SMT architecture
sousaedu686720b2021-11-24 02:16:11 +0000739 numa[
garciadeblasaca8cb52023-12-21 16:28:15 +0100740 (
741 "cores"
742 if guest_epa_quota.get("cpu-thread-pinning-policy") == "ISOLATE"
743 else "threads"
744 )
sousaedu686720b2021-11-24 02:16:11 +0000745 ] = max(vcpu_count, 1)
746 local_epa_vcpu_set = True
747
748 return numa, local_epa_vcpu_set
749
750 @staticmethod
751 def _process_epa_params(
752 target_flavor: Dict[str, Any],
753 ) -> Dict[str, Any]:
754 """[summary]
755
756 Args:
757 target_flavor (Dict[str, Any]): [description]
758
759 Returns:
760 Dict[str, Any]: [description]
761 """
762 extended = {}
763 numa = {}
sritharan09dcc582022-10-13 05:43:13 +0000764 numa_list = []
sousaedu686720b2021-11-24 02:16:11 +0000765
766 if target_flavor.get("guest-epa"):
767 guest_epa = target_flavor["guest-epa"]
768
sritharan09dcc582022-10-13 05:43:13 +0000769 numa_list, epa_vcpu_set = Ns._process_guest_epa_numa_params(
sousaedu686720b2021-11-24 02:16:11 +0000770 guest_epa_quota=guest_epa
771 )
772
773 if guest_epa.get("mempage-size"):
774 extended["mempage-size"] = guest_epa.get("mempage-size")
775
sritharan09dcc582022-10-13 05:43:13 +0000776 if guest_epa.get("cpu-pinning-policy"):
777 extended["cpu-pinning-policy"] = guest_epa.get("cpu-pinning-policy")
778
779 if guest_epa.get("cpu-thread-pinning-policy"):
780 extended["cpu-thread-pinning-policy"] = guest_epa.get(
781 "cpu-thread-pinning-policy"
782 )
783
784 if guest_epa.get("numa-node-policy"):
785 if guest_epa.get("numa-node-policy").get("mem-policy"):
786 extended["mem-policy"] = guest_epa.get("numa-node-policy").get(
787 "mem-policy"
788 )
789
sousaedu686720b2021-11-24 02:16:11 +0000790 tmp_numa, epa_vcpu_set = Ns._process_guest_epa_cpu_pinning_params(
791 guest_epa_quota=guest_epa,
792 vcpu_count=int(target_flavor.get("vcpu-count", 1)),
793 epa_vcpu_set=epa_vcpu_set,
794 )
sritharan09dcc582022-10-13 05:43:13 +0000795 for numa in numa_list:
796 numa.update(tmp_numa)
sousaedu686720b2021-11-24 02:16:11 +0000797
798 extended.update(
799 Ns._process_guest_epa_quota_params(
800 guest_epa_quota=guest_epa,
801 epa_vcpu_set=epa_vcpu_set,
802 )
803 )
804
805 if numa:
sritharan09dcc582022-10-13 05:43:13 +0000806 extended["numas"] = numa_list
sousaedu686720b2021-11-24 02:16:11 +0000807
808 return extended
809
810 @staticmethod
811 def _process_flavor_params(
812 target_flavor: Dict[str, Any],
813 indata: Dict[str, Any],
814 vim_info: Dict[str, Any],
815 target_record_id: str,
sousaedu0b1e7342021-12-07 15:33:46 +0000816 **kwargs: Dict[str, Any],
sousaedu686720b2021-11-24 02:16:11 +0000817 ) -> Dict[str, Any]:
818 """[summary]
819
820 Args:
821 target_flavor (Dict[str, Any]): [description]
822 indata (Dict[str, Any]): [description]
823 vim_info (Dict[str, Any]): [description]
824 target_record_id (str): [description]
825
826 Returns:
827 Dict[str, Any]: [description]
828 """
aticigcf14bb12022-05-19 13:03:17 +0300829 db = kwargs.get("db")
830 target_vdur = {}
831
Gabriel Cubaa5233f82023-08-07 18:43:26 -0500832 for vnf in indata.get("vnf", []):
833 for vdur in vnf.get("vdur", []):
834 if vdur.get("ns-flavor-id") == target_flavor.get("id"):
835 target_vdur = vdur
836
837 vim_flavor_id = (
838 target_vdur.get("additionalParams", {}).get("OSM", {}).get("vim_flavor_id")
839 )
840 if vim_flavor_id: # vim-flavor-id was passed so flavor won't be created
841 return {"find_params": {"vim_flavor_id": vim_flavor_id}}
842
sousaedu686720b2021-11-24 02:16:11 +0000843 flavor_data = {
844 "disk": int(target_flavor["storage-gb"]),
845 "ram": int(target_flavor["memory-mb"]),
846 "vcpus": int(target_flavor["vcpu-count"]),
847 }
848
aticigcf14bb12022-05-19 13:03:17 +0300849 if db and isinstance(indata.get("vnf"), list):
850 vnfd_id = indata.get("vnf")[0].get("vnfd-id")
851 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
852 # check if there is persistent root disk
853 for vdu in vnfd.get("vdu", ()):
854 if vdu["name"] == target_vdur.get("vdu-name"):
855 for vsd in vnfd.get("virtual-storage-desc", ()):
856 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
857 root_disk = vsd
garciadeblas6a0147f2024-08-19 08:02:04 +0000858 if root_disk.get("type-of-storage", "").endswith(
859 "persistent-storage"
aticigcf14bb12022-05-19 13:03:17 +0300860 ):
861 flavor_data["disk"] = 0
862
sousaedu686720b2021-11-24 02:16:11 +0000863 for storage in target_vdur.get("virtual-storages", []):
864 if (
865 storage.get("type-of-storage")
866 == "etsi-nfv-descriptors:ephemeral-storage"
867 ):
868 flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0))
869 elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
870 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
871
872 extended = Ns._process_epa_params(target_flavor)
873 if extended:
874 flavor_data["extended"] = extended
875
876 extra_dict = {"find_params": {"flavor_data": flavor_data}}
877 flavor_data_name = flavor_data.copy()
878 flavor_data_name["name"] = target_flavor["name"]
879 extra_dict["params"] = {"flavor_data": flavor_data_name}
sousaedu686720b2021-11-24 02:16:11 +0000880 return extra_dict
881
sousaedua4bac082021-12-05 19:31:03 +0000882 @staticmethod
Lovejeet Singhdf486552023-05-09 22:41:09 +0530883 def _prefix_ip_address(ip_address):
884 if "/" not in ip_address:
885 ip_address += "/32"
886 return ip_address
887
888 @staticmethod
889 def _process_ip_proto(ip_proto):
890 if ip_proto:
891 if ip_proto == 1:
892 ip_proto = "icmp"
893 elif ip_proto == 6:
894 ip_proto = "tcp"
895 elif ip_proto == 17:
896 ip_proto = "udp"
897 return ip_proto
898
899 @staticmethod
900 def _process_classification_params(
901 target_classification: Dict[str, Any],
902 indata: Dict[str, Any],
903 vim_info: Dict[str, Any],
904 target_record_id: str,
905 **kwargs: Dict[str, Any],
906 ) -> Dict[str, Any]:
907 """[summary]
908
909 Args:
910 target_classification (Dict[str, Any]): Classification dictionary parameters that needs to be processed to create resource on VIM
911 indata (Dict[str, Any]): Deployment info
912 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
913 target_record_id (str): Task record ID.
914 **kwargs (Dict[str, Any]): Used to send additional information to the task.
915
916 Returns:
917 Dict[str, Any]: Return parameters required to create classification and Items on which classification is dependent.
918 """
919 vnfr_id = target_classification["vnfr_id"]
920 vdur_id = target_classification["vdur_id"]
921 port_index = target_classification["ingress_port_index"]
922 extra_dict = {}
923
924 classification_data = {
925 "name": target_classification["id"],
926 "source_port_range_min": target_classification["source-port"],
927 "source_port_range_max": target_classification["source-port"],
928 "destination_port_range_min": target_classification["destination-port"],
929 "destination_port_range_max": target_classification["destination-port"],
930 }
931
932 classification_data["source_ip_prefix"] = Ns._prefix_ip_address(
933 target_classification["source-ip-address"]
934 )
935
936 classification_data["destination_ip_prefix"] = Ns._prefix_ip_address(
937 target_classification["destination-ip-address"]
938 )
939
940 classification_data["protocol"] = Ns._process_ip_proto(
941 int(target_classification["ip-proto"])
942 )
943
944 db = kwargs.get("db")
945 vdu_text = Ns._get_vnfr_vdur_text(db, vnfr_id, vdur_id)
946
947 extra_dict = {"depends_on": [vdu_text]}
948
949 extra_dict = {"depends_on": [vdu_text]}
950 classification_data["logical_source_port"] = "TASK-" + vdu_text
951 classification_data["logical_source_port_index"] = port_index
952
953 extra_dict["params"] = classification_data
954
955 return extra_dict
956
957 @staticmethod
958 def _process_sfi_params(
959 target_sfi: Dict[str, Any],
960 indata: Dict[str, Any],
961 vim_info: Dict[str, Any],
962 target_record_id: str,
963 **kwargs: Dict[str, Any],
964 ) -> Dict[str, Any]:
965 """[summary]
966
967 Args:
968 target_sfi (Dict[str, Any]): SFI dictionary parameters that needs to be processed to create resource on VIM
969 indata (Dict[str, Any]): deployment info
970 vim_info (Dict[str, Any]): To add items created by OSM on the VIM.
971 target_record_id (str): Task record ID.
972 **kwargs (Dict[str, Any]): Used to send additional information to the task.
973
974 Returns:
975 Dict[str, Any]: Return parameters required to create SFI and Items on which SFI is dependent.
976 """
977
978 vnfr_id = target_sfi["vnfr_id"]
979 vdur_id = target_sfi["vdur_id"]
980
981 sfi_data = {
982 "name": target_sfi["id"],
983 "ingress_port_index": target_sfi["ingress_port_index"],
984 "egress_port_index": target_sfi["egress_port_index"],
985 }
986
987 db = kwargs.get("db")
988 vdu_text = Ns._get_vnfr_vdur_text(db, vnfr_id, vdur_id)
989
990 extra_dict = {"depends_on": [vdu_text]}
991 sfi_data["ingress_port"] = "TASK-" + vdu_text
992 sfi_data["egress_port"] = "TASK-" + vdu_text
993
994 extra_dict["params"] = sfi_data
995
996 return extra_dict
997
998 @staticmethod
999 def _get_vnfr_vdur_text(db, vnfr_id, vdur_id):
1000 vnf_preffix = "vnfrs:{}".format(vnfr_id)
1001 db_vnfr = db.get_one("vnfrs", {"_id": vnfr_id})
1002 vdur_list = []
1003 vdu_text = ""
1004
1005 if db_vnfr:
1006 vdur_list = [
1007 vdur["id"] for vdur in db_vnfr["vdur"] if vdur["vdu-id-ref"] == vdur_id
1008 ]
1009
1010 if vdur_list:
1011 vdu_text = vnf_preffix + ":vdur." + vdur_list[0]
1012
1013 return vdu_text
1014
1015 @staticmethod
1016 def _process_sf_params(
1017 target_sf: Dict[str, Any],
1018 indata: Dict[str, Any],
1019 vim_info: Dict[str, Any],
1020 target_record_id: str,
1021 **kwargs: Dict[str, Any],
1022 ) -> Dict[str, Any]:
1023 """[summary]
1024
1025 Args:
1026 target_sf (Dict[str, Any]): SF dictionary parameters that needs to be processed to create resource on VIM
1027 indata (Dict[str, Any]): Deployment info.
1028 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
1029 target_record_id (str): Task record ID.
1030 **kwargs (Dict[str, Any]): Used to send additional information to the task.
1031
1032 Returns:
1033 Dict[str, Any]: Return parameters required to create SF and Items on which SF is dependent.
1034 """
1035
1036 nsr_id = kwargs.get("nsr_id", "")
1037 sfis = target_sf["sfis"]
1038 ns_preffix = "nsrs:{}".format(nsr_id)
1039 extra_dict = {"depends_on": [], "params": []}
1040 sf_data = {"name": target_sf["id"], "sfis": sfis}
1041
1042 for count, sfi in enumerate(sfis):
1043 sfi_text = ns_preffix + ":sfi." + sfi
1044 sfis[count] = "TASK-" + sfi_text
1045 extra_dict["depends_on"].append(sfi_text)
1046
1047 extra_dict["params"] = sf_data
1048
1049 return extra_dict
1050
1051 @staticmethod
1052 def _process_sfp_params(
1053 target_sfp: Dict[str, Any],
1054 indata: Dict[str, Any],
1055 vim_info: Dict[str, Any],
1056 target_record_id: str,
1057 **kwargs: Dict[str, Any],
1058 ) -> Dict[str, Any]:
1059 """[summary]
1060
1061 Args:
1062 target_sfp (Dict[str, Any]): SFP dictionary parameters that needs to be processed to create resource on VIM.
1063 indata (Dict[str, Any]): Deployment info
1064 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
1065 target_record_id (str): Task record ID.
1066 **kwargs (Dict[str, Any]): Used to send additional information to the task.
1067
1068 Returns:
1069 Dict[str, Any]: Return parameters required to create SFP and Items on which SFP is dependent.
1070 """
1071
1072 nsr_id = kwargs.get("nsr_id")
1073 sfs = target_sfp["sfs"]
1074 classifications = target_sfp["classifications"]
1075 ns_preffix = "nsrs:{}".format(nsr_id)
1076 extra_dict = {"depends_on": [], "params": []}
1077 sfp_data = {
1078 "name": target_sfp["id"],
1079 "sfs": sfs,
1080 "classifications": classifications,
1081 }
1082
1083 for count, sf in enumerate(sfs):
1084 sf_text = ns_preffix + ":sf." + sf
1085 sfs[count] = "TASK-" + sf_text
1086 extra_dict["depends_on"].append(sf_text)
1087
1088 for count, classi in enumerate(classifications):
1089 classi_text = ns_preffix + ":classification." + classi
1090 classifications[count] = "TASK-" + classi_text
1091 extra_dict["depends_on"].append(classi_text)
1092
1093 extra_dict["params"] = sfp_data
1094
1095 return extra_dict
1096
1097 @staticmethod
sousaedu0ee9fdb2021-12-06 00:17:54 +00001098 def _process_net_params(
1099 target_vld: Dict[str, Any],
1100 indata: Dict[str, Any],
1101 vim_info: Dict[str, Any],
1102 target_record_id: str,
sousaedu0b1e7342021-12-07 15:33:46 +00001103 **kwargs: Dict[str, Any],
sousaedu0ee9fdb2021-12-06 00:17:54 +00001104 ) -> Dict[str, Any]:
1105 """Function to process network parameters.
1106
1107 Args:
1108 target_vld (Dict[str, Any]): [description]
1109 indata (Dict[str, Any]): [description]
1110 vim_info (Dict[str, Any]): [description]
1111 target_record_id (str): [description]
1112
1113 Returns:
1114 Dict[str, Any]: [description]
1115 """
1116 extra_dict = {}
1117
1118 if vim_info.get("sdn"):
1119 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
1120 # ns_preffix = "nsrs:{}".format(nsr_id)
1121 # remove the ending ".sdn
1122 vld_target_record_id, _, _ = target_record_id.rpartition(".")
1123 extra_dict["params"] = {
1124 k: vim_info[k]
1125 for k in ("sdn-ports", "target_vim", "vlds", "type")
1126 if vim_info.get(k)
1127 }
1128
1129 # TODO needed to add target_id in the dependency.
1130 if vim_info.get("target_vim"):
1131 extra_dict["depends_on"] = [
1132 f"{vim_info.get('target_vim')} {vld_target_record_id}"
1133 ]
1134
1135 return extra_dict
1136
1137 if vim_info.get("vim_network_name"):
1138 extra_dict["find_params"] = {
1139 "filter_dict": {
1140 "name": vim_info.get("vim_network_name"),
1141 },
1142 }
1143 elif vim_info.get("vim_network_id"):
1144 extra_dict["find_params"] = {
1145 "filter_dict": {
1146 "id": vim_info.get("vim_network_id"),
1147 },
1148 }
Gabriel Cuba0d8ce072022-12-14 18:33:50 -05001149 elif target_vld.get("mgmt-network") and not vim_info.get("provider_network"):
sousaedu0ee9fdb2021-12-06 00:17:54 +00001150 extra_dict["find_params"] = {
1151 "mgmt": True,
1152 "name": target_vld["id"],
1153 }
1154 else:
1155 # create
1156 extra_dict["params"] = {
1157 "net_name": (
1158 f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
1159 ),
Gabriel Cuba4c1dd542023-02-14 12:43:32 -05001160 "ip_profile": vim_info.get("ip_profile"),
sousaedu0ee9fdb2021-12-06 00:17:54 +00001161 "provider_network_profile": vim_info.get("provider_network"),
1162 }
1163
1164 if not target_vld.get("underlay"):
1165 extra_dict["params"]["net_type"] = "bridge"
1166 else:
1167 extra_dict["params"]["net_type"] = (
1168 "ptp" if target_vld.get("type") == "ELINE" else "data"
1169 )
1170
1171 return extra_dict
1172
sousaedu0b1e7342021-12-07 15:33:46 +00001173 @staticmethod
aticigcf14bb12022-05-19 13:03:17 +03001174 def find_persistent_root_volumes(
1175 vnfd: dict,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001176 target_vdu: dict,
aticigcf14bb12022-05-19 13:03:17 +03001177 vdu_instantiation_volumes_list: list,
1178 disk_list: list,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001179 ) -> Dict[str, any]:
aticigcf14bb12022-05-19 13:03:17 +03001180 """Find the persistent root volumes and add them to the disk_list
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001181 by parsing the instantiation parameters.
aticigcf14bb12022-05-19 13:03:17 +03001182
1183 Args:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001184 vnfd (dict): VNF descriptor
1185 target_vdu (dict): processed VDU
1186 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
1187 disk_list (list): to be filled up
aticigcf14bb12022-05-19 13:03:17 +03001188
1189 Returns:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001190 persistent_root_disk (dict): Details of persistent root disk
aticigcf14bb12022-05-19 13:03:17 +03001191
1192 """
1193 persistent_root_disk = {}
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001194 # There can be only one root disk, when we find it, it will return the result
aticigcf14bb12022-05-19 13:03:17 +03001195
1196 for vdu, vsd in product(
1197 vnfd.get("vdu", ()), vnfd.get("virtual-storage-desc", ())
1198 ):
1199 if (
1200 vdu["name"] == target_vdu["vdu-name"]
1201 and vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]
1202 ):
1203 root_disk = vsd
garciadeblas6a0147f2024-08-19 08:02:04 +00001204 if root_disk.get("type-of-storage", "").endswith("persistent-storage"):
aticigcf14bb12022-05-19 13:03:17 +03001205 for vdu_volume in vdu_instantiation_volumes_list:
aticigcf14bb12022-05-19 13:03:17 +03001206 if (
1207 vdu_volume["vim-volume-id"]
1208 and root_disk["id"] == vdu_volume["name"]
1209 ):
aticigcf14bb12022-05-19 13:03:17 +03001210 persistent_root_disk[vsd["id"]] = {
1211 "vim_volume_id": vdu_volume["vim-volume-id"],
1212 "image_id": vdu.get("sw-image-desc"),
1213 }
1214
1215 disk_list.append(persistent_root_disk[vsd["id"]])
1216
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001217 return persistent_root_disk
aticigcf14bb12022-05-19 13:03:17 +03001218
1219 else:
aticigcf14bb12022-05-19 13:03:17 +03001220 if root_disk.get("size-of-storage"):
1221 persistent_root_disk[vsd["id"]] = {
1222 "image_id": vdu.get("sw-image-desc"),
1223 "size": root_disk.get("size-of-storage"),
aticig2f4ab6c2022-09-03 18:15:20 +03001224 "keep": Ns.is_volume_keeping_required(root_disk),
aticigcf14bb12022-05-19 13:03:17 +03001225 }
1226
1227 disk_list.append(persistent_root_disk[vsd["id"]])
aticigcf14bb12022-05-19 13:03:17 +03001228
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001229 return persistent_root_disk
Luis Vega95e83692023-08-08 00:35:41 +00001230 return persistent_root_disk
aticigcf14bb12022-05-19 13:03:17 +03001231
1232 @staticmethod
1233 def find_persistent_volumes(
1234 persistent_root_disk: dict,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001235 target_vdu: dict,
aticigcf14bb12022-05-19 13:03:17 +03001236 vdu_instantiation_volumes_list: list,
1237 disk_list: list,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001238 ) -> None:
aticigcf14bb12022-05-19 13:03:17 +03001239 """Find the ordinary persistent volumes and add them to the disk_list
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001240 by parsing the instantiation parameters.
aticigcf14bb12022-05-19 13:03:17 +03001241
1242 Args:
1243 persistent_root_disk: persistent root disk dictionary
1244 target_vdu: processed VDU
1245 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1246 disk_list: to be filled up
1247
aticigcf14bb12022-05-19 13:03:17 +03001248 """
1249 # Find the ordinary volumes which are not added to the persistent_root_disk
1250 persistent_disk = {}
1251 for disk in target_vdu.get("virtual-storages", {}):
1252 if (
garciadeblas6a0147f2024-08-19 08:02:04 +00001253 disk.get("type-of-storage", "").endswith("persistent-storage")
aticigcf14bb12022-05-19 13:03:17 +03001254 and disk["id"] not in persistent_root_disk.keys()
1255 ):
1256 for vdu_volume in vdu_instantiation_volumes_list:
aticigcf14bb12022-05-19 13:03:17 +03001257 if vdu_volume["vim-volume-id"] and disk["id"] == vdu_volume["name"]:
aticigcf14bb12022-05-19 13:03:17 +03001258 persistent_disk[disk["id"]] = {
1259 "vim_volume_id": vdu_volume["vim-volume-id"],
1260 }
1261 disk_list.append(persistent_disk[disk["id"]])
1262
1263 else:
1264 if disk["id"] not in persistent_disk.keys():
1265 persistent_disk[disk["id"]] = {
1266 "size": disk.get("size-of-storage"),
aticig2f4ab6c2022-09-03 18:15:20 +03001267 "keep": Ns.is_volume_keeping_required(disk),
aticigcf14bb12022-05-19 13:03:17 +03001268 }
1269 disk_list.append(persistent_disk[disk["id"]])
1270
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001271 @staticmethod
aticig2f4ab6c2022-09-03 18:15:20 +03001272 def is_volume_keeping_required(virtual_storage_desc: Dict[str, Any]) -> bool:
1273 """Function to decide keeping persistent volume
1274 upon VDU deletion.
1275
1276 Args:
1277 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1278
1279 Returns:
1280 bool (True/False)
1281 """
1282
1283 if not virtual_storage_desc.get("vdu-storage-requirements"):
1284 return False
1285 for item in virtual_storage_desc.get("vdu-storage-requirements", {}):
vegall364627c2023-03-17 15:09:50 +00001286 if item.get("key") == "keep-volume" and item.get("value").lower() == "true":
aticig2f4ab6c2022-09-03 18:15:20 +03001287 return True
1288 return False
1289
1290 @staticmethod
vegall364627c2023-03-17 15:09:50 +00001291 def is_shared_volume(
1292 virtual_storage_desc: Dict[str, Any], vnfd_id: str
1293 ) -> (str, bool):
1294 """Function to decide if the volume type is multi attached or not .
1295
1296 Args:
1297 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1298 vnfd_id (str): vnfd id
1299
1300 Returns:
1301 bool (True/False)
1302 name (str) New name if it is a multiattach disk
1303 """
1304
1305 if vdu_storage_requirements := virtual_storage_desc.get(
1306 "vdu-storage-requirements", {}
1307 ):
1308 for item in vdu_storage_requirements:
1309 if (
1310 item.get("key") == "multiattach"
1311 and item.get("value").lower() == "true"
1312 ):
1313 name = f"shared-{virtual_storage_desc['id']}-{vnfd_id}"
1314 return name, True
1315 return virtual_storage_desc["id"], False
1316
1317 @staticmethod
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001318 def _sort_vdu_interfaces(target_vdu: dict) -> None:
1319 """Sort the interfaces according to position number.
1320
1321 Args:
1322 target_vdu (dict): Details of VDU to be created
1323
1324 """
1325 # If the position info is provided for all the interfaces, it will be sorted
1326 # according to position number ascendingly.
1327 sorted_interfaces = sorted(
1328 target_vdu["interfaces"],
1329 key=lambda x: (x.get("position") is None, x.get("position")),
1330 )
1331 target_vdu["interfaces"] = sorted_interfaces
1332
1333 @staticmethod
1334 def _partially_locate_vdu_interfaces(target_vdu: dict) -> None:
1335 """Only place the interfaces which has specific position.
1336
1337 Args:
1338 target_vdu (dict): Details of VDU to be created
1339
1340 """
1341 # If the position info is provided for some interfaces but not all of them, the interfaces
1342 # which has specific position numbers will be placed and others' positions will not be taken care.
1343 if any(
1344 i.get("position") + 1
1345 for i in target_vdu["interfaces"]
1346 if i.get("position") is not None
1347 ):
1348 n = len(target_vdu["interfaces"])
1349 sorted_interfaces = [-1] * n
1350 k, m = 0, 0
1351
1352 while k < n:
1353 if target_vdu["interfaces"][k].get("position") is not None:
1354 if any(i.get("position") == 0 for i in target_vdu["interfaces"]):
1355 idx = target_vdu["interfaces"][k]["position"] + 1
1356 else:
1357 idx = target_vdu["interfaces"][k]["position"]
1358 sorted_interfaces[idx - 1] = target_vdu["interfaces"][k]
1359 k += 1
1360
1361 while m < n:
1362 if target_vdu["interfaces"][m].get("position") is None:
1363 idy = sorted_interfaces.index(-1)
1364 sorted_interfaces[idy] = target_vdu["interfaces"][m]
1365 m += 1
1366
1367 target_vdu["interfaces"] = sorted_interfaces
1368
1369 @staticmethod
1370 def _prepare_vdu_cloud_init(
1371 target_vdu: dict, vdu2cloud_init: dict, db: object, fs: object
1372 ) -> Dict:
1373 """Fill cloud_config dict with cloud init details.
1374
1375 Args:
1376 target_vdu (dict): Details of VDU to be created
1377 vdu2cloud_init (dict): Cloud init dict
1378 db (object): DB object
1379 fs (object): FS object
1380
1381 Returns:
1382 cloud_config (dict): Cloud config details of VDU
1383
1384 """
1385 # cloud config
1386 cloud_config = {}
1387
1388 if target_vdu.get("cloud-init"):
1389 if target_vdu["cloud-init"] not in vdu2cloud_init:
1390 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1391 db=db,
1392 fs=fs,
1393 location=target_vdu["cloud-init"],
1394 )
1395
1396 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1397 cloud_config["user-data"] = Ns._parse_jinja2(
1398 cloud_init_content=cloud_content_,
1399 params=target_vdu.get("additionalParams"),
1400 context=target_vdu["cloud-init"],
1401 )
1402
1403 if target_vdu.get("boot-data-drive"):
1404 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1405
1406 return cloud_config
1407
1408 @staticmethod
1409 def _check_vld_information_of_interfaces(
1410 interface: dict, ns_preffix: str, vnf_preffix: str
1411 ) -> Optional[str]:
1412 """Prepare the net_text by the virtual link information for vnf and ns level.
1413 Args:
1414 interface (dict): Interface details
1415 ns_preffix (str): Prefix of NS
1416 vnf_preffix (str): Prefix of VNF
1417
1418 Returns:
1419 net_text (str): information of net
1420
1421 """
1422 net_text = ""
1423 if interface.get("ns-vld-id"):
1424 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
1425 elif interface.get("vnf-vld-id"):
1426 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
1427
1428 return net_text
1429
1430 @staticmethod
1431 def _prepare_interface_port_security(interface: dict) -> None:
1432 """
1433
1434 Args:
1435 interface (dict): Interface details
1436
1437 """
1438 if "port-security-enabled" in interface:
1439 interface["port_security"] = interface.pop("port-security-enabled")
1440
1441 if "port-security-disable-strategy" in interface:
1442 interface["port_security_disable_strategy"] = interface.pop(
1443 "port-security-disable-strategy"
1444 )
1445
1446 @staticmethod
1447 def _create_net_item_of_interface(interface: dict, net_text: str) -> dict:
1448 """Prepare net item including name, port security, floating ip etc.
1449
1450 Args:
1451 interface (dict): Interface details
1452 net_text (str): information of net
1453
1454 Returns:
1455 net_item (dict): Dict including net details
1456
1457 """
1458
1459 net_item = {
1460 x: v
1461 for x, v in interface.items()
1462 if x
1463 in (
1464 "name",
1465 "vpci",
1466 "port_security",
1467 "port_security_disable_strategy",
1468 "floating_ip",
1469 )
1470 }
1471 net_item["net_id"] = "TASK-" + net_text
1472 net_item["type"] = "virtual"
1473
1474 return net_item
1475
1476 @staticmethod
1477 def _prepare_type_of_interface(
1478 interface: dict, tasks_by_target_record_id: dict, net_text: str, net_item: dict
1479 ) -> None:
1480 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1481
1482 Args:
1483 interface (dict): Interface details
1484 tasks_by_target_record_id (dict): Task details
1485 net_text (str): information of net
1486 net_item (dict): Dict including net details
1487
1488 """
1489 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1490 # TODO floating_ip: True/False (or it can be None)
1491
1492 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1493 # Mark the net create task as type data
1494 if deep_get(
1495 tasks_by_target_record_id,
1496 net_text,
1497 "extra_dict",
1498 "params",
1499 "net_type",
1500 ):
1501 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1502 "net_type"
1503 ] = "data"
1504
1505 net_item["use"] = "data"
1506 net_item["model"] = interface["type"]
1507 net_item["type"] = interface["type"]
1508
1509 elif (
1510 interface.get("type") == "OM-MGMT"
1511 or interface.get("mgmt-interface")
1512 or interface.get("mgmt-vnf")
1513 ):
1514 net_item["use"] = "mgmt"
1515
1516 else:
1517 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1518 net_item["use"] = "bridge"
1519 net_item["model"] = interface.get("type")
1520
1521 @staticmethod
1522 def _prepare_vdu_interfaces(
1523 target_vdu: dict,
1524 extra_dict: dict,
1525 ns_preffix: str,
1526 vnf_preffix: str,
1527 logger: object,
1528 tasks_by_target_record_id: dict,
1529 net_list: list,
1530 ) -> None:
1531 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1532
1533 Args:
1534 target_vdu (dict): VDU to be created
1535 extra_dict (dict): Dictionary to be filled
1536 ns_preffix (str): NS prefix as string
1537 vnf_preffix (str): VNF prefix as string
1538 logger (object): Logger Object
1539 tasks_by_target_record_id (dict): Task details
1540 net_list (list): Net list of VDU
1541 """
1542 for iface_index, interface in enumerate(target_vdu["interfaces"]):
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001543 net_text = Ns._check_vld_information_of_interfaces(
1544 interface, ns_preffix, vnf_preffix
1545 )
1546 if not net_text:
1547 # Interface not connected to any vld
1548 logger.error(
1549 "Interface {} from vdu {} not connected to any vld".format(
1550 iface_index, target_vdu["vdu-name"]
1551 )
1552 )
1553 continue
1554
1555 extra_dict["depends_on"].append(net_text)
1556
1557 Ns._prepare_interface_port_security(interface)
1558
1559 net_item = Ns._create_net_item_of_interface(interface, net_text)
1560
1561 Ns._prepare_type_of_interface(
1562 interface, tasks_by_target_record_id, net_text, net_item
1563 )
1564
1565 if interface.get("ip-address"):
1566 net_item["ip_address"] = interface["ip-address"]
1567
1568 if interface.get("mac-address"):
1569 net_item["mac_address"] = interface["mac-address"]
1570
1571 net_list.append(net_item)
1572
1573 if interface.get("mgmt-vnf"):
1574 extra_dict["mgmt_vnf_interface"] = iface_index
1575 elif interface.get("mgmt-interface"):
1576 extra_dict["mgmt_vdu_interface"] = iface_index
1577
1578 @staticmethod
1579 def _prepare_vdu_ssh_keys(
1580 target_vdu: dict, ro_nsr_public_key: dict, cloud_config: dict
1581 ) -> None:
1582 """Add ssh keys to cloud config.
1583
1584 Args:
1585 target_vdu (dict): Details of VDU to be created
1586 ro_nsr_public_key (dict): RO NSR public Key
1587 cloud_config (dict): Cloud config details
1588
1589 """
1590 ssh_keys = []
1591
1592 if target_vdu.get("ssh-keys"):
1593 ssh_keys += target_vdu.get("ssh-keys")
1594
1595 if target_vdu.get("ssh-access-required"):
1596 ssh_keys.append(ro_nsr_public_key)
1597
1598 if ssh_keys:
1599 cloud_config["key-pairs"] = ssh_keys
1600
1601 @staticmethod
1602 def _select_persistent_root_disk(vsd: dict, vdu: dict) -> dict:
1603 """Selects the persistent root disk if exists.
1604 Args:
1605 vsd (dict): Virtual storage descriptors in VNFD
1606 vdu (dict): VNF descriptor
1607
1608 Returns:
1609 root_disk (dict): Selected persistent root disk
1610 """
1611 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1612 root_disk = vsd
garciadeblas6a0147f2024-08-19 08:02:04 +00001613 if root_disk.get("type-of-storage", "").endswith(
1614 "persistent-storage"
1615 ) and root_disk.get("size-of-storage"):
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001616 return root_disk
1617
1618 @staticmethod
1619 def _add_persistent_root_disk_to_disk_list(
1620 vnfd: dict, target_vdu: dict, persistent_root_disk: dict, disk_list: list
1621 ) -> None:
1622 """Find the persistent root disk and add to disk list.
1623
1624 Args:
1625 vnfd (dict): VNF descriptor
1626 target_vdu (dict): Details of VDU to be created
1627 persistent_root_disk (dict): Details of persistent root disk
1628 disk_list (list): Disks of VDU
1629
1630 """
1631 for vdu in vnfd.get("vdu", ()):
1632 if vdu["name"] == target_vdu["vdu-name"]:
1633 for vsd in vnfd.get("virtual-storage-desc", ()):
1634 root_disk = Ns._select_persistent_root_disk(vsd, vdu)
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001635 if not root_disk:
1636 continue
1637
1638 persistent_root_disk[vsd["id"]] = {
1639 "image_id": vdu.get("sw-image-desc"),
1640 "size": root_disk["size-of-storage"],
aticig2f4ab6c2022-09-03 18:15:20 +03001641 "keep": Ns.is_volume_keeping_required(root_disk),
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001642 }
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001643 disk_list.append(persistent_root_disk[vsd["id"]])
1644 break
1645
1646 @staticmethod
1647 def _add_persistent_ordinary_disks_to_disk_list(
1648 target_vdu: dict,
1649 persistent_root_disk: dict,
1650 persistent_ordinary_disk: dict,
1651 disk_list: list,
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001652 extra_dict: dict,
vegall364627c2023-03-17 15:09:50 +00001653 vnf_id: str = None,
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001654 nsr_id: str = None,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001655 ) -> None:
1656 """Fill the disk list by adding persistent ordinary disks.
1657
1658 Args:
1659 target_vdu (dict): Details of VDU to be created
1660 persistent_root_disk (dict): Details of persistent root disk
1661 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1662 disk_list (list): Disks of VDU
1663
1664 """
1665 if target_vdu.get("virtual-storages"):
1666 for disk in target_vdu["virtual-storages"]:
1667 if (
garciadeblas6a0147f2024-08-19 08:02:04 +00001668 disk.get("type-of-storage", "").endswith("persistent-storage")
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001669 and disk["id"] not in persistent_root_disk.keys()
1670 ):
vegall364627c2023-03-17 15:09:50 +00001671 name, multiattach = Ns.is_shared_volume(disk, vnf_id)
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001672 persistent_ordinary_disk[disk["id"]] = {
vegall364627c2023-03-17 15:09:50 +00001673 "name": name,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001674 "size": disk["size-of-storage"],
aticig2f4ab6c2022-09-03 18:15:20 +03001675 "keep": Ns.is_volume_keeping_required(disk),
vegall364627c2023-03-17 15:09:50 +00001676 "multiattach": multiattach,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001677 }
1678 disk_list.append(persistent_ordinary_disk[disk["id"]])
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001679 if multiattach: # VDU creation has to wait for shared volumes
1680 extra_dict["depends_on"].append(
1681 f"nsrs:{nsr_id}:shared-volumes.{name}"
1682 )
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001683
1684 @staticmethod
1685 def _prepare_vdu_affinity_group_list(
1686 target_vdu: dict, extra_dict: dict, ns_preffix: str
1687 ) -> List[Dict[str, any]]:
1688 """Process affinity group details to prepare affinity group list.
1689
1690 Args:
1691 target_vdu (dict): Details of VDU to be created
1692 extra_dict (dict): Dictionary to be filled
1693 ns_preffix (str): Prefix as string
1694
1695 Returns:
1696
1697 affinity_group_list (list): Affinity group details
1698
1699 """
1700 affinity_group_list = []
1701
1702 if target_vdu.get("affinity-or-anti-affinity-group-id"):
1703 for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1704 affinity_group = {}
1705 affinity_group_text = (
1706 ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1707 )
1708
1709 if not isinstance(extra_dict.get("depends_on"), list):
1710 raise NsException("Invalid extra_dict format.")
1711
1712 extra_dict["depends_on"].append(affinity_group_text)
1713 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1714 affinity_group_list.append(affinity_group)
1715
1716 return affinity_group_list
aticigcf14bb12022-05-19 13:03:17 +03001717
1718 @staticmethod
sousaedu0b1e7342021-12-07 15:33:46 +00001719 def _process_vdu_params(
1720 target_vdu: Dict[str, Any],
1721 indata: Dict[str, Any],
1722 vim_info: Dict[str, Any],
1723 target_record_id: str,
1724 **kwargs: Dict[str, Any],
1725 ) -> Dict[str, Any]:
1726 """Function to process VDU parameters.
1727
1728 Args:
1729 target_vdu (Dict[str, Any]): [description]
1730 indata (Dict[str, Any]): [description]
1731 vim_info (Dict[str, Any]): [description]
1732 target_record_id (str): [description]
1733
1734 Returns:
1735 Dict[str, Any]: [description]
1736 """
1737 vnfr_id = kwargs.get("vnfr_id")
1738 nsr_id = kwargs.get("nsr_id")
1739 vnfr = kwargs.get("vnfr")
1740 vdu2cloud_init = kwargs.get("vdu2cloud_init")
1741 tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id")
1742 logger = kwargs.get("logger")
1743 db = kwargs.get("db")
1744 fs = kwargs.get("fs")
1745 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1746
1747 vnf_preffix = "vnfrs:{}".format(vnfr_id)
1748 ns_preffix = "nsrs:{}".format(nsr_id)
1749 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
Gabriel Cubaa5233f82023-08-07 18:43:26 -05001750 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
1751 extra_dict = {"depends_on": [image_text, flavor_text]}
sousaedu0b1e7342021-12-07 15:33:46 +00001752 net_list = []
aticig179e0022022-03-29 13:15:45 +03001753 persistent_root_disk = {}
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001754 persistent_ordinary_disk = {}
aticigcf14bb12022-05-19 13:03:17 +03001755 vdu_instantiation_volumes_list = []
aticig179e0022022-03-29 13:15:45 +03001756 disk_list = []
1757 vnfd_id = vnfr["vnfd-id"]
1758 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001759 # If the position info is provided for all the interfaces, it will be sorted
1760 # according to position number ascendingly.
1761 if all(
1762 True if i.get("position") is not None else False
1763 for i in target_vdu["interfaces"]
1764 ):
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001765 Ns._sort_vdu_interfaces(target_vdu)
1766
1767 # If the position info is provided for some interfaces but not all of them, the interfaces
1768 # which has specific position numbers will be placed and others' positions will not be taken care.
1769 else:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001770 Ns._partially_locate_vdu_interfaces(target_vdu)
1771
1772 # If the position info is not provided for the interfaces, interfaces will be attached
1773 # according to the order in the VNFD.
1774 Ns._prepare_vdu_interfaces(
1775 target_vdu,
1776 extra_dict,
1777 ns_preffix,
1778 vnf_preffix,
1779 logger,
1780 tasks_by_target_record_id,
1781 net_list,
1782 )
1783
1784 # cloud config
1785 cloud_config = Ns._prepare_vdu_cloud_init(target_vdu, vdu2cloud_init, db, fs)
1786
1787 # Prepare VDU ssh keys
1788 Ns._prepare_vdu_ssh_keys(target_vdu, ro_nsr_public_key, cloud_config)
1789
aticigcf14bb12022-05-19 13:03:17 +03001790 if target_vdu.get("additionalParams"):
1791 vdu_instantiation_volumes_list = (
Gabriel Cuba730cfaf2023-03-13 22:26:38 -05001792 target_vdu.get("additionalParams").get("OSM", {}).get("vdu_volumes")
aticigcf14bb12022-05-19 13:03:17 +03001793 )
1794
1795 if vdu_instantiation_volumes_list:
aticigcf14bb12022-05-19 13:03:17 +03001796 # Find the root volumes and add to the disk_list
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001797 persistent_root_disk = Ns.find_persistent_root_volumes(
aticigcf14bb12022-05-19 13:03:17 +03001798 vnfd, target_vdu, vdu_instantiation_volumes_list, disk_list
1799 )
1800
1801 # Find the ordinary volumes which are not added to the persistent_root_disk
1802 # and put them to the disk list
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001803 Ns.find_persistent_volumes(
aticigcf14bb12022-05-19 13:03:17 +03001804 persistent_root_disk,
1805 target_vdu,
1806 vdu_instantiation_volumes_list,
1807 disk_list,
1808 )
1809
1810 else:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001811 # Vdu_instantiation_volumes_list is empty
1812 # First get add the persistent root disks to disk_list
1813 Ns._add_persistent_root_disk_to_disk_list(
1814 vnfd, target_vdu, persistent_root_disk, disk_list
1815 )
1816 # Add the persistent non-root disks to disk_list
1817 Ns._add_persistent_ordinary_disks_to_disk_list(
vegall364627c2023-03-17 15:09:50 +00001818 target_vdu,
1819 persistent_root_disk,
1820 persistent_ordinary_disk,
1821 disk_list,
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001822 extra_dict,
vegall364627c2023-03-17 15:09:50 +00001823 vnfd["id"],
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001824 nsr_id,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001825 )
aticigcf14bb12022-05-19 13:03:17 +03001826
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001827 affinity_group_list = Ns._prepare_vdu_affinity_group_list(
1828 target_vdu, extra_dict, ns_preffix
1829 )
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001830
kayal2001f81a8652024-06-27 11:04:09 +05301831 instance_name = "{}-{}-{}-{}".format(
1832 indata["name"],
1833 vnfr["member-vnf-index-ref"],
1834 target_vdu["vdu-name"],
1835 target_vdu.get("count-index") or 0,
1836 )
1837 if additional_params := target_vdu.get("additionalParams"):
1838 if additional_params.get("OSM", {}).get("instance_name"):
1839 instance_name = additional_params.get("OSM", {}).get("instance_name")
1840 if count_index := target_vdu.get("count-index"):
1841 if count_index >= 1:
1842 instance_name = "{}-{}".format(instance_name, count_index)
1843
sousaedu0b1e7342021-12-07 15:33:46 +00001844 extra_dict["params"] = {
kayal2001f81a8652024-06-27 11:04:09 +05301845 "name": instance_name,
sousaedu0b1e7342021-12-07 15:33:46 +00001846 "description": target_vdu["vdu-name"],
1847 "start": True,
1848 "image_id": "TASK-" + image_text,
Gabriel Cubaa5233f82023-08-07 18:43:26 -05001849 "flavor_id": "TASK-" + flavor_text,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001850 "affinity_group_list": affinity_group_list,
sousaedu0b1e7342021-12-07 15:33:46 +00001851 "net_list": net_list,
1852 "cloud_config": cloud_config or None,
1853 "disk_list": disk_list,
1854 "availability_zone_index": None, # TODO
1855 "availability_zone_list": None, # TODO
1856 }
vegall364627c2023-03-17 15:09:50 +00001857 return extra_dict
sousaedu0b1e7342021-12-07 15:33:46 +00001858
vegall364627c2023-03-17 15:09:50 +00001859 @staticmethod
1860 def _process_shared_volumes_params(
1861 target_shared_volume: Dict[str, Any],
1862 indata: Dict[str, Any],
1863 vim_info: Dict[str, Any],
1864 target_record_id: str,
1865 **kwargs: Dict[str, Any],
1866 ) -> Dict[str, Any]:
1867 extra_dict = {}
1868 shared_volume_data = {
1869 "size": target_shared_volume["size-of-storage"],
1870 "name": target_shared_volume["id"],
1871 "type": target_shared_volume["type-of-storage"],
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001872 "keep": Ns.is_volume_keeping_required(target_shared_volume),
vegall364627c2023-03-17 15:09:50 +00001873 }
1874 extra_dict["params"] = shared_volume_data
sousaedu0b1e7342021-12-07 15:33:46 +00001875 return extra_dict
1876
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001877 @staticmethod
1878 def _process_affinity_group_params(
1879 target_affinity_group: Dict[str, Any],
1880 indata: Dict[str, Any],
1881 vim_info: Dict[str, Any],
1882 target_record_id: str,
1883 **kwargs: Dict[str, Any],
1884 ) -> Dict[str, Any]:
1885 """Get affinity or anti-affinity group parameters.
1886
1887 Args:
1888 target_affinity_group (Dict[str, Any]): [description]
1889 indata (Dict[str, Any]): [description]
1890 vim_info (Dict[str, Any]): [description]
1891 target_record_id (str): [description]
1892
1893 Returns:
1894 Dict[str, Any]: [description]
1895 """
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001896
palaciosj8f2060b2022-02-24 12:05:59 +00001897 extra_dict = {}
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001898 affinity_group_data = {
1899 "name": target_affinity_group["name"],
1900 "type": target_affinity_group["type"],
1901 "scope": target_affinity_group["scope"],
1902 }
1903
Alexis Romero123de182022-04-26 19:24:40 +02001904 if target_affinity_group.get("vim-affinity-group-id"):
1905 affinity_group_data["vim-affinity-group-id"] = target_affinity_group[
1906 "vim-affinity-group-id"
1907 ]
1908
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001909 extra_dict["params"] = {
1910 "affinity_group_data": affinity_group_data,
1911 }
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001912 return extra_dict
1913
palaciosj8f2060b2022-02-24 12:05:59 +00001914 @staticmethod
1915 def _process_recreate_vdu_params(
1916 existing_vdu: Dict[str, Any],
1917 db_nsr: Dict[str, Any],
1918 vim_info: Dict[str, Any],
1919 target_record_id: str,
1920 target_id: str,
elumalaif8d9d322024-05-08 17:19:13 +05301921 flavor_task_id: str,
palaciosj8f2060b2022-02-24 12:05:59 +00001922 **kwargs: Dict[str, Any],
1923 ) -> Dict[str, Any]:
1924 """Function to process VDU parameters to recreate.
1925
1926 Args:
1927 existing_vdu (Dict[str, Any]): [description]
1928 db_nsr (Dict[str, Any]): [description]
1929 vim_info (Dict[str, Any]): [description]
1930 target_record_id (str): [description]
1931 target_id (str): [description]
1932
1933 Returns:
1934 Dict[str, Any]: [description]
1935 """
1936 vnfr = kwargs.get("vnfr")
1937 vdu2cloud_init = kwargs.get("vdu2cloud_init")
aticig285185e2022-05-02 21:23:48 +03001938 # logger = kwargs.get("logger")
palaciosj8f2060b2022-02-24 12:05:59 +00001939 db = kwargs.get("db")
1940 fs = kwargs.get("fs")
1941 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1942
1943 extra_dict = {}
1944 net_list = []
1945
1946 vim_details = {}
1947 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
vegall364627c2023-03-17 15:09:50 +00001948
palaciosj8f2060b2022-02-24 12:05:59 +00001949 if vim_details_text:
1950 vim_details = yaml.safe_load(f"{vim_details_text}")
1951
1952 for iface_index, interface in enumerate(existing_vdu["interfaces"]):
palaciosj8f2060b2022-02-24 12:05:59 +00001953 if "port-security-enabled" in interface:
1954 interface["port_security"] = interface.pop("port-security-enabled")
1955
1956 if "port-security-disable-strategy" in interface:
1957 interface["port_security_disable_strategy"] = interface.pop(
1958 "port-security-disable-strategy"
1959 )
1960
1961 net_item = {
1962 x: v
1963 for x, v in interface.items()
1964 if x
1965 in (
1966 "name",
1967 "vpci",
1968 "port_security",
1969 "port_security_disable_strategy",
1970 "floating_ip",
1971 )
1972 }
garciadeblasbf235192022-06-13 10:02:51 +02001973 existing_ifaces = existing_vdu["vim_info"][target_id].get(
1974 "interfaces_backup", []
1975 )
palaciosj8f2060b2022-02-24 12:05:59 +00001976 net_id = next(
aticig285185e2022-05-02 21:23:48 +03001977 (
1978 i["vim_net_id"]
1979 for i in existing_ifaces
1980 if i["ip_address"] == interface["ip-address"]
1981 ),
palaciosj8f2060b2022-02-24 12:05:59 +00001982 None,
1983 )
1984
1985 net_item["net_id"] = net_id
1986 net_item["type"] = "virtual"
1987
1988 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1989 # TODO floating_ip: True/False (or it can be None)
1990 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1991 net_item["use"] = "data"
1992 net_item["model"] = interface["type"]
1993 net_item["type"] = interface["type"]
1994 elif (
1995 interface.get("type") == "OM-MGMT"
1996 or interface.get("mgmt-interface")
1997 or interface.get("mgmt-vnf")
1998 ):
1999 net_item["use"] = "mgmt"
2000 else:
2001 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
2002 net_item["use"] = "bridge"
2003 net_item["model"] = interface.get("type")
2004
2005 if interface.get("ip-address"):
rahulda707572023-08-30 15:06:49 +05302006 dual_ip = interface.get("ip-address").split(";")
2007 if len(dual_ip) == 2:
2008 net_item["ip_address"] = dual_ip
2009 else:
2010 net_item["ip_address"] = interface["ip-address"]
palaciosj8f2060b2022-02-24 12:05:59 +00002011
2012 if interface.get("mac-address"):
2013 net_item["mac_address"] = interface["mac-address"]
2014
2015 net_list.append(net_item)
2016
2017 if interface.get("mgmt-vnf"):
2018 extra_dict["mgmt_vnf_interface"] = iface_index
2019 elif interface.get("mgmt-interface"):
2020 extra_dict["mgmt_vdu_interface"] = iface_index
2021
2022 # cloud config
2023 cloud_config = {}
2024
2025 if existing_vdu.get("cloud-init"):
2026 if existing_vdu["cloud-init"] not in vdu2cloud_init:
2027 vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init(
2028 db=db,
2029 fs=fs,
2030 location=existing_vdu["cloud-init"],
2031 )
2032
2033 cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
2034 cloud_config["user-data"] = Ns._parse_jinja2(
2035 cloud_init_content=cloud_content_,
2036 params=existing_vdu.get("additionalParams"),
2037 context=existing_vdu["cloud-init"],
2038 )
2039
2040 if existing_vdu.get("boot-data-drive"):
2041 cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
2042
2043 ssh_keys = []
2044
2045 if existing_vdu.get("ssh-keys"):
2046 ssh_keys += existing_vdu.get("ssh-keys")
2047
2048 if existing_vdu.get("ssh-access-required"):
2049 ssh_keys.append(ro_nsr_public_key)
2050
2051 if ssh_keys:
2052 cloud_config["key-pairs"] = ssh_keys
2053
2054 disk_list = []
2055 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2056 disk_list.append({"vim_id": vol_id["id"]})
2057
2058 affinity_group_list = []
2059
2060 if existing_vdu.get("affinity-or-anti-affinity-group-id"):
2061 affinity_group = {}
2062 for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]:
2063 for group in db_nsr.get("affinity-or-anti-affinity-group"):
aticig285185e2022-05-02 21:23:48 +03002064 if (
2065 group["id"] == affinity_group_id
2066 and group["vim_info"][target_id].get("vim_id", None) is not None
2067 ):
2068 affinity_group["affinity_group_id"] = group["vim_info"][
2069 target_id
2070 ].get("vim_id", None)
palaciosj8f2060b2022-02-24 12:05:59 +00002071 affinity_group_list.append(affinity_group)
2072
kayal2001f81a8652024-06-27 11:04:09 +05302073 instance_name = "{}-{}-{}-{}".format(
2074 db_nsr["name"],
2075 vnfr["member-vnf-index-ref"],
2076 existing_vdu["vdu-name"],
2077 existing_vdu.get("count-index") or 0,
2078 )
2079 if additional_params := existing_vdu.get("additionalParams"):
2080 if additional_params.get("OSM", {}).get("instance_name"):
2081 instance_name = additional_params.get("OSM", {}).get("instance_name")
2082 if count_index := existing_vdu.get("count-index"):
2083 if count_index >= 1:
2084 instance_name = "{}-{}".format(instance_name, count_index)
2085
palaciosj8f2060b2022-02-24 12:05:59 +00002086 extra_dict["params"] = {
kayal2001f81a8652024-06-27 11:04:09 +05302087 "name": instance_name,
palaciosj8f2060b2022-02-24 12:05:59 +00002088 "description": existing_vdu["vdu-name"],
2089 "start": True,
2090 "image_id": vim_details["image"]["id"],
elumalaif8d9d322024-05-08 17:19:13 +05302091 "flavor_id": "TASK-" + flavor_task_id,
palaciosj8f2060b2022-02-24 12:05:59 +00002092 "affinity_group_list": affinity_group_list,
2093 "net_list": net_list,
2094 "cloud_config": cloud_config or None,
2095 "disk_list": disk_list,
2096 "availability_zone_index": None, # TODO
2097 "availability_zone_list": None, # TODO
2098 }
2099
2100 return extra_dict
2101
gallardoa1c2b402022-02-11 12:41:59 +00002102 def calculate_diff_items(
2103 self,
2104 indata,
2105 db_nsr,
2106 db_ro_nsr,
2107 db_nsr_update,
2108 item,
2109 tasks_by_target_record_id,
2110 action_id,
2111 nsr_id,
2112 task_index,
2113 vnfr_id=None,
2114 vnfr=None,
2115 ):
2116 """Function that returns the incremental changes (creation, deletion)
2117 related to a specific item `item` to be done. This function should be
2118 called for NS instantiation, NS termination, NS update to add a new VNF
2119 or a new VLD, remove a VNF or VLD, etc.
palaciosj8f2060b2022-02-24 12:05:59 +00002120 Item can be `net`, `flavor`, `image` or `vdu`.
gallardoa1c2b402022-02-11 12:41:59 +00002121 It takes a list of target items from indata (which came from the REST API)
2122 and compares with the existing items from db_ro_nsr, identifying the
2123 incremental changes to be done. During the comparison, it calls the method
2124 `process_params` (which was passed as parameter, and is particular for each
2125 `item`)
2126
2127 Args:
2128 indata (Dict[str, Any]): deployment info
2129 db_nsr: NSR record from DB
2130 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2131 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2132 item (str): element to process (net, vdu...)
2133 tasks_by_target_record_id (Dict[str, Any]):
2134 [<target_record_id>, <task>]
2135 action_id (str): action id
2136 nsr_id (str): NSR id
2137 task_index (number): task index to add to task name
2138 vnfr_id (str): VNFR id
2139 vnfr (Dict[str, Any]): VNFR info
2140
2141 Returns:
2142 List: list with the incremental changes (deletes, creates) for each item
2143 number: current task index
2144 """
2145
2146 diff_items = []
2147 db_path = ""
2148 db_record = ""
2149 target_list = []
2150 existing_list = []
2151 process_params = None
2152 vdu2cloud_init = indata.get("cloud_init_content") or {}
2153 ro_nsr_public_key = db_ro_nsr["public_key"]
gallardoa1c2b402022-02-11 12:41:59 +00002154 # According to the type of item, the path, the target_list,
2155 # the existing_list and the method to process params are set
2156 db_path = self.db_path_map[item]
2157 process_params = self.process_params_function_map[item]
Lovejeet Singhdf486552023-05-09 22:41:09 +05302158
2159 if item in ("sfp", "classification", "sf", "sfi"):
2160 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
2161 target_vnffg = indata.get("vnffg", [])[0]
2162 target_list = target_vnffg[item]
2163 existing_list = db_nsr.get(item, [])
2164 elif item in ("net", "vdu"):
palaciosj8f2060b2022-02-24 12:05:59 +00002165 # This case is specific for the NS VLD (not applied to VDU)
gallardoa1c2b402022-02-11 12:41:59 +00002166 if vnfr is None:
2167 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
aticig2b24d622022-03-11 15:03:55 +03002168 target_list = indata.get("ns", []).get(db_path, [])
gallardoa1c2b402022-02-11 12:41:59 +00002169 existing_list = db_nsr.get(db_path, [])
palaciosj8f2060b2022-02-24 12:05:59 +00002170 # This case is common for VNF VLDs and VNF VDUs
gallardoa1c2b402022-02-11 12:41:59 +00002171 else:
2172 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
2173 target_vnf = next(
2174 (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
2175 None,
2176 )
2177 target_list = target_vnf.get(db_path, []) if target_vnf else []
2178 existing_list = vnfr.get(db_path, [])
vegall364627c2023-03-17 15:09:50 +00002179 elif item in (
2180 "image",
2181 "flavor",
2182 "affinity-or-anti-affinity-group",
2183 "shared-volumes",
2184 ):
gallardoa1c2b402022-02-11 12:41:59 +00002185 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
2186 target_list = indata.get(item, [])
2187 existing_list = db_nsr.get(item, [])
2188 else:
2189 raise NsException("Item not supported: {}", item)
gallardoa1c2b402022-02-11 12:41:59 +00002190 # ensure all the target_list elements has an "id". If not assign the index as id
2191 if target_list is None:
2192 target_list = []
2193 for target_index, tl in enumerate(target_list):
2194 if tl and not tl.get("id"):
2195 tl["id"] = str(target_index)
gallardoa1c2b402022-02-11 12:41:59 +00002196 # step 1 items (networks,vdus,...) to be deleted/updated
2197 for item_index, existing_item in enumerate(existing_list):
2198 target_item = next(
2199 (t for t in target_list if t["id"] == existing_item["id"]),
2200 None,
2201 )
gallardoa1c2b402022-02-11 12:41:59 +00002202 for target_vim, existing_viminfo in existing_item.get(
2203 "vim_info", {}
2204 ).items():
2205 if existing_viminfo is None:
2206 continue
2207
2208 if target_item:
2209 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
2210 else:
2211 target_viminfo = None
2212
2213 if target_viminfo is None:
2214 # must be deleted
2215 self._assign_vim(target_vim)
2216 target_record_id = "{}.{}".format(db_record, existing_item["id"])
2217 item_ = item
2218
gifrerenombf3e9a82022-03-07 17:55:20 +00002219 if target_vim.startswith("sdn") or target_vim.startswith("wim"):
gallardoa1c2b402022-02-11 12:41:59 +00002220 # item must be sdn-net instead of net if target_vim is a sdn
2221 item_ = "sdn_net"
2222 target_record_id += ".sdn"
2223
2224 deployment_info = {
2225 "action_id": action_id,
2226 "nsr_id": nsr_id,
2227 "task_index": task_index,
2228 }
2229
2230 diff_items.append(
2231 {
2232 "deployment_info": deployment_info,
2233 "target_id": target_vim,
2234 "item": item_,
2235 "action": "DELETE",
2236 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
2237 "target_record_id": target_record_id,
2238 }
2239 )
2240 task_index += 1
2241
2242 # step 2 items (networks,vdus,...) to be created
2243 for target_item in target_list:
2244 item_index = -1
gallardoa1c2b402022-02-11 12:41:59 +00002245 for item_index, existing_item in enumerate(existing_list):
2246 if existing_item["id"] == target_item["id"]:
2247 break
2248 else:
2249 item_index += 1
2250 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
2251 existing_list.append(target_item)
2252 existing_item = None
2253
2254 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
2255 existing_viminfo = None
2256
2257 if existing_item:
2258 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
2259
2260 if existing_viminfo is not None:
2261 continue
2262
2263 target_record_id = "{}.{}".format(db_record, target_item["id"])
2264 item_ = item
2265
gifrerenombf3e9a82022-03-07 17:55:20 +00002266 if target_vim.startswith("sdn") or target_vim.startswith("wim"):
gallardoa1c2b402022-02-11 12:41:59 +00002267 # item must be sdn-net instead of net if target_vim is a sdn
2268 item_ = "sdn_net"
2269 target_record_id += ".sdn"
2270
2271 kwargs = {}
aticigddff2b02022-09-03 23:06:37 +03002272 self.logger.debug(
palaciosj8f2060b2022-02-24 12:05:59 +00002273 "ns.calculate_diff_items target_item={}".format(target_item)
2274 )
aticigcf14bb12022-05-19 13:03:17 +03002275 if process_params == Ns._process_flavor_params:
2276 kwargs.update(
2277 {
2278 "db": self.db,
2279 }
2280 )
aticigddff2b02022-09-03 23:06:37 +03002281 self.logger.debug(
aticigcf14bb12022-05-19 13:03:17 +03002282 "calculate_diff_items for flavor kwargs={}".format(kwargs)
2283 )
2284
gallardoa1c2b402022-02-11 12:41:59 +00002285 if process_params == Ns._process_vdu_params:
aticigddff2b02022-09-03 23:06:37 +03002286 self.logger.debug("calculate_diff_items self.fs={}".format(self.fs))
gallardoa1c2b402022-02-11 12:41:59 +00002287 kwargs.update(
2288 {
2289 "vnfr_id": vnfr_id,
2290 "nsr_id": nsr_id,
2291 "vnfr": vnfr,
2292 "vdu2cloud_init": vdu2cloud_init,
2293 "tasks_by_target_record_id": tasks_by_target_record_id,
2294 "logger": self.logger,
2295 "db": self.db,
2296 "fs": self.fs,
2297 "ro_nsr_public_key": ro_nsr_public_key,
2298 }
2299 )
aticigddff2b02022-09-03 23:06:37 +03002300 self.logger.debug("calculate_diff_items kwargs={}".format(kwargs))
Lovejeet Singhdf486552023-05-09 22:41:09 +05302301 if (
2302 process_params == Ns._process_sfi_params
2303 or Ns._process_sf_params
2304 or Ns._process_classification_params
2305 or Ns._process_sfp_params
2306 ):
2307 kwargs.update({"nsr_id": nsr_id, "db": self.db})
2308
2309 self.logger.debug("calculate_diff_items kwargs={}".format(kwargs))
2310
gallardoa1c2b402022-02-11 12:41:59 +00002311 extra_dict = process_params(
2312 target_item,
2313 indata,
2314 target_viminfo,
2315 target_record_id,
2316 **kwargs,
2317 )
2318 self._assign_vim(target_vim)
2319
2320 deployment_info = {
2321 "action_id": action_id,
2322 "nsr_id": nsr_id,
2323 "task_index": task_index,
2324 }
2325
gallardo0108e942022-03-14 18:16:41 +00002326 new_item = {
2327 "deployment_info": deployment_info,
2328 "target_id": target_vim,
2329 "item": item_,
2330 "action": "CREATE",
2331 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
2332 "target_record_id": target_record_id,
2333 "extra_dict": extra_dict,
2334 "common_id": target_item.get("common_id", None),
2335 }
2336 diff_items.append(new_item)
2337 tasks_by_target_record_id[target_record_id] = new_item
gallardoa1c2b402022-02-11 12:41:59 +00002338 task_index += 1
2339
2340 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
2341
2342 return diff_items, task_index
2343
Lovejeet Singhdf486552023-05-09 22:41:09 +05302344 def _process_vnfgd_sfp(self, sfp):
2345 processed_sfp = {}
2346 # getting sfp name, sfs and classifications in sfp to store it in processed_sfp
2347 processed_sfp["id"] = sfp["id"]
2348 sfs_in_sfp = [
2349 sf["id"] for sf in sfp.get("position-desc-id", [])[0].get("cp-profile-id")
2350 ]
2351 classifications_in_sfp = [
2352 classi["id"]
2353 for classi in sfp.get("position-desc-id", [])[0].get("match-attributes")
2354 ]
2355
2356 # creating a list of sfp with sfs and classifications
2357 processed_sfp["sfs"] = sfs_in_sfp
2358 processed_sfp["classifications"] = classifications_in_sfp
2359
2360 return processed_sfp
2361
2362 def _process_vnfgd_sf(self, sf):
2363 processed_sf = {}
2364 # getting name of sf
2365 processed_sf["id"] = sf["id"]
2366 # getting sfis in sf
2367 sfis_in_sf = sf.get("constituent-profile-elements")
2368 sorted_sfis = sorted(sfis_in_sf, key=lambda i: i["order"])
2369 # getting sfis names
2370 processed_sf["sfis"] = [sfi["id"] for sfi in sorted_sfis]
2371
2372 return processed_sf
2373
2374 def _process_vnfgd_sfi(self, sfi, db_vnfrs):
2375 processed_sfi = {}
2376 # getting name of sfi
2377 processed_sfi["id"] = sfi["id"]
2378
2379 # getting ports in sfi
2380 ingress_port = sfi["ingress-constituent-cpd-id"]
2381 egress_port = sfi["egress-constituent-cpd-id"]
2382 sfi_vnf_member_index = sfi["constituent-base-element-id"]
2383
2384 processed_sfi["ingress_port"] = ingress_port
2385 processed_sfi["egress_port"] = egress_port
2386
2387 all_vnfrs = db_vnfrs.values()
2388
2389 sfi_vnfr = [
2390 element
2391 for element in all_vnfrs
2392 if element["member-vnf-index-ref"] == sfi_vnf_member_index
2393 ]
2394 processed_sfi["vnfr_id"] = sfi_vnfr[0]["id"]
2395
2396 sfi_vnfr_cp = sfi_vnfr[0]["connection-point"]
2397
2398 ingress_port_index = [
2399 c for c, element in enumerate(sfi_vnfr_cp) if element["id"] == ingress_port
2400 ]
2401 ingress_port_index = ingress_port_index[0]
2402
2403 processed_sfi["vdur_id"] = sfi_vnfr_cp[ingress_port_index][
2404 "connection-point-vdu-id"
2405 ]
2406 processed_sfi["ingress_port_index"] = ingress_port_index
2407 processed_sfi["egress_port_index"] = ingress_port_index
2408
2409 if egress_port != ingress_port:
2410 egress_port_index = [
2411 c
2412 for c, element in enumerate(sfi_vnfr_cp)
2413 if element["id"] == egress_port
2414 ]
2415 processed_sfi["egress_port_index"] = egress_port_index
2416
2417 return processed_sfi
2418
2419 def _process_vnfgd_classification(self, classification, db_vnfrs):
2420 processed_classification = {}
2421
2422 processed_classification = deepcopy(classification)
2423 classi_vnf_member_index = processed_classification[
2424 "constituent-base-element-id"
2425 ]
2426 logical_source_port = processed_classification["constituent-cpd-id"]
2427
2428 all_vnfrs = db_vnfrs.values()
2429
2430 classi_vnfr = [
2431 element
2432 for element in all_vnfrs
2433 if element["member-vnf-index-ref"] == classi_vnf_member_index
2434 ]
2435 processed_classification["vnfr_id"] = classi_vnfr[0]["id"]
2436
2437 classi_vnfr_cp = classi_vnfr[0]["connection-point"]
2438
2439 ingress_port_index = [
2440 c
2441 for c, element in enumerate(classi_vnfr_cp)
2442 if element["id"] == logical_source_port
2443 ]
2444 ingress_port_index = ingress_port_index[0]
2445
2446 processed_classification["ingress_port_index"] = ingress_port_index
2447 processed_classification["vdur_id"] = classi_vnfr_cp[ingress_port_index][
2448 "connection-point-vdu-id"
2449 ]
2450
2451 return processed_classification
2452
2453 def _update_db_nsr_with_vnffg(self, processed_vnffg, vim_info, nsr_id):
2454 """This method used to add viminfo dict to sfi, sf sfp and classification in indata and count info in db_nsr.
2455
2456 Args:
2457 processed_vnffg (Dict[str, Any]): deployment info
2458 vim_info (Dict): dictionary to store VIM resource information
2459 nsr_id (str): NSR id
2460
2461 Returns: None
2462 """
2463
2464 nsr_sfi = {}
2465 nsr_sf = {}
2466 nsr_sfp = {}
2467 nsr_classification = {}
2468 db_nsr_vnffg = deepcopy(processed_vnffg)
2469
2470 for count, sfi in enumerate(processed_vnffg["sfi"]):
2471 sfi["vim_info"] = vim_info
2472 sfi_count = "sfi.{}".format(count)
2473 nsr_sfi[sfi_count] = db_nsr_vnffg["sfi"][count]
2474
2475 self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sfi)
2476
2477 for count, sf in enumerate(processed_vnffg["sf"]):
2478 sf["vim_info"] = vim_info
2479 sf_count = "sf.{}".format(count)
2480 nsr_sf[sf_count] = db_nsr_vnffg["sf"][count]
2481
2482 self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sf)
2483
2484 for count, sfp in enumerate(processed_vnffg["sfp"]):
2485 sfp["vim_info"] = vim_info
2486 sfp_count = "sfp.{}".format(count)
2487 nsr_sfp[sfp_count] = db_nsr_vnffg["sfp"][count]
2488
2489 self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sfp)
2490
2491 for count, classi in enumerate(processed_vnffg["classification"]):
2492 classi["vim_info"] = vim_info
2493 classification_count = "classification.{}".format(count)
2494 nsr_classification[classification_count] = db_nsr_vnffg["classification"][
2495 count
2496 ]
2497
2498 self.db.set_list("nsrs", {"_id": nsr_id}, nsr_classification)
2499
2500 def process_vnffgd_descriptor(
2501 self,
2502 indata: dict,
2503 nsr_id: str,
2504 db_nsr: dict,
2505 db_vnfrs: dict,
2506 ) -> dict:
2507 """This method used to process vnffgd parameters from descriptor.
2508
2509 Args:
2510 indata (Dict[str, Any]): deployment info
2511 nsr_id (str): NSR id
2512 db_nsr: NSR record from DB
2513 db_vnfrs: VNFRS record from DB
2514
2515 Returns:
2516 Dict: Processed vnffg parameters.
2517 """
2518
2519 processed_vnffg = {}
2520 vnffgd = db_nsr.get("nsd", {}).get("vnffgd")
2521 vnf_list = indata.get("vnf", [])
2522 vim_text = ""
2523
2524 if vnf_list:
2525 vim_text = "vim:" + vnf_list[0].get("vim-account-id", "")
2526
2527 vim_info = {}
2528 vim_info[vim_text] = {}
2529 processed_sfps = []
2530 processed_classifications = []
2531 processed_sfs = []
2532 processed_sfis = []
2533
2534 # setting up intial empty entries for vnffg items in mongodb.
2535 self.db.set_list(
2536 "nsrs",
2537 {"_id": nsr_id},
2538 {
2539 "sfi": [],
2540 "sf": [],
2541 "sfp": [],
2542 "classification": [],
2543 },
2544 )
2545
2546 vnffg = vnffgd[0]
2547 # getting sfps
2548 sfps = vnffg.get("nfpd")
2549 for sfp in sfps:
2550 processed_sfp = self._process_vnfgd_sfp(sfp)
2551 # appending the list of processed sfps
2552 processed_sfps.append(processed_sfp)
2553
2554 # getting sfs in sfp
2555 sfs = sfp.get("position-desc-id")[0].get("cp-profile-id")
2556 for sf in sfs:
2557 processed_sf = self._process_vnfgd_sf(sf)
2558
2559 # appending the list of processed sfs
2560 processed_sfs.append(processed_sf)
2561
2562 # getting sfis in sf
2563 sfis_in_sf = sf.get("constituent-profile-elements")
2564 sorted_sfis = sorted(sfis_in_sf, key=lambda i: i["order"])
2565
2566 for sfi in sorted_sfis:
2567 processed_sfi = self._process_vnfgd_sfi(sfi, db_vnfrs)
2568
2569 processed_sfis.append(processed_sfi)
2570
2571 classifications = sfp.get("position-desc-id")[0].get("match-attributes")
2572 # getting classifications from sfp
2573 for classification in classifications:
2574 processed_classification = self._process_vnfgd_classification(
2575 classification, db_vnfrs
2576 )
2577
2578 processed_classifications.append(processed_classification)
2579
2580 processed_vnffg["sfi"] = processed_sfis
2581 processed_vnffg["sf"] = processed_sfs
2582 processed_vnffg["classification"] = processed_classifications
2583 processed_vnffg["sfp"] = processed_sfps
2584
2585 # adding viminfo dict to sfi, sf sfp and classification
2586 self._update_db_nsr_with_vnffg(processed_vnffg, vim_info, nsr_id)
2587
2588 # updating indata with vnffg porcessed parameters
2589 indata["vnffg"].append(processed_vnffg)
2590
gallardoa1c2b402022-02-11 12:41:59 +00002591 def calculate_all_differences_to_deploy(
2592 self,
2593 indata,
2594 nsr_id,
2595 db_nsr,
2596 db_vnfrs,
2597 db_ro_nsr,
2598 db_nsr_update,
2599 db_vnfrs_update,
2600 action_id,
2601 tasks_by_target_record_id,
2602 ):
2603 """This method calculates the ordered list of items (`changes_list`)
2604 to be created and deleted.
2605
2606 Args:
2607 indata (Dict[str, Any]): deployment info
2608 nsr_id (str): NSR id
2609 db_nsr: NSR record from DB
2610 db_vnfrs: VNFRS record from DB
2611 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2612 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2613 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2614 action_id (str): action id
2615 tasks_by_target_record_id (Dict[str, Any]):
2616 [<target_record_id>, <task>]
2617
2618 Returns:
2619 List: ordered list of items to be created and deleted.
2620 """
2621
2622 task_index = 0
2623 # set list with diffs:
2624 changes_list = []
2625
Lovejeet Singhdf486552023-05-09 22:41:09 +05302626 # processing vnffg from descriptor parameter
2627 vnffgd = db_nsr.get("nsd").get("vnffgd")
2628 if vnffgd is not None:
2629 indata["vnffg"] = []
2630 vnf_list = indata["vnf"]
2631 processed_vnffg = {}
2632
2633 # in case of ns-delete
2634 if not vnf_list:
2635 processed_vnffg["sfi"] = []
2636 processed_vnffg["sf"] = []
2637 processed_vnffg["classification"] = []
2638 processed_vnffg["sfp"] = []
2639
2640 indata["vnffg"].append(processed_vnffg)
2641
2642 else:
2643 self.process_vnffgd_descriptor(
2644 indata=indata,
2645 nsr_id=nsr_id,
2646 db_nsr=db_nsr,
2647 db_vnfrs=db_vnfrs,
2648 )
2649
2650 # getting updated db_nsr having vnffg parameters
2651 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2652
2653 self.logger.debug(
2654 "After processing vnffd parameters indata={} nsr={}".format(
2655 indata, db_nsr
2656 )
2657 )
2658
2659 for item in ["sfp", "classification", "sf", "sfi"]:
2660 self.logger.debug("process NS={} {}".format(nsr_id, item))
2661 diff_items, task_index = self.calculate_diff_items(
2662 indata=indata,
2663 db_nsr=db_nsr,
2664 db_ro_nsr=db_ro_nsr,
2665 db_nsr_update=db_nsr_update,
2666 item=item,
2667 tasks_by_target_record_id=tasks_by_target_record_id,
2668 action_id=action_id,
2669 nsr_id=nsr_id,
2670 task_index=task_index,
2671 vnfr_id=None,
2672 )
2673 changes_list += diff_items
2674
gallardoa1c2b402022-02-11 12:41:59 +00002675 # NS vld, image and flavor
vegall364627c2023-03-17 15:09:50 +00002676 for item in [
2677 "net",
2678 "image",
2679 "flavor",
2680 "affinity-or-anti-affinity-group",
vegall364627c2023-03-17 15:09:50 +00002681 ]:
gallardoa1c2b402022-02-11 12:41:59 +00002682 self.logger.debug("process NS={} {}".format(nsr_id, item))
2683 diff_items, task_index = self.calculate_diff_items(
2684 indata=indata,
2685 db_nsr=db_nsr,
2686 db_ro_nsr=db_ro_nsr,
2687 db_nsr_update=db_nsr_update,
2688 item=item,
2689 tasks_by_target_record_id=tasks_by_target_record_id,
2690 action_id=action_id,
2691 nsr_id=nsr_id,
2692 task_index=task_index,
2693 vnfr_id=None,
2694 )
2695 changes_list += diff_items
2696
2697 # VNF vlds and vdus
2698 for vnfr_id, vnfr in db_vnfrs.items():
2699 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05002700 for item in ["net", "vdu", "shared-volumes"]:
gallardoa1c2b402022-02-11 12:41:59 +00002701 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
2702 diff_items, task_index = self.calculate_diff_items(
2703 indata=indata,
2704 db_nsr=db_nsr,
2705 db_ro_nsr=db_ro_nsr,
2706 db_nsr_update=db_vnfrs_update[vnfr["_id"]],
2707 item=item,
2708 tasks_by_target_record_id=tasks_by_target_record_id,
2709 action_id=action_id,
2710 nsr_id=nsr_id,
2711 task_index=task_index,
2712 vnfr_id=vnfr_id,
2713 vnfr=vnfr,
2714 )
2715 changes_list += diff_items
2716
2717 return changes_list
2718
2719 def define_all_tasks(
2720 self,
2721 changes_list,
2722 db_new_tasks,
2723 tasks_by_target_record_id,
2724 ):
2725 """Function to create all the task structures obtanied from
2726 the method calculate_all_differences_to_deploy
2727
2728 Args:
2729 changes_list (List): ordered list of items to be created or deleted
2730 db_new_tasks (List): tasks list to be created
2731 action_id (str): action id
2732 tasks_by_target_record_id (Dict[str, Any]):
2733 [<target_record_id>, <task>]
2734
2735 """
2736
2737 for change in changes_list:
2738 task = Ns._create_task(
2739 deployment_info=change["deployment_info"],
2740 target_id=change["target_id"],
2741 item=change["item"],
2742 action=change["action"],
2743 target_record=change["target_record"],
2744 target_record_id=change["target_record_id"],
2745 extra_dict=change.get("extra_dict", None),
2746 )
2747
aticigddff2b02022-09-03 23:06:37 +03002748 self.logger.debug("ns.define_all_tasks task={}".format(task))
gallardoa1c2b402022-02-11 12:41:59 +00002749 tasks_by_target_record_id[change["target_record_id"]] = task
2750 db_new_tasks.append(task)
2751
2752 if change.get("common_id"):
2753 task["common_id"] = change["common_id"]
2754
2755 def upload_all_tasks(
2756 self,
2757 db_new_tasks,
2758 now,
2759 ):
2760 """Function to save all tasks in the common DB
2761
2762 Args:
2763 db_new_tasks (List): tasks list to be created
2764 now (time): current time
2765
2766 """
2767
2768 nb_ro_tasks = 0 # for logging
2769
2770 for db_task in db_new_tasks:
2771 target_id = db_task.pop("target_id")
2772 common_id = db_task.get("common_id")
2773
palaciosj42eb06f2022-05-05 14:59:36 +00002774 # Do not chek tasks with vim_status DELETED
2775 # because in manual heealing there are two tasks for the same vdur:
2776 # one with vim_status deleted and the other one with the actual VM status.
2777
gallardoa1c2b402022-02-11 12:41:59 +00002778 if common_id:
2779 if self.db.set_one(
2780 "ro_tasks",
2781 q_filter={
2782 "target_id": target_id,
2783 "tasks.common_id": common_id,
palaciosj42eb06f2022-05-05 14:59:36 +00002784 "vim_info.vim_status.ne": "DELETED",
gallardoa1c2b402022-02-11 12:41:59 +00002785 },
2786 update_dict={"to_check_at": now, "modified_at": now},
2787 push={"tasks": db_task},
2788 fail_on_empty=False,
2789 ):
2790 continue
2791
2792 if not self.db.set_one(
2793 "ro_tasks",
2794 q_filter={
2795 "target_id": target_id,
2796 "tasks.target_record": db_task["target_record"],
palaciosj42eb06f2022-05-05 14:59:36 +00002797 "vim_info.vim_status.ne": "DELETED",
gallardoa1c2b402022-02-11 12:41:59 +00002798 },
2799 update_dict={"to_check_at": now, "modified_at": now},
2800 push={"tasks": db_task},
2801 fail_on_empty=False,
2802 ):
2803 # Create a ro_task
2804 self.logger.debug("Updating database, Creating ro_tasks")
2805 db_ro_task = Ns._create_ro_task(target_id, db_task)
2806 nb_ro_tasks += 1
2807 self.db.create("ro_tasks", db_ro_task)
2808
2809 self.logger.debug(
2810 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2811 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2812 )
2813 )
2814
palaciosj8f2060b2022-02-24 12:05:59 +00002815 def upload_recreate_tasks(
2816 self,
2817 db_new_tasks,
2818 now,
2819 ):
2820 """Function to save recreate tasks in the common DB
2821
2822 Args:
2823 db_new_tasks (List): tasks list to be created
2824 now (time): current time
2825
2826 """
2827
2828 nb_ro_tasks = 0 # for logging
2829
2830 for db_task in db_new_tasks:
2831 target_id = db_task.pop("target_id")
aticigddff2b02022-09-03 23:06:37 +03002832 self.logger.debug("target_id={} db_task={}".format(target_id, db_task))
palaciosj8f2060b2022-02-24 12:05:59 +00002833
2834 action = db_task.get("action", None)
2835
2836 # Create a ro_task
2837 self.logger.debug("Updating database, Creating ro_tasks")
2838 db_ro_task = Ns._create_ro_task(target_id, db_task)
2839
aticig285185e2022-05-02 21:23:48 +03002840 # If DELETE task: the associated created items should be removed
palaciosj8f2060b2022-02-24 12:05:59 +00002841 # (except persistent volumes):
2842 if action == "DELETE":
2843 db_ro_task["vim_info"]["created"] = True
aticig285185e2022-05-02 21:23:48 +03002844 db_ro_task["vim_info"]["created_items"] = db_task.get(
2845 "created_items", {}
2846 )
palaciosj42eb06f2022-05-05 14:59:36 +00002847 db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get(
2848 "volumes_to_hold", []
2849 )
palaciosj8f2060b2022-02-24 12:05:59 +00002850 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
2851
2852 nb_ro_tasks += 1
aticigddff2b02022-09-03 23:06:37 +03002853 self.logger.debug("upload_all_tasks db_ro_task={}".format(db_ro_task))
palaciosj8f2060b2022-02-24 12:05:59 +00002854 self.db.create("ro_tasks", db_ro_task)
2855
2856 self.logger.debug(
2857 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2858 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2859 )
2860 )
2861
2862 def _prepare_created_items_for_healing(
2863 self,
palaciosj42eb06f2022-05-05 14:59:36 +00002864 nsr_id,
2865 target_record,
palaciosj8f2060b2022-02-24 12:05:59 +00002866 ):
palaciosj42eb06f2022-05-05 14:59:36 +00002867 created_items = {}
2868 # Get created_items from ro_task
2869 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2870 for ro_task in ro_tasks:
2871 for task in ro_task["tasks"]:
2872 if (
2873 task["target_record"] == target_record
2874 and task["action"] == "CREATE"
2875 and ro_task["vim_info"]["created_items"]
2876 ):
2877 created_items = ro_task["vim_info"]["created_items"]
2878 break
palaciosj8f2060b2022-02-24 12:05:59 +00002879
palaciosj42eb06f2022-05-05 14:59:36 +00002880 return created_items
palaciosj8f2060b2022-02-24 12:05:59 +00002881
2882 def _prepare_persistent_volumes_for_healing(
2883 self,
2884 target_id,
2885 existing_vdu,
2886 ):
2887 # The associated volumes of the VM shouldn't be removed
2888 volumes_list = []
2889 vim_details = {}
2890 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
2891 if vim_details_text:
2892 vim_details = yaml.safe_load(f"{vim_details_text}")
2893
2894 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2895 volumes_list.append(vol_id["id"])
2896
2897 return volumes_list
2898
elumalaif8d9d322024-05-08 17:19:13 +05302899 def _process_recreate_flavor_params(
2900 self,
2901 existing_vdu: Dict[str, Any],
2902 db_nsr: Dict[str, Any],
2903 vim_info: Dict[str, Any],
2904 target_record_id: str,
2905 **kwargs: Dict[str, Any],
2906 ) -> Dict[str, Any]:
2907 """Method to process Flavor parameters to recreate.
2908
2909 Args:
2910 existing_vdu (Dict[str, Any]): [description]
2911 db_nsr (Dict[str, Any]): [description]
2912 vim_info (Dict[str, Any]): [description]
2913 target_record_id (str): [description]
2914 target_id (str): [description]
2915 kwargs (dict)
2916
2917 Returns:
2918 vdu_flavor_dict: (Dict[str, Any])
2919
2920 """
2921 try:
2922 vdu_flavor_id = existing_vdu.get("ns-flavor-id")
2923 target_flavor = next(
2924 filter(
2925 lambda vdu_flavor_dict: vdu_flavor_dict["id"] == vdu_flavor_id,
2926 db_nsr.get("flavor"),
2927 ),
2928 None,
2929 )
2930 vdu_flavor_dict = Ns._process_flavor_params(
2931 target_flavor=target_flavor,
2932 indata={},
2933 vim_info=vim_info,
2934 target_record_id=target_record_id,
2935 **kwargs,
2936 )
2937 vdu_flavor_dict["name"] = target_flavor["name"]
2938 return vdu_flavor_dict
2939
2940 except (DbException, KeyError, ValueError, TypeError) as error:
2941 raise NsException(error)
2942
2943 def _prepare_flavor_create_item(
2944 self,
2945 existing_instance: dict,
2946 db_nsr: dict,
2947 target_viminfo: dict,
2948 target_record_id: str,
2949 target_vim: str,
2950 action_id: str,
2951 task_index: int,
2952 item_index: int,
2953 db_record_flavor: str,
2954 changes_list: list,
2955 **kwargs,
2956 ) -> str:
2957 flavor_data = self._process_recreate_flavor_params(
2958 existing_instance,
2959 db_nsr,
2960 target_viminfo,
2961 target_record_id,
2962 **kwargs,
2963 )
2964 flavor_task_id = f"{action_id}:{task_index}"
2965
2966 flavor_item = {
2967 "deployment_info": {
2968 "action_id": action_id,
2969 "nsr_id": kwargs["nsr_id"],
2970 "task_index": task_index,
2971 },
2972 "target_id": target_vim,
2973 "item": "flavor",
2974 "action": "CREATE",
2975 "target_record": f"{db_record_flavor}.{item_index}.vim_info.{target_vim}",
2976 # "target_record_id": "{}.{}".format(
2977 # db_record_flavor, existing_instance["id"]
2978 # ),
2979 "target_record_id": target_record_id,
2980 "extra_dict": flavor_data,
2981 "task_id": flavor_task_id,
2982 }
2983 changes_list.append(flavor_item)
2984
2985 return flavor_task_id
2986
palaciosj8f2060b2022-02-24 12:05:59 +00002987 def prepare_changes_to_recreate(
2988 self,
2989 indata,
2990 nsr_id,
2991 db_nsr,
2992 db_vnfrs,
2993 db_ro_nsr,
2994 action_id,
2995 tasks_by_target_record_id,
2996 ):
2997 """This method will obtain an ordered list of items (`changes_list`)
2998 to be created and deleted to meet the recreate request.
2999 """
3000
3001 self.logger.debug(
3002 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
3003 )
3004
3005 task_index = 0
3006 # set list with diffs:
3007 changes_list = []
3008 db_path = self.db_path_map["vdu"]
elumalaif8d9d322024-05-08 17:19:13 +05303009 db_path_flavor = self.db_path_map["flavor"]
palaciosj8f2060b2022-02-24 12:05:59 +00003010 target_list = indata.get("healVnfData", {})
3011 vdu2cloud_init = indata.get("cloud_init_content") or {}
3012 ro_nsr_public_key = db_ro_nsr["public_key"]
3013
3014 # Check each VNF of the target
3015 for target_vnf in target_list:
Gabriel Cubab1bc6692022-08-19 18:23:00 -05003016 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
3017 vnfr_id = target_vnf["vnfInstanceId"]
elumalai321d2e92023-04-28 17:03:07 +05303018 existing_vnf = db_vnfrs.get(vnfr_id, {})
Gabriel Cubab1bc6692022-08-19 18:23:00 -05003019 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
elumalaif8d9d322024-05-08 17:19:13 +05303020 db_record_flavor = "nsrs:{}:{}".format(nsr_id, db_path_flavor)
Gabriel Cubab1bc6692022-08-19 18:23:00 -05003021 # vim_account_id = existing_vnf.get("vim-account-id", "")
palaciosj8f2060b2022-02-24 12:05:59 +00003022
Gabriel Cubab1bc6692022-08-19 18:23:00 -05003023 target_vdus = target_vnf.get("additionalParams", {}).get("vdu", [])
palaciosj8f2060b2022-02-24 12:05:59 +00003024 # Check each VDU of this VNF
Gabriel Cubab1bc6692022-08-19 18:23:00 -05003025 if not target_vdus:
3026 # Create target_vdu_list from DB, if VDUs are not specified
3027 target_vdus = []
3028 for existing_vdu in existing_vnf.get("vdur"):
3029 vdu_name = existing_vdu.get("vdu-name", None)
3030 vdu_index = existing_vdu.get("count-index", 0)
3031 vdu_to_be_healed = {"vdu-id": vdu_name, "count-index": vdu_index}
3032 target_vdus.append(vdu_to_be_healed)
3033 for target_vdu in target_vdus:
palaciosj8f2060b2022-02-24 12:05:59 +00003034 vdu_name = target_vdu.get("vdu-id", None)
3035 # For multi instance VDU count-index is mandatory
3036 # For single session VDU count-indes is 0
3037 count_index = target_vdu.get("count-index", 0)
3038 item_index = 0
elumalai321d2e92023-04-28 17:03:07 +05303039 existing_instance = {}
3040 if existing_vnf:
3041 for instance in existing_vnf.get("vdur", {}):
3042 if (
3043 instance["vdu-name"] == vdu_name
3044 and instance["count-index"] == count_index
3045 ):
3046 existing_instance = instance
elumalaif8d9d322024-05-08 17:19:13 +05303047 item_index_flv = instance.get("ns-flavor-id")
3048 target_record_id_flv = "{}.{}".format(
3049 db_record_flavor, instance.get("ns-flavor-id")
3050 )
elumalai321d2e92023-04-28 17:03:07 +05303051 break
3052 else:
3053 item_index += 1
palaciosj8f2060b2022-02-24 12:05:59 +00003054
3055 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
3056
3057 # The target VIM is the one already existing in DB to recreate
3058 for target_vim, target_viminfo in existing_instance.get(
3059 "vim_info", {}
3060 ).items():
3061 # step 1 vdu to be deleted
3062 self._assign_vim(target_vim)
3063 deployment_info = {
3064 "action_id": action_id,
3065 "nsr_id": nsr_id,
3066 "task_index": task_index,
3067 }
3068
3069 target_record = f"{db_record}.{item_index}.vim_info.{target_vim}"
3070 created_items = self._prepare_created_items_for_healing(
palaciosj42eb06f2022-05-05 14:59:36 +00003071 nsr_id, target_record
palaciosj8f2060b2022-02-24 12:05:59 +00003072 )
3073
3074 volumes_to_hold = self._prepare_persistent_volumes_for_healing(
3075 target_vim, existing_instance
3076 )
3077
3078 # Specific extra params for recreate tasks:
3079 extra_dict = {
3080 "created_items": created_items,
3081 "vim_id": existing_instance["vim-id"],
3082 "volumes_to_hold": volumes_to_hold,
3083 }
3084
3085 changes_list.append(
3086 {
3087 "deployment_info": deployment_info,
3088 "target_id": target_vim,
3089 "item": "vdu",
3090 "action": "DELETE",
3091 "target_record": target_record,
3092 "target_record_id": target_record_id,
3093 "extra_dict": extra_dict,
3094 }
3095 )
3096 delete_task_id = f"{action_id}:{task_index}"
3097 task_index += 1
3098
elumalaif8d9d322024-05-08 17:19:13 +05303099 kwargs = {
3100 "vnfr_id": vnfr_id,
3101 "nsr_id": nsr_id,
3102 "vnfr": existing_vnf,
3103 "vdu2cloud_init": vdu2cloud_init,
3104 "tasks_by_target_record_id": tasks_by_target_record_id,
3105 "logger": self.logger,
3106 "db": self.db,
3107 "fs": self.fs,
3108 "ro_nsr_public_key": ro_nsr_public_key,
3109 }
3110
3111 # step 2 check if old flavor exists or prepare to create it
3112 flavor_task_id = self._prepare_flavor_create_item(
3113 existing_instance=existing_instance,
3114 db_nsr=db_nsr,
3115 target_viminfo=target_viminfo,
3116 target_record_id=target_record_id_flv,
3117 target_vim=target_vim,
3118 action_id=action_id,
3119 task_index=task_index + 1,
3120 item_index=item_index_flv,
3121 db_record_flavor=db_record_flavor,
3122 changes_list=changes_list,
3123 **kwargs,
3124 )
3125
3126 # step 3 vdu to be created
palaciosj8f2060b2022-02-24 12:05:59 +00003127 kwargs = {}
3128 kwargs.update(
3129 {
3130 "vnfr_id": vnfr_id,
3131 "nsr_id": nsr_id,
3132 "vnfr": existing_vnf,
3133 "vdu2cloud_init": vdu2cloud_init,
3134 "tasks_by_target_record_id": tasks_by_target_record_id,
3135 "logger": self.logger,
3136 "db": self.db,
3137 "fs": self.fs,
3138 "ro_nsr_public_key": ro_nsr_public_key,
3139 }
3140 )
3141
3142 extra_dict = self._process_recreate_vdu_params(
3143 existing_instance,
3144 db_nsr,
3145 target_viminfo,
3146 target_record_id,
3147 target_vim,
elumalaif8d9d322024-05-08 17:19:13 +05303148 flavor_task_id,
palaciosj8f2060b2022-02-24 12:05:59 +00003149 **kwargs,
3150 )
3151
3152 # The CREATE task depens on the DELETE task
3153 extra_dict["depends_on"] = [delete_task_id]
elumalaif8d9d322024-05-08 17:19:13 +05303154 extra_dict["depends_on"].append(flavor_task_id)
palaciosj8f2060b2022-02-24 12:05:59 +00003155
palaciosj42eb06f2022-05-05 14:59:36 +00003156 # Add volumes created from created_items if any
3157 # Ports should be deleted with delete task and automatically created with create task
3158 volumes = {}
3159 for k, v in created_items.items():
3160 try:
3161 k_item, _, k_id = k.partition(":")
3162 if k_item == "volume":
3163 volumes[k] = v
3164 except Exception as e:
3165 self.logger.error(
3166 "Error evaluating created item {}: {}".format(k, e)
3167 )
3168 extra_dict["previous_created_volumes"] = volumes
3169
palaciosj8f2060b2022-02-24 12:05:59 +00003170 deployment_info = {
3171 "action_id": action_id,
3172 "nsr_id": nsr_id,
3173 "task_index": task_index,
3174 }
3175 self._assign_vim(target_vim)
3176
3177 new_item = {
3178 "deployment_info": deployment_info,
3179 "target_id": target_vim,
3180 "item": "vdu",
3181 "action": "CREATE",
3182 "target_record": target_record,
3183 "target_record_id": target_record_id,
3184 "extra_dict": extra_dict,
3185 }
3186 changes_list.append(new_item)
3187 tasks_by_target_record_id[target_record_id] = new_item
3188 task_index += 1
3189
3190 return changes_list
3191
kayal200153f34cf2024-03-14 22:33:28 +05303192 def _remove_old_ro_tasks(self, nsr_id: str, changes_list: list, task_param) -> None:
3193 """Delete all ro_tasks registered for the targets vdurs (target_record)
3194 If task of type CREATE exist then vim will try to get info form deleted VMs.
3195 So remove all task related to target record.
3196
3197 Args:
3198 nsr_id (str): NS record ID
3199 changes_list (list): list of dictionaries to create tasks later
3200 """
3201
3202 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
3203 for change in changes_list:
3204 if task_param == "task_id":
3205 param_to_check = "{}:{}".format(
3206 change.get("deployment_info", {}).get("action_id"),
3207 change.get("deployment_info", {}).get("task_index"),
3208 )
3209 elif task_param == "target_record":
3210 param_to_check = change["target_record"]
3211 for ro_task in ro_tasks:
3212 for task in ro_task["tasks"]:
3213 if task[task_param] == param_to_check:
3214 self.db.del_one(
3215 "ro_tasks",
3216 q_filter={
3217 "_id": ro_task["_id"],
3218 "modified_at": ro_task["modified_at"],
3219 },
3220 fail_on_empty=False,
3221 )
3222
palaciosj8f2060b2022-02-24 12:05:59 +00003223 def recreate(self, session, indata, version, nsr_id, *args, **kwargs):
3224 self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata))
3225 # TODO: validate_input(indata, recreate_schema)
3226 action_id = indata.get("action_id", str(uuid4()))
3227 # get current deployment
3228 db_vnfrs = {} # vnf's info indexed by _id
3229 step = ""
3230 logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
3231 nsr_id, action_id, indata
3232 )
3233 self.logger.debug(logging_text + "Enter")
3234
3235 try:
3236 step = "Getting ns and vnfr record from db"
3237 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3238 db_new_tasks = []
3239 tasks_by_target_record_id = {}
3240 # read from db: vnf's of this ns
3241 step = "Getting vnfrs from db"
3242 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
3243 self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list))
3244
3245 if not db_vnfrs_list:
3246 raise NsException("Cannot obtain associated VNF for ns")
3247
3248 for vnfr in db_vnfrs_list:
3249 db_vnfrs[vnfr["_id"]] = vnfr
3250
3251 now = time()
3252 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
3253 self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr))
3254
3255 if not db_ro_nsr:
3256 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
3257
3258 with self.write_lock:
3259 # NS
3260 step = "process NS elements"
3261 changes_list = self.prepare_changes_to_recreate(
3262 indata=indata,
3263 nsr_id=nsr_id,
3264 db_nsr=db_nsr,
3265 db_vnfrs=db_vnfrs,
3266 db_ro_nsr=db_ro_nsr,
3267 action_id=action_id,
3268 tasks_by_target_record_id=tasks_by_target_record_id,
3269 )
3270
kayal200153f34cf2024-03-14 22:33:28 +05303271 self._remove_old_ro_tasks(nsr_id, changes_list, "target_record")
palaciosj8f2060b2022-02-24 12:05:59 +00003272 self.define_all_tasks(
3273 changes_list=changes_list,
3274 db_new_tasks=db_new_tasks,
3275 tasks_by_target_record_id=tasks_by_target_record_id,
3276 )
3277
3278 # Delete all ro_tasks registered for the targets vdurs (target_record)
aticig285185e2022-05-02 21:23:48 +03003279 # If task of type CREATE exist then vim will try to get info form deleted VMs.
palaciosj8f2060b2022-02-24 12:05:59 +00003280 # So remove all task related to target record.
3281 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
3282 for change in changes_list:
3283 for ro_task in ro_tasks:
3284 for task in ro_task["tasks"]:
3285 if task["target_record"] == change["target_record"]:
3286 self.db.del_one(
3287 "ro_tasks",
3288 q_filter={
3289 "_id": ro_task["_id"],
3290 "modified_at": ro_task["modified_at"],
3291 },
3292 fail_on_empty=False,
3293 )
aticig285185e2022-05-02 21:23:48 +03003294
palaciosj8f2060b2022-02-24 12:05:59 +00003295 step = "Updating database, Appending tasks to ro_tasks"
3296 self.upload_recreate_tasks(
3297 db_new_tasks=db_new_tasks,
3298 now=now,
3299 )
3300
3301 self.logger.debug(
3302 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3303 )
3304
3305 return (
3306 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3307 action_id,
3308 True,
3309 )
3310 except Exception as e:
3311 if isinstance(e, (DbException, NsException)):
3312 self.logger.error(
3313 logging_text + "Exit Exception while '{}': {}".format(step, e)
3314 )
3315 else:
3316 e = traceback_format_exc()
3317 self.logger.critical(
3318 logging_text + "Exit Exception while '{}': {}".format(step, e),
3319 exc_info=True,
3320 )
3321
3322 raise NsException(e)
3323
tierno1d213f42020-04-24 14:02:51 +00003324 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +00003325 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
tierno1d213f42020-04-24 14:02:51 +00003326 validate_input(indata, deploy_schema)
3327 action_id = indata.get("action_id", str(uuid4()))
3328 task_index = 0
3329 # get current deployment
sousaedu80135b92021-02-17 15:05:18 +01003330 db_nsr_update = {} # update operation on nsrs
tierno1d213f42020-04-24 14:02:51 +00003331 db_vnfrs_update = {}
sousaedu80135b92021-02-17 15:05:18 +01003332 db_vnfrs = {} # vnf's info indexed by _id
sousaedu80135b92021-02-17 15:05:18 +01003333 step = ""
tierno1d213f42020-04-24 14:02:51 +00003334 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3335 self.logger.debug(logging_text + "Enter")
sousaedu80135b92021-02-17 15:05:18 +01003336
tierno1d213f42020-04-24 14:02:51 +00003337 try:
3338 step = "Getting ns and vnfr record from db"
tierno1d213f42020-04-24 14:02:51 +00003339 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
palaciosj8f2060b2022-02-24 12:05:59 +00003340 self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr))
tierno1d213f42020-04-24 14:02:51 +00003341 db_new_tasks = []
tierno70eeb182020-10-19 16:38:00 +00003342 tasks_by_target_record_id = {}
tierno1d213f42020-04-24 14:02:51 +00003343 # read from db: vnf's of this ns
3344 step = "Getting vnfrs from db"
3345 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
sousaedu80135b92021-02-17 15:05:18 +01003346
tierno1d213f42020-04-24 14:02:51 +00003347 if not db_vnfrs_list:
3348 raise NsException("Cannot obtain associated VNF for ns")
sousaedu80135b92021-02-17 15:05:18 +01003349
tierno1d213f42020-04-24 14:02:51 +00003350 for vnfr in db_vnfrs_list:
3351 db_vnfrs[vnfr["_id"]] = vnfr
3352 db_vnfrs_update[vnfr["_id"]] = {}
palaciosj8f2060b2022-02-24 12:05:59 +00003353 self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs))
sousaedu80135b92021-02-17 15:05:18 +01003354
tierno1d213f42020-04-24 14:02:51 +00003355 now = time()
3356 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
sousaedu80135b92021-02-17 15:05:18 +01003357
tierno1d213f42020-04-24 14:02:51 +00003358 if not db_ro_nsr:
3359 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
sousaedu80135b92021-02-17 15:05:18 +01003360
tierno1d213f42020-04-24 14:02:51 +00003361 # check that action_id is not in the list of actions. Suffixed with :index
3362 if action_id in db_ro_nsr["actions"]:
3363 index = 1
sousaedu80135b92021-02-17 15:05:18 +01003364
tierno1d213f42020-04-24 14:02:51 +00003365 while True:
3366 new_action_id = "{}:{}".format(action_id, index)
sousaedu80135b92021-02-17 15:05:18 +01003367
tierno1d213f42020-04-24 14:02:51 +00003368 if new_action_id not in db_ro_nsr["actions"]:
3369 action_id = new_action_id
sousaedu80135b92021-02-17 15:05:18 +01003370 self.logger.debug(
3371 logging_text
3372 + "Changing action_id in use to {}".format(action_id)
3373 )
tierno1d213f42020-04-24 14:02:51 +00003374 break
sousaedu80135b92021-02-17 15:05:18 +01003375
tierno1d213f42020-04-24 14:02:51 +00003376 index += 1
3377
tierno1d213f42020-04-24 14:02:51 +00003378 def _process_action(indata):
tierno1d213f42020-04-24 14:02:51 +00003379 nonlocal db_new_tasks
sousaedu89278b82021-11-19 01:01:32 +00003380 nonlocal action_id
3381 nonlocal nsr_id
tierno1d213f42020-04-24 14:02:51 +00003382 nonlocal task_index
3383 nonlocal db_vnfrs
3384 nonlocal db_ro_nsr
3385
tierno70eeb182020-10-19 16:38:00 +00003386 if indata["action"]["action"] == "inject_ssh_key":
3387 key = indata["action"].get("key")
3388 user = indata["action"].get("user")
3389 password = indata["action"].get("password")
sousaedu80135b92021-02-17 15:05:18 +01003390
tierno1d213f42020-04-24 14:02:51 +00003391 for vnf in indata.get("vnf", ()):
tierno70eeb182020-10-19 16:38:00 +00003392 if vnf["_id"] not in db_vnfrs:
tierno1d213f42020-04-24 14:02:51 +00003393 raise NsException("Invalid vnf={}".format(vnf["_id"]))
sousaedu80135b92021-02-17 15:05:18 +01003394
tierno1d213f42020-04-24 14:02:51 +00003395 db_vnfr = db_vnfrs[vnf["_id"]]
sousaedu80135b92021-02-17 15:05:18 +01003396
tierno1d213f42020-04-24 14:02:51 +00003397 for target_vdu in vnf.get("vdur", ()):
sousaedu80135b92021-02-17 15:05:18 +01003398 vdu_index, vdur = next(
3399 (
3400 i_v
3401 for i_v in enumerate(db_vnfr["vdur"])
3402 if i_v[1]["id"] == target_vdu["id"]
3403 ),
3404 (None, None),
3405 )
3406
tierno1d213f42020-04-24 14:02:51 +00003407 if not vdur:
sousaedu80135b92021-02-17 15:05:18 +01003408 raise NsException(
3409 "Invalid vdu vnf={}.{}".format(
3410 vnf["_id"], target_vdu["id"]
3411 )
3412 )
3413
3414 target_vim, vim_info = next(
3415 k_v for k_v in vdur["vim_info"].items()
3416 )
tierno86153522020-12-06 18:27:16 +00003417 self._assign_vim(target_vim)
sousaedu80135b92021-02-17 15:05:18 +01003418 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
3419 vnf["_id"], vdu_index
3420 )
tierno1d213f42020-04-24 14:02:51 +00003421 extra_dict = {
sousaedu80135b92021-02-17 15:05:18 +01003422 "depends_on": [
3423 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
3424 ],
tierno1d213f42020-04-24 14:02:51 +00003425 "params": {
tierno70eeb182020-10-19 16:38:00 +00003426 "ip_address": vdur.get("ip-address"),
tierno1d213f42020-04-24 14:02:51 +00003427 "user": user,
3428 "key": key,
3429 "password": password,
3430 "private_key": db_ro_nsr["private_key"],
3431 "salt": db_ro_nsr["_id"],
sousaedu80135b92021-02-17 15:05:18 +01003432 "schema_version": db_ro_nsr["_admin"][
3433 "schema_version"
3434 ],
3435 },
tierno1d213f42020-04-24 14:02:51 +00003436 }
sousaedu89278b82021-11-19 01:01:32 +00003437
3438 deployment_info = {
3439 "action_id": action_id,
3440 "nsr_id": nsr_id,
3441 "task_index": task_index,
3442 }
3443
3444 task = Ns._create_task(
3445 deployment_info=deployment_info,
3446 target_id=target_vim,
3447 item="vdu",
3448 action="EXEC",
sousaedu80135b92021-02-17 15:05:18 +01003449 target_record=target_record,
3450 target_record_id=None,
3451 extra_dict=extra_dict,
3452 )
sousaedu89278b82021-11-19 01:01:32 +00003453
3454 task_index = deployment_info.get("task_index")
3455
tierno70eeb182020-10-19 16:38:00 +00003456 db_new_tasks.append(task)
tierno1d213f42020-04-24 14:02:51 +00003457
3458 with self.write_lock:
3459 if indata.get("action"):
3460 _process_action(indata)
3461 else:
3462 # compute network differences
gallardoa1c2b402022-02-11 12:41:59 +00003463 # NS
3464 step = "process NS elements"
3465 changes_list = self.calculate_all_differences_to_deploy(
3466 indata=indata,
3467 nsr_id=nsr_id,
3468 db_nsr=db_nsr,
3469 db_vnfrs=db_vnfrs,
3470 db_ro_nsr=db_ro_nsr,
3471 db_nsr_update=db_nsr_update,
3472 db_vnfrs_update=db_vnfrs_update,
3473 action_id=action_id,
3474 tasks_by_target_record_id=tasks_by_target_record_id,
3475 )
kayal200153f34cf2024-03-14 22:33:28 +05303476 self._remove_old_ro_tasks(nsr_id, changes_list, "task_id")
gallardoa1c2b402022-02-11 12:41:59 +00003477 self.define_all_tasks(
3478 changes_list=changes_list,
3479 db_new_tasks=db_new_tasks,
3480 tasks_by_target_record_id=tasks_by_target_record_id,
sousaedu80135b92021-02-17 15:05:18 +01003481 )
tierno1d213f42020-04-24 14:02:51 +00003482
gallardoa1c2b402022-02-11 12:41:59 +00003483 step = "Updating database, Appending tasks to ro_tasks"
3484 self.upload_all_tasks(
3485 db_new_tasks=db_new_tasks,
3486 now=now,
3487 )
sousaedu80135b92021-02-17 15:05:18 +01003488
tierno1d213f42020-04-24 14:02:51 +00003489 step = "Updating database, nsrs"
3490 if db_nsr_update:
3491 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
sousaedu80135b92021-02-17 15:05:18 +01003492
tierno1d213f42020-04-24 14:02:51 +00003493 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
3494 if db_vnfr_update:
3495 step = "Updating database, vnfrs={}".format(vnfr_id)
3496 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
3497
sousaedu80135b92021-02-17 15:05:18 +01003498 self.logger.debug(
gallardoa1c2b402022-02-11 12:41:59 +00003499 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
sousaedu80135b92021-02-17 15:05:18 +01003500 )
tierno1d213f42020-04-24 14:02:51 +00003501
sousaedu80135b92021-02-17 15:05:18 +01003502 return (
3503 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3504 action_id,
3505 True,
3506 )
tierno1d213f42020-04-24 14:02:51 +00003507 except Exception as e:
3508 if isinstance(e, (DbException, NsException)):
sousaedu80135b92021-02-17 15:05:18 +01003509 self.logger.error(
3510 logging_text + "Exit Exception while '{}': {}".format(step, e)
3511 )
tierno1d213f42020-04-24 14:02:51 +00003512 else:
3513 e = traceback_format_exc()
sousaedu80135b92021-02-17 15:05:18 +01003514 self.logger.critical(
3515 logging_text + "Exit Exception while '{}': {}".format(step, e),
3516 exc_info=True,
3517 )
3518
tierno1d213f42020-04-24 14:02:51 +00003519 raise NsException(e)
3520
3521 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +00003522 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
tierno1d213f42020-04-24 14:02:51 +00003523 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
sousaedu80135b92021-02-17 15:05:18 +01003524
tierno70eeb182020-10-19 16:38:00 +00003525 with self.write_lock:
3526 try:
3527 NsWorker.delete_db_tasks(self.db, nsr_id, None)
3528 except NsWorkerException as e:
3529 raise NsException(e)
sousaedu80135b92021-02-17 15:05:18 +01003530
tierno1d213f42020-04-24 14:02:51 +00003531 return None, None, True
3532
3533 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
palaciosj8f2060b2022-02-24 12:05:59 +00003534 self.logger.debug(
3535 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
3536 version, nsr_id, action_id, indata
3537 )
3538 )
tierno1d213f42020-04-24 14:02:51 +00003539 task_list = []
3540 done = 0
3541 total = 0
3542 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
3543 global_status = "DONE"
3544 details = []
sousaedu80135b92021-02-17 15:05:18 +01003545
tierno1d213f42020-04-24 14:02:51 +00003546 for ro_task in ro_tasks:
3547 for task in ro_task["tasks"]:
tierno70eeb182020-10-19 16:38:00 +00003548 if task and task["action_id"] == action_id:
tierno1d213f42020-04-24 14:02:51 +00003549 task_list.append(task)
3550 total += 1
sousaedu80135b92021-02-17 15:05:18 +01003551
tierno1d213f42020-04-24 14:02:51 +00003552 if task["status"] == "FAILED":
3553 global_status = "FAILED"
sousaedu80135b92021-02-17 15:05:18 +01003554 error_text = "Error at {} {}: {}".format(
3555 task["action"].lower(),
3556 task["item"],
aticig79ac6df2022-05-06 16:09:52 +03003557 ro_task["vim_info"].get("vim_message") or "unknown",
sousaedu80135b92021-02-17 15:05:18 +01003558 )
tierno70eeb182020-10-19 16:38:00 +00003559 details.append(error_text)
tierno1d213f42020-04-24 14:02:51 +00003560 elif task["status"] in ("SCHEDULED", "BUILD"):
3561 if global_status != "FAILED":
3562 global_status = "BUILD"
3563 else:
3564 done += 1
sousaedu80135b92021-02-17 15:05:18 +01003565
tierno1d213f42020-04-24 14:02:51 +00003566 return_data = {
3567 "status": global_status,
garciadeblasaca8cb52023-12-21 16:28:15 +01003568 "details": (
3569 ". ".join(details) if details else "progress {}/{}".format(done, total)
3570 ),
tierno1d213f42020-04-24 14:02:51 +00003571 "nsr_id": nsr_id,
3572 "action_id": action_id,
sousaedu80135b92021-02-17 15:05:18 +01003573 "tasks": task_list,
tierno1d213f42020-04-24 14:02:51 +00003574 }
sousaedu80135b92021-02-17 15:05:18 +01003575
tierno1d213f42020-04-24 14:02:51 +00003576 return return_data, None, True
3577
palaciosj8f2060b2022-02-24 12:05:59 +00003578 def recreate_status(
3579 self, session, indata, version, nsr_id, action_id, *args, **kwargs
3580 ):
3581 return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
3582
tierno1d213f42020-04-24 14:02:51 +00003583 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
sousaedu80135b92021-02-17 15:05:18 +01003584 print(
3585 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
3586 session, indata, version, nsr_id, action_id
3587 )
3588 )
3589
tierno1d213f42020-04-24 14:02:51 +00003590 return None, None, True
3591
k4.rahul78f474e2022-05-02 15:47:57 +00003592 def rebuild_start_stop_task(
3593 self,
3594 vdu_id,
3595 vnf_id,
3596 vdu_index,
3597 action_id,
3598 nsr_id,
3599 task_index,
3600 target_vim,
3601 extra_dict,
3602 ):
3603 self._assign_vim(target_vim)
Patricia Reinoso17852162023-06-15 07:33:04 +00003604 target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3605 vnf_id, vdu_index, target_vim
3606 )
k4.rahul78f474e2022-05-02 15:47:57 +00003607 target_record_id = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_id)
3608 deployment_info = {
3609 "action_id": action_id,
3610 "nsr_id": nsr_id,
3611 "task_index": task_index,
3612 }
3613
3614 task = Ns._create_task(
3615 deployment_info=deployment_info,
3616 target_id=target_vim,
3617 item="update",
3618 action="EXEC",
3619 target_record=target_record,
3620 target_record_id=target_record_id,
3621 extra_dict=extra_dict,
3622 )
3623 return task
3624
3625 def rebuild_start_stop(
3626 self, session, action_dict, version, nsr_id, *args, **kwargs
3627 ):
3628 task_index = 0
3629 extra_dict = {}
3630 now = time()
3631 action_id = action_dict.get("action_id", str(uuid4()))
3632 step = ""
3633 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3634 self.logger.debug(logging_text + "Enter")
3635
3636 action = list(action_dict.keys())[0]
3637 task_dict = action_dict.get(action)
3638 vim_vm_id = action_dict.get(action).get("vim_vm_id")
3639
3640 if action_dict.get("stop"):
3641 action = "shutoff"
3642 db_new_tasks = []
3643 try:
3644 step = "lock the operation & do task creation"
3645 with self.write_lock:
3646 extra_dict["params"] = {
3647 "vim_vm_id": vim_vm_id,
3648 "action": action,
3649 }
3650 task = self.rebuild_start_stop_task(
3651 task_dict["vdu_id"],
3652 task_dict["vnf_id"],
3653 task_dict["vdu_index"],
3654 action_id,
3655 nsr_id,
3656 task_index,
3657 task_dict["target_vim"],
3658 extra_dict,
3659 )
3660 db_new_tasks.append(task)
3661 step = "upload Task to db"
3662 self.upload_all_tasks(
3663 db_new_tasks=db_new_tasks,
3664 now=now,
3665 )
3666 self.logger.debug(
3667 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3668 )
3669 return (
3670 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3671 action_id,
3672 True,
3673 )
3674 except Exception as e:
3675 if isinstance(e, (DbException, NsException)):
3676 self.logger.error(
3677 logging_text + "Exit Exception while '{}': {}".format(step, e)
3678 )
3679 else:
3680 e = traceback_format_exc()
3681 self.logger.critical(
3682 logging_text + "Exit Exception while '{}': {}".format(step, e),
3683 exc_info=True,
3684 )
3685 raise NsException(e)
3686
tierno1d213f42020-04-24 14:02:51 +00003687 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
3688 nsrs = self.db.get_list("nsrs", {})
3689 return_data = []
sousaedu80135b92021-02-17 15:05:18 +01003690
tierno1d213f42020-04-24 14:02:51 +00003691 for ns in nsrs:
3692 return_data.append({"_id": ns["_id"], "name": ns["name"]})
sousaedu80135b92021-02-17 15:05:18 +01003693
tierno1d213f42020-04-24 14:02:51 +00003694 return return_data, None, True
3695
3696 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
3697 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
3698 return_data = []
sousaedu80135b92021-02-17 15:05:18 +01003699
tierno1d213f42020-04-24 14:02:51 +00003700 for ro_task in ro_tasks:
3701 for task in ro_task["tasks"]:
3702 if task["action_id"] not in return_data:
3703 return_data.append(task["action_id"])
sousaedu80135b92021-02-17 15:05:18 +01003704
tierno1d213f42020-04-24 14:02:51 +00003705 return return_data, None, True
elumalai8658c2c2022-04-28 19:09:31 +05303706
3707 def migrate_task(
3708 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3709 ):
3710 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3711 self._assign_vim(target_vim)
Patricia Reinoso17852162023-06-15 07:33:04 +00003712 target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3713 vnf["_id"], vdu_index, target_vim
3714 )
elumalai8658c2c2022-04-28 19:09:31 +05303715 target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3716 deployment_info = {
3717 "action_id": action_id,
3718 "nsr_id": nsr_id,
3719 "task_index": task_index,
3720 }
3721
3722 task = Ns._create_task(
3723 deployment_info=deployment_info,
3724 target_id=target_vim,
3725 item="migrate",
3726 action="EXEC",
3727 target_record=target_record,
3728 target_record_id=target_record_id,
3729 extra_dict=extra_dict,
3730 )
3731
3732 return task
3733
3734 def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
3735 task_index = 0
3736 extra_dict = {}
3737 now = time()
3738 action_id = indata.get("action_id", str(uuid4()))
3739 step = ""
3740 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3741 self.logger.debug(logging_text + "Enter")
3742 try:
3743 vnf_instance_id = indata["vnfInstanceId"]
3744 step = "Getting vnfrs from db"
3745 db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3746 vdu = indata.get("vdu")
3747 migrateToHost = indata.get("migrateToHost")
3748 db_new_tasks = []
3749
3750 with self.write_lock:
3751 if vdu is not None:
3752 vdu_id = indata["vdu"]["vduId"]
3753 vdu_count_index = indata["vdu"].get("vduCountIndex", 0)
3754 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3755 if (
3756 vdu["vdu-id-ref"] == vdu_id
3757 and vdu["count-index"] == vdu_count_index
3758 ):
3759 extra_dict["params"] = {
3760 "vim_vm_id": vdu["vim-id"],
3761 "migrate_host": migrateToHost,
3762 "vdu_vim_info": vdu["vim_info"],
3763 }
3764 step = "Creating migration task for vdu:{}".format(vdu)
3765 task = self.migrate_task(
3766 vdu,
3767 db_vnfr,
3768 vdu_index,
3769 action_id,
3770 nsr_id,
3771 task_index,
3772 extra_dict,
3773 )
3774 db_new_tasks.append(task)
3775 task_index += 1
3776 break
3777 else:
elumalai8658c2c2022-04-28 19:09:31 +05303778 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3779 extra_dict["params"] = {
3780 "vim_vm_id": vdu["vim-id"],
3781 "migrate_host": migrateToHost,
3782 "vdu_vim_info": vdu["vim_info"],
3783 }
3784 step = "Creating migration task for vdu:{}".format(vdu)
3785 task = self.migrate_task(
3786 vdu,
3787 db_vnfr,
3788 vdu_index,
3789 action_id,
3790 nsr_id,
3791 task_index,
3792 extra_dict,
3793 )
3794 db_new_tasks.append(task)
3795 task_index += 1
3796
3797 self.upload_all_tasks(
3798 db_new_tasks=db_new_tasks,
3799 now=now,
3800 )
3801
3802 self.logger.debug(
3803 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3804 )
3805 return (
3806 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3807 action_id,
3808 True,
3809 )
3810 except Exception as e:
3811 if isinstance(e, (DbException, NsException)):
3812 self.logger.error(
3813 logging_text + "Exit Exception while '{}': {}".format(step, e)
3814 )
3815 else:
3816 e = traceback_format_exc()
3817 self.logger.critical(
3818 logging_text + "Exit Exception while '{}': {}".format(step, e),
3819 exc_info=True,
3820 )
3821 raise NsException(e)
sritharan29a4c1a2022-05-05 12:15:04 +00003822
3823 def verticalscale_task(
3824 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3825 ):
3826 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3827 self._assign_vim(target_vim)
Rahul Kumar06e914f2023-11-08 06:25:06 +00003828 ns_preffix = "nsrs:{}".format(nsr_id)
3829 flavor_text = ns_preffix + ":flavor." + vdu["ns-flavor-id"]
3830 extra_dict["depends_on"] = [flavor_text]
3831 extra_dict["params"].update({"flavor_id": "TASK-" + flavor_text})
Patricia Reinoso17852162023-06-15 07:33:04 +00003832 target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3833 vnf["_id"], vdu_index, target_vim
3834 )
sritharan29a4c1a2022-05-05 12:15:04 +00003835 target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3836 deployment_info = {
3837 "action_id": action_id,
3838 "nsr_id": nsr_id,
3839 "task_index": task_index,
3840 }
3841
3842 task = Ns._create_task(
3843 deployment_info=deployment_info,
3844 target_id=target_vim,
3845 item="verticalscale",
3846 action="EXEC",
3847 target_record=target_record,
3848 target_record_id=target_record_id,
3849 extra_dict=extra_dict,
3850 )
3851 return task
3852
Rahul Kumar06e914f2023-11-08 06:25:06 +00003853 def verticalscale_flavor_task(
3854 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3855 ):
3856 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3857 self._assign_vim(target_vim)
3858 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3859 target_record = "nsrs:{}:flavor.{}.vim_info.{}".format(
3860 nsr_id, len(db_nsr["flavor"]) - 1, target_vim
3861 )
3862 target_record_id = "nsrs:{}:flavor.{}".format(nsr_id, len(db_nsr["flavor"]) - 1)
3863 deployment_info = {
3864 "action_id": action_id,
3865 "nsr_id": nsr_id,
3866 "task_index": task_index,
3867 }
3868 task = Ns._create_task(
3869 deployment_info=deployment_info,
3870 target_id=target_vim,
3871 item="flavor",
3872 action="CREATE",
3873 target_record=target_record,
3874 target_record_id=target_record_id,
3875 extra_dict=extra_dict,
3876 )
3877 return task
3878
sritharan29a4c1a2022-05-05 12:15:04 +00003879 def verticalscale(self, session, indata, version, nsr_id, *args, **kwargs):
3880 task_index = 0
3881 extra_dict = {}
Rahul Kumar06e914f2023-11-08 06:25:06 +00003882 flavor_extra_dict = {}
sritharan29a4c1a2022-05-05 12:15:04 +00003883 now = time()
3884 action_id = indata.get("action_id", str(uuid4()))
3885 step = ""
3886 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3887 self.logger.debug(logging_text + "Enter")
3888 try:
3889 VnfFlavorData = indata.get("changeVnfFlavorData")
3890 vnf_instance_id = VnfFlavorData["vnfInstanceId"]
3891 step = "Getting vnfrs from db"
3892 db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3893 vduid = VnfFlavorData["additionalParams"]["vduid"]
3894 vduCountIndex = VnfFlavorData["additionalParams"]["vduCountIndex"]
3895 virtualMemory = VnfFlavorData["additionalParams"]["virtualMemory"]
3896 numVirtualCpu = VnfFlavorData["additionalParams"]["numVirtualCpu"]
3897 sizeOfStorage = VnfFlavorData["additionalParams"]["sizeOfStorage"]
3898 flavor_dict = {
3899 "name": vduid + "-flv",
3900 "ram": virtualMemory,
3901 "vcpus": numVirtualCpu,
3902 "disk": sizeOfStorage,
3903 }
Rahul Kumar06e914f2023-11-08 06:25:06 +00003904 flavor_data = {
3905 "ram": virtualMemory,
3906 "vcpus": numVirtualCpu,
3907 "disk": sizeOfStorage,
3908 }
3909 flavor_extra_dict["find_params"] = {"flavor_data": flavor_data}
3910 flavor_extra_dict["params"] = {"flavor_data": flavor_dict}
sritharan29a4c1a2022-05-05 12:15:04 +00003911 db_new_tasks = []
3912 step = "Creating Tasks for vertical scaling"
3913 with self.write_lock:
3914 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3915 if (
3916 vdu["vdu-id-ref"] == vduid
3917 and vdu["count-index"] == vduCountIndex
3918 ):
3919 extra_dict["params"] = {
3920 "vim_vm_id": vdu["vim-id"],
3921 "flavor_dict": flavor_dict,
Rahul Kumar06e914f2023-11-08 06:25:06 +00003922 "vdu-id-ref": vdu["vdu-id-ref"],
3923 "count-index": vdu["count-index"],
3924 "vnf_instance_id": vnf_instance_id,
sritharan29a4c1a2022-05-05 12:15:04 +00003925 }
Rahul Kumar06e914f2023-11-08 06:25:06 +00003926 task = self.verticalscale_flavor_task(
3927 vdu,
3928 db_vnfr,
3929 vdu_index,
3930 action_id,
3931 nsr_id,
3932 task_index,
3933 flavor_extra_dict,
3934 )
3935 db_new_tasks.append(task)
3936 task_index += 1
sritharan29a4c1a2022-05-05 12:15:04 +00003937 task = self.verticalscale_task(
3938 vdu,
3939 db_vnfr,
3940 vdu_index,
3941 action_id,
3942 nsr_id,
3943 task_index,
3944 extra_dict,
3945 )
3946 db_new_tasks.append(task)
3947 task_index += 1
3948 break
3949 self.upload_all_tasks(
3950 db_new_tasks=db_new_tasks,
3951 now=now,
3952 )
3953 self.logger.debug(
3954 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3955 )
3956 return (
3957 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3958 action_id,
3959 True,
3960 )
3961 except Exception as e:
3962 if isinstance(e, (DbException, NsException)):
3963 self.logger.error(
3964 logging_text + "Exit Exception while '{}': {}".format(step, e)
3965 )
3966 else:
3967 e = traceback_format_exc()
3968 self.logger.critical(
3969 logging_text + "Exit Exception while '{}': {}".format(step, e),
3970 exc_info=True,
3971 )
3972 raise NsException(e)