blob: b73cf5233aa3792bae243b359dd048a7d374bd5b [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
858 if (
859 root_disk.get("type-of-storage")
860 == "persistent-storage:persistent-storage"
861 ):
862 flavor_data["disk"] = 0
863
sousaedu686720b2021-11-24 02:16:11 +0000864 for storage in target_vdur.get("virtual-storages", []):
865 if (
866 storage.get("type-of-storage")
867 == "etsi-nfv-descriptors:ephemeral-storage"
868 ):
869 flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0))
870 elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
871 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
872
873 extended = Ns._process_epa_params(target_flavor)
874 if extended:
875 flavor_data["extended"] = extended
876
877 extra_dict = {"find_params": {"flavor_data": flavor_data}}
878 flavor_data_name = flavor_data.copy()
879 flavor_data_name["name"] = target_flavor["name"]
880 extra_dict["params"] = {"flavor_data": flavor_data_name}
sousaedu686720b2021-11-24 02:16:11 +0000881 return extra_dict
882
sousaedua4bac082021-12-05 19:31:03 +0000883 @staticmethod
Lovejeet Singhdf486552023-05-09 22:41:09 +0530884 def _prefix_ip_address(ip_address):
885 if "/" not in ip_address:
886 ip_address += "/32"
887 return ip_address
888
889 @staticmethod
890 def _process_ip_proto(ip_proto):
891 if ip_proto:
892 if ip_proto == 1:
893 ip_proto = "icmp"
894 elif ip_proto == 6:
895 ip_proto = "tcp"
896 elif ip_proto == 17:
897 ip_proto = "udp"
898 return ip_proto
899
900 @staticmethod
901 def _process_classification_params(
902 target_classification: Dict[str, Any],
903 indata: Dict[str, Any],
904 vim_info: Dict[str, Any],
905 target_record_id: str,
906 **kwargs: Dict[str, Any],
907 ) -> Dict[str, Any]:
908 """[summary]
909
910 Args:
911 target_classification (Dict[str, Any]): Classification dictionary parameters that needs to be processed to create resource on VIM
912 indata (Dict[str, Any]): Deployment info
913 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
914 target_record_id (str): Task record ID.
915 **kwargs (Dict[str, Any]): Used to send additional information to the task.
916
917 Returns:
918 Dict[str, Any]: Return parameters required to create classification and Items on which classification is dependent.
919 """
920 vnfr_id = target_classification["vnfr_id"]
921 vdur_id = target_classification["vdur_id"]
922 port_index = target_classification["ingress_port_index"]
923 extra_dict = {}
924
925 classification_data = {
926 "name": target_classification["id"],
927 "source_port_range_min": target_classification["source-port"],
928 "source_port_range_max": target_classification["source-port"],
929 "destination_port_range_min": target_classification["destination-port"],
930 "destination_port_range_max": target_classification["destination-port"],
931 }
932
933 classification_data["source_ip_prefix"] = Ns._prefix_ip_address(
934 target_classification["source-ip-address"]
935 )
936
937 classification_data["destination_ip_prefix"] = Ns._prefix_ip_address(
938 target_classification["destination-ip-address"]
939 )
940
941 classification_data["protocol"] = Ns._process_ip_proto(
942 int(target_classification["ip-proto"])
943 )
944
945 db = kwargs.get("db")
946 vdu_text = Ns._get_vnfr_vdur_text(db, vnfr_id, vdur_id)
947
948 extra_dict = {"depends_on": [vdu_text]}
949
950 extra_dict = {"depends_on": [vdu_text]}
951 classification_data["logical_source_port"] = "TASK-" + vdu_text
952 classification_data["logical_source_port_index"] = port_index
953
954 extra_dict["params"] = classification_data
955
956 return extra_dict
957
958 @staticmethod
959 def _process_sfi_params(
960 target_sfi: Dict[str, Any],
961 indata: Dict[str, Any],
962 vim_info: Dict[str, Any],
963 target_record_id: str,
964 **kwargs: Dict[str, Any],
965 ) -> Dict[str, Any]:
966 """[summary]
967
968 Args:
969 target_sfi (Dict[str, Any]): SFI dictionary parameters that needs to be processed to create resource on VIM
970 indata (Dict[str, Any]): deployment info
971 vim_info (Dict[str, Any]): To add items created by OSM on the VIM.
972 target_record_id (str): Task record ID.
973 **kwargs (Dict[str, Any]): Used to send additional information to the task.
974
975 Returns:
976 Dict[str, Any]: Return parameters required to create SFI and Items on which SFI is dependent.
977 """
978
979 vnfr_id = target_sfi["vnfr_id"]
980 vdur_id = target_sfi["vdur_id"]
981
982 sfi_data = {
983 "name": target_sfi["id"],
984 "ingress_port_index": target_sfi["ingress_port_index"],
985 "egress_port_index": target_sfi["egress_port_index"],
986 }
987
988 db = kwargs.get("db")
989 vdu_text = Ns._get_vnfr_vdur_text(db, vnfr_id, vdur_id)
990
991 extra_dict = {"depends_on": [vdu_text]}
992 sfi_data["ingress_port"] = "TASK-" + vdu_text
993 sfi_data["egress_port"] = "TASK-" + vdu_text
994
995 extra_dict["params"] = sfi_data
996
997 return extra_dict
998
999 @staticmethod
1000 def _get_vnfr_vdur_text(db, vnfr_id, vdur_id):
1001 vnf_preffix = "vnfrs:{}".format(vnfr_id)
1002 db_vnfr = db.get_one("vnfrs", {"_id": vnfr_id})
1003 vdur_list = []
1004 vdu_text = ""
1005
1006 if db_vnfr:
1007 vdur_list = [
1008 vdur["id"] for vdur in db_vnfr["vdur"] if vdur["vdu-id-ref"] == vdur_id
1009 ]
1010
1011 if vdur_list:
1012 vdu_text = vnf_preffix + ":vdur." + vdur_list[0]
1013
1014 return vdu_text
1015
1016 @staticmethod
1017 def _process_sf_params(
1018 target_sf: Dict[str, Any],
1019 indata: Dict[str, Any],
1020 vim_info: Dict[str, Any],
1021 target_record_id: str,
1022 **kwargs: Dict[str, Any],
1023 ) -> Dict[str, Any]:
1024 """[summary]
1025
1026 Args:
1027 target_sf (Dict[str, Any]): SF dictionary parameters that needs to be processed to create resource on VIM
1028 indata (Dict[str, Any]): Deployment info.
1029 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
1030 target_record_id (str): Task record ID.
1031 **kwargs (Dict[str, Any]): Used to send additional information to the task.
1032
1033 Returns:
1034 Dict[str, Any]: Return parameters required to create SF and Items on which SF is dependent.
1035 """
1036
1037 nsr_id = kwargs.get("nsr_id", "")
1038 sfis = target_sf["sfis"]
1039 ns_preffix = "nsrs:{}".format(nsr_id)
1040 extra_dict = {"depends_on": [], "params": []}
1041 sf_data = {"name": target_sf["id"], "sfis": sfis}
1042
1043 for count, sfi in enumerate(sfis):
1044 sfi_text = ns_preffix + ":sfi." + sfi
1045 sfis[count] = "TASK-" + sfi_text
1046 extra_dict["depends_on"].append(sfi_text)
1047
1048 extra_dict["params"] = sf_data
1049
1050 return extra_dict
1051
1052 @staticmethod
1053 def _process_sfp_params(
1054 target_sfp: Dict[str, Any],
1055 indata: Dict[str, Any],
1056 vim_info: Dict[str, Any],
1057 target_record_id: str,
1058 **kwargs: Dict[str, Any],
1059 ) -> Dict[str, Any]:
1060 """[summary]
1061
1062 Args:
1063 target_sfp (Dict[str, Any]): SFP dictionary parameters that needs to be processed to create resource on VIM.
1064 indata (Dict[str, Any]): Deployment info
1065 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
1066 target_record_id (str): Task record ID.
1067 **kwargs (Dict[str, Any]): Used to send additional information to the task.
1068
1069 Returns:
1070 Dict[str, Any]: Return parameters required to create SFP and Items on which SFP is dependent.
1071 """
1072
1073 nsr_id = kwargs.get("nsr_id")
1074 sfs = target_sfp["sfs"]
1075 classifications = target_sfp["classifications"]
1076 ns_preffix = "nsrs:{}".format(nsr_id)
1077 extra_dict = {"depends_on": [], "params": []}
1078 sfp_data = {
1079 "name": target_sfp["id"],
1080 "sfs": sfs,
1081 "classifications": classifications,
1082 }
1083
1084 for count, sf in enumerate(sfs):
1085 sf_text = ns_preffix + ":sf." + sf
1086 sfs[count] = "TASK-" + sf_text
1087 extra_dict["depends_on"].append(sf_text)
1088
1089 for count, classi in enumerate(classifications):
1090 classi_text = ns_preffix + ":classification." + classi
1091 classifications[count] = "TASK-" + classi_text
1092 extra_dict["depends_on"].append(classi_text)
1093
1094 extra_dict["params"] = sfp_data
1095
1096 return extra_dict
1097
1098 @staticmethod
sousaedu0ee9fdb2021-12-06 00:17:54 +00001099 def _process_net_params(
1100 target_vld: Dict[str, Any],
1101 indata: Dict[str, Any],
1102 vim_info: Dict[str, Any],
1103 target_record_id: str,
sousaedu0b1e7342021-12-07 15:33:46 +00001104 **kwargs: Dict[str, Any],
sousaedu0ee9fdb2021-12-06 00:17:54 +00001105 ) -> Dict[str, Any]:
1106 """Function to process network parameters.
1107
1108 Args:
1109 target_vld (Dict[str, Any]): [description]
1110 indata (Dict[str, Any]): [description]
1111 vim_info (Dict[str, Any]): [description]
1112 target_record_id (str): [description]
1113
1114 Returns:
1115 Dict[str, Any]: [description]
1116 """
1117 extra_dict = {}
1118
1119 if vim_info.get("sdn"):
1120 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
1121 # ns_preffix = "nsrs:{}".format(nsr_id)
1122 # remove the ending ".sdn
1123 vld_target_record_id, _, _ = target_record_id.rpartition(".")
1124 extra_dict["params"] = {
1125 k: vim_info[k]
1126 for k in ("sdn-ports", "target_vim", "vlds", "type")
1127 if vim_info.get(k)
1128 }
1129
1130 # TODO needed to add target_id in the dependency.
1131 if vim_info.get("target_vim"):
1132 extra_dict["depends_on"] = [
1133 f"{vim_info.get('target_vim')} {vld_target_record_id}"
1134 ]
1135
1136 return extra_dict
1137
1138 if vim_info.get("vim_network_name"):
1139 extra_dict["find_params"] = {
1140 "filter_dict": {
1141 "name": vim_info.get("vim_network_name"),
1142 },
1143 }
1144 elif vim_info.get("vim_network_id"):
1145 extra_dict["find_params"] = {
1146 "filter_dict": {
1147 "id": vim_info.get("vim_network_id"),
1148 },
1149 }
Gabriel Cuba0d8ce072022-12-14 18:33:50 -05001150 elif target_vld.get("mgmt-network") and not vim_info.get("provider_network"):
sousaedu0ee9fdb2021-12-06 00:17:54 +00001151 extra_dict["find_params"] = {
1152 "mgmt": True,
1153 "name": target_vld["id"],
1154 }
1155 else:
1156 # create
1157 extra_dict["params"] = {
1158 "net_name": (
1159 f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
1160 ),
Gabriel Cuba4c1dd542023-02-14 12:43:32 -05001161 "ip_profile": vim_info.get("ip_profile"),
sousaedu0ee9fdb2021-12-06 00:17:54 +00001162 "provider_network_profile": vim_info.get("provider_network"),
1163 }
1164
1165 if not target_vld.get("underlay"):
1166 extra_dict["params"]["net_type"] = "bridge"
1167 else:
1168 extra_dict["params"]["net_type"] = (
1169 "ptp" if target_vld.get("type") == "ELINE" else "data"
1170 )
1171
1172 return extra_dict
1173
sousaedu0b1e7342021-12-07 15:33:46 +00001174 @staticmethod
aticigcf14bb12022-05-19 13:03:17 +03001175 def find_persistent_root_volumes(
1176 vnfd: dict,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001177 target_vdu: dict,
aticigcf14bb12022-05-19 13:03:17 +03001178 vdu_instantiation_volumes_list: list,
1179 disk_list: list,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001180 ) -> Dict[str, any]:
aticigcf14bb12022-05-19 13:03:17 +03001181 """Find the persistent root volumes and add them to the disk_list
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001182 by parsing the instantiation parameters.
aticigcf14bb12022-05-19 13:03:17 +03001183
1184 Args:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001185 vnfd (dict): VNF descriptor
1186 target_vdu (dict): processed VDU
1187 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
1188 disk_list (list): to be filled up
aticigcf14bb12022-05-19 13:03:17 +03001189
1190 Returns:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001191 persistent_root_disk (dict): Details of persistent root disk
aticigcf14bb12022-05-19 13:03:17 +03001192
1193 """
1194 persistent_root_disk = {}
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001195 # There can be only one root disk, when we find it, it will return the result
aticigcf14bb12022-05-19 13:03:17 +03001196
1197 for vdu, vsd in product(
1198 vnfd.get("vdu", ()), vnfd.get("virtual-storage-desc", ())
1199 ):
1200 if (
1201 vdu["name"] == target_vdu["vdu-name"]
1202 and vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]
1203 ):
1204 root_disk = vsd
1205 if (
1206 root_disk.get("type-of-storage")
1207 == "persistent-storage:persistent-storage"
1208 ):
1209 for vdu_volume in vdu_instantiation_volumes_list:
aticigcf14bb12022-05-19 13:03:17 +03001210 if (
1211 vdu_volume["vim-volume-id"]
1212 and root_disk["id"] == vdu_volume["name"]
1213 ):
aticigcf14bb12022-05-19 13:03:17 +03001214 persistent_root_disk[vsd["id"]] = {
1215 "vim_volume_id": vdu_volume["vim-volume-id"],
1216 "image_id": vdu.get("sw-image-desc"),
1217 }
1218
1219 disk_list.append(persistent_root_disk[vsd["id"]])
1220
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001221 return persistent_root_disk
aticigcf14bb12022-05-19 13:03:17 +03001222
1223 else:
aticigcf14bb12022-05-19 13:03:17 +03001224 if root_disk.get("size-of-storage"):
1225 persistent_root_disk[vsd["id"]] = {
1226 "image_id": vdu.get("sw-image-desc"),
1227 "size": root_disk.get("size-of-storage"),
aticig2f4ab6c2022-09-03 18:15:20 +03001228 "keep": Ns.is_volume_keeping_required(root_disk),
aticigcf14bb12022-05-19 13:03:17 +03001229 }
1230
1231 disk_list.append(persistent_root_disk[vsd["id"]])
aticigcf14bb12022-05-19 13:03:17 +03001232
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001233 return persistent_root_disk
Luis Vega95e83692023-08-08 00:35:41 +00001234 return persistent_root_disk
aticigcf14bb12022-05-19 13:03:17 +03001235
1236 @staticmethod
1237 def find_persistent_volumes(
1238 persistent_root_disk: dict,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001239 target_vdu: dict,
aticigcf14bb12022-05-19 13:03:17 +03001240 vdu_instantiation_volumes_list: list,
1241 disk_list: list,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001242 ) -> None:
aticigcf14bb12022-05-19 13:03:17 +03001243 """Find the ordinary persistent volumes and add them to the disk_list
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001244 by parsing the instantiation parameters.
aticigcf14bb12022-05-19 13:03:17 +03001245
1246 Args:
1247 persistent_root_disk: persistent root disk dictionary
1248 target_vdu: processed VDU
1249 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1250 disk_list: to be filled up
1251
aticigcf14bb12022-05-19 13:03:17 +03001252 """
1253 # Find the ordinary volumes which are not added to the persistent_root_disk
1254 persistent_disk = {}
1255 for disk in target_vdu.get("virtual-storages", {}):
1256 if (
1257 disk.get("type-of-storage") == "persistent-storage:persistent-storage"
1258 and disk["id"] not in persistent_root_disk.keys()
1259 ):
1260 for vdu_volume in vdu_instantiation_volumes_list:
aticigcf14bb12022-05-19 13:03:17 +03001261 if vdu_volume["vim-volume-id"] and disk["id"] == vdu_volume["name"]:
aticigcf14bb12022-05-19 13:03:17 +03001262 persistent_disk[disk["id"]] = {
1263 "vim_volume_id": vdu_volume["vim-volume-id"],
1264 }
1265 disk_list.append(persistent_disk[disk["id"]])
1266
1267 else:
1268 if disk["id"] not in persistent_disk.keys():
1269 persistent_disk[disk["id"]] = {
1270 "size": disk.get("size-of-storage"),
aticig2f4ab6c2022-09-03 18:15:20 +03001271 "keep": Ns.is_volume_keeping_required(disk),
aticigcf14bb12022-05-19 13:03:17 +03001272 }
1273 disk_list.append(persistent_disk[disk["id"]])
1274
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001275 @staticmethod
aticig2f4ab6c2022-09-03 18:15:20 +03001276 def is_volume_keeping_required(virtual_storage_desc: Dict[str, Any]) -> bool:
1277 """Function to decide keeping persistent volume
1278 upon VDU deletion.
1279
1280 Args:
1281 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1282
1283 Returns:
1284 bool (True/False)
1285 """
1286
1287 if not virtual_storage_desc.get("vdu-storage-requirements"):
1288 return False
1289 for item in virtual_storage_desc.get("vdu-storage-requirements", {}):
vegall364627c2023-03-17 15:09:50 +00001290 if item.get("key") == "keep-volume" and item.get("value").lower() == "true":
aticig2f4ab6c2022-09-03 18:15:20 +03001291 return True
1292 return False
1293
1294 @staticmethod
vegall364627c2023-03-17 15:09:50 +00001295 def is_shared_volume(
1296 virtual_storage_desc: Dict[str, Any], vnfd_id: str
1297 ) -> (str, bool):
1298 """Function to decide if the volume type is multi attached or not .
1299
1300 Args:
1301 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1302 vnfd_id (str): vnfd id
1303
1304 Returns:
1305 bool (True/False)
1306 name (str) New name if it is a multiattach disk
1307 """
1308
1309 if vdu_storage_requirements := virtual_storage_desc.get(
1310 "vdu-storage-requirements", {}
1311 ):
1312 for item in vdu_storage_requirements:
1313 if (
1314 item.get("key") == "multiattach"
1315 and item.get("value").lower() == "true"
1316 ):
1317 name = f"shared-{virtual_storage_desc['id']}-{vnfd_id}"
1318 return name, True
1319 return virtual_storage_desc["id"], False
1320
1321 @staticmethod
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001322 def _sort_vdu_interfaces(target_vdu: dict) -> None:
1323 """Sort the interfaces according to position number.
1324
1325 Args:
1326 target_vdu (dict): Details of VDU to be created
1327
1328 """
1329 # If the position info is provided for all the interfaces, it will be sorted
1330 # according to position number ascendingly.
1331 sorted_interfaces = sorted(
1332 target_vdu["interfaces"],
1333 key=lambda x: (x.get("position") is None, x.get("position")),
1334 )
1335 target_vdu["interfaces"] = sorted_interfaces
1336
1337 @staticmethod
1338 def _partially_locate_vdu_interfaces(target_vdu: dict) -> None:
1339 """Only place the interfaces which has specific position.
1340
1341 Args:
1342 target_vdu (dict): Details of VDU to be created
1343
1344 """
1345 # If the position info is provided for some interfaces but not all of them, the interfaces
1346 # which has specific position numbers will be placed and others' positions will not be taken care.
1347 if any(
1348 i.get("position") + 1
1349 for i in target_vdu["interfaces"]
1350 if i.get("position") is not None
1351 ):
1352 n = len(target_vdu["interfaces"])
1353 sorted_interfaces = [-1] * n
1354 k, m = 0, 0
1355
1356 while k < n:
1357 if target_vdu["interfaces"][k].get("position") is not None:
1358 if any(i.get("position") == 0 for i in target_vdu["interfaces"]):
1359 idx = target_vdu["interfaces"][k]["position"] + 1
1360 else:
1361 idx = target_vdu["interfaces"][k]["position"]
1362 sorted_interfaces[idx - 1] = target_vdu["interfaces"][k]
1363 k += 1
1364
1365 while m < n:
1366 if target_vdu["interfaces"][m].get("position") is None:
1367 idy = sorted_interfaces.index(-1)
1368 sorted_interfaces[idy] = target_vdu["interfaces"][m]
1369 m += 1
1370
1371 target_vdu["interfaces"] = sorted_interfaces
1372
1373 @staticmethod
1374 def _prepare_vdu_cloud_init(
1375 target_vdu: dict, vdu2cloud_init: dict, db: object, fs: object
1376 ) -> Dict:
1377 """Fill cloud_config dict with cloud init details.
1378
1379 Args:
1380 target_vdu (dict): Details of VDU to be created
1381 vdu2cloud_init (dict): Cloud init dict
1382 db (object): DB object
1383 fs (object): FS object
1384
1385 Returns:
1386 cloud_config (dict): Cloud config details of VDU
1387
1388 """
1389 # cloud config
1390 cloud_config = {}
1391
1392 if target_vdu.get("cloud-init"):
1393 if target_vdu["cloud-init"] not in vdu2cloud_init:
1394 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1395 db=db,
1396 fs=fs,
1397 location=target_vdu["cloud-init"],
1398 )
1399
1400 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1401 cloud_config["user-data"] = Ns._parse_jinja2(
1402 cloud_init_content=cloud_content_,
1403 params=target_vdu.get("additionalParams"),
1404 context=target_vdu["cloud-init"],
1405 )
1406
1407 if target_vdu.get("boot-data-drive"):
1408 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1409
1410 return cloud_config
1411
1412 @staticmethod
1413 def _check_vld_information_of_interfaces(
1414 interface: dict, ns_preffix: str, vnf_preffix: str
1415 ) -> Optional[str]:
1416 """Prepare the net_text by the virtual link information for vnf and ns level.
1417 Args:
1418 interface (dict): Interface details
1419 ns_preffix (str): Prefix of NS
1420 vnf_preffix (str): Prefix of VNF
1421
1422 Returns:
1423 net_text (str): information of net
1424
1425 """
1426 net_text = ""
1427 if interface.get("ns-vld-id"):
1428 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
1429 elif interface.get("vnf-vld-id"):
1430 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
1431
1432 return net_text
1433
1434 @staticmethod
1435 def _prepare_interface_port_security(interface: dict) -> None:
1436 """
1437
1438 Args:
1439 interface (dict): Interface details
1440
1441 """
1442 if "port-security-enabled" in interface:
1443 interface["port_security"] = interface.pop("port-security-enabled")
1444
1445 if "port-security-disable-strategy" in interface:
1446 interface["port_security_disable_strategy"] = interface.pop(
1447 "port-security-disable-strategy"
1448 )
1449
1450 @staticmethod
1451 def _create_net_item_of_interface(interface: dict, net_text: str) -> dict:
1452 """Prepare net item including name, port security, floating ip etc.
1453
1454 Args:
1455 interface (dict): Interface details
1456 net_text (str): information of net
1457
1458 Returns:
1459 net_item (dict): Dict including net details
1460
1461 """
1462
1463 net_item = {
1464 x: v
1465 for x, v in interface.items()
1466 if x
1467 in (
1468 "name",
1469 "vpci",
1470 "port_security",
1471 "port_security_disable_strategy",
1472 "floating_ip",
1473 )
1474 }
1475 net_item["net_id"] = "TASK-" + net_text
1476 net_item["type"] = "virtual"
1477
1478 return net_item
1479
1480 @staticmethod
1481 def _prepare_type_of_interface(
1482 interface: dict, tasks_by_target_record_id: dict, net_text: str, net_item: dict
1483 ) -> None:
1484 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1485
1486 Args:
1487 interface (dict): Interface details
1488 tasks_by_target_record_id (dict): Task details
1489 net_text (str): information of net
1490 net_item (dict): Dict including net details
1491
1492 """
1493 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1494 # TODO floating_ip: True/False (or it can be None)
1495
1496 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1497 # Mark the net create task as type data
1498 if deep_get(
1499 tasks_by_target_record_id,
1500 net_text,
1501 "extra_dict",
1502 "params",
1503 "net_type",
1504 ):
1505 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1506 "net_type"
1507 ] = "data"
1508
1509 net_item["use"] = "data"
1510 net_item["model"] = interface["type"]
1511 net_item["type"] = interface["type"]
1512
1513 elif (
1514 interface.get("type") == "OM-MGMT"
1515 or interface.get("mgmt-interface")
1516 or interface.get("mgmt-vnf")
1517 ):
1518 net_item["use"] = "mgmt"
1519
1520 else:
1521 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1522 net_item["use"] = "bridge"
1523 net_item["model"] = interface.get("type")
1524
1525 @staticmethod
1526 def _prepare_vdu_interfaces(
1527 target_vdu: dict,
1528 extra_dict: dict,
1529 ns_preffix: str,
1530 vnf_preffix: str,
1531 logger: object,
1532 tasks_by_target_record_id: dict,
1533 net_list: list,
1534 ) -> None:
1535 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1536
1537 Args:
1538 target_vdu (dict): VDU to be created
1539 extra_dict (dict): Dictionary to be filled
1540 ns_preffix (str): NS prefix as string
1541 vnf_preffix (str): VNF prefix as string
1542 logger (object): Logger Object
1543 tasks_by_target_record_id (dict): Task details
1544 net_list (list): Net list of VDU
1545 """
1546 for iface_index, interface in enumerate(target_vdu["interfaces"]):
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001547 net_text = Ns._check_vld_information_of_interfaces(
1548 interface, ns_preffix, vnf_preffix
1549 )
1550 if not net_text:
1551 # Interface not connected to any vld
1552 logger.error(
1553 "Interface {} from vdu {} not connected to any vld".format(
1554 iface_index, target_vdu["vdu-name"]
1555 )
1556 )
1557 continue
1558
1559 extra_dict["depends_on"].append(net_text)
1560
1561 Ns._prepare_interface_port_security(interface)
1562
1563 net_item = Ns._create_net_item_of_interface(interface, net_text)
1564
1565 Ns._prepare_type_of_interface(
1566 interface, tasks_by_target_record_id, net_text, net_item
1567 )
1568
1569 if interface.get("ip-address"):
1570 net_item["ip_address"] = interface["ip-address"]
1571
1572 if interface.get("mac-address"):
1573 net_item["mac_address"] = interface["mac-address"]
1574
1575 net_list.append(net_item)
1576
1577 if interface.get("mgmt-vnf"):
1578 extra_dict["mgmt_vnf_interface"] = iface_index
1579 elif interface.get("mgmt-interface"):
1580 extra_dict["mgmt_vdu_interface"] = iface_index
1581
1582 @staticmethod
1583 def _prepare_vdu_ssh_keys(
1584 target_vdu: dict, ro_nsr_public_key: dict, cloud_config: dict
1585 ) -> None:
1586 """Add ssh keys to cloud config.
1587
1588 Args:
1589 target_vdu (dict): Details of VDU to be created
1590 ro_nsr_public_key (dict): RO NSR public Key
1591 cloud_config (dict): Cloud config details
1592
1593 """
1594 ssh_keys = []
1595
1596 if target_vdu.get("ssh-keys"):
1597 ssh_keys += target_vdu.get("ssh-keys")
1598
1599 if target_vdu.get("ssh-access-required"):
1600 ssh_keys.append(ro_nsr_public_key)
1601
1602 if ssh_keys:
1603 cloud_config["key-pairs"] = ssh_keys
1604
1605 @staticmethod
1606 def _select_persistent_root_disk(vsd: dict, vdu: dict) -> dict:
1607 """Selects the persistent root disk if exists.
1608 Args:
1609 vsd (dict): Virtual storage descriptors in VNFD
1610 vdu (dict): VNF descriptor
1611
1612 Returns:
1613 root_disk (dict): Selected persistent root disk
1614 """
1615 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1616 root_disk = vsd
1617 if root_disk.get(
1618 "type-of-storage"
1619 ) == "persistent-storage:persistent-storage" and root_disk.get(
1620 "size-of-storage"
1621 ):
1622 return root_disk
1623
1624 @staticmethod
1625 def _add_persistent_root_disk_to_disk_list(
1626 vnfd: dict, target_vdu: dict, persistent_root_disk: dict, disk_list: list
1627 ) -> None:
1628 """Find the persistent root disk and add to disk list.
1629
1630 Args:
1631 vnfd (dict): VNF descriptor
1632 target_vdu (dict): Details of VDU to be created
1633 persistent_root_disk (dict): Details of persistent root disk
1634 disk_list (list): Disks of VDU
1635
1636 """
1637 for vdu in vnfd.get("vdu", ()):
1638 if vdu["name"] == target_vdu["vdu-name"]:
1639 for vsd in vnfd.get("virtual-storage-desc", ()):
1640 root_disk = Ns._select_persistent_root_disk(vsd, vdu)
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001641 if not root_disk:
1642 continue
1643
1644 persistent_root_disk[vsd["id"]] = {
1645 "image_id": vdu.get("sw-image-desc"),
1646 "size": root_disk["size-of-storage"],
aticig2f4ab6c2022-09-03 18:15:20 +03001647 "keep": Ns.is_volume_keeping_required(root_disk),
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001648 }
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001649 disk_list.append(persistent_root_disk[vsd["id"]])
1650 break
1651
1652 @staticmethod
1653 def _add_persistent_ordinary_disks_to_disk_list(
1654 target_vdu: dict,
1655 persistent_root_disk: dict,
1656 persistent_ordinary_disk: dict,
1657 disk_list: list,
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001658 extra_dict: dict,
vegall364627c2023-03-17 15:09:50 +00001659 vnf_id: str = None,
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001660 nsr_id: str = None,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001661 ) -> None:
1662 """Fill the disk list by adding persistent ordinary disks.
1663
1664 Args:
1665 target_vdu (dict): Details of VDU to be created
1666 persistent_root_disk (dict): Details of persistent root disk
1667 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1668 disk_list (list): Disks of VDU
1669
1670 """
1671 if target_vdu.get("virtual-storages"):
1672 for disk in target_vdu["virtual-storages"]:
1673 if (
1674 disk.get("type-of-storage")
1675 == "persistent-storage:persistent-storage"
1676 and disk["id"] not in persistent_root_disk.keys()
1677 ):
vegall364627c2023-03-17 15:09:50 +00001678 name, multiattach = Ns.is_shared_volume(disk, vnf_id)
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001679 persistent_ordinary_disk[disk["id"]] = {
vegall364627c2023-03-17 15:09:50 +00001680 "name": name,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001681 "size": disk["size-of-storage"],
aticig2f4ab6c2022-09-03 18:15:20 +03001682 "keep": Ns.is_volume_keeping_required(disk),
vegall364627c2023-03-17 15:09:50 +00001683 "multiattach": multiattach,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001684 }
1685 disk_list.append(persistent_ordinary_disk[disk["id"]])
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001686 if multiattach: # VDU creation has to wait for shared volumes
1687 extra_dict["depends_on"].append(
1688 f"nsrs:{nsr_id}:shared-volumes.{name}"
1689 )
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001690
1691 @staticmethod
1692 def _prepare_vdu_affinity_group_list(
1693 target_vdu: dict, extra_dict: dict, ns_preffix: str
1694 ) -> List[Dict[str, any]]:
1695 """Process affinity group details to prepare affinity group list.
1696
1697 Args:
1698 target_vdu (dict): Details of VDU to be created
1699 extra_dict (dict): Dictionary to be filled
1700 ns_preffix (str): Prefix as string
1701
1702 Returns:
1703
1704 affinity_group_list (list): Affinity group details
1705
1706 """
1707 affinity_group_list = []
1708
1709 if target_vdu.get("affinity-or-anti-affinity-group-id"):
1710 for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1711 affinity_group = {}
1712 affinity_group_text = (
1713 ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1714 )
1715
1716 if not isinstance(extra_dict.get("depends_on"), list):
1717 raise NsException("Invalid extra_dict format.")
1718
1719 extra_dict["depends_on"].append(affinity_group_text)
1720 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1721 affinity_group_list.append(affinity_group)
1722
1723 return affinity_group_list
aticigcf14bb12022-05-19 13:03:17 +03001724
1725 @staticmethod
sousaedu0b1e7342021-12-07 15:33:46 +00001726 def _process_vdu_params(
1727 target_vdu: Dict[str, Any],
1728 indata: Dict[str, Any],
1729 vim_info: Dict[str, Any],
1730 target_record_id: str,
1731 **kwargs: Dict[str, Any],
1732 ) -> Dict[str, Any]:
1733 """Function to process VDU parameters.
1734
1735 Args:
1736 target_vdu (Dict[str, Any]): [description]
1737 indata (Dict[str, Any]): [description]
1738 vim_info (Dict[str, Any]): [description]
1739 target_record_id (str): [description]
1740
1741 Returns:
1742 Dict[str, Any]: [description]
1743 """
1744 vnfr_id = kwargs.get("vnfr_id")
1745 nsr_id = kwargs.get("nsr_id")
1746 vnfr = kwargs.get("vnfr")
1747 vdu2cloud_init = kwargs.get("vdu2cloud_init")
1748 tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id")
1749 logger = kwargs.get("logger")
1750 db = kwargs.get("db")
1751 fs = kwargs.get("fs")
1752 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1753
1754 vnf_preffix = "vnfrs:{}".format(vnfr_id)
1755 ns_preffix = "nsrs:{}".format(nsr_id)
1756 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
Gabriel Cubaa5233f82023-08-07 18:43:26 -05001757 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
1758 extra_dict = {"depends_on": [image_text, flavor_text]}
sousaedu0b1e7342021-12-07 15:33:46 +00001759 net_list = []
aticig179e0022022-03-29 13:15:45 +03001760 persistent_root_disk = {}
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001761 persistent_ordinary_disk = {}
aticigcf14bb12022-05-19 13:03:17 +03001762 vdu_instantiation_volumes_list = []
aticig179e0022022-03-29 13:15:45 +03001763 disk_list = []
1764 vnfd_id = vnfr["vnfd-id"]
1765 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001766 # If the position info is provided for all the interfaces, it will be sorted
1767 # according to position number ascendingly.
1768 if all(
1769 True if i.get("position") is not None else False
1770 for i in target_vdu["interfaces"]
1771 ):
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001772 Ns._sort_vdu_interfaces(target_vdu)
1773
1774 # If the position info is provided for some interfaces but not all of them, the interfaces
1775 # which has specific position numbers will be placed and others' positions will not be taken care.
1776 else:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001777 Ns._partially_locate_vdu_interfaces(target_vdu)
1778
1779 # If the position info is not provided for the interfaces, interfaces will be attached
1780 # according to the order in the VNFD.
1781 Ns._prepare_vdu_interfaces(
1782 target_vdu,
1783 extra_dict,
1784 ns_preffix,
1785 vnf_preffix,
1786 logger,
1787 tasks_by_target_record_id,
1788 net_list,
1789 )
1790
1791 # cloud config
1792 cloud_config = Ns._prepare_vdu_cloud_init(target_vdu, vdu2cloud_init, db, fs)
1793
1794 # Prepare VDU ssh keys
1795 Ns._prepare_vdu_ssh_keys(target_vdu, ro_nsr_public_key, cloud_config)
1796
aticigcf14bb12022-05-19 13:03:17 +03001797 if target_vdu.get("additionalParams"):
1798 vdu_instantiation_volumes_list = (
Gabriel Cuba730cfaf2023-03-13 22:26:38 -05001799 target_vdu.get("additionalParams").get("OSM", {}).get("vdu_volumes")
aticigcf14bb12022-05-19 13:03:17 +03001800 )
1801
1802 if vdu_instantiation_volumes_list:
aticigcf14bb12022-05-19 13:03:17 +03001803 # Find the root volumes and add to the disk_list
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001804 persistent_root_disk = Ns.find_persistent_root_volumes(
aticigcf14bb12022-05-19 13:03:17 +03001805 vnfd, target_vdu, vdu_instantiation_volumes_list, disk_list
1806 )
1807
1808 # Find the ordinary volumes which are not added to the persistent_root_disk
1809 # and put them to the disk list
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001810 Ns.find_persistent_volumes(
aticigcf14bb12022-05-19 13:03:17 +03001811 persistent_root_disk,
1812 target_vdu,
1813 vdu_instantiation_volumes_list,
1814 disk_list,
1815 )
1816
1817 else:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001818 # Vdu_instantiation_volumes_list is empty
1819 # First get add the persistent root disks to disk_list
1820 Ns._add_persistent_root_disk_to_disk_list(
1821 vnfd, target_vdu, persistent_root_disk, disk_list
1822 )
1823 # Add the persistent non-root disks to disk_list
1824 Ns._add_persistent_ordinary_disks_to_disk_list(
vegall364627c2023-03-17 15:09:50 +00001825 target_vdu,
1826 persistent_root_disk,
1827 persistent_ordinary_disk,
1828 disk_list,
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001829 extra_dict,
vegall364627c2023-03-17 15:09:50 +00001830 vnfd["id"],
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001831 nsr_id,
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001832 )
aticigcf14bb12022-05-19 13:03:17 +03001833
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03001834 affinity_group_list = Ns._prepare_vdu_affinity_group_list(
1835 target_vdu, extra_dict, ns_preffix
1836 )
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001837
kayal2001f81a8652024-06-27 11:04:09 +05301838 instance_name = "{}-{}-{}-{}".format(
1839 indata["name"],
1840 vnfr["member-vnf-index-ref"],
1841 target_vdu["vdu-name"],
1842 target_vdu.get("count-index") or 0,
1843 )
1844 if additional_params := target_vdu.get("additionalParams"):
1845 if additional_params.get("OSM", {}).get("instance_name"):
1846 instance_name = additional_params.get("OSM", {}).get("instance_name")
1847 if count_index := target_vdu.get("count-index"):
1848 if count_index >= 1:
1849 instance_name = "{}-{}".format(instance_name, count_index)
1850
sousaedu0b1e7342021-12-07 15:33:46 +00001851 extra_dict["params"] = {
kayal2001f81a8652024-06-27 11:04:09 +05301852 "name": instance_name,
sousaedu0b1e7342021-12-07 15:33:46 +00001853 "description": target_vdu["vdu-name"],
1854 "start": True,
1855 "image_id": "TASK-" + image_text,
Gabriel Cubaa5233f82023-08-07 18:43:26 -05001856 "flavor_id": "TASK-" + flavor_text,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001857 "affinity_group_list": affinity_group_list,
sousaedu0b1e7342021-12-07 15:33:46 +00001858 "net_list": net_list,
1859 "cloud_config": cloud_config or None,
1860 "disk_list": disk_list,
1861 "availability_zone_index": None, # TODO
1862 "availability_zone_list": None, # TODO
1863 }
vegall364627c2023-03-17 15:09:50 +00001864 return extra_dict
sousaedu0b1e7342021-12-07 15:33:46 +00001865
vegall364627c2023-03-17 15:09:50 +00001866 @staticmethod
1867 def _process_shared_volumes_params(
1868 target_shared_volume: Dict[str, Any],
1869 indata: Dict[str, Any],
1870 vim_info: Dict[str, Any],
1871 target_record_id: str,
1872 **kwargs: Dict[str, Any],
1873 ) -> Dict[str, Any]:
1874 extra_dict = {}
1875 shared_volume_data = {
1876 "size": target_shared_volume["size-of-storage"],
1877 "name": target_shared_volume["id"],
1878 "type": target_shared_volume["type-of-storage"],
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05001879 "keep": Ns.is_volume_keeping_required(target_shared_volume),
vegall364627c2023-03-17 15:09:50 +00001880 }
1881 extra_dict["params"] = shared_volume_data
sousaedu0b1e7342021-12-07 15:33:46 +00001882 return extra_dict
1883
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001884 @staticmethod
1885 def _process_affinity_group_params(
1886 target_affinity_group: Dict[str, Any],
1887 indata: Dict[str, Any],
1888 vim_info: Dict[str, Any],
1889 target_record_id: str,
1890 **kwargs: Dict[str, Any],
1891 ) -> Dict[str, Any]:
1892 """Get affinity or anti-affinity group parameters.
1893
1894 Args:
1895 target_affinity_group (Dict[str, Any]): [description]
1896 indata (Dict[str, Any]): [description]
1897 vim_info (Dict[str, Any]): [description]
1898 target_record_id (str): [description]
1899
1900 Returns:
1901 Dict[str, Any]: [description]
1902 """
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001903
palaciosj8f2060b2022-02-24 12:05:59 +00001904 extra_dict = {}
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001905 affinity_group_data = {
1906 "name": target_affinity_group["name"],
1907 "type": target_affinity_group["type"],
1908 "scope": target_affinity_group["scope"],
1909 }
1910
Alexis Romero123de182022-04-26 19:24:40 +02001911 if target_affinity_group.get("vim-affinity-group-id"):
1912 affinity_group_data["vim-affinity-group-id"] = target_affinity_group[
1913 "vim-affinity-group-id"
1914 ]
1915
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001916 extra_dict["params"] = {
1917 "affinity_group_data": affinity_group_data,
1918 }
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001919 return extra_dict
1920
palaciosj8f2060b2022-02-24 12:05:59 +00001921 @staticmethod
1922 def _process_recreate_vdu_params(
1923 existing_vdu: Dict[str, Any],
1924 db_nsr: Dict[str, Any],
1925 vim_info: Dict[str, Any],
1926 target_record_id: str,
1927 target_id: str,
1928 **kwargs: Dict[str, Any],
1929 ) -> Dict[str, Any]:
1930 """Function to process VDU parameters to recreate.
1931
1932 Args:
1933 existing_vdu (Dict[str, Any]): [description]
1934 db_nsr (Dict[str, Any]): [description]
1935 vim_info (Dict[str, Any]): [description]
1936 target_record_id (str): [description]
1937 target_id (str): [description]
1938
1939 Returns:
1940 Dict[str, Any]: [description]
1941 """
1942 vnfr = kwargs.get("vnfr")
1943 vdu2cloud_init = kwargs.get("vdu2cloud_init")
aticig285185e2022-05-02 21:23:48 +03001944 # logger = kwargs.get("logger")
palaciosj8f2060b2022-02-24 12:05:59 +00001945 db = kwargs.get("db")
1946 fs = kwargs.get("fs")
1947 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1948
1949 extra_dict = {}
1950 net_list = []
1951
1952 vim_details = {}
1953 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
vegall364627c2023-03-17 15:09:50 +00001954
palaciosj8f2060b2022-02-24 12:05:59 +00001955 if vim_details_text:
1956 vim_details = yaml.safe_load(f"{vim_details_text}")
1957
1958 for iface_index, interface in enumerate(existing_vdu["interfaces"]):
palaciosj8f2060b2022-02-24 12:05:59 +00001959 if "port-security-enabled" in interface:
1960 interface["port_security"] = interface.pop("port-security-enabled")
1961
1962 if "port-security-disable-strategy" in interface:
1963 interface["port_security_disable_strategy"] = interface.pop(
1964 "port-security-disable-strategy"
1965 )
1966
1967 net_item = {
1968 x: v
1969 for x, v in interface.items()
1970 if x
1971 in (
1972 "name",
1973 "vpci",
1974 "port_security",
1975 "port_security_disable_strategy",
1976 "floating_ip",
1977 )
1978 }
garciadeblasbf235192022-06-13 10:02:51 +02001979 existing_ifaces = existing_vdu["vim_info"][target_id].get(
1980 "interfaces_backup", []
1981 )
palaciosj8f2060b2022-02-24 12:05:59 +00001982 net_id = next(
aticig285185e2022-05-02 21:23:48 +03001983 (
1984 i["vim_net_id"]
1985 for i in existing_ifaces
1986 if i["ip_address"] == interface["ip-address"]
1987 ),
palaciosj8f2060b2022-02-24 12:05:59 +00001988 None,
1989 )
1990
1991 net_item["net_id"] = net_id
1992 net_item["type"] = "virtual"
1993
1994 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1995 # TODO floating_ip: True/False (or it can be None)
1996 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1997 net_item["use"] = "data"
1998 net_item["model"] = interface["type"]
1999 net_item["type"] = interface["type"]
2000 elif (
2001 interface.get("type") == "OM-MGMT"
2002 or interface.get("mgmt-interface")
2003 or interface.get("mgmt-vnf")
2004 ):
2005 net_item["use"] = "mgmt"
2006 else:
2007 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
2008 net_item["use"] = "bridge"
2009 net_item["model"] = interface.get("type")
2010
2011 if interface.get("ip-address"):
rahulda707572023-08-30 15:06:49 +05302012 dual_ip = interface.get("ip-address").split(";")
2013 if len(dual_ip) == 2:
2014 net_item["ip_address"] = dual_ip
2015 else:
2016 net_item["ip_address"] = interface["ip-address"]
palaciosj8f2060b2022-02-24 12:05:59 +00002017
2018 if interface.get("mac-address"):
2019 net_item["mac_address"] = interface["mac-address"]
2020
2021 net_list.append(net_item)
2022
2023 if interface.get("mgmt-vnf"):
2024 extra_dict["mgmt_vnf_interface"] = iface_index
2025 elif interface.get("mgmt-interface"):
2026 extra_dict["mgmt_vdu_interface"] = iface_index
2027
2028 # cloud config
2029 cloud_config = {}
2030
2031 if existing_vdu.get("cloud-init"):
2032 if existing_vdu["cloud-init"] not in vdu2cloud_init:
2033 vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init(
2034 db=db,
2035 fs=fs,
2036 location=existing_vdu["cloud-init"],
2037 )
2038
2039 cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
2040 cloud_config["user-data"] = Ns._parse_jinja2(
2041 cloud_init_content=cloud_content_,
2042 params=existing_vdu.get("additionalParams"),
2043 context=existing_vdu["cloud-init"],
2044 )
2045
2046 if existing_vdu.get("boot-data-drive"):
2047 cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
2048
2049 ssh_keys = []
2050
2051 if existing_vdu.get("ssh-keys"):
2052 ssh_keys += existing_vdu.get("ssh-keys")
2053
2054 if existing_vdu.get("ssh-access-required"):
2055 ssh_keys.append(ro_nsr_public_key)
2056
2057 if ssh_keys:
2058 cloud_config["key-pairs"] = ssh_keys
2059
2060 disk_list = []
2061 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2062 disk_list.append({"vim_id": vol_id["id"]})
2063
2064 affinity_group_list = []
2065
2066 if existing_vdu.get("affinity-or-anti-affinity-group-id"):
2067 affinity_group = {}
2068 for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]:
2069 for group in db_nsr.get("affinity-or-anti-affinity-group"):
aticig285185e2022-05-02 21:23:48 +03002070 if (
2071 group["id"] == affinity_group_id
2072 and group["vim_info"][target_id].get("vim_id", None) is not None
2073 ):
2074 affinity_group["affinity_group_id"] = group["vim_info"][
2075 target_id
2076 ].get("vim_id", None)
palaciosj8f2060b2022-02-24 12:05:59 +00002077 affinity_group_list.append(affinity_group)
2078
kayal2001f81a8652024-06-27 11:04:09 +05302079 instance_name = "{}-{}-{}-{}".format(
2080 db_nsr["name"],
2081 vnfr["member-vnf-index-ref"],
2082 existing_vdu["vdu-name"],
2083 existing_vdu.get("count-index") or 0,
2084 )
2085 if additional_params := existing_vdu.get("additionalParams"):
2086 if additional_params.get("OSM", {}).get("instance_name"):
2087 instance_name = additional_params.get("OSM", {}).get("instance_name")
2088 if count_index := existing_vdu.get("count-index"):
2089 if count_index >= 1:
2090 instance_name = "{}-{}".format(instance_name, count_index)
2091
palaciosj8f2060b2022-02-24 12:05:59 +00002092 extra_dict["params"] = {
kayal2001f81a8652024-06-27 11:04:09 +05302093 "name": instance_name,
palaciosj8f2060b2022-02-24 12:05:59 +00002094 "description": existing_vdu["vdu-name"],
2095 "start": True,
2096 "image_id": vim_details["image"]["id"],
2097 "flavor_id": vim_details["flavor"]["id"],
2098 "affinity_group_list": affinity_group_list,
2099 "net_list": net_list,
2100 "cloud_config": cloud_config or None,
2101 "disk_list": disk_list,
2102 "availability_zone_index": None, # TODO
2103 "availability_zone_list": None, # TODO
2104 }
2105
2106 return extra_dict
2107
gallardoa1c2b402022-02-11 12:41:59 +00002108 def calculate_diff_items(
2109 self,
2110 indata,
2111 db_nsr,
2112 db_ro_nsr,
2113 db_nsr_update,
2114 item,
2115 tasks_by_target_record_id,
2116 action_id,
2117 nsr_id,
2118 task_index,
2119 vnfr_id=None,
2120 vnfr=None,
2121 ):
2122 """Function that returns the incremental changes (creation, deletion)
2123 related to a specific item `item` to be done. This function should be
2124 called for NS instantiation, NS termination, NS update to add a new VNF
2125 or a new VLD, remove a VNF or VLD, etc.
palaciosj8f2060b2022-02-24 12:05:59 +00002126 Item can be `net`, `flavor`, `image` or `vdu`.
gallardoa1c2b402022-02-11 12:41:59 +00002127 It takes a list of target items from indata (which came from the REST API)
2128 and compares with the existing items from db_ro_nsr, identifying the
2129 incremental changes to be done. During the comparison, it calls the method
2130 `process_params` (which was passed as parameter, and is particular for each
2131 `item`)
2132
2133 Args:
2134 indata (Dict[str, Any]): deployment info
2135 db_nsr: NSR record from DB
2136 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2137 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2138 item (str): element to process (net, vdu...)
2139 tasks_by_target_record_id (Dict[str, Any]):
2140 [<target_record_id>, <task>]
2141 action_id (str): action id
2142 nsr_id (str): NSR id
2143 task_index (number): task index to add to task name
2144 vnfr_id (str): VNFR id
2145 vnfr (Dict[str, Any]): VNFR info
2146
2147 Returns:
2148 List: list with the incremental changes (deletes, creates) for each item
2149 number: current task index
2150 """
2151
2152 diff_items = []
2153 db_path = ""
2154 db_record = ""
2155 target_list = []
2156 existing_list = []
2157 process_params = None
2158 vdu2cloud_init = indata.get("cloud_init_content") or {}
2159 ro_nsr_public_key = db_ro_nsr["public_key"]
gallardoa1c2b402022-02-11 12:41:59 +00002160 # According to the type of item, the path, the target_list,
2161 # the existing_list and the method to process params are set
2162 db_path = self.db_path_map[item]
2163 process_params = self.process_params_function_map[item]
Lovejeet Singhdf486552023-05-09 22:41:09 +05302164
2165 if item in ("sfp", "classification", "sf", "sfi"):
2166 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
2167 target_vnffg = indata.get("vnffg", [])[0]
2168 target_list = target_vnffg[item]
2169 existing_list = db_nsr.get(item, [])
2170 elif item in ("net", "vdu"):
palaciosj8f2060b2022-02-24 12:05:59 +00002171 # This case is specific for the NS VLD (not applied to VDU)
gallardoa1c2b402022-02-11 12:41:59 +00002172 if vnfr is None:
2173 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
aticig2b24d622022-03-11 15:03:55 +03002174 target_list = indata.get("ns", []).get(db_path, [])
gallardoa1c2b402022-02-11 12:41:59 +00002175 existing_list = db_nsr.get(db_path, [])
palaciosj8f2060b2022-02-24 12:05:59 +00002176 # This case is common for VNF VLDs and VNF VDUs
gallardoa1c2b402022-02-11 12:41:59 +00002177 else:
2178 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
2179 target_vnf = next(
2180 (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
2181 None,
2182 )
2183 target_list = target_vnf.get(db_path, []) if target_vnf else []
2184 existing_list = vnfr.get(db_path, [])
vegall364627c2023-03-17 15:09:50 +00002185 elif item in (
2186 "image",
2187 "flavor",
2188 "affinity-or-anti-affinity-group",
2189 "shared-volumes",
2190 ):
gallardoa1c2b402022-02-11 12:41:59 +00002191 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
2192 target_list = indata.get(item, [])
2193 existing_list = db_nsr.get(item, [])
2194 else:
2195 raise NsException("Item not supported: {}", item)
gallardoa1c2b402022-02-11 12:41:59 +00002196 # ensure all the target_list elements has an "id". If not assign the index as id
2197 if target_list is None:
2198 target_list = []
2199 for target_index, tl in enumerate(target_list):
2200 if tl and not tl.get("id"):
2201 tl["id"] = str(target_index)
gallardoa1c2b402022-02-11 12:41:59 +00002202 # step 1 items (networks,vdus,...) to be deleted/updated
2203 for item_index, existing_item in enumerate(existing_list):
2204 target_item = next(
2205 (t for t in target_list if t["id"] == existing_item["id"]),
2206 None,
2207 )
gallardoa1c2b402022-02-11 12:41:59 +00002208 for target_vim, existing_viminfo in existing_item.get(
2209 "vim_info", {}
2210 ).items():
2211 if existing_viminfo is None:
2212 continue
2213
2214 if target_item:
2215 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
2216 else:
2217 target_viminfo = None
2218
2219 if target_viminfo is None:
2220 # must be deleted
2221 self._assign_vim(target_vim)
2222 target_record_id = "{}.{}".format(db_record, existing_item["id"])
2223 item_ = item
2224
gifrerenombf3e9a82022-03-07 17:55:20 +00002225 if target_vim.startswith("sdn") or target_vim.startswith("wim"):
gallardoa1c2b402022-02-11 12:41:59 +00002226 # item must be sdn-net instead of net if target_vim is a sdn
2227 item_ = "sdn_net"
2228 target_record_id += ".sdn"
2229
2230 deployment_info = {
2231 "action_id": action_id,
2232 "nsr_id": nsr_id,
2233 "task_index": task_index,
2234 }
2235
2236 diff_items.append(
2237 {
2238 "deployment_info": deployment_info,
2239 "target_id": target_vim,
2240 "item": item_,
2241 "action": "DELETE",
2242 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
2243 "target_record_id": target_record_id,
2244 }
2245 )
2246 task_index += 1
2247
2248 # step 2 items (networks,vdus,...) to be created
2249 for target_item in target_list:
2250 item_index = -1
gallardoa1c2b402022-02-11 12:41:59 +00002251 for item_index, existing_item in enumerate(existing_list):
2252 if existing_item["id"] == target_item["id"]:
2253 break
2254 else:
2255 item_index += 1
2256 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
2257 existing_list.append(target_item)
2258 existing_item = None
2259
2260 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
2261 existing_viminfo = None
2262
2263 if existing_item:
2264 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
2265
2266 if existing_viminfo is not None:
2267 continue
2268
2269 target_record_id = "{}.{}".format(db_record, target_item["id"])
2270 item_ = item
2271
gifrerenombf3e9a82022-03-07 17:55:20 +00002272 if target_vim.startswith("sdn") or target_vim.startswith("wim"):
gallardoa1c2b402022-02-11 12:41:59 +00002273 # item must be sdn-net instead of net if target_vim is a sdn
2274 item_ = "sdn_net"
2275 target_record_id += ".sdn"
2276
2277 kwargs = {}
aticigddff2b02022-09-03 23:06:37 +03002278 self.logger.debug(
palaciosj8f2060b2022-02-24 12:05:59 +00002279 "ns.calculate_diff_items target_item={}".format(target_item)
2280 )
aticigcf14bb12022-05-19 13:03:17 +03002281 if process_params == Ns._process_flavor_params:
2282 kwargs.update(
2283 {
2284 "db": self.db,
2285 }
2286 )
aticigddff2b02022-09-03 23:06:37 +03002287 self.logger.debug(
aticigcf14bb12022-05-19 13:03:17 +03002288 "calculate_diff_items for flavor kwargs={}".format(kwargs)
2289 )
2290
gallardoa1c2b402022-02-11 12:41:59 +00002291 if process_params == Ns._process_vdu_params:
aticigddff2b02022-09-03 23:06:37 +03002292 self.logger.debug("calculate_diff_items self.fs={}".format(self.fs))
gallardoa1c2b402022-02-11 12:41:59 +00002293 kwargs.update(
2294 {
2295 "vnfr_id": vnfr_id,
2296 "nsr_id": nsr_id,
2297 "vnfr": vnfr,
2298 "vdu2cloud_init": vdu2cloud_init,
2299 "tasks_by_target_record_id": tasks_by_target_record_id,
2300 "logger": self.logger,
2301 "db": self.db,
2302 "fs": self.fs,
2303 "ro_nsr_public_key": ro_nsr_public_key,
2304 }
2305 )
aticigddff2b02022-09-03 23:06:37 +03002306 self.logger.debug("calculate_diff_items kwargs={}".format(kwargs))
Lovejeet Singhdf486552023-05-09 22:41:09 +05302307 if (
2308 process_params == Ns._process_sfi_params
2309 or Ns._process_sf_params
2310 or Ns._process_classification_params
2311 or Ns._process_sfp_params
2312 ):
2313 kwargs.update({"nsr_id": nsr_id, "db": self.db})
2314
2315 self.logger.debug("calculate_diff_items kwargs={}".format(kwargs))
2316
gallardoa1c2b402022-02-11 12:41:59 +00002317 extra_dict = process_params(
2318 target_item,
2319 indata,
2320 target_viminfo,
2321 target_record_id,
2322 **kwargs,
2323 )
2324 self._assign_vim(target_vim)
2325
2326 deployment_info = {
2327 "action_id": action_id,
2328 "nsr_id": nsr_id,
2329 "task_index": task_index,
2330 }
2331
gallardo0108e942022-03-14 18:16:41 +00002332 new_item = {
2333 "deployment_info": deployment_info,
2334 "target_id": target_vim,
2335 "item": item_,
2336 "action": "CREATE",
2337 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
2338 "target_record_id": target_record_id,
2339 "extra_dict": extra_dict,
2340 "common_id": target_item.get("common_id", None),
2341 }
2342 diff_items.append(new_item)
2343 tasks_by_target_record_id[target_record_id] = new_item
gallardoa1c2b402022-02-11 12:41:59 +00002344 task_index += 1
2345
2346 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
2347
2348 return diff_items, task_index
2349
Lovejeet Singhdf486552023-05-09 22:41:09 +05302350 def _process_vnfgd_sfp(self, sfp):
2351 processed_sfp = {}
2352 # getting sfp name, sfs and classifications in sfp to store it in processed_sfp
2353 processed_sfp["id"] = sfp["id"]
2354 sfs_in_sfp = [
2355 sf["id"] for sf in sfp.get("position-desc-id", [])[0].get("cp-profile-id")
2356 ]
2357 classifications_in_sfp = [
2358 classi["id"]
2359 for classi in sfp.get("position-desc-id", [])[0].get("match-attributes")
2360 ]
2361
2362 # creating a list of sfp with sfs and classifications
2363 processed_sfp["sfs"] = sfs_in_sfp
2364 processed_sfp["classifications"] = classifications_in_sfp
2365
2366 return processed_sfp
2367
2368 def _process_vnfgd_sf(self, sf):
2369 processed_sf = {}
2370 # getting name of sf
2371 processed_sf["id"] = sf["id"]
2372 # getting sfis in sf
2373 sfis_in_sf = sf.get("constituent-profile-elements")
2374 sorted_sfis = sorted(sfis_in_sf, key=lambda i: i["order"])
2375 # getting sfis names
2376 processed_sf["sfis"] = [sfi["id"] for sfi in sorted_sfis]
2377
2378 return processed_sf
2379
2380 def _process_vnfgd_sfi(self, sfi, db_vnfrs):
2381 processed_sfi = {}
2382 # getting name of sfi
2383 processed_sfi["id"] = sfi["id"]
2384
2385 # getting ports in sfi
2386 ingress_port = sfi["ingress-constituent-cpd-id"]
2387 egress_port = sfi["egress-constituent-cpd-id"]
2388 sfi_vnf_member_index = sfi["constituent-base-element-id"]
2389
2390 processed_sfi["ingress_port"] = ingress_port
2391 processed_sfi["egress_port"] = egress_port
2392
2393 all_vnfrs = db_vnfrs.values()
2394
2395 sfi_vnfr = [
2396 element
2397 for element in all_vnfrs
2398 if element["member-vnf-index-ref"] == sfi_vnf_member_index
2399 ]
2400 processed_sfi["vnfr_id"] = sfi_vnfr[0]["id"]
2401
2402 sfi_vnfr_cp = sfi_vnfr[0]["connection-point"]
2403
2404 ingress_port_index = [
2405 c for c, element in enumerate(sfi_vnfr_cp) if element["id"] == ingress_port
2406 ]
2407 ingress_port_index = ingress_port_index[0]
2408
2409 processed_sfi["vdur_id"] = sfi_vnfr_cp[ingress_port_index][
2410 "connection-point-vdu-id"
2411 ]
2412 processed_sfi["ingress_port_index"] = ingress_port_index
2413 processed_sfi["egress_port_index"] = ingress_port_index
2414
2415 if egress_port != ingress_port:
2416 egress_port_index = [
2417 c
2418 for c, element in enumerate(sfi_vnfr_cp)
2419 if element["id"] == egress_port
2420 ]
2421 processed_sfi["egress_port_index"] = egress_port_index
2422
2423 return processed_sfi
2424
2425 def _process_vnfgd_classification(self, classification, db_vnfrs):
2426 processed_classification = {}
2427
2428 processed_classification = deepcopy(classification)
2429 classi_vnf_member_index = processed_classification[
2430 "constituent-base-element-id"
2431 ]
2432 logical_source_port = processed_classification["constituent-cpd-id"]
2433
2434 all_vnfrs = db_vnfrs.values()
2435
2436 classi_vnfr = [
2437 element
2438 for element in all_vnfrs
2439 if element["member-vnf-index-ref"] == classi_vnf_member_index
2440 ]
2441 processed_classification["vnfr_id"] = classi_vnfr[0]["id"]
2442
2443 classi_vnfr_cp = classi_vnfr[0]["connection-point"]
2444
2445 ingress_port_index = [
2446 c
2447 for c, element in enumerate(classi_vnfr_cp)
2448 if element["id"] == logical_source_port
2449 ]
2450 ingress_port_index = ingress_port_index[0]
2451
2452 processed_classification["ingress_port_index"] = ingress_port_index
2453 processed_classification["vdur_id"] = classi_vnfr_cp[ingress_port_index][
2454 "connection-point-vdu-id"
2455 ]
2456
2457 return processed_classification
2458
2459 def _update_db_nsr_with_vnffg(self, processed_vnffg, vim_info, nsr_id):
2460 """This method used to add viminfo dict to sfi, sf sfp and classification in indata and count info in db_nsr.
2461
2462 Args:
2463 processed_vnffg (Dict[str, Any]): deployment info
2464 vim_info (Dict): dictionary to store VIM resource information
2465 nsr_id (str): NSR id
2466
2467 Returns: None
2468 """
2469
2470 nsr_sfi = {}
2471 nsr_sf = {}
2472 nsr_sfp = {}
2473 nsr_classification = {}
2474 db_nsr_vnffg = deepcopy(processed_vnffg)
2475
2476 for count, sfi in enumerate(processed_vnffg["sfi"]):
2477 sfi["vim_info"] = vim_info
2478 sfi_count = "sfi.{}".format(count)
2479 nsr_sfi[sfi_count] = db_nsr_vnffg["sfi"][count]
2480
2481 self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sfi)
2482
2483 for count, sf in enumerate(processed_vnffg["sf"]):
2484 sf["vim_info"] = vim_info
2485 sf_count = "sf.{}".format(count)
2486 nsr_sf[sf_count] = db_nsr_vnffg["sf"][count]
2487
2488 self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sf)
2489
2490 for count, sfp in enumerate(processed_vnffg["sfp"]):
2491 sfp["vim_info"] = vim_info
2492 sfp_count = "sfp.{}".format(count)
2493 nsr_sfp[sfp_count] = db_nsr_vnffg["sfp"][count]
2494
2495 self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sfp)
2496
2497 for count, classi in enumerate(processed_vnffg["classification"]):
2498 classi["vim_info"] = vim_info
2499 classification_count = "classification.{}".format(count)
2500 nsr_classification[classification_count] = db_nsr_vnffg["classification"][
2501 count
2502 ]
2503
2504 self.db.set_list("nsrs", {"_id": nsr_id}, nsr_classification)
2505
2506 def process_vnffgd_descriptor(
2507 self,
2508 indata: dict,
2509 nsr_id: str,
2510 db_nsr: dict,
2511 db_vnfrs: dict,
2512 ) -> dict:
2513 """This method used to process vnffgd parameters from descriptor.
2514
2515 Args:
2516 indata (Dict[str, Any]): deployment info
2517 nsr_id (str): NSR id
2518 db_nsr: NSR record from DB
2519 db_vnfrs: VNFRS record from DB
2520
2521 Returns:
2522 Dict: Processed vnffg parameters.
2523 """
2524
2525 processed_vnffg = {}
2526 vnffgd = db_nsr.get("nsd", {}).get("vnffgd")
2527 vnf_list = indata.get("vnf", [])
2528 vim_text = ""
2529
2530 if vnf_list:
2531 vim_text = "vim:" + vnf_list[0].get("vim-account-id", "")
2532
2533 vim_info = {}
2534 vim_info[vim_text] = {}
2535 processed_sfps = []
2536 processed_classifications = []
2537 processed_sfs = []
2538 processed_sfis = []
2539
2540 # setting up intial empty entries for vnffg items in mongodb.
2541 self.db.set_list(
2542 "nsrs",
2543 {"_id": nsr_id},
2544 {
2545 "sfi": [],
2546 "sf": [],
2547 "sfp": [],
2548 "classification": [],
2549 },
2550 )
2551
2552 vnffg = vnffgd[0]
2553 # getting sfps
2554 sfps = vnffg.get("nfpd")
2555 for sfp in sfps:
2556 processed_sfp = self._process_vnfgd_sfp(sfp)
2557 # appending the list of processed sfps
2558 processed_sfps.append(processed_sfp)
2559
2560 # getting sfs in sfp
2561 sfs = sfp.get("position-desc-id")[0].get("cp-profile-id")
2562 for sf in sfs:
2563 processed_sf = self._process_vnfgd_sf(sf)
2564
2565 # appending the list of processed sfs
2566 processed_sfs.append(processed_sf)
2567
2568 # getting sfis in sf
2569 sfis_in_sf = sf.get("constituent-profile-elements")
2570 sorted_sfis = sorted(sfis_in_sf, key=lambda i: i["order"])
2571
2572 for sfi in sorted_sfis:
2573 processed_sfi = self._process_vnfgd_sfi(sfi, db_vnfrs)
2574
2575 processed_sfis.append(processed_sfi)
2576
2577 classifications = sfp.get("position-desc-id")[0].get("match-attributes")
2578 # getting classifications from sfp
2579 for classification in classifications:
2580 processed_classification = self._process_vnfgd_classification(
2581 classification, db_vnfrs
2582 )
2583
2584 processed_classifications.append(processed_classification)
2585
2586 processed_vnffg["sfi"] = processed_sfis
2587 processed_vnffg["sf"] = processed_sfs
2588 processed_vnffg["classification"] = processed_classifications
2589 processed_vnffg["sfp"] = processed_sfps
2590
2591 # adding viminfo dict to sfi, sf sfp and classification
2592 self._update_db_nsr_with_vnffg(processed_vnffg, vim_info, nsr_id)
2593
2594 # updating indata with vnffg porcessed parameters
2595 indata["vnffg"].append(processed_vnffg)
2596
gallardoa1c2b402022-02-11 12:41:59 +00002597 def calculate_all_differences_to_deploy(
2598 self,
2599 indata,
2600 nsr_id,
2601 db_nsr,
2602 db_vnfrs,
2603 db_ro_nsr,
2604 db_nsr_update,
2605 db_vnfrs_update,
2606 action_id,
2607 tasks_by_target_record_id,
2608 ):
2609 """This method calculates the ordered list of items (`changes_list`)
2610 to be created and deleted.
2611
2612 Args:
2613 indata (Dict[str, Any]): deployment info
2614 nsr_id (str): NSR id
2615 db_nsr: NSR record from DB
2616 db_vnfrs: VNFRS record from DB
2617 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2618 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2619 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2620 action_id (str): action id
2621 tasks_by_target_record_id (Dict[str, Any]):
2622 [<target_record_id>, <task>]
2623
2624 Returns:
2625 List: ordered list of items to be created and deleted.
2626 """
2627
2628 task_index = 0
2629 # set list with diffs:
2630 changes_list = []
2631
Lovejeet Singhdf486552023-05-09 22:41:09 +05302632 # processing vnffg from descriptor parameter
2633 vnffgd = db_nsr.get("nsd").get("vnffgd")
2634 if vnffgd is not None:
2635 indata["vnffg"] = []
2636 vnf_list = indata["vnf"]
2637 processed_vnffg = {}
2638
2639 # in case of ns-delete
2640 if not vnf_list:
2641 processed_vnffg["sfi"] = []
2642 processed_vnffg["sf"] = []
2643 processed_vnffg["classification"] = []
2644 processed_vnffg["sfp"] = []
2645
2646 indata["vnffg"].append(processed_vnffg)
2647
2648 else:
2649 self.process_vnffgd_descriptor(
2650 indata=indata,
2651 nsr_id=nsr_id,
2652 db_nsr=db_nsr,
2653 db_vnfrs=db_vnfrs,
2654 )
2655
2656 # getting updated db_nsr having vnffg parameters
2657 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2658
2659 self.logger.debug(
2660 "After processing vnffd parameters indata={} nsr={}".format(
2661 indata, db_nsr
2662 )
2663 )
2664
2665 for item in ["sfp", "classification", "sf", "sfi"]:
2666 self.logger.debug("process NS={} {}".format(nsr_id, item))
2667 diff_items, task_index = self.calculate_diff_items(
2668 indata=indata,
2669 db_nsr=db_nsr,
2670 db_ro_nsr=db_ro_nsr,
2671 db_nsr_update=db_nsr_update,
2672 item=item,
2673 tasks_by_target_record_id=tasks_by_target_record_id,
2674 action_id=action_id,
2675 nsr_id=nsr_id,
2676 task_index=task_index,
2677 vnfr_id=None,
2678 )
2679 changes_list += diff_items
2680
gallardoa1c2b402022-02-11 12:41:59 +00002681 # NS vld, image and flavor
vegall364627c2023-03-17 15:09:50 +00002682 for item in [
2683 "net",
2684 "image",
2685 "flavor",
2686 "affinity-or-anti-affinity-group",
vegall364627c2023-03-17 15:09:50 +00002687 ]:
gallardoa1c2b402022-02-11 12:41:59 +00002688 self.logger.debug("process NS={} {}".format(nsr_id, item))
2689 diff_items, task_index = self.calculate_diff_items(
2690 indata=indata,
2691 db_nsr=db_nsr,
2692 db_ro_nsr=db_ro_nsr,
2693 db_nsr_update=db_nsr_update,
2694 item=item,
2695 tasks_by_target_record_id=tasks_by_target_record_id,
2696 action_id=action_id,
2697 nsr_id=nsr_id,
2698 task_index=task_index,
2699 vnfr_id=None,
2700 )
2701 changes_list += diff_items
2702
2703 # VNF vlds and vdus
2704 for vnfr_id, vnfr in db_vnfrs.items():
2705 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05002706 for item in ["net", "vdu", "shared-volumes"]:
gallardoa1c2b402022-02-11 12:41:59 +00002707 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
2708 diff_items, task_index = self.calculate_diff_items(
2709 indata=indata,
2710 db_nsr=db_nsr,
2711 db_ro_nsr=db_ro_nsr,
2712 db_nsr_update=db_vnfrs_update[vnfr["_id"]],
2713 item=item,
2714 tasks_by_target_record_id=tasks_by_target_record_id,
2715 action_id=action_id,
2716 nsr_id=nsr_id,
2717 task_index=task_index,
2718 vnfr_id=vnfr_id,
2719 vnfr=vnfr,
2720 )
2721 changes_list += diff_items
2722
2723 return changes_list
2724
2725 def define_all_tasks(
2726 self,
2727 changes_list,
2728 db_new_tasks,
2729 tasks_by_target_record_id,
2730 ):
2731 """Function to create all the task structures obtanied from
2732 the method calculate_all_differences_to_deploy
2733
2734 Args:
2735 changes_list (List): ordered list of items to be created or deleted
2736 db_new_tasks (List): tasks list to be created
2737 action_id (str): action id
2738 tasks_by_target_record_id (Dict[str, Any]):
2739 [<target_record_id>, <task>]
2740
2741 """
2742
2743 for change in changes_list:
2744 task = Ns._create_task(
2745 deployment_info=change["deployment_info"],
2746 target_id=change["target_id"],
2747 item=change["item"],
2748 action=change["action"],
2749 target_record=change["target_record"],
2750 target_record_id=change["target_record_id"],
2751 extra_dict=change.get("extra_dict", None),
2752 )
2753
aticigddff2b02022-09-03 23:06:37 +03002754 self.logger.debug("ns.define_all_tasks task={}".format(task))
gallardoa1c2b402022-02-11 12:41:59 +00002755 tasks_by_target_record_id[change["target_record_id"]] = task
2756 db_new_tasks.append(task)
2757
2758 if change.get("common_id"):
2759 task["common_id"] = change["common_id"]
2760
2761 def upload_all_tasks(
2762 self,
2763 db_new_tasks,
2764 now,
2765 ):
2766 """Function to save all tasks in the common DB
2767
2768 Args:
2769 db_new_tasks (List): tasks list to be created
2770 now (time): current time
2771
2772 """
2773
2774 nb_ro_tasks = 0 # for logging
2775
2776 for db_task in db_new_tasks:
2777 target_id = db_task.pop("target_id")
2778 common_id = db_task.get("common_id")
2779
palaciosj42eb06f2022-05-05 14:59:36 +00002780 # Do not chek tasks with vim_status DELETED
2781 # because in manual heealing there are two tasks for the same vdur:
2782 # one with vim_status deleted and the other one with the actual VM status.
2783
gallardoa1c2b402022-02-11 12:41:59 +00002784 if common_id:
2785 if self.db.set_one(
2786 "ro_tasks",
2787 q_filter={
2788 "target_id": target_id,
2789 "tasks.common_id": common_id,
palaciosj42eb06f2022-05-05 14:59:36 +00002790 "vim_info.vim_status.ne": "DELETED",
gallardoa1c2b402022-02-11 12:41:59 +00002791 },
2792 update_dict={"to_check_at": now, "modified_at": now},
2793 push={"tasks": db_task},
2794 fail_on_empty=False,
2795 ):
2796 continue
2797
2798 if not self.db.set_one(
2799 "ro_tasks",
2800 q_filter={
2801 "target_id": target_id,
2802 "tasks.target_record": db_task["target_record"],
palaciosj42eb06f2022-05-05 14:59:36 +00002803 "vim_info.vim_status.ne": "DELETED",
gallardoa1c2b402022-02-11 12:41:59 +00002804 },
2805 update_dict={"to_check_at": now, "modified_at": now},
2806 push={"tasks": db_task},
2807 fail_on_empty=False,
2808 ):
2809 # Create a ro_task
2810 self.logger.debug("Updating database, Creating ro_tasks")
2811 db_ro_task = Ns._create_ro_task(target_id, db_task)
2812 nb_ro_tasks += 1
2813 self.db.create("ro_tasks", db_ro_task)
2814
2815 self.logger.debug(
2816 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2817 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2818 )
2819 )
2820
palaciosj8f2060b2022-02-24 12:05:59 +00002821 def upload_recreate_tasks(
2822 self,
2823 db_new_tasks,
2824 now,
2825 ):
2826 """Function to save recreate tasks in the common DB
2827
2828 Args:
2829 db_new_tasks (List): tasks list to be created
2830 now (time): current time
2831
2832 """
2833
2834 nb_ro_tasks = 0 # for logging
2835
2836 for db_task in db_new_tasks:
2837 target_id = db_task.pop("target_id")
aticigddff2b02022-09-03 23:06:37 +03002838 self.logger.debug("target_id={} db_task={}".format(target_id, db_task))
palaciosj8f2060b2022-02-24 12:05:59 +00002839
2840 action = db_task.get("action", None)
2841
2842 # Create a ro_task
2843 self.logger.debug("Updating database, Creating ro_tasks")
2844 db_ro_task = Ns._create_ro_task(target_id, db_task)
2845
aticig285185e2022-05-02 21:23:48 +03002846 # If DELETE task: the associated created items should be removed
palaciosj8f2060b2022-02-24 12:05:59 +00002847 # (except persistent volumes):
2848 if action == "DELETE":
2849 db_ro_task["vim_info"]["created"] = True
aticig285185e2022-05-02 21:23:48 +03002850 db_ro_task["vim_info"]["created_items"] = db_task.get(
2851 "created_items", {}
2852 )
palaciosj42eb06f2022-05-05 14:59:36 +00002853 db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get(
2854 "volumes_to_hold", []
2855 )
palaciosj8f2060b2022-02-24 12:05:59 +00002856 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
2857
2858 nb_ro_tasks += 1
aticigddff2b02022-09-03 23:06:37 +03002859 self.logger.debug("upload_all_tasks db_ro_task={}".format(db_ro_task))
palaciosj8f2060b2022-02-24 12:05:59 +00002860 self.db.create("ro_tasks", db_ro_task)
2861
2862 self.logger.debug(
2863 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2864 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2865 )
2866 )
2867
2868 def _prepare_created_items_for_healing(
2869 self,
palaciosj42eb06f2022-05-05 14:59:36 +00002870 nsr_id,
2871 target_record,
palaciosj8f2060b2022-02-24 12:05:59 +00002872 ):
palaciosj42eb06f2022-05-05 14:59:36 +00002873 created_items = {}
2874 # Get created_items from ro_task
2875 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2876 for ro_task in ro_tasks:
2877 for task in ro_task["tasks"]:
2878 if (
2879 task["target_record"] == target_record
2880 and task["action"] == "CREATE"
2881 and ro_task["vim_info"]["created_items"]
2882 ):
2883 created_items = ro_task["vim_info"]["created_items"]
2884 break
palaciosj8f2060b2022-02-24 12:05:59 +00002885
palaciosj42eb06f2022-05-05 14:59:36 +00002886 return created_items
palaciosj8f2060b2022-02-24 12:05:59 +00002887
2888 def _prepare_persistent_volumes_for_healing(
2889 self,
2890 target_id,
2891 existing_vdu,
2892 ):
2893 # The associated volumes of the VM shouldn't be removed
2894 volumes_list = []
2895 vim_details = {}
2896 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
2897 if vim_details_text:
2898 vim_details = yaml.safe_load(f"{vim_details_text}")
2899
2900 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2901 volumes_list.append(vol_id["id"])
2902
2903 return volumes_list
2904
2905 def prepare_changes_to_recreate(
2906 self,
2907 indata,
2908 nsr_id,
2909 db_nsr,
2910 db_vnfrs,
2911 db_ro_nsr,
2912 action_id,
2913 tasks_by_target_record_id,
2914 ):
2915 """This method will obtain an ordered list of items (`changes_list`)
2916 to be created and deleted to meet the recreate request.
2917 """
2918
2919 self.logger.debug(
2920 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
2921 )
2922
2923 task_index = 0
2924 # set list with diffs:
2925 changes_list = []
2926 db_path = self.db_path_map["vdu"]
2927 target_list = indata.get("healVnfData", {})
2928 vdu2cloud_init = indata.get("cloud_init_content") or {}
2929 ro_nsr_public_key = db_ro_nsr["public_key"]
2930
2931 # Check each VNF of the target
2932 for target_vnf in target_list:
Gabriel Cubab1bc6692022-08-19 18:23:00 -05002933 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2934 vnfr_id = target_vnf["vnfInstanceId"]
elumalai321d2e92023-04-28 17:03:07 +05302935 existing_vnf = db_vnfrs.get(vnfr_id, {})
Gabriel Cubab1bc6692022-08-19 18:23:00 -05002936 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
2937 # vim_account_id = existing_vnf.get("vim-account-id", "")
palaciosj8f2060b2022-02-24 12:05:59 +00002938
Gabriel Cubab1bc6692022-08-19 18:23:00 -05002939 target_vdus = target_vnf.get("additionalParams", {}).get("vdu", [])
palaciosj8f2060b2022-02-24 12:05:59 +00002940 # Check each VDU of this VNF
Gabriel Cubab1bc6692022-08-19 18:23:00 -05002941 if not target_vdus:
2942 # Create target_vdu_list from DB, if VDUs are not specified
2943 target_vdus = []
2944 for existing_vdu in existing_vnf.get("vdur"):
2945 vdu_name = existing_vdu.get("vdu-name", None)
2946 vdu_index = existing_vdu.get("count-index", 0)
2947 vdu_to_be_healed = {"vdu-id": vdu_name, "count-index": vdu_index}
2948 target_vdus.append(vdu_to_be_healed)
2949 for target_vdu in target_vdus:
palaciosj8f2060b2022-02-24 12:05:59 +00002950 vdu_name = target_vdu.get("vdu-id", None)
2951 # For multi instance VDU count-index is mandatory
2952 # For single session VDU count-indes is 0
2953 count_index = target_vdu.get("count-index", 0)
2954 item_index = 0
elumalai321d2e92023-04-28 17:03:07 +05302955 existing_instance = {}
2956 if existing_vnf:
2957 for instance in existing_vnf.get("vdur", {}):
2958 if (
2959 instance["vdu-name"] == vdu_name
2960 and instance["count-index"] == count_index
2961 ):
2962 existing_instance = instance
2963 break
2964 else:
2965 item_index += 1
palaciosj8f2060b2022-02-24 12:05:59 +00002966
2967 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
2968
2969 # The target VIM is the one already existing in DB to recreate
2970 for target_vim, target_viminfo in existing_instance.get(
2971 "vim_info", {}
2972 ).items():
2973 # step 1 vdu to be deleted
2974 self._assign_vim(target_vim)
2975 deployment_info = {
2976 "action_id": action_id,
2977 "nsr_id": nsr_id,
2978 "task_index": task_index,
2979 }
2980
2981 target_record = f"{db_record}.{item_index}.vim_info.{target_vim}"
2982 created_items = self._prepare_created_items_for_healing(
palaciosj42eb06f2022-05-05 14:59:36 +00002983 nsr_id, target_record
palaciosj8f2060b2022-02-24 12:05:59 +00002984 )
2985
2986 volumes_to_hold = self._prepare_persistent_volumes_for_healing(
2987 target_vim, existing_instance
2988 )
2989
2990 # Specific extra params for recreate tasks:
2991 extra_dict = {
2992 "created_items": created_items,
2993 "vim_id": existing_instance["vim-id"],
2994 "volumes_to_hold": volumes_to_hold,
2995 }
2996
2997 changes_list.append(
2998 {
2999 "deployment_info": deployment_info,
3000 "target_id": target_vim,
3001 "item": "vdu",
3002 "action": "DELETE",
3003 "target_record": target_record,
3004 "target_record_id": target_record_id,
3005 "extra_dict": extra_dict,
3006 }
3007 )
3008 delete_task_id = f"{action_id}:{task_index}"
3009 task_index += 1
3010
3011 # step 2 vdu to be created
3012 kwargs = {}
3013 kwargs.update(
3014 {
3015 "vnfr_id": vnfr_id,
3016 "nsr_id": nsr_id,
3017 "vnfr": existing_vnf,
3018 "vdu2cloud_init": vdu2cloud_init,
3019 "tasks_by_target_record_id": tasks_by_target_record_id,
3020 "logger": self.logger,
3021 "db": self.db,
3022 "fs": self.fs,
3023 "ro_nsr_public_key": ro_nsr_public_key,
3024 }
3025 )
3026
3027 extra_dict = self._process_recreate_vdu_params(
3028 existing_instance,
3029 db_nsr,
3030 target_viminfo,
3031 target_record_id,
3032 target_vim,
3033 **kwargs,
3034 )
3035
3036 # The CREATE task depens on the DELETE task
3037 extra_dict["depends_on"] = [delete_task_id]
3038
palaciosj42eb06f2022-05-05 14:59:36 +00003039 # Add volumes created from created_items if any
3040 # Ports should be deleted with delete task and automatically created with create task
3041 volumes = {}
3042 for k, v in created_items.items():
3043 try:
3044 k_item, _, k_id = k.partition(":")
3045 if k_item == "volume":
3046 volumes[k] = v
3047 except Exception as e:
3048 self.logger.error(
3049 "Error evaluating created item {}: {}".format(k, e)
3050 )
3051 extra_dict["previous_created_volumes"] = volumes
3052
palaciosj8f2060b2022-02-24 12:05:59 +00003053 deployment_info = {
3054 "action_id": action_id,
3055 "nsr_id": nsr_id,
3056 "task_index": task_index,
3057 }
3058 self._assign_vim(target_vim)
3059
3060 new_item = {
3061 "deployment_info": deployment_info,
3062 "target_id": target_vim,
3063 "item": "vdu",
3064 "action": "CREATE",
3065 "target_record": target_record,
3066 "target_record_id": target_record_id,
3067 "extra_dict": extra_dict,
3068 }
3069 changes_list.append(new_item)
3070 tasks_by_target_record_id[target_record_id] = new_item
3071 task_index += 1
3072
3073 return changes_list
3074
3075 def recreate(self, session, indata, version, nsr_id, *args, **kwargs):
3076 self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata))
3077 # TODO: validate_input(indata, recreate_schema)
3078 action_id = indata.get("action_id", str(uuid4()))
3079 # get current deployment
3080 db_vnfrs = {} # vnf's info indexed by _id
3081 step = ""
3082 logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
3083 nsr_id, action_id, indata
3084 )
3085 self.logger.debug(logging_text + "Enter")
3086
3087 try:
3088 step = "Getting ns and vnfr record from db"
3089 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3090 db_new_tasks = []
3091 tasks_by_target_record_id = {}
3092 # read from db: vnf's of this ns
3093 step = "Getting vnfrs from db"
3094 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
3095 self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list))
3096
3097 if not db_vnfrs_list:
3098 raise NsException("Cannot obtain associated VNF for ns")
3099
3100 for vnfr in db_vnfrs_list:
3101 db_vnfrs[vnfr["_id"]] = vnfr
3102
3103 now = time()
3104 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
3105 self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr))
3106
3107 if not db_ro_nsr:
3108 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
3109
3110 with self.write_lock:
3111 # NS
3112 step = "process NS elements"
3113 changes_list = self.prepare_changes_to_recreate(
3114 indata=indata,
3115 nsr_id=nsr_id,
3116 db_nsr=db_nsr,
3117 db_vnfrs=db_vnfrs,
3118 db_ro_nsr=db_ro_nsr,
3119 action_id=action_id,
3120 tasks_by_target_record_id=tasks_by_target_record_id,
3121 )
3122
3123 self.define_all_tasks(
3124 changes_list=changes_list,
3125 db_new_tasks=db_new_tasks,
3126 tasks_by_target_record_id=tasks_by_target_record_id,
3127 )
3128
3129 # Delete all ro_tasks registered for the targets vdurs (target_record)
aticig285185e2022-05-02 21:23:48 +03003130 # If task of type CREATE exist then vim will try to get info form deleted VMs.
palaciosj8f2060b2022-02-24 12:05:59 +00003131 # So remove all task related to target record.
3132 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
3133 for change in changes_list:
3134 for ro_task in ro_tasks:
3135 for task in ro_task["tasks"]:
3136 if task["target_record"] == change["target_record"]:
3137 self.db.del_one(
3138 "ro_tasks",
3139 q_filter={
3140 "_id": ro_task["_id"],
3141 "modified_at": ro_task["modified_at"],
3142 },
3143 fail_on_empty=False,
3144 )
aticig285185e2022-05-02 21:23:48 +03003145
palaciosj8f2060b2022-02-24 12:05:59 +00003146 step = "Updating database, Appending tasks to ro_tasks"
3147 self.upload_recreate_tasks(
3148 db_new_tasks=db_new_tasks,
3149 now=now,
3150 )
3151
3152 self.logger.debug(
3153 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3154 )
3155
3156 return (
3157 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3158 action_id,
3159 True,
3160 )
3161 except Exception as e:
3162 if isinstance(e, (DbException, NsException)):
3163 self.logger.error(
3164 logging_text + "Exit Exception while '{}': {}".format(step, e)
3165 )
3166 else:
3167 e = traceback_format_exc()
3168 self.logger.critical(
3169 logging_text + "Exit Exception while '{}': {}".format(step, e),
3170 exc_info=True,
3171 )
3172
3173 raise NsException(e)
3174
tierno1d213f42020-04-24 14:02:51 +00003175 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +00003176 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
tierno1d213f42020-04-24 14:02:51 +00003177 validate_input(indata, deploy_schema)
3178 action_id = indata.get("action_id", str(uuid4()))
3179 task_index = 0
3180 # get current deployment
sousaedu80135b92021-02-17 15:05:18 +01003181 db_nsr_update = {} # update operation on nsrs
tierno1d213f42020-04-24 14:02:51 +00003182 db_vnfrs_update = {}
sousaedu80135b92021-02-17 15:05:18 +01003183 db_vnfrs = {} # vnf's info indexed by _id
sousaedu80135b92021-02-17 15:05:18 +01003184 step = ""
tierno1d213f42020-04-24 14:02:51 +00003185 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3186 self.logger.debug(logging_text + "Enter")
sousaedu80135b92021-02-17 15:05:18 +01003187
tierno1d213f42020-04-24 14:02:51 +00003188 try:
3189 step = "Getting ns and vnfr record from db"
tierno1d213f42020-04-24 14:02:51 +00003190 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
palaciosj8f2060b2022-02-24 12:05:59 +00003191 self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr))
tierno1d213f42020-04-24 14:02:51 +00003192 db_new_tasks = []
tierno70eeb182020-10-19 16:38:00 +00003193 tasks_by_target_record_id = {}
tierno1d213f42020-04-24 14:02:51 +00003194 # read from db: vnf's of this ns
3195 step = "Getting vnfrs from db"
3196 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
sousaedu80135b92021-02-17 15:05:18 +01003197
tierno1d213f42020-04-24 14:02:51 +00003198 if not db_vnfrs_list:
3199 raise NsException("Cannot obtain associated VNF for ns")
sousaedu80135b92021-02-17 15:05:18 +01003200
tierno1d213f42020-04-24 14:02:51 +00003201 for vnfr in db_vnfrs_list:
3202 db_vnfrs[vnfr["_id"]] = vnfr
3203 db_vnfrs_update[vnfr["_id"]] = {}
palaciosj8f2060b2022-02-24 12:05:59 +00003204 self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs))
sousaedu80135b92021-02-17 15:05:18 +01003205
tierno1d213f42020-04-24 14:02:51 +00003206 now = time()
3207 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
sousaedu80135b92021-02-17 15:05:18 +01003208
tierno1d213f42020-04-24 14:02:51 +00003209 if not db_ro_nsr:
3210 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
sousaedu80135b92021-02-17 15:05:18 +01003211
tierno1d213f42020-04-24 14:02:51 +00003212 # check that action_id is not in the list of actions. Suffixed with :index
3213 if action_id in db_ro_nsr["actions"]:
3214 index = 1
sousaedu80135b92021-02-17 15:05:18 +01003215
tierno1d213f42020-04-24 14:02:51 +00003216 while True:
3217 new_action_id = "{}:{}".format(action_id, index)
sousaedu80135b92021-02-17 15:05:18 +01003218
tierno1d213f42020-04-24 14:02:51 +00003219 if new_action_id not in db_ro_nsr["actions"]:
3220 action_id = new_action_id
sousaedu80135b92021-02-17 15:05:18 +01003221 self.logger.debug(
3222 logging_text
3223 + "Changing action_id in use to {}".format(action_id)
3224 )
tierno1d213f42020-04-24 14:02:51 +00003225 break
sousaedu80135b92021-02-17 15:05:18 +01003226
tierno1d213f42020-04-24 14:02:51 +00003227 index += 1
3228
tierno1d213f42020-04-24 14:02:51 +00003229 def _process_action(indata):
tierno1d213f42020-04-24 14:02:51 +00003230 nonlocal db_new_tasks
sousaedu89278b82021-11-19 01:01:32 +00003231 nonlocal action_id
3232 nonlocal nsr_id
tierno1d213f42020-04-24 14:02:51 +00003233 nonlocal task_index
3234 nonlocal db_vnfrs
3235 nonlocal db_ro_nsr
3236
tierno70eeb182020-10-19 16:38:00 +00003237 if indata["action"]["action"] == "inject_ssh_key":
3238 key = indata["action"].get("key")
3239 user = indata["action"].get("user")
3240 password = indata["action"].get("password")
sousaedu80135b92021-02-17 15:05:18 +01003241
tierno1d213f42020-04-24 14:02:51 +00003242 for vnf in indata.get("vnf", ()):
tierno70eeb182020-10-19 16:38:00 +00003243 if vnf["_id"] not in db_vnfrs:
tierno1d213f42020-04-24 14:02:51 +00003244 raise NsException("Invalid vnf={}".format(vnf["_id"]))
sousaedu80135b92021-02-17 15:05:18 +01003245
tierno1d213f42020-04-24 14:02:51 +00003246 db_vnfr = db_vnfrs[vnf["_id"]]
sousaedu80135b92021-02-17 15:05:18 +01003247
tierno1d213f42020-04-24 14:02:51 +00003248 for target_vdu in vnf.get("vdur", ()):
sousaedu80135b92021-02-17 15:05:18 +01003249 vdu_index, vdur = next(
3250 (
3251 i_v
3252 for i_v in enumerate(db_vnfr["vdur"])
3253 if i_v[1]["id"] == target_vdu["id"]
3254 ),
3255 (None, None),
3256 )
3257
tierno1d213f42020-04-24 14:02:51 +00003258 if not vdur:
sousaedu80135b92021-02-17 15:05:18 +01003259 raise NsException(
3260 "Invalid vdu vnf={}.{}".format(
3261 vnf["_id"], target_vdu["id"]
3262 )
3263 )
3264
3265 target_vim, vim_info = next(
3266 k_v for k_v in vdur["vim_info"].items()
3267 )
tierno86153522020-12-06 18:27:16 +00003268 self._assign_vim(target_vim)
sousaedu80135b92021-02-17 15:05:18 +01003269 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
3270 vnf["_id"], vdu_index
3271 )
tierno1d213f42020-04-24 14:02:51 +00003272 extra_dict = {
sousaedu80135b92021-02-17 15:05:18 +01003273 "depends_on": [
3274 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
3275 ],
tierno1d213f42020-04-24 14:02:51 +00003276 "params": {
tierno70eeb182020-10-19 16:38:00 +00003277 "ip_address": vdur.get("ip-address"),
tierno1d213f42020-04-24 14:02:51 +00003278 "user": user,
3279 "key": key,
3280 "password": password,
3281 "private_key": db_ro_nsr["private_key"],
3282 "salt": db_ro_nsr["_id"],
sousaedu80135b92021-02-17 15:05:18 +01003283 "schema_version": db_ro_nsr["_admin"][
3284 "schema_version"
3285 ],
3286 },
tierno1d213f42020-04-24 14:02:51 +00003287 }
sousaedu89278b82021-11-19 01:01:32 +00003288
3289 deployment_info = {
3290 "action_id": action_id,
3291 "nsr_id": nsr_id,
3292 "task_index": task_index,
3293 }
3294
3295 task = Ns._create_task(
3296 deployment_info=deployment_info,
3297 target_id=target_vim,
3298 item="vdu",
3299 action="EXEC",
sousaedu80135b92021-02-17 15:05:18 +01003300 target_record=target_record,
3301 target_record_id=None,
3302 extra_dict=extra_dict,
3303 )
sousaedu89278b82021-11-19 01:01:32 +00003304
3305 task_index = deployment_info.get("task_index")
3306
tierno70eeb182020-10-19 16:38:00 +00003307 db_new_tasks.append(task)
tierno1d213f42020-04-24 14:02:51 +00003308
3309 with self.write_lock:
3310 if indata.get("action"):
3311 _process_action(indata)
3312 else:
3313 # compute network differences
gallardoa1c2b402022-02-11 12:41:59 +00003314 # NS
3315 step = "process NS elements"
3316 changes_list = self.calculate_all_differences_to_deploy(
3317 indata=indata,
3318 nsr_id=nsr_id,
3319 db_nsr=db_nsr,
3320 db_vnfrs=db_vnfrs,
3321 db_ro_nsr=db_ro_nsr,
3322 db_nsr_update=db_nsr_update,
3323 db_vnfrs_update=db_vnfrs_update,
3324 action_id=action_id,
3325 tasks_by_target_record_id=tasks_by_target_record_id,
3326 )
3327 self.define_all_tasks(
3328 changes_list=changes_list,
3329 db_new_tasks=db_new_tasks,
3330 tasks_by_target_record_id=tasks_by_target_record_id,
sousaedu80135b92021-02-17 15:05:18 +01003331 )
tierno1d213f42020-04-24 14:02:51 +00003332
gallardoa1c2b402022-02-11 12:41:59 +00003333 step = "Updating database, Appending tasks to ro_tasks"
3334 self.upload_all_tasks(
3335 db_new_tasks=db_new_tasks,
3336 now=now,
3337 )
sousaedu80135b92021-02-17 15:05:18 +01003338
tierno1d213f42020-04-24 14:02:51 +00003339 step = "Updating database, nsrs"
3340 if db_nsr_update:
3341 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
sousaedu80135b92021-02-17 15:05:18 +01003342
tierno1d213f42020-04-24 14:02:51 +00003343 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
3344 if db_vnfr_update:
3345 step = "Updating database, vnfrs={}".format(vnfr_id)
3346 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
3347
sousaedu80135b92021-02-17 15:05:18 +01003348 self.logger.debug(
gallardoa1c2b402022-02-11 12:41:59 +00003349 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
sousaedu80135b92021-02-17 15:05:18 +01003350 )
tierno1d213f42020-04-24 14:02:51 +00003351
sousaedu80135b92021-02-17 15:05:18 +01003352 return (
3353 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3354 action_id,
3355 True,
3356 )
tierno1d213f42020-04-24 14:02:51 +00003357 except Exception as e:
3358 if isinstance(e, (DbException, NsException)):
sousaedu80135b92021-02-17 15:05:18 +01003359 self.logger.error(
3360 logging_text + "Exit Exception while '{}': {}".format(step, e)
3361 )
tierno1d213f42020-04-24 14:02:51 +00003362 else:
3363 e = traceback_format_exc()
sousaedu80135b92021-02-17 15:05:18 +01003364 self.logger.critical(
3365 logging_text + "Exit Exception while '{}': {}".format(step, e),
3366 exc_info=True,
3367 )
3368
tierno1d213f42020-04-24 14:02:51 +00003369 raise NsException(e)
3370
3371 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +00003372 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
tierno1d213f42020-04-24 14:02:51 +00003373 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
sousaedu80135b92021-02-17 15:05:18 +01003374
tierno70eeb182020-10-19 16:38:00 +00003375 with self.write_lock:
3376 try:
3377 NsWorker.delete_db_tasks(self.db, nsr_id, None)
3378 except NsWorkerException as e:
3379 raise NsException(e)
sousaedu80135b92021-02-17 15:05:18 +01003380
tierno1d213f42020-04-24 14:02:51 +00003381 return None, None, True
3382
3383 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
palaciosj8f2060b2022-02-24 12:05:59 +00003384 self.logger.debug(
3385 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
3386 version, nsr_id, action_id, indata
3387 )
3388 )
tierno1d213f42020-04-24 14:02:51 +00003389 task_list = []
3390 done = 0
3391 total = 0
3392 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
3393 global_status = "DONE"
3394 details = []
sousaedu80135b92021-02-17 15:05:18 +01003395
tierno1d213f42020-04-24 14:02:51 +00003396 for ro_task in ro_tasks:
3397 for task in ro_task["tasks"]:
tierno70eeb182020-10-19 16:38:00 +00003398 if task and task["action_id"] == action_id:
tierno1d213f42020-04-24 14:02:51 +00003399 task_list.append(task)
3400 total += 1
sousaedu80135b92021-02-17 15:05:18 +01003401
tierno1d213f42020-04-24 14:02:51 +00003402 if task["status"] == "FAILED":
3403 global_status = "FAILED"
sousaedu80135b92021-02-17 15:05:18 +01003404 error_text = "Error at {} {}: {}".format(
3405 task["action"].lower(),
3406 task["item"],
aticig79ac6df2022-05-06 16:09:52 +03003407 ro_task["vim_info"].get("vim_message") or "unknown",
sousaedu80135b92021-02-17 15:05:18 +01003408 )
tierno70eeb182020-10-19 16:38:00 +00003409 details.append(error_text)
tierno1d213f42020-04-24 14:02:51 +00003410 elif task["status"] in ("SCHEDULED", "BUILD"):
3411 if global_status != "FAILED":
3412 global_status = "BUILD"
3413 else:
3414 done += 1
sousaedu80135b92021-02-17 15:05:18 +01003415
tierno1d213f42020-04-24 14:02:51 +00003416 return_data = {
3417 "status": global_status,
garciadeblasaca8cb52023-12-21 16:28:15 +01003418 "details": (
3419 ". ".join(details) if details else "progress {}/{}".format(done, total)
3420 ),
tierno1d213f42020-04-24 14:02:51 +00003421 "nsr_id": nsr_id,
3422 "action_id": action_id,
sousaedu80135b92021-02-17 15:05:18 +01003423 "tasks": task_list,
tierno1d213f42020-04-24 14:02:51 +00003424 }
sousaedu80135b92021-02-17 15:05:18 +01003425
tierno1d213f42020-04-24 14:02:51 +00003426 return return_data, None, True
3427
palaciosj8f2060b2022-02-24 12:05:59 +00003428 def recreate_status(
3429 self, session, indata, version, nsr_id, action_id, *args, **kwargs
3430 ):
3431 return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
3432
tierno1d213f42020-04-24 14:02:51 +00003433 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
sousaedu80135b92021-02-17 15:05:18 +01003434 print(
3435 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
3436 session, indata, version, nsr_id, action_id
3437 )
3438 )
3439
tierno1d213f42020-04-24 14:02:51 +00003440 return None, None, True
3441
k4.rahul78f474e2022-05-02 15:47:57 +00003442 def rebuild_start_stop_task(
3443 self,
3444 vdu_id,
3445 vnf_id,
3446 vdu_index,
3447 action_id,
3448 nsr_id,
3449 task_index,
3450 target_vim,
3451 extra_dict,
3452 ):
3453 self._assign_vim(target_vim)
Patricia Reinoso17852162023-06-15 07:33:04 +00003454 target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3455 vnf_id, vdu_index, target_vim
3456 )
k4.rahul78f474e2022-05-02 15:47:57 +00003457 target_record_id = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_id)
3458 deployment_info = {
3459 "action_id": action_id,
3460 "nsr_id": nsr_id,
3461 "task_index": task_index,
3462 }
3463
3464 task = Ns._create_task(
3465 deployment_info=deployment_info,
3466 target_id=target_vim,
3467 item="update",
3468 action="EXEC",
3469 target_record=target_record,
3470 target_record_id=target_record_id,
3471 extra_dict=extra_dict,
3472 )
3473 return task
3474
3475 def rebuild_start_stop(
3476 self, session, action_dict, version, nsr_id, *args, **kwargs
3477 ):
3478 task_index = 0
3479 extra_dict = {}
3480 now = time()
3481 action_id = action_dict.get("action_id", str(uuid4()))
3482 step = ""
3483 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3484 self.logger.debug(logging_text + "Enter")
3485
3486 action = list(action_dict.keys())[0]
3487 task_dict = action_dict.get(action)
3488 vim_vm_id = action_dict.get(action).get("vim_vm_id")
3489
3490 if action_dict.get("stop"):
3491 action = "shutoff"
3492 db_new_tasks = []
3493 try:
3494 step = "lock the operation & do task creation"
3495 with self.write_lock:
3496 extra_dict["params"] = {
3497 "vim_vm_id": vim_vm_id,
3498 "action": action,
3499 }
3500 task = self.rebuild_start_stop_task(
3501 task_dict["vdu_id"],
3502 task_dict["vnf_id"],
3503 task_dict["vdu_index"],
3504 action_id,
3505 nsr_id,
3506 task_index,
3507 task_dict["target_vim"],
3508 extra_dict,
3509 )
3510 db_new_tasks.append(task)
3511 step = "upload Task to db"
3512 self.upload_all_tasks(
3513 db_new_tasks=db_new_tasks,
3514 now=now,
3515 )
3516 self.logger.debug(
3517 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3518 )
3519 return (
3520 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3521 action_id,
3522 True,
3523 )
3524 except Exception as e:
3525 if isinstance(e, (DbException, NsException)):
3526 self.logger.error(
3527 logging_text + "Exit Exception while '{}': {}".format(step, e)
3528 )
3529 else:
3530 e = traceback_format_exc()
3531 self.logger.critical(
3532 logging_text + "Exit Exception while '{}': {}".format(step, e),
3533 exc_info=True,
3534 )
3535 raise NsException(e)
3536
tierno1d213f42020-04-24 14:02:51 +00003537 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
3538 nsrs = self.db.get_list("nsrs", {})
3539 return_data = []
sousaedu80135b92021-02-17 15:05:18 +01003540
tierno1d213f42020-04-24 14:02:51 +00003541 for ns in nsrs:
3542 return_data.append({"_id": ns["_id"], "name": ns["name"]})
sousaedu80135b92021-02-17 15:05:18 +01003543
tierno1d213f42020-04-24 14:02:51 +00003544 return return_data, None, True
3545
3546 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
3547 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
3548 return_data = []
sousaedu80135b92021-02-17 15:05:18 +01003549
tierno1d213f42020-04-24 14:02:51 +00003550 for ro_task in ro_tasks:
3551 for task in ro_task["tasks"]:
3552 if task["action_id"] not in return_data:
3553 return_data.append(task["action_id"])
sousaedu80135b92021-02-17 15:05:18 +01003554
tierno1d213f42020-04-24 14:02:51 +00003555 return return_data, None, True
elumalai8658c2c2022-04-28 19:09:31 +05303556
3557 def migrate_task(
3558 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3559 ):
3560 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3561 self._assign_vim(target_vim)
Patricia Reinoso17852162023-06-15 07:33:04 +00003562 target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3563 vnf["_id"], vdu_index, target_vim
3564 )
elumalai8658c2c2022-04-28 19:09:31 +05303565 target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3566 deployment_info = {
3567 "action_id": action_id,
3568 "nsr_id": nsr_id,
3569 "task_index": task_index,
3570 }
3571
3572 task = Ns._create_task(
3573 deployment_info=deployment_info,
3574 target_id=target_vim,
3575 item="migrate",
3576 action="EXEC",
3577 target_record=target_record,
3578 target_record_id=target_record_id,
3579 extra_dict=extra_dict,
3580 )
3581
3582 return task
3583
3584 def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
3585 task_index = 0
3586 extra_dict = {}
3587 now = time()
3588 action_id = indata.get("action_id", str(uuid4()))
3589 step = ""
3590 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3591 self.logger.debug(logging_text + "Enter")
3592 try:
3593 vnf_instance_id = indata["vnfInstanceId"]
3594 step = "Getting vnfrs from db"
3595 db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3596 vdu = indata.get("vdu")
3597 migrateToHost = indata.get("migrateToHost")
3598 db_new_tasks = []
3599
3600 with self.write_lock:
3601 if vdu is not None:
3602 vdu_id = indata["vdu"]["vduId"]
3603 vdu_count_index = indata["vdu"].get("vduCountIndex", 0)
3604 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3605 if (
3606 vdu["vdu-id-ref"] == vdu_id
3607 and vdu["count-index"] == vdu_count_index
3608 ):
3609 extra_dict["params"] = {
3610 "vim_vm_id": vdu["vim-id"],
3611 "migrate_host": migrateToHost,
3612 "vdu_vim_info": vdu["vim_info"],
3613 }
3614 step = "Creating migration task for vdu:{}".format(vdu)
3615 task = self.migrate_task(
3616 vdu,
3617 db_vnfr,
3618 vdu_index,
3619 action_id,
3620 nsr_id,
3621 task_index,
3622 extra_dict,
3623 )
3624 db_new_tasks.append(task)
3625 task_index += 1
3626 break
3627 else:
elumalai8658c2c2022-04-28 19:09:31 +05303628 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3629 extra_dict["params"] = {
3630 "vim_vm_id": vdu["vim-id"],
3631 "migrate_host": migrateToHost,
3632 "vdu_vim_info": vdu["vim_info"],
3633 }
3634 step = "Creating migration task for vdu:{}".format(vdu)
3635 task = self.migrate_task(
3636 vdu,
3637 db_vnfr,
3638 vdu_index,
3639 action_id,
3640 nsr_id,
3641 task_index,
3642 extra_dict,
3643 )
3644 db_new_tasks.append(task)
3645 task_index += 1
3646
3647 self.upload_all_tasks(
3648 db_new_tasks=db_new_tasks,
3649 now=now,
3650 )
3651
3652 self.logger.debug(
3653 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3654 )
3655 return (
3656 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3657 action_id,
3658 True,
3659 )
3660 except Exception as e:
3661 if isinstance(e, (DbException, NsException)):
3662 self.logger.error(
3663 logging_text + "Exit Exception while '{}': {}".format(step, e)
3664 )
3665 else:
3666 e = traceback_format_exc()
3667 self.logger.critical(
3668 logging_text + "Exit Exception while '{}': {}".format(step, e),
3669 exc_info=True,
3670 )
3671 raise NsException(e)
sritharan29a4c1a2022-05-05 12:15:04 +00003672
3673 def verticalscale_task(
3674 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3675 ):
3676 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3677 self._assign_vim(target_vim)
Rahul Kumar06e914f2023-11-08 06:25:06 +00003678 ns_preffix = "nsrs:{}".format(nsr_id)
3679 flavor_text = ns_preffix + ":flavor." + vdu["ns-flavor-id"]
3680 extra_dict["depends_on"] = [flavor_text]
3681 extra_dict["params"].update({"flavor_id": "TASK-" + flavor_text})
Patricia Reinoso17852162023-06-15 07:33:04 +00003682 target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3683 vnf["_id"], vdu_index, target_vim
3684 )
sritharan29a4c1a2022-05-05 12:15:04 +00003685 target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3686 deployment_info = {
3687 "action_id": action_id,
3688 "nsr_id": nsr_id,
3689 "task_index": task_index,
3690 }
3691
3692 task = Ns._create_task(
3693 deployment_info=deployment_info,
3694 target_id=target_vim,
3695 item="verticalscale",
3696 action="EXEC",
3697 target_record=target_record,
3698 target_record_id=target_record_id,
3699 extra_dict=extra_dict,
3700 )
3701 return task
3702
Rahul Kumar06e914f2023-11-08 06:25:06 +00003703 def verticalscale_flavor_task(
3704 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3705 ):
3706 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3707 self._assign_vim(target_vim)
3708 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3709 target_record = "nsrs:{}:flavor.{}.vim_info.{}".format(
3710 nsr_id, len(db_nsr["flavor"]) - 1, target_vim
3711 )
3712 target_record_id = "nsrs:{}:flavor.{}".format(nsr_id, len(db_nsr["flavor"]) - 1)
3713 deployment_info = {
3714 "action_id": action_id,
3715 "nsr_id": nsr_id,
3716 "task_index": task_index,
3717 }
3718 task = Ns._create_task(
3719 deployment_info=deployment_info,
3720 target_id=target_vim,
3721 item="flavor",
3722 action="CREATE",
3723 target_record=target_record,
3724 target_record_id=target_record_id,
3725 extra_dict=extra_dict,
3726 )
3727 return task
3728
sritharan29a4c1a2022-05-05 12:15:04 +00003729 def verticalscale(self, session, indata, version, nsr_id, *args, **kwargs):
3730 task_index = 0
3731 extra_dict = {}
Rahul Kumar06e914f2023-11-08 06:25:06 +00003732 flavor_extra_dict = {}
sritharan29a4c1a2022-05-05 12:15:04 +00003733 now = time()
3734 action_id = indata.get("action_id", str(uuid4()))
3735 step = ""
3736 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3737 self.logger.debug(logging_text + "Enter")
3738 try:
3739 VnfFlavorData = indata.get("changeVnfFlavorData")
3740 vnf_instance_id = VnfFlavorData["vnfInstanceId"]
3741 step = "Getting vnfrs from db"
3742 db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3743 vduid = VnfFlavorData["additionalParams"]["vduid"]
3744 vduCountIndex = VnfFlavorData["additionalParams"]["vduCountIndex"]
3745 virtualMemory = VnfFlavorData["additionalParams"]["virtualMemory"]
3746 numVirtualCpu = VnfFlavorData["additionalParams"]["numVirtualCpu"]
3747 sizeOfStorage = VnfFlavorData["additionalParams"]["sizeOfStorage"]
3748 flavor_dict = {
3749 "name": vduid + "-flv",
3750 "ram": virtualMemory,
3751 "vcpus": numVirtualCpu,
3752 "disk": sizeOfStorage,
3753 }
Rahul Kumar06e914f2023-11-08 06:25:06 +00003754 flavor_data = {
3755 "ram": virtualMemory,
3756 "vcpus": numVirtualCpu,
3757 "disk": sizeOfStorage,
3758 }
3759 flavor_extra_dict["find_params"] = {"flavor_data": flavor_data}
3760 flavor_extra_dict["params"] = {"flavor_data": flavor_dict}
sritharan29a4c1a2022-05-05 12:15:04 +00003761 db_new_tasks = []
3762 step = "Creating Tasks for vertical scaling"
3763 with self.write_lock:
3764 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3765 if (
3766 vdu["vdu-id-ref"] == vduid
3767 and vdu["count-index"] == vduCountIndex
3768 ):
3769 extra_dict["params"] = {
3770 "vim_vm_id": vdu["vim-id"],
3771 "flavor_dict": flavor_dict,
Rahul Kumar06e914f2023-11-08 06:25:06 +00003772 "vdu-id-ref": vdu["vdu-id-ref"],
3773 "count-index": vdu["count-index"],
3774 "vnf_instance_id": vnf_instance_id,
sritharan29a4c1a2022-05-05 12:15:04 +00003775 }
Rahul Kumar06e914f2023-11-08 06:25:06 +00003776 task = self.verticalscale_flavor_task(
3777 vdu,
3778 db_vnfr,
3779 vdu_index,
3780 action_id,
3781 nsr_id,
3782 task_index,
3783 flavor_extra_dict,
3784 )
3785 db_new_tasks.append(task)
3786 task_index += 1
sritharan29a4c1a2022-05-05 12:15:04 +00003787 task = self.verticalscale_task(
3788 vdu,
3789 db_vnfr,
3790 vdu_index,
3791 action_id,
3792 nsr_id,
3793 task_index,
3794 extra_dict,
3795 )
3796 db_new_tasks.append(task)
3797 task_index += 1
3798 break
3799 self.upload_all_tasks(
3800 db_new_tasks=db_new_tasks,
3801 now=now,
3802 )
3803 self.logger.debug(
3804 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3805 )
3806 return (
3807 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3808 action_id,
3809 True,
3810 )
3811 except Exception as e:
3812 if isinstance(e, (DbException, NsException)):
3813 self.logger.error(
3814 logging_text + "Exit Exception while '{}': {}".format(step, e)
3815 )
3816 else:
3817 e = traceback_format_exc()
3818 self.logger.critical(
3819 logging_text + "Exit Exception while '{}': {}".format(step, e),
3820 exc_info=True,
3821 )
3822 raise NsException(e)