| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 1 | # -*- 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 | |
| sousaedu | 049cbb1 | 2022-01-05 11:39:35 +0000 | [diff] [blame] | 19 | from http import HTTPStatus |
| aticig | cf14bb1 | 2022-05-19 13:03:17 +0300 | [diff] [blame] | 20 | from itertools import product |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 21 | import logging |
| sousaedu | 049cbb1 | 2022-01-05 11:39:35 +0000 | [diff] [blame] | 22 | from random import choice as random_choice |
| 23 | from threading import Lock |
| 24 | from time import time |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 25 | from traceback import format_exc as traceback_format_exc |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 26 | from typing import Any, Dict, Tuple, Type |
| sousaedu | 049cbb1 | 2022-01-05 11:39:35 +0000 | [diff] [blame] | 27 | from uuid import uuid4 |
| 28 | |
| 29 | from cryptography.hazmat.backends import default_backend as crypto_default_backend |
| 30 | from cryptography.hazmat.primitives import serialization as crypto_serialization |
| 31 | from cryptography.hazmat.primitives.asymmetric import rsa |
| 32 | from jinja2 import ( |
| 33 | Environment, |
| 34 | StrictUndefined, |
| 35 | TemplateError, |
| 36 | TemplateNotFound, |
| 37 | UndefinedError, |
| 38 | ) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 39 | from osm_common import ( |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 40 | dbmemory, |
| sousaedu | 049cbb1 | 2022-01-05 11:39:35 +0000 | [diff] [blame] | 41 | dbmongo, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 42 | fslocal, |
| 43 | fsmongo, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 44 | msgkafka, |
| sousaedu | 049cbb1 | 2022-01-05 11:39:35 +0000 | [diff] [blame] | 45 | msglocal, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 46 | version as common_version, |
| 47 | ) |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 48 | from osm_common.dbbase import DbBase, DbException |
| 49 | from osm_common.fsbase import FsBase, FsException |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 50 | from osm_common.msgbase import MsgException |
| sousaedu | 049cbb1 | 2022-01-05 11:39:35 +0000 | [diff] [blame] | 51 | from osm_ng_ro.ns_thread import deep_get, NsWorker, NsWorkerException |
| 52 | from osm_ng_ro.validation import deploy_schema, validate_input |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 53 | import yaml |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 54 | |
| 55 | __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>" |
| 56 | min_common_version = "0.1.16" |
| 57 | |
| 58 | |
| 59 | class NsException(Exception): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 60 | def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST): |
| 61 | self.http_code = http_code |
| 62 | super(Exception, self).__init__(message) |
| 63 | |
| 64 | |
| 65 | def get_process_id(): |
| 66 | """ |
| 67 | Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it |
| 68 | will provide a random one |
| 69 | :return: Obtained ID |
| 70 | """ |
| 71 | # Try getting docker id. If fails, get pid |
| 72 | try: |
| 73 | with open("/proc/self/cgroup", "r") as f: |
| 74 | text_id_ = f.readline() |
| 75 | _, _, text_id = text_id_.rpartition("/") |
| 76 | text_id = text_id.replace("\n", "")[:12] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 77 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 78 | if text_id: |
| 79 | return text_id |
| 80 | except Exception: |
| 81 | pass |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 82 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 83 | # Return a random id |
| 84 | return "".join(random_choice("0123456789abcdef") for _ in range(12)) |
| 85 | |
| 86 | |
| 87 | def versiontuple(v): |
| 88 | """utility for compare dot separate versions. Fills with zeros to proper number comparison""" |
| 89 | filled = [] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 90 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 91 | for point in v.split("."): |
| 92 | filled.append(point.zfill(8)) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 93 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 94 | return tuple(filled) |
| 95 | |
| 96 | |
| 97 | class Ns(object): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 98 | def __init__(self): |
| 99 | self.db = None |
| 100 | self.fs = None |
| 101 | self.msg = None |
| 102 | self.config = None |
| 103 | # self.operations = None |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 104 | self.logger = None |
| 105 | # ^ Getting logger inside method self.start because parent logger (ro) is not available yet. |
| 106 | # If done now it will not be linked to parent not getting its handler and level |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 107 | self.map_topic = {} |
| 108 | self.write_lock = None |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 109 | self.vims_assigned = {} |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 110 | self.next_worker = 0 |
| 111 | self.plugins = {} |
| 112 | self.workers = [] |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 113 | self.process_params_function_map = { |
| 114 | "net": Ns._process_net_params, |
| 115 | "image": Ns._process_image_params, |
| 116 | "flavor": Ns._process_flavor_params, |
| 117 | "vdu": Ns._process_vdu_params, |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 118 | "affinity-or-anti-affinity-group": Ns._process_affinity_group_params, |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 119 | } |
| 120 | self.db_path_map = { |
| 121 | "net": "vld", |
| 122 | "image": "image", |
| 123 | "flavor": "flavor", |
| 124 | "vdu": "vdur", |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 125 | "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group", |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 126 | } |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 127 | |
| 128 | def init_db(self, target_version): |
| 129 | pass |
| 130 | |
| 131 | def start(self, config): |
| 132 | """ |
| 133 | Connect to database, filesystem storage, and messaging |
| 134 | :param config: two level dictionary with configuration. Top level should contain 'database', 'storage', |
| 135 | :param config: Configuration of db, storage, etc |
| 136 | :return: None |
| 137 | """ |
| 138 | self.config = config |
| 139 | self.config["process_id"] = get_process_id() # used for HA identity |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 140 | self.logger = logging.getLogger("ro.ns") |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 141 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 142 | # check right version of common |
| 143 | if versiontuple(common_version) < versiontuple(min_common_version): |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 144 | raise NsException( |
| 145 | "Not compatible osm/common version '{}'. Needed '{}' or higher".format( |
| 146 | common_version, min_common_version |
| 147 | ) |
| 148 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 149 | |
| 150 | try: |
| 151 | if not self.db: |
| 152 | if config["database"]["driver"] == "mongo": |
| 153 | self.db = dbmongo.DbMongo() |
| 154 | self.db.db_connect(config["database"]) |
| 155 | elif config["database"]["driver"] == "memory": |
| 156 | self.db = dbmemory.DbMemory() |
| 157 | self.db.db_connect(config["database"]) |
| 158 | else: |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 159 | raise NsException( |
| 160 | "Invalid configuration param '{}' at '[database]':'driver'".format( |
| 161 | config["database"]["driver"] |
| 162 | ) |
| 163 | ) |
| 164 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 165 | if not self.fs: |
| 166 | if config["storage"]["driver"] == "local": |
| 167 | self.fs = fslocal.FsLocal() |
| 168 | self.fs.fs_connect(config["storage"]) |
| 169 | elif config["storage"]["driver"] == "mongo": |
| 170 | self.fs = fsmongo.FsMongo() |
| 171 | self.fs.fs_connect(config["storage"]) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 172 | elif config["storage"]["driver"] is None: |
| 173 | pass |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 174 | else: |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 175 | raise NsException( |
| 176 | "Invalid configuration param '{}' at '[storage]':'driver'".format( |
| 177 | config["storage"]["driver"] |
| 178 | ) |
| 179 | ) |
| 180 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 181 | if not self.msg: |
| 182 | if config["message"]["driver"] == "local": |
| 183 | self.msg = msglocal.MsgLocal() |
| 184 | self.msg.connect(config["message"]) |
| 185 | elif config["message"]["driver"] == "kafka": |
| 186 | self.msg = msgkafka.MsgKafka() |
| 187 | self.msg.connect(config["message"]) |
| 188 | else: |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 189 | raise NsException( |
| 190 | "Invalid configuration param '{}' at '[message]':'driver'".format( |
| 191 | config["message"]["driver"] |
| 192 | ) |
| 193 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 194 | |
| 195 | # TODO load workers to deal with exising database tasks |
| 196 | |
| 197 | self.write_lock = Lock() |
| 198 | except (DbException, FsException, MsgException) as e: |
| 199 | raise NsException(str(e), http_code=e.http_code) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 200 | |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 201 | def get_assigned_vims(self): |
| 202 | return list(self.vims_assigned.keys()) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 203 | |
| 204 | def stop(self): |
| 205 | try: |
| 206 | if self.db: |
| 207 | self.db.db_disconnect() |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 208 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 209 | if self.fs: |
| 210 | self.fs.fs_disconnect() |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 211 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 212 | if self.msg: |
| 213 | self.msg.disconnect() |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 214 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 215 | self.write_lock = None |
| 216 | except (DbException, FsException, MsgException) as e: |
| 217 | raise NsException(str(e), http_code=e.http_code) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 218 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 219 | for worker in self.workers: |
| 220 | worker.insert_task(("terminate",)) |
| 221 | |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 222 | def _create_worker(self): |
| 223 | """ |
| 224 | Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the |
| 225 | limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread |
| 226 | return the index of the assigned worker thread. Worker threads are storead at self.workers |
| 227 | """ |
| 228 | # Look for a thread in idle status |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 229 | worker_id = next( |
| 230 | ( |
| 231 | i |
| 232 | for i in range(len(self.workers)) |
| 233 | if self.workers[i] and self.workers[i].idle |
| 234 | ), |
| 235 | None, |
| 236 | ) |
| 237 | |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 238 | if worker_id is not None: |
| 239 | # unset idle status to avoid race conditions |
| 240 | self.workers[worker_id].idle = False |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 241 | else: |
| 242 | worker_id = len(self.workers) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 243 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 244 | if worker_id < self.config["global"]["server.ns_threads"]: |
| 245 | # create a new worker |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 246 | self.workers.append( |
| 247 | NsWorker(worker_id, self.config, self.plugins, self.db) |
| 248 | ) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 249 | self.workers[worker_id].start() |
| 250 | else: |
| 251 | # reached maximum number of threads, assign VIM to an existing one |
| 252 | worker_id = self.next_worker |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 253 | self.next_worker = (self.next_worker + 1) % self.config["global"][ |
| 254 | "server.ns_threads" |
| 255 | ] |
| 256 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 257 | return worker_id |
| 258 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 259 | def assign_vim(self, target_id): |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 260 | with self.write_lock: |
| 261 | return self._assign_vim(target_id) |
| 262 | |
| 263 | def _assign_vim(self, target_id): |
| 264 | if target_id not in self.vims_assigned: |
| 265 | worker_id = self.vims_assigned[target_id] = self._create_worker() |
| 266 | self.workers[worker_id].insert_task(("load_vim", target_id)) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 267 | |
| 268 | def reload_vim(self, target_id): |
| 269 | # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed, |
| 270 | # this is because database VIM information is cached for threads working with SDN |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 271 | with self.write_lock: |
| 272 | for worker in self.workers: |
| 273 | if worker and not worker.idle: |
| 274 | worker.insert_task(("reload_vim", target_id)) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 275 | |
| 276 | def unload_vim(self, target_id): |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 277 | with self.write_lock: |
| 278 | return self._unload_vim(target_id) |
| 279 | |
| 280 | def _unload_vim(self, target_id): |
| 281 | if target_id in self.vims_assigned: |
| 282 | worker_id = self.vims_assigned[target_id] |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 283 | self.workers[worker_id].insert_task(("unload_vim", target_id)) |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 284 | del self.vims_assigned[target_id] |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 285 | |
| 286 | def check_vim(self, target_id): |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 287 | with self.write_lock: |
| 288 | if target_id in self.vims_assigned: |
| 289 | worker_id = self.vims_assigned[target_id] |
| 290 | else: |
| 291 | worker_id = self._create_worker() |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 292 | |
| 293 | worker = self.workers[worker_id] |
| 294 | worker.insert_task(("check_vim", target_id)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 295 | |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 296 | def unload_unused_vims(self): |
| 297 | with self.write_lock: |
| 298 | vims_to_unload = [] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 299 | |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 300 | for target_id in self.vims_assigned: |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 301 | if not self.db.get_one( |
| 302 | "ro_tasks", |
| 303 | q_filter={ |
| 304 | "target_id": target_id, |
| 305 | "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"], |
| 306 | }, |
| 307 | fail_on_empty=False, |
| 308 | ): |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 309 | vims_to_unload.append(target_id) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 310 | |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 311 | for target_id in vims_to_unload: |
| 312 | self._unload_vim(target_id) |
| 313 | |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 314 | @staticmethod |
| 315 | def _get_cloud_init( |
| 316 | db: Type[DbBase], |
| 317 | fs: Type[FsBase], |
| 318 | location: str, |
| 319 | ) -> str: |
| 320 | """This method reads cloud init from a file. |
| 321 | |
| 322 | Note: Not used as cloud init content is provided in the http body. |
| 323 | |
| 324 | Args: |
| 325 | db (Type[DbBase]): [description] |
| 326 | fs (Type[FsBase]): [description] |
| 327 | location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex' |
| 328 | |
| 329 | Raises: |
| 330 | NsException: [description] |
| 331 | NsException: [description] |
| 332 | |
| 333 | Returns: |
| 334 | str: [description] |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 335 | """ |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 336 | vnfd_id, _, other = location.partition(":") |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 337 | _type, _, name = other.partition(":") |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 338 | vnfd = db.get_one("vnfds", {"_id": vnfd_id}) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 339 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 340 | if _type == "file": |
| 341 | base_folder = vnfd["_admin"]["storage"] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 342 | cloud_init_file = "{}/{}/cloud_init/{}".format( |
| 343 | base_folder["folder"], base_folder["pkg-dir"], name |
| 344 | ) |
| 345 | |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 346 | if not fs: |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 347 | raise NsException( |
| 348 | "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format( |
| 349 | cloud_init_file |
| 350 | ) |
| 351 | ) |
| 352 | |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 353 | with fs.file_open(cloud_init_file, "r") as ci_file: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 354 | cloud_init_content = ci_file.read() |
| 355 | elif _type == "vdu": |
| 356 | cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"] |
| 357 | else: |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 358 | raise NsException("Mismatch descriptor for cloud init: {}".format(location)) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 359 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 360 | return cloud_init_content |
| 361 | |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 362 | @staticmethod |
| 363 | def _parse_jinja2( |
| 364 | cloud_init_content: str, |
| 365 | params: Dict[str, Any], |
| 366 | context: str, |
| 367 | ) -> str: |
| 368 | """Function that processes the cloud init to replace Jinja2 encoded parameters. |
| 369 | |
| 370 | Args: |
| 371 | cloud_init_content (str): [description] |
| 372 | params (Dict[str, Any]): [description] |
| 373 | context (str): [description] |
| 374 | |
| 375 | Raises: |
| 376 | NsException: [description] |
| 377 | NsException: [description] |
| 378 | |
| 379 | Returns: |
| 380 | str: [description] |
| 381 | """ |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 382 | try: |
| 383 | env = Environment(undefined=StrictUndefined) |
| 384 | template = env.from_string(cloud_init_content) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 385 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 386 | return template.render(params or {}) |
| 387 | except UndefinedError as e: |
| 388 | raise NsException( |
| 389 | "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters" |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 390 | "inside the 'additionalParamsForVnf' block".format(e, context) |
| 391 | ) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 392 | except (TemplateError, TemplateNotFound) as e: |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 393 | raise NsException( |
| 394 | "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format( |
| 395 | context, e |
| 396 | ) |
| 397 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 398 | |
| 399 | def _create_db_ro_nsrs(self, nsr_id, now): |
| 400 | try: |
| 401 | key = rsa.generate_private_key( |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 402 | backend=crypto_default_backend(), public_exponent=65537, key_size=2048 |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 403 | ) |
| 404 | private_key = key.private_bytes( |
| 405 | crypto_serialization.Encoding.PEM, |
| 406 | crypto_serialization.PrivateFormat.PKCS8, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 407 | crypto_serialization.NoEncryption(), |
| 408 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 409 | public_key = key.public_key().public_bytes( |
| 410 | crypto_serialization.Encoding.OpenSSH, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 411 | crypto_serialization.PublicFormat.OpenSSH, |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 412 | ) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 413 | private_key = private_key.decode("utf8") |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 414 | # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY' |
| 415 | i = private_key.find("\n") |
| 416 | private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 417 | public_key = public_key.decode("utf8") |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 418 | except Exception as e: |
| 419 | raise NsException("Cannot create ssh-keys: {}".format(e)) |
| 420 | |
| 421 | schema_version = "1.1" |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 422 | private_key_encrypted = self.db.encrypt( |
| 423 | private_key, schema_version=schema_version, salt=nsr_id |
| 424 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 425 | db_content = { |
| 426 | "_id": nsr_id, |
| 427 | "_admin": { |
| 428 | "created": now, |
| 429 | "modified": now, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 430 | "schema_version": schema_version, |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 431 | }, |
| 432 | "public_key": public_key, |
| 433 | "private_key": private_key_encrypted, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 434 | "actions": [], |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 435 | } |
| 436 | self.db.create("ro_nsrs", db_content) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 437 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 438 | return db_content |
| 439 | |
| sousaedu | 89278b8 | 2021-11-19 01:01:32 +0000 | [diff] [blame] | 440 | @staticmethod |
| 441 | def _create_task( |
| 442 | deployment_info: Dict[str, Any], |
| 443 | target_id: str, |
| 444 | item: str, |
| 445 | action: str, |
| 446 | target_record: str, |
| 447 | target_record_id: str, |
| 448 | extra_dict: Dict[str, Any] = None, |
| 449 | ) -> Dict[str, Any]: |
| 450 | """Function to create task dict from deployment information. |
| 451 | |
| 452 | Args: |
| 453 | deployment_info (Dict[str, Any]): [description] |
| 454 | target_id (str): [description] |
| 455 | item (str): [description] |
| 456 | action (str): [description] |
| 457 | target_record (str): [description] |
| 458 | target_record_id (str): [description] |
| 459 | extra_dict (Dict[str, Any], optional): [description]. Defaults to None. |
| 460 | |
| 461 | Returns: |
| 462 | Dict[str, Any]: [description] |
| 463 | """ |
| 464 | task = { |
| 465 | "target_id": target_id, # it will be removed before pushing at database |
| 466 | "action_id": deployment_info.get("action_id"), |
| 467 | "nsr_id": deployment_info.get("nsr_id"), |
| 468 | "task_id": f"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}", |
| 469 | "status": "SCHEDULED", |
| 470 | "action": action, |
| 471 | "item": item, |
| 472 | "target_record": target_record, |
| 473 | "target_record_id": target_record_id, |
| 474 | } |
| 475 | |
| 476 | if extra_dict: |
| 477 | task.update(extra_dict) # params, find_params, depends_on |
| 478 | |
| 479 | deployment_info["task_index"] = deployment_info.get("task_index", 0) + 1 |
| 480 | |
| 481 | return task |
| 482 | |
| sousaedu | 839e5ca | 2021-11-19 16:41:38 +0000 | [diff] [blame] | 483 | @staticmethod |
| 484 | def _create_ro_task( |
| 485 | target_id: str, |
| 486 | task: Dict[str, Any], |
| 487 | ) -> Dict[str, Any]: |
| 488 | """Function to create an RO task from task information. |
| 489 | |
| 490 | Args: |
| 491 | target_id (str): [description] |
| 492 | task (Dict[str, Any]): [description] |
| 493 | |
| 494 | Returns: |
| 495 | Dict[str, Any]: [description] |
| 496 | """ |
| 497 | now = time() |
| 498 | |
| 499 | _id = task.get("task_id") |
| 500 | db_ro_task = { |
| 501 | "_id": _id, |
| 502 | "locked_by": None, |
| 503 | "locked_at": 0.0, |
| 504 | "target_id": target_id, |
| 505 | "vim_info": { |
| 506 | "created": False, |
| 507 | "created_items": None, |
| 508 | "vim_id": None, |
| 509 | "vim_name": None, |
| 510 | "vim_status": None, |
| 511 | "vim_details": None, |
| aticig | 79ac6df | 2022-05-06 16:09:52 +0300 | [diff] [blame] | 512 | "vim_message": None, |
| sousaedu | 839e5ca | 2021-11-19 16:41:38 +0000 | [diff] [blame] | 513 | "refresh_at": None, |
| 514 | }, |
| 515 | "modified_at": now, |
| 516 | "created_at": now, |
| 517 | "to_check_at": now, |
| 518 | "tasks": [task], |
| 519 | } |
| 520 | |
| 521 | return db_ro_task |
| 522 | |
| sousaedu | a0a3330 | 2021-11-21 16:21:13 +0000 | [diff] [blame] | 523 | @staticmethod |
| 524 | def _process_image_params( |
| 525 | target_image: Dict[str, Any], |
| sousaedu | 686720b | 2021-11-24 02:16:11 +0000 | [diff] [blame] | 526 | indata: Dict[str, Any], |
| sousaedu | a0a3330 | 2021-11-21 16:21:13 +0000 | [diff] [blame] | 527 | vim_info: Dict[str, Any], |
| 528 | target_record_id: str, |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 529 | **kwargs: Dict[str, Any], |
| sousaedu | a0a3330 | 2021-11-21 16:21:13 +0000 | [diff] [blame] | 530 | ) -> Dict[str, Any]: |
| 531 | """Function to process VDU image parameters. |
| 532 | |
| 533 | Args: |
| 534 | target_image (Dict[str, Any]): [description] |
| sousaedu | 686720b | 2021-11-24 02:16:11 +0000 | [diff] [blame] | 535 | indata (Dict[str, Any]): [description] |
| sousaedu | a0a3330 | 2021-11-21 16:21:13 +0000 | [diff] [blame] | 536 | vim_info (Dict[str, Any]): [description] |
| 537 | target_record_id (str): [description] |
| 538 | |
| 539 | Returns: |
| 540 | Dict[str, Any]: [description] |
| 541 | """ |
| 542 | find_params = {} |
| 543 | |
| 544 | if target_image.get("image"): |
| 545 | find_params["filter_dict"] = {"name": target_image.get("image")} |
| 546 | |
| 547 | if target_image.get("vim_image_id"): |
| 548 | find_params["filter_dict"] = {"id": target_image.get("vim_image_id")} |
| 549 | |
| 550 | if target_image.get("image_checksum"): |
| 551 | find_params["filter_dict"] = { |
| 552 | "checksum": target_image.get("image_checksum") |
| 553 | } |
| 554 | |
| 555 | return {"find_params": find_params} |
| 556 | |
| sousaedu | abdfe78 | 2021-11-22 23:56:28 +0000 | [diff] [blame] | 557 | @staticmethod |
| 558 | def _get_resource_allocation_params( |
| 559 | quota_descriptor: Dict[str, Any], |
| 560 | ) -> Dict[str, Any]: |
| 561 | """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the |
| 562 | descriptor object. |
| 563 | |
| 564 | Args: |
| 565 | quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor |
| 566 | |
| 567 | Returns: |
| 568 | Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object |
| 569 | """ |
| 570 | quota = {} |
| 571 | |
| 572 | if quota_descriptor.get("limit"): |
| 573 | quota["limit"] = int(quota_descriptor["limit"]) |
| 574 | |
| 575 | if quota_descriptor.get("reserve"): |
| 576 | quota["reserve"] = int(quota_descriptor["reserve"]) |
| 577 | |
| 578 | if quota_descriptor.get("shares"): |
| 579 | quota["shares"] = int(quota_descriptor["shares"]) |
| 580 | |
| 581 | return quota |
| 582 | |
| sousaedu | 686720b | 2021-11-24 02:16:11 +0000 | [diff] [blame] | 583 | @staticmethod |
| 584 | def _process_guest_epa_quota_params( |
| 585 | guest_epa_quota: Dict[str, Any], |
| 586 | epa_vcpu_set: bool, |
| 587 | ) -> Dict[str, Any]: |
| 588 | """Function to extract the guest epa quota parameters. |
| 589 | |
| 590 | Args: |
| 591 | guest_epa_quota (Dict[str, Any]): [description] |
| 592 | epa_vcpu_set (bool): [description] |
| 593 | |
| 594 | Returns: |
| 595 | Dict[str, Any]: [description] |
| 596 | """ |
| 597 | result = {} |
| 598 | |
| 599 | if guest_epa_quota.get("cpu-quota") and not epa_vcpu_set: |
| 600 | cpuquota = Ns._get_resource_allocation_params( |
| 601 | guest_epa_quota.get("cpu-quota") |
| 602 | ) |
| 603 | |
| 604 | if cpuquota: |
| 605 | result["cpu-quota"] = cpuquota |
| 606 | |
| 607 | if guest_epa_quota.get("mem-quota"): |
| 608 | vduquota = Ns._get_resource_allocation_params( |
| 609 | guest_epa_quota.get("mem-quota") |
| 610 | ) |
| 611 | |
| 612 | if vduquota: |
| 613 | result["mem-quota"] = vduquota |
| 614 | |
| 615 | if guest_epa_quota.get("disk-io-quota"): |
| 616 | diskioquota = Ns._get_resource_allocation_params( |
| 617 | guest_epa_quota.get("disk-io-quota") |
| 618 | ) |
| 619 | |
| 620 | if diskioquota: |
| 621 | result["disk-io-quota"] = diskioquota |
| 622 | |
| 623 | if guest_epa_quota.get("vif-quota"): |
| 624 | vifquota = Ns._get_resource_allocation_params( |
| 625 | guest_epa_quota.get("vif-quota") |
| 626 | ) |
| 627 | |
| 628 | if vifquota: |
| 629 | result["vif-quota"] = vifquota |
| 630 | |
| 631 | return result |
| 632 | |
| 633 | @staticmethod |
| 634 | def _process_guest_epa_numa_params( |
| 635 | guest_epa_quota: Dict[str, Any], |
| 636 | ) -> Tuple[Dict[str, Any], bool]: |
| 637 | """[summary] |
| 638 | |
| 639 | Args: |
| 640 | guest_epa_quota (Dict[str, Any]): [description] |
| 641 | |
| 642 | Returns: |
| 643 | Tuple[Dict[str, Any], bool]: [description] |
| 644 | """ |
| 645 | numa = {} |
| 646 | epa_vcpu_set = False |
| 647 | |
| 648 | if guest_epa_quota.get("numa-node-policy"): |
| 649 | numa_node_policy = guest_epa_quota.get("numa-node-policy") |
| 650 | |
| 651 | if numa_node_policy.get("node"): |
| 652 | numa_node = numa_node_policy["node"][0] |
| 653 | |
| 654 | if numa_node.get("num-cores"): |
| 655 | numa["cores"] = numa_node["num-cores"] |
| 656 | epa_vcpu_set = True |
| 657 | |
| 658 | paired_threads = numa_node.get("paired-threads", {}) |
| 659 | if paired_threads.get("num-paired-threads"): |
| 660 | numa["paired-threads"] = int( |
| 661 | numa_node["paired-threads"]["num-paired-threads"] |
| 662 | ) |
| 663 | epa_vcpu_set = True |
| 664 | |
| 665 | if paired_threads.get("paired-thread-ids"): |
| 666 | numa["paired-threads-id"] = [] |
| 667 | |
| 668 | for pair in paired_threads["paired-thread-ids"]: |
| 669 | numa["paired-threads-id"].append( |
| 670 | ( |
| 671 | str(pair["thread-a"]), |
| 672 | str(pair["thread-b"]), |
| 673 | ) |
| 674 | ) |
| 675 | |
| 676 | if numa_node.get("num-threads"): |
| 677 | numa["threads"] = int(numa_node["num-threads"]) |
| 678 | epa_vcpu_set = True |
| 679 | |
| 680 | if numa_node.get("memory-mb"): |
| 681 | numa["memory"] = max(int(int(numa_node["memory-mb"]) / 1024), 1) |
| 682 | |
| 683 | return numa, epa_vcpu_set |
| 684 | |
| 685 | @staticmethod |
| 686 | def _process_guest_epa_cpu_pinning_params( |
| 687 | guest_epa_quota: Dict[str, Any], |
| 688 | vcpu_count: int, |
| 689 | epa_vcpu_set: bool, |
| 690 | ) -> Tuple[Dict[str, Any], bool]: |
| 691 | """[summary] |
| 692 | |
| 693 | Args: |
| 694 | guest_epa_quota (Dict[str, Any]): [description] |
| 695 | vcpu_count (int): [description] |
| 696 | epa_vcpu_set (bool): [description] |
| 697 | |
| 698 | Returns: |
| 699 | Tuple[Dict[str, Any], bool]: [description] |
| 700 | """ |
| 701 | numa = {} |
| 702 | local_epa_vcpu_set = epa_vcpu_set |
| 703 | |
| 704 | if ( |
| 705 | guest_epa_quota.get("cpu-pinning-policy") == "DEDICATED" |
| 706 | and not epa_vcpu_set |
| 707 | ): |
| 708 | numa[ |
| 709 | "cores" |
| 710 | if guest_epa_quota.get("cpu-thread-pinning-policy") != "PREFER" |
| 711 | else "threads" |
| 712 | ] = max(vcpu_count, 1) |
| 713 | local_epa_vcpu_set = True |
| 714 | |
| 715 | return numa, local_epa_vcpu_set |
| 716 | |
| 717 | @staticmethod |
| 718 | def _process_epa_params( |
| 719 | target_flavor: Dict[str, Any], |
| 720 | ) -> Dict[str, Any]: |
| 721 | """[summary] |
| 722 | |
| 723 | Args: |
| 724 | target_flavor (Dict[str, Any]): [description] |
| 725 | |
| 726 | Returns: |
| 727 | Dict[str, Any]: [description] |
| 728 | """ |
| 729 | extended = {} |
| 730 | numa = {} |
| 731 | |
| 732 | if target_flavor.get("guest-epa"): |
| 733 | guest_epa = target_flavor["guest-epa"] |
| 734 | |
| 735 | numa, epa_vcpu_set = Ns._process_guest_epa_numa_params( |
| 736 | guest_epa_quota=guest_epa |
| 737 | ) |
| 738 | |
| 739 | if guest_epa.get("mempage-size"): |
| 740 | extended["mempage-size"] = guest_epa.get("mempage-size") |
| 741 | |
| 742 | tmp_numa, epa_vcpu_set = Ns._process_guest_epa_cpu_pinning_params( |
| 743 | guest_epa_quota=guest_epa, |
| 744 | vcpu_count=int(target_flavor.get("vcpu-count", 1)), |
| 745 | epa_vcpu_set=epa_vcpu_set, |
| 746 | ) |
| 747 | numa.update(tmp_numa) |
| 748 | |
| 749 | extended.update( |
| 750 | Ns._process_guest_epa_quota_params( |
| 751 | guest_epa_quota=guest_epa, |
| 752 | epa_vcpu_set=epa_vcpu_set, |
| 753 | ) |
| 754 | ) |
| 755 | |
| 756 | if numa: |
| 757 | extended["numas"] = [numa] |
| 758 | |
| 759 | return extended |
| 760 | |
| 761 | @staticmethod |
| 762 | def _process_flavor_params( |
| 763 | target_flavor: Dict[str, Any], |
| 764 | indata: Dict[str, Any], |
| 765 | vim_info: Dict[str, Any], |
| 766 | target_record_id: str, |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 767 | **kwargs: Dict[str, Any], |
| sousaedu | 686720b | 2021-11-24 02:16:11 +0000 | [diff] [blame] | 768 | ) -> Dict[str, Any]: |
| 769 | """[summary] |
| 770 | |
| 771 | Args: |
| 772 | target_flavor (Dict[str, Any]): [description] |
| 773 | indata (Dict[str, Any]): [description] |
| 774 | vim_info (Dict[str, Any]): [description] |
| 775 | target_record_id (str): [description] |
| 776 | |
| 777 | Returns: |
| 778 | Dict[str, Any]: [description] |
| 779 | """ |
| aticig | cf14bb1 | 2022-05-19 13:03:17 +0300 | [diff] [blame] | 780 | db = kwargs.get("db") |
| 781 | target_vdur = {} |
| 782 | |
| sousaedu | 686720b | 2021-11-24 02:16:11 +0000 | [diff] [blame] | 783 | flavor_data = { |
| 784 | "disk": int(target_flavor["storage-gb"]), |
| 785 | "ram": int(target_flavor["memory-mb"]), |
| 786 | "vcpus": int(target_flavor["vcpu-count"]), |
| 787 | } |
| 788 | |
| sousaedu | 686720b | 2021-11-24 02:16:11 +0000 | [diff] [blame] | 789 | for vnf in indata.get("vnf", []): |
| 790 | for vdur in vnf.get("vdur", []): |
| aticig | cf14bb1 | 2022-05-19 13:03:17 +0300 | [diff] [blame] | 791 | if vdur.get("ns-flavor-id") == target_flavor.get("id"): |
| sousaedu | 686720b | 2021-11-24 02:16:11 +0000 | [diff] [blame] | 792 | target_vdur = vdur |
| 793 | |
| aticig | cf14bb1 | 2022-05-19 13:03:17 +0300 | [diff] [blame] | 794 | if db and isinstance(indata.get("vnf"), list): |
| 795 | vnfd_id = indata.get("vnf")[0].get("vnfd-id") |
| 796 | vnfd = db.get_one("vnfds", {"_id": vnfd_id}) |
| 797 | # check if there is persistent root disk |
| 798 | for vdu in vnfd.get("vdu", ()): |
| 799 | if vdu["name"] == target_vdur.get("vdu-name"): |
| 800 | for vsd in vnfd.get("virtual-storage-desc", ()): |
| 801 | if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]: |
| 802 | root_disk = vsd |
| 803 | if ( |
| 804 | root_disk.get("type-of-storage") |
| 805 | == "persistent-storage:persistent-storage" |
| 806 | ): |
| 807 | flavor_data["disk"] = 0 |
| 808 | |
| sousaedu | 686720b | 2021-11-24 02:16:11 +0000 | [diff] [blame] | 809 | for storage in target_vdur.get("virtual-storages", []): |
| 810 | if ( |
| 811 | storage.get("type-of-storage") |
| 812 | == "etsi-nfv-descriptors:ephemeral-storage" |
| 813 | ): |
| 814 | flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0)) |
| 815 | elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage": |
| 816 | flavor_data["swap"] = int(storage.get("size-of-storage", 0)) |
| 817 | |
| 818 | extended = Ns._process_epa_params(target_flavor) |
| 819 | if extended: |
| 820 | flavor_data["extended"] = extended |
| 821 | |
| 822 | extra_dict = {"find_params": {"flavor_data": flavor_data}} |
| 823 | flavor_data_name = flavor_data.copy() |
| 824 | flavor_data_name["name"] = target_flavor["name"] |
| 825 | extra_dict["params"] = {"flavor_data": flavor_data_name} |
| 826 | |
| 827 | return extra_dict |
| 828 | |
| sousaedu | a4bac08 | 2021-12-05 19:31:03 +0000 | [diff] [blame] | 829 | @staticmethod |
| 830 | def _ip_profile_to_ro( |
| 831 | ip_profile: Dict[str, Any], |
| 832 | ) -> Dict[str, Any]: |
| 833 | """[summary] |
| 834 | |
| 835 | Args: |
| 836 | ip_profile (Dict[str, Any]): [description] |
| 837 | |
| 838 | Returns: |
| 839 | Dict[str, Any]: [description] |
| 840 | """ |
| 841 | if not ip_profile: |
| 842 | return None |
| 843 | |
| 844 | ro_ip_profile = { |
| 845 | "ip_version": "IPv4" |
| 846 | if "v4" in ip_profile.get("ip-version", "ipv4") |
| 847 | else "IPv6", |
| 848 | "subnet_address": ip_profile.get("subnet-address"), |
| 849 | "gateway_address": ip_profile.get("gateway-address"), |
| 850 | "dhcp_enabled": ip_profile.get("dhcp-params", {}).get("enabled", False), |
| 851 | "dhcp_start_address": ip_profile.get("dhcp-params", {}).get( |
| 852 | "start-address", None |
| 853 | ), |
| 854 | "dhcp_count": ip_profile.get("dhcp-params", {}).get("count", None), |
| 855 | } |
| 856 | |
| 857 | if ip_profile.get("dns-server"): |
| 858 | ro_ip_profile["dns_address"] = ";".join( |
| 859 | [v["address"] for v in ip_profile["dns-server"] if v.get("address")] |
| 860 | ) |
| 861 | |
| 862 | if ip_profile.get("security-group"): |
| 863 | ro_ip_profile["security_group"] = ip_profile["security-group"] |
| 864 | |
| 865 | return ro_ip_profile |
| 866 | |
| sousaedu | 0ee9fdb | 2021-12-06 00:17:54 +0000 | [diff] [blame] | 867 | @staticmethod |
| 868 | def _process_net_params( |
| 869 | target_vld: Dict[str, Any], |
| 870 | indata: Dict[str, Any], |
| 871 | vim_info: Dict[str, Any], |
| 872 | target_record_id: str, |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 873 | **kwargs: Dict[str, Any], |
| sousaedu | 0ee9fdb | 2021-12-06 00:17:54 +0000 | [diff] [blame] | 874 | ) -> Dict[str, Any]: |
| 875 | """Function to process network parameters. |
| 876 | |
| 877 | Args: |
| 878 | target_vld (Dict[str, Any]): [description] |
| 879 | indata (Dict[str, Any]): [description] |
| 880 | vim_info (Dict[str, Any]): [description] |
| 881 | target_record_id (str): [description] |
| 882 | |
| 883 | Returns: |
| 884 | Dict[str, Any]: [description] |
| 885 | """ |
| 886 | extra_dict = {} |
| 887 | |
| 888 | if vim_info.get("sdn"): |
| 889 | # vnf_preffix = "vnfrs:{}".format(vnfr_id) |
| 890 | # ns_preffix = "nsrs:{}".format(nsr_id) |
| 891 | # remove the ending ".sdn |
| 892 | vld_target_record_id, _, _ = target_record_id.rpartition(".") |
| 893 | extra_dict["params"] = { |
| 894 | k: vim_info[k] |
| 895 | for k in ("sdn-ports", "target_vim", "vlds", "type") |
| 896 | if vim_info.get(k) |
| 897 | } |
| 898 | |
| 899 | # TODO needed to add target_id in the dependency. |
| 900 | if vim_info.get("target_vim"): |
| 901 | extra_dict["depends_on"] = [ |
| 902 | f"{vim_info.get('target_vim')} {vld_target_record_id}" |
| 903 | ] |
| 904 | |
| 905 | return extra_dict |
| 906 | |
| 907 | if vim_info.get("vim_network_name"): |
| 908 | extra_dict["find_params"] = { |
| 909 | "filter_dict": { |
| 910 | "name": vim_info.get("vim_network_name"), |
| 911 | }, |
| 912 | } |
| 913 | elif vim_info.get("vim_network_id"): |
| 914 | extra_dict["find_params"] = { |
| 915 | "filter_dict": { |
| 916 | "id": vim_info.get("vim_network_id"), |
| 917 | }, |
| 918 | } |
| 919 | elif target_vld.get("mgmt-network"): |
| 920 | extra_dict["find_params"] = { |
| 921 | "mgmt": True, |
| 922 | "name": target_vld["id"], |
| 923 | } |
| 924 | else: |
| 925 | # create |
| 926 | extra_dict["params"] = { |
| 927 | "net_name": ( |
| 928 | f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}" |
| 929 | ), |
| 930 | "ip_profile": Ns._ip_profile_to_ro(vim_info.get("ip_profile")), |
| 931 | "provider_network_profile": vim_info.get("provider_network"), |
| 932 | } |
| 933 | |
| 934 | if not target_vld.get("underlay"): |
| 935 | extra_dict["params"]["net_type"] = "bridge" |
| 936 | else: |
| 937 | extra_dict["params"]["net_type"] = ( |
| 938 | "ptp" if target_vld.get("type") == "ELINE" else "data" |
| 939 | ) |
| 940 | |
| 941 | return extra_dict |
| 942 | |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 943 | @staticmethod |
| aticig | cf14bb1 | 2022-05-19 13:03:17 +0300 | [diff] [blame] | 944 | def find_persistent_root_volumes( |
| 945 | vnfd: dict, |
| 946 | target_vdu: str, |
| 947 | vdu_instantiation_volumes_list: list, |
| 948 | disk_list: list, |
| 949 | ) -> (list, dict): |
| 950 | """Find the persistent root volumes and add them to the disk_list |
| 951 | by parsing the instantiation parameters |
| 952 | |
| 953 | Args: |
| 954 | vnfd: VNFD |
| 955 | target_vdu: processed VDU |
| 956 | vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list |
| 957 | disk_list: to be filled up |
| 958 | |
| 959 | Returns: |
| 960 | disk_list: filled VDU list which is used for VDU creation |
| 961 | |
| 962 | """ |
| 963 | persistent_root_disk = {} |
| 964 | |
| 965 | for vdu, vsd in product( |
| 966 | vnfd.get("vdu", ()), vnfd.get("virtual-storage-desc", ()) |
| 967 | ): |
| 968 | if ( |
| 969 | vdu["name"] == target_vdu["vdu-name"] |
| 970 | and vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0] |
| 971 | ): |
| 972 | root_disk = vsd |
| 973 | if ( |
| 974 | root_disk.get("type-of-storage") |
| 975 | == "persistent-storage:persistent-storage" |
| 976 | ): |
| 977 | for vdu_volume in vdu_instantiation_volumes_list: |
| 978 | |
| 979 | if ( |
| 980 | vdu_volume["vim-volume-id"] |
| 981 | and root_disk["id"] == vdu_volume["name"] |
| 982 | ): |
| 983 | |
| 984 | persistent_root_disk[vsd["id"]] = { |
| 985 | "vim_volume_id": vdu_volume["vim-volume-id"], |
| 986 | "image_id": vdu.get("sw-image-desc"), |
| 987 | } |
| 988 | |
| 989 | disk_list.append(persistent_root_disk[vsd["id"]]) |
| 990 | |
| 991 | # There can be only one root disk, when we find it, it will return the result |
| 992 | return disk_list, persistent_root_disk |
| 993 | |
| 994 | else: |
| 995 | |
| 996 | if root_disk.get("size-of-storage"): |
| 997 | persistent_root_disk[vsd["id"]] = { |
| 998 | "image_id": vdu.get("sw-image-desc"), |
| 999 | "size": root_disk.get("size-of-storage"), |
| 1000 | } |
| 1001 | |
| 1002 | disk_list.append(persistent_root_disk[vsd["id"]]) |
| 1003 | return disk_list, persistent_root_disk |
| 1004 | |
| 1005 | return disk_list, persistent_root_disk |
| 1006 | |
| 1007 | @staticmethod |
| 1008 | def find_persistent_volumes( |
| 1009 | persistent_root_disk: dict, |
| 1010 | target_vdu: str, |
| 1011 | vdu_instantiation_volumes_list: list, |
| 1012 | disk_list: list, |
| 1013 | ) -> list: |
| 1014 | """Find the ordinary persistent volumes and add them to the disk_list |
| 1015 | by parsing the instantiation parameters |
| 1016 | |
| 1017 | Args: |
| 1018 | persistent_root_disk: persistent root disk dictionary |
| 1019 | target_vdu: processed VDU |
| 1020 | vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list |
| 1021 | disk_list: to be filled up |
| 1022 | |
| 1023 | Returns: |
| 1024 | disk_list: filled VDU list which is used for VDU creation |
| 1025 | |
| 1026 | """ |
| 1027 | # Find the ordinary volumes which are not added to the persistent_root_disk |
| 1028 | persistent_disk = {} |
| 1029 | for disk in target_vdu.get("virtual-storages", {}): |
| 1030 | if ( |
| 1031 | disk.get("type-of-storage") == "persistent-storage:persistent-storage" |
| 1032 | and disk["id"] not in persistent_root_disk.keys() |
| 1033 | ): |
| 1034 | for vdu_volume in vdu_instantiation_volumes_list: |
| 1035 | |
| 1036 | if vdu_volume["vim-volume-id"] and disk["id"] == vdu_volume["name"]: |
| 1037 | |
| 1038 | persistent_disk[disk["id"]] = { |
| 1039 | "vim_volume_id": vdu_volume["vim-volume-id"], |
| 1040 | } |
| 1041 | disk_list.append(persistent_disk[disk["id"]]) |
| 1042 | |
| 1043 | else: |
| 1044 | if disk["id"] not in persistent_disk.keys(): |
| 1045 | persistent_disk[disk["id"]] = { |
| 1046 | "size": disk.get("size-of-storage"), |
| 1047 | } |
| 1048 | disk_list.append(persistent_disk[disk["id"]]) |
| 1049 | |
| 1050 | return disk_list |
| 1051 | |
| 1052 | @staticmethod |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 1053 | def _process_vdu_params( |
| 1054 | target_vdu: 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 | """Function to process VDU parameters. |
| 1061 | |
| 1062 | Args: |
| 1063 | target_vdu (Dict[str, Any]): [description] |
| 1064 | indata (Dict[str, Any]): [description] |
| 1065 | vim_info (Dict[str, Any]): [description] |
| 1066 | target_record_id (str): [description] |
| 1067 | |
| 1068 | Returns: |
| 1069 | Dict[str, Any]: [description] |
| 1070 | """ |
| 1071 | vnfr_id = kwargs.get("vnfr_id") |
| 1072 | nsr_id = kwargs.get("nsr_id") |
| 1073 | vnfr = kwargs.get("vnfr") |
| 1074 | vdu2cloud_init = kwargs.get("vdu2cloud_init") |
| 1075 | tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id") |
| 1076 | logger = kwargs.get("logger") |
| 1077 | db = kwargs.get("db") |
| 1078 | fs = kwargs.get("fs") |
| 1079 | ro_nsr_public_key = kwargs.get("ro_nsr_public_key") |
| 1080 | |
| 1081 | vnf_preffix = "vnfrs:{}".format(vnfr_id) |
| 1082 | ns_preffix = "nsrs:{}".format(nsr_id) |
| 1083 | image_text = ns_preffix + ":image." + target_vdu["ns-image-id"] |
| 1084 | flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"] |
| 1085 | extra_dict = {"depends_on": [image_text, flavor_text]} |
| 1086 | net_list = [] |
| 1087 | |
| aticig | d2a67cd | 2022-06-16 01:28:29 +0300 | [diff] [blame] | 1088 | # If the position info is provided for all the interfaces, it will be sorted |
| 1089 | # according to position number ascendingly. |
| aticig | 6585ea3 | 2022-06-24 16:01:05 +0300 | [diff] [blame^] | 1090 | if all( |
| 1091 | i.get("position") + 1 |
| 1092 | for i in target_vdu["interfaces"] |
| 1093 | if i.get("position") is not None |
| 1094 | ): |
| aticig | d2a67cd | 2022-06-16 01:28:29 +0300 | [diff] [blame] | 1095 | sorted_interfaces = sorted( |
| 1096 | target_vdu["interfaces"], |
| 1097 | key=lambda x: (x.get("position") is None, x.get("position")), |
| 1098 | ) |
| 1099 | target_vdu["interfaces"] = sorted_interfaces |
| 1100 | |
| 1101 | # If the position info is provided for some interfaces but not all of them, the interfaces |
| 1102 | # which has specific position numbers will be placed and others' positions will not be taken care. |
| 1103 | else: |
| aticig | 6585ea3 | 2022-06-24 16:01:05 +0300 | [diff] [blame^] | 1104 | if any( |
| 1105 | i.get("position") + 1 |
| 1106 | for i in target_vdu["interfaces"] |
| 1107 | if i.get("position") is not None |
| 1108 | ): |
| aticig | d2a67cd | 2022-06-16 01:28:29 +0300 | [diff] [blame] | 1109 | n = len(target_vdu["interfaces"]) |
| 1110 | sorted_interfaces = [-1] * n |
| 1111 | k, m = 0, 0 |
| 1112 | while k < n: |
| 1113 | if target_vdu["interfaces"][k].get("position"): |
| 1114 | idx = target_vdu["interfaces"][k]["position"] |
| 1115 | sorted_interfaces[idx - 1] = target_vdu["interfaces"][k] |
| 1116 | k += 1 |
| 1117 | while m < n: |
| 1118 | if not target_vdu["interfaces"][m].get("position"): |
| 1119 | idy = sorted_interfaces.index(-1) |
| 1120 | sorted_interfaces[idy] = target_vdu["interfaces"][m] |
| 1121 | m += 1 |
| 1122 | |
| 1123 | target_vdu["interfaces"] = sorted_interfaces |
| 1124 | |
| 1125 | # If the position info is not provided for the interfaces, interfaces will be attached |
| 1126 | # according to the order in the VNFD. |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 1127 | for iface_index, interface in enumerate(target_vdu["interfaces"]): |
| 1128 | if interface.get("ns-vld-id"): |
| 1129 | net_text = ns_preffix + ":vld." + interface["ns-vld-id"] |
| 1130 | elif interface.get("vnf-vld-id"): |
| 1131 | net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"] |
| 1132 | else: |
| 1133 | logger.error( |
| 1134 | "Interface {} from vdu {} not connected to any vld".format( |
| 1135 | iface_index, target_vdu["vdu-name"] |
| 1136 | ) |
| 1137 | ) |
| 1138 | |
| 1139 | continue # interface not connected to any vld |
| 1140 | |
| 1141 | extra_dict["depends_on"].append(net_text) |
| 1142 | |
| 1143 | if "port-security-enabled" in interface: |
| 1144 | interface["port_security"] = interface.pop("port-security-enabled") |
| 1145 | |
| 1146 | if "port-security-disable-strategy" in interface: |
| 1147 | interface["port_security_disable_strategy"] = interface.pop( |
| 1148 | "port-security-disable-strategy" |
| 1149 | ) |
| 1150 | |
| 1151 | net_item = { |
| 1152 | x: v |
| 1153 | for x, v in interface.items() |
| 1154 | if x |
| 1155 | in ( |
| 1156 | "name", |
| 1157 | "vpci", |
| 1158 | "port_security", |
| 1159 | "port_security_disable_strategy", |
| 1160 | "floating_ip", |
| 1161 | ) |
| 1162 | } |
| 1163 | net_item["net_id"] = "TASK-" + net_text |
| 1164 | net_item["type"] = "virtual" |
| 1165 | |
| 1166 | # TODO mac_address: used for SR-IOV ifaces #TODO for other types |
| 1167 | # TODO floating_ip: True/False (or it can be None) |
| 1168 | if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"): |
| 1169 | # mark the net create task as type data |
| 1170 | if deep_get( |
| 1171 | tasks_by_target_record_id, |
| 1172 | net_text, |
| gallardo | 0108e94 | 2022-03-14 18:16:41 +0000 | [diff] [blame] | 1173 | "extra_dict", |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 1174 | "params", |
| 1175 | "net_type", |
| 1176 | ): |
| gallardo | 0108e94 | 2022-03-14 18:16:41 +0000 | [diff] [blame] | 1177 | tasks_by_target_record_id[net_text]["extra_dict"]["params"][ |
| 1178 | "net_type" |
| 1179 | ] = "data" |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 1180 | |
| 1181 | net_item["use"] = "data" |
| 1182 | net_item["model"] = interface["type"] |
| 1183 | net_item["type"] = interface["type"] |
| 1184 | elif ( |
| 1185 | interface.get("type") == "OM-MGMT" |
| 1186 | or interface.get("mgmt-interface") |
| 1187 | or interface.get("mgmt-vnf") |
| 1188 | ): |
| 1189 | net_item["use"] = "mgmt" |
| 1190 | else: |
| 1191 | # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"): |
| 1192 | net_item["use"] = "bridge" |
| 1193 | net_item["model"] = interface.get("type") |
| 1194 | |
| 1195 | if interface.get("ip-address"): |
| 1196 | net_item["ip_address"] = interface["ip-address"] |
| 1197 | |
| 1198 | if interface.get("mac-address"): |
| 1199 | net_item["mac_address"] = interface["mac-address"] |
| 1200 | |
| 1201 | net_list.append(net_item) |
| 1202 | |
| 1203 | if interface.get("mgmt-vnf"): |
| 1204 | extra_dict["mgmt_vnf_interface"] = iface_index |
| 1205 | elif interface.get("mgmt-interface"): |
| 1206 | extra_dict["mgmt_vdu_interface"] = iface_index |
| 1207 | |
| 1208 | # cloud config |
| 1209 | cloud_config = {} |
| 1210 | |
| 1211 | if target_vdu.get("cloud-init"): |
| 1212 | if target_vdu["cloud-init"] not in vdu2cloud_init: |
| 1213 | vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init( |
| 1214 | db=db, |
| 1215 | fs=fs, |
| 1216 | location=target_vdu["cloud-init"], |
| 1217 | ) |
| 1218 | |
| 1219 | cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]] |
| 1220 | cloud_config["user-data"] = Ns._parse_jinja2( |
| 1221 | cloud_init_content=cloud_content_, |
| 1222 | params=target_vdu.get("additionalParams"), |
| 1223 | context=target_vdu["cloud-init"], |
| 1224 | ) |
| 1225 | |
| 1226 | if target_vdu.get("boot-data-drive"): |
| 1227 | cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive") |
| 1228 | |
| 1229 | ssh_keys = [] |
| 1230 | |
| 1231 | if target_vdu.get("ssh-keys"): |
| 1232 | ssh_keys += target_vdu.get("ssh-keys") |
| 1233 | |
| 1234 | if target_vdu.get("ssh-access-required"): |
| 1235 | ssh_keys.append(ro_nsr_public_key) |
| 1236 | |
| 1237 | if ssh_keys: |
| 1238 | cloud_config["key-pairs"] = ssh_keys |
| 1239 | |
| aticig | 179e002 | 2022-03-29 13:15:45 +0300 | [diff] [blame] | 1240 | persistent_root_disk = {} |
| aticig | cf14bb1 | 2022-05-19 13:03:17 +0300 | [diff] [blame] | 1241 | vdu_instantiation_volumes_list = [] |
| aticig | 179e002 | 2022-03-29 13:15:45 +0300 | [diff] [blame] | 1242 | disk_list = [] |
| 1243 | vnfd_id = vnfr["vnfd-id"] |
| 1244 | vnfd = db.get_one("vnfds", {"_id": vnfd_id}) |
| aticig | 179e002 | 2022-03-29 13:15:45 +0300 | [diff] [blame] | 1245 | |
| aticig | cf14bb1 | 2022-05-19 13:03:17 +0300 | [diff] [blame] | 1246 | if target_vdu.get("additionalParams"): |
| 1247 | vdu_instantiation_volumes_list = ( |
| 1248 | target_vdu.get("additionalParams").get("OSM").get("vdu_volumes") |
| 1249 | ) |
| 1250 | |
| 1251 | if vdu_instantiation_volumes_list: |
| 1252 | |
| 1253 | # Find the root volumes and add to the disk_list |
| 1254 | (disk_list, persistent_root_disk,) = Ns.find_persistent_root_volumes( |
| 1255 | vnfd, target_vdu, vdu_instantiation_volumes_list, disk_list |
| 1256 | ) |
| 1257 | |
| 1258 | # Find the ordinary volumes which are not added to the persistent_root_disk |
| 1259 | # and put them to the disk list |
| 1260 | disk_list = Ns.find_persistent_volumes( |
| 1261 | persistent_root_disk, |
| 1262 | target_vdu, |
| 1263 | vdu_instantiation_volumes_list, |
| 1264 | disk_list, |
| 1265 | ) |
| 1266 | |
| 1267 | else: |
| 1268 | |
| 1269 | # vdu_instantiation_volumes_list is empty |
| 1270 | for vdu in vnfd.get("vdu", ()): |
| 1271 | if vdu["name"] == target_vdu["vdu-name"]: |
| 1272 | for vsd in vnfd.get("virtual-storage-desc", ()): |
| 1273 | if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]: |
| 1274 | root_disk = vsd |
| 1275 | if root_disk.get( |
| 1276 | "type-of-storage" |
| 1277 | ) == "persistent-storage:persistent-storage" and root_disk.get( |
| 1278 | "size-of-storage" |
| 1279 | ): |
| 1280 | persistent_root_disk[vsd["id"]] = { |
| 1281 | "image_id": vdu.get("sw-image-desc"), |
| 1282 | "size": root_disk["size-of-storage"], |
| 1283 | } |
| 1284 | disk_list.append(persistent_root_disk[vsd["id"]]) |
| 1285 | |
| 1286 | if target_vdu.get("virtual-storages"): |
| 1287 | for disk in target_vdu["virtual-storages"]: |
| 1288 | if ( |
| 1289 | disk.get("type-of-storage") |
| 1290 | == "persistent-storage:persistent-storage" |
| 1291 | and disk["id"] not in persistent_root_disk.keys() |
| 1292 | ): |
| 1293 | disk_list.append({"size": disk["size-of-storage"]}) |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 1294 | |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 1295 | affinity_group_list = [] |
| 1296 | |
| 1297 | if target_vdu.get("affinity-or-anti-affinity-group-id"): |
| 1298 | affinity_group = {} |
| 1299 | for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]: |
| 1300 | affinity_group_text = ( |
| 1301 | ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id |
| 1302 | ) |
| 1303 | |
| 1304 | extra_dict["depends_on"].append(affinity_group_text) |
| 1305 | affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text |
| 1306 | affinity_group_list.append(affinity_group) |
| 1307 | |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 1308 | extra_dict["params"] = { |
| 1309 | "name": "{}-{}-{}-{}".format( |
| 1310 | indata["name"][:16], |
| 1311 | vnfr["member-vnf-index-ref"][:16], |
| 1312 | target_vdu["vdu-name"][:32], |
| 1313 | target_vdu.get("count-index") or 0, |
| 1314 | ), |
| 1315 | "description": target_vdu["vdu-name"], |
| 1316 | "start": True, |
| 1317 | "image_id": "TASK-" + image_text, |
| 1318 | "flavor_id": "TASK-" + flavor_text, |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 1319 | "affinity_group_list": affinity_group_list, |
| sousaedu | 0b1e734 | 2021-12-07 15:33:46 +0000 | [diff] [blame] | 1320 | "net_list": net_list, |
| 1321 | "cloud_config": cloud_config or None, |
| 1322 | "disk_list": disk_list, |
| 1323 | "availability_zone_index": None, # TODO |
| 1324 | "availability_zone_list": None, # TODO |
| 1325 | } |
| 1326 | |
| 1327 | return extra_dict |
| 1328 | |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 1329 | @staticmethod |
| 1330 | def _process_affinity_group_params( |
| 1331 | target_affinity_group: Dict[str, Any], |
| 1332 | indata: Dict[str, Any], |
| 1333 | vim_info: Dict[str, Any], |
| 1334 | target_record_id: str, |
| 1335 | **kwargs: Dict[str, Any], |
| 1336 | ) -> Dict[str, Any]: |
| 1337 | """Get affinity or anti-affinity group parameters. |
| 1338 | |
| 1339 | Args: |
| 1340 | target_affinity_group (Dict[str, Any]): [description] |
| 1341 | indata (Dict[str, Any]): [description] |
| 1342 | vim_info (Dict[str, Any]): [description] |
| 1343 | target_record_id (str): [description] |
| 1344 | |
| 1345 | Returns: |
| 1346 | Dict[str, Any]: [description] |
| 1347 | """ |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 1348 | |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1349 | extra_dict = {} |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 1350 | affinity_group_data = { |
| 1351 | "name": target_affinity_group["name"], |
| 1352 | "type": target_affinity_group["type"], |
| 1353 | "scope": target_affinity_group["scope"], |
| 1354 | } |
| 1355 | |
| Alexis Romero | 123de18 | 2022-04-26 19:24:40 +0200 | [diff] [blame] | 1356 | if target_affinity_group.get("vim-affinity-group-id"): |
| 1357 | affinity_group_data["vim-affinity-group-id"] = target_affinity_group[ |
| 1358 | "vim-affinity-group-id" |
| 1359 | ] |
| 1360 | |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 1361 | extra_dict["params"] = { |
| 1362 | "affinity_group_data": affinity_group_data, |
| 1363 | } |
| 1364 | |
| 1365 | return extra_dict |
| 1366 | |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1367 | @staticmethod |
| 1368 | def _process_recreate_vdu_params( |
| 1369 | existing_vdu: Dict[str, Any], |
| 1370 | db_nsr: Dict[str, Any], |
| 1371 | vim_info: Dict[str, Any], |
| 1372 | target_record_id: str, |
| 1373 | target_id: str, |
| 1374 | **kwargs: Dict[str, Any], |
| 1375 | ) -> Dict[str, Any]: |
| 1376 | """Function to process VDU parameters to recreate. |
| 1377 | |
| 1378 | Args: |
| 1379 | existing_vdu (Dict[str, Any]): [description] |
| 1380 | db_nsr (Dict[str, Any]): [description] |
| 1381 | vim_info (Dict[str, Any]): [description] |
| 1382 | target_record_id (str): [description] |
| 1383 | target_id (str): [description] |
| 1384 | |
| 1385 | Returns: |
| 1386 | Dict[str, Any]: [description] |
| 1387 | """ |
| 1388 | vnfr = kwargs.get("vnfr") |
| 1389 | vdu2cloud_init = kwargs.get("vdu2cloud_init") |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 1390 | # logger = kwargs.get("logger") |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1391 | db = kwargs.get("db") |
| 1392 | fs = kwargs.get("fs") |
| 1393 | ro_nsr_public_key = kwargs.get("ro_nsr_public_key") |
| 1394 | |
| 1395 | extra_dict = {} |
| 1396 | net_list = [] |
| 1397 | |
| 1398 | vim_details = {} |
| 1399 | vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None) |
| 1400 | if vim_details_text: |
| 1401 | vim_details = yaml.safe_load(f"{vim_details_text}") |
| 1402 | |
| 1403 | for iface_index, interface in enumerate(existing_vdu["interfaces"]): |
| 1404 | |
| 1405 | if "port-security-enabled" in interface: |
| 1406 | interface["port_security"] = interface.pop("port-security-enabled") |
| 1407 | |
| 1408 | if "port-security-disable-strategy" in interface: |
| 1409 | interface["port_security_disable_strategy"] = interface.pop( |
| 1410 | "port-security-disable-strategy" |
| 1411 | ) |
| 1412 | |
| 1413 | net_item = { |
| 1414 | x: v |
| 1415 | for x, v in interface.items() |
| 1416 | if x |
| 1417 | in ( |
| 1418 | "name", |
| 1419 | "vpci", |
| 1420 | "port_security", |
| 1421 | "port_security_disable_strategy", |
| 1422 | "floating_ip", |
| 1423 | ) |
| 1424 | } |
| garciadeblas | bf23519 | 2022-06-13 10:02:51 +0200 | [diff] [blame] | 1425 | existing_ifaces = existing_vdu["vim_info"][target_id].get( |
| 1426 | "interfaces_backup", [] |
| 1427 | ) |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1428 | net_id = next( |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 1429 | ( |
| 1430 | i["vim_net_id"] |
| 1431 | for i in existing_ifaces |
| 1432 | if i["ip_address"] == interface["ip-address"] |
| 1433 | ), |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1434 | None, |
| 1435 | ) |
| 1436 | |
| 1437 | net_item["net_id"] = net_id |
| 1438 | net_item["type"] = "virtual" |
| 1439 | |
| 1440 | # TODO mac_address: used for SR-IOV ifaces #TODO for other types |
| 1441 | # TODO floating_ip: True/False (or it can be None) |
| 1442 | if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"): |
| 1443 | net_item["use"] = "data" |
| 1444 | net_item["model"] = interface["type"] |
| 1445 | net_item["type"] = interface["type"] |
| 1446 | elif ( |
| 1447 | interface.get("type") == "OM-MGMT" |
| 1448 | or interface.get("mgmt-interface") |
| 1449 | or interface.get("mgmt-vnf") |
| 1450 | ): |
| 1451 | net_item["use"] = "mgmt" |
| 1452 | else: |
| 1453 | # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"): |
| 1454 | net_item["use"] = "bridge" |
| 1455 | net_item["model"] = interface.get("type") |
| 1456 | |
| 1457 | if interface.get("ip-address"): |
| 1458 | net_item["ip_address"] = interface["ip-address"] |
| 1459 | |
| 1460 | if interface.get("mac-address"): |
| 1461 | net_item["mac_address"] = interface["mac-address"] |
| 1462 | |
| 1463 | net_list.append(net_item) |
| 1464 | |
| 1465 | if interface.get("mgmt-vnf"): |
| 1466 | extra_dict["mgmt_vnf_interface"] = iface_index |
| 1467 | elif interface.get("mgmt-interface"): |
| 1468 | extra_dict["mgmt_vdu_interface"] = iface_index |
| 1469 | |
| 1470 | # cloud config |
| 1471 | cloud_config = {} |
| 1472 | |
| 1473 | if existing_vdu.get("cloud-init"): |
| 1474 | if existing_vdu["cloud-init"] not in vdu2cloud_init: |
| 1475 | vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init( |
| 1476 | db=db, |
| 1477 | fs=fs, |
| 1478 | location=existing_vdu["cloud-init"], |
| 1479 | ) |
| 1480 | |
| 1481 | cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]] |
| 1482 | cloud_config["user-data"] = Ns._parse_jinja2( |
| 1483 | cloud_init_content=cloud_content_, |
| 1484 | params=existing_vdu.get("additionalParams"), |
| 1485 | context=existing_vdu["cloud-init"], |
| 1486 | ) |
| 1487 | |
| 1488 | if existing_vdu.get("boot-data-drive"): |
| 1489 | cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive") |
| 1490 | |
| 1491 | ssh_keys = [] |
| 1492 | |
| 1493 | if existing_vdu.get("ssh-keys"): |
| 1494 | ssh_keys += existing_vdu.get("ssh-keys") |
| 1495 | |
| 1496 | if existing_vdu.get("ssh-access-required"): |
| 1497 | ssh_keys.append(ro_nsr_public_key) |
| 1498 | |
| 1499 | if ssh_keys: |
| 1500 | cloud_config["key-pairs"] = ssh_keys |
| 1501 | |
| 1502 | disk_list = [] |
| 1503 | for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []): |
| 1504 | disk_list.append({"vim_id": vol_id["id"]}) |
| 1505 | |
| 1506 | affinity_group_list = [] |
| 1507 | |
| 1508 | if existing_vdu.get("affinity-or-anti-affinity-group-id"): |
| 1509 | affinity_group = {} |
| 1510 | for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]: |
| 1511 | for group in db_nsr.get("affinity-or-anti-affinity-group"): |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 1512 | if ( |
| 1513 | group["id"] == affinity_group_id |
| 1514 | and group["vim_info"][target_id].get("vim_id", None) is not None |
| 1515 | ): |
| 1516 | affinity_group["affinity_group_id"] = group["vim_info"][ |
| 1517 | target_id |
| 1518 | ].get("vim_id", None) |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1519 | affinity_group_list.append(affinity_group) |
| 1520 | |
| 1521 | extra_dict["params"] = { |
| 1522 | "name": "{}-{}-{}-{}".format( |
| 1523 | db_nsr["name"][:16], |
| 1524 | vnfr["member-vnf-index-ref"][:16], |
| 1525 | existing_vdu["vdu-name"][:32], |
| 1526 | existing_vdu.get("count-index") or 0, |
| 1527 | ), |
| 1528 | "description": existing_vdu["vdu-name"], |
| 1529 | "start": True, |
| 1530 | "image_id": vim_details["image"]["id"], |
| 1531 | "flavor_id": vim_details["flavor"]["id"], |
| 1532 | "affinity_group_list": affinity_group_list, |
| 1533 | "net_list": net_list, |
| 1534 | "cloud_config": cloud_config or None, |
| 1535 | "disk_list": disk_list, |
| 1536 | "availability_zone_index": None, # TODO |
| 1537 | "availability_zone_list": None, # TODO |
| 1538 | } |
| 1539 | |
| 1540 | return extra_dict |
| 1541 | |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1542 | def calculate_diff_items( |
| 1543 | self, |
| 1544 | indata, |
| 1545 | db_nsr, |
| 1546 | db_ro_nsr, |
| 1547 | db_nsr_update, |
| 1548 | item, |
| 1549 | tasks_by_target_record_id, |
| 1550 | action_id, |
| 1551 | nsr_id, |
| 1552 | task_index, |
| 1553 | vnfr_id=None, |
| 1554 | vnfr=None, |
| 1555 | ): |
| 1556 | """Function that returns the incremental changes (creation, deletion) |
| 1557 | related to a specific item `item` to be done. This function should be |
| 1558 | called for NS instantiation, NS termination, NS update to add a new VNF |
| 1559 | or a new VLD, remove a VNF or VLD, etc. |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1560 | Item can be `net`, `flavor`, `image` or `vdu`. |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1561 | It takes a list of target items from indata (which came from the REST API) |
| 1562 | and compares with the existing items from db_ro_nsr, identifying the |
| 1563 | incremental changes to be done. During the comparison, it calls the method |
| 1564 | `process_params` (which was passed as parameter, and is particular for each |
| 1565 | `item`) |
| 1566 | |
| 1567 | Args: |
| 1568 | indata (Dict[str, Any]): deployment info |
| 1569 | db_nsr: NSR record from DB |
| 1570 | db_ro_nsr (Dict[str, Any]): record from "ro_nsrs" |
| 1571 | db_nsr_update (Dict[str, Any]): NSR info to update in DB |
| 1572 | item (str): element to process (net, vdu...) |
| 1573 | tasks_by_target_record_id (Dict[str, Any]): |
| 1574 | [<target_record_id>, <task>] |
| 1575 | action_id (str): action id |
| 1576 | nsr_id (str): NSR id |
| 1577 | task_index (number): task index to add to task name |
| 1578 | vnfr_id (str): VNFR id |
| 1579 | vnfr (Dict[str, Any]): VNFR info |
| 1580 | |
| 1581 | Returns: |
| 1582 | List: list with the incremental changes (deletes, creates) for each item |
| 1583 | number: current task index |
| 1584 | """ |
| 1585 | |
| 1586 | diff_items = [] |
| 1587 | db_path = "" |
| 1588 | db_record = "" |
| 1589 | target_list = [] |
| 1590 | existing_list = [] |
| 1591 | process_params = None |
| 1592 | vdu2cloud_init = indata.get("cloud_init_content") or {} |
| 1593 | ro_nsr_public_key = db_ro_nsr["public_key"] |
| 1594 | |
| 1595 | # According to the type of item, the path, the target_list, |
| 1596 | # the existing_list and the method to process params are set |
| 1597 | db_path = self.db_path_map[item] |
| 1598 | process_params = self.process_params_function_map[item] |
| 1599 | if item in ("net", "vdu"): |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1600 | # This case is specific for the NS VLD (not applied to VDU) |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1601 | if vnfr is None: |
| 1602 | db_record = "nsrs:{}:{}".format(nsr_id, db_path) |
| aticig | 2b24d62 | 2022-03-11 15:03:55 +0300 | [diff] [blame] | 1603 | target_list = indata.get("ns", []).get(db_path, []) |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1604 | existing_list = db_nsr.get(db_path, []) |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1605 | # This case is common for VNF VLDs and VNF VDUs |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1606 | else: |
| 1607 | db_record = "vnfrs:{}:{}".format(vnfr_id, db_path) |
| 1608 | target_vnf = next( |
| 1609 | (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id), |
| 1610 | None, |
| 1611 | ) |
| 1612 | target_list = target_vnf.get(db_path, []) if target_vnf else [] |
| 1613 | existing_list = vnfr.get(db_path, []) |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 1614 | elif item in ("image", "flavor", "affinity-or-anti-affinity-group"): |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1615 | db_record = "nsrs:{}:{}".format(nsr_id, db_path) |
| 1616 | target_list = indata.get(item, []) |
| 1617 | existing_list = db_nsr.get(item, []) |
| 1618 | else: |
| 1619 | raise NsException("Item not supported: {}", item) |
| 1620 | |
| 1621 | # ensure all the target_list elements has an "id". If not assign the index as id |
| 1622 | if target_list is None: |
| 1623 | target_list = [] |
| 1624 | for target_index, tl in enumerate(target_list): |
| 1625 | if tl and not tl.get("id"): |
| 1626 | tl["id"] = str(target_index) |
| 1627 | |
| 1628 | # step 1 items (networks,vdus,...) to be deleted/updated |
| 1629 | for item_index, existing_item in enumerate(existing_list): |
| 1630 | target_item = next( |
| 1631 | (t for t in target_list if t["id"] == existing_item["id"]), |
| 1632 | None, |
| 1633 | ) |
| 1634 | |
| 1635 | for target_vim, existing_viminfo in existing_item.get( |
| 1636 | "vim_info", {} |
| 1637 | ).items(): |
| 1638 | if existing_viminfo is None: |
| 1639 | continue |
| 1640 | |
| 1641 | if target_item: |
| 1642 | target_viminfo = target_item.get("vim_info", {}).get(target_vim) |
| 1643 | else: |
| 1644 | target_viminfo = None |
| 1645 | |
| 1646 | if target_viminfo is None: |
| 1647 | # must be deleted |
| 1648 | self._assign_vim(target_vim) |
| 1649 | target_record_id = "{}.{}".format(db_record, existing_item["id"]) |
| 1650 | item_ = item |
| 1651 | |
| 1652 | if target_vim.startswith("sdn"): |
| 1653 | # item must be sdn-net instead of net if target_vim is a sdn |
| 1654 | item_ = "sdn_net" |
| 1655 | target_record_id += ".sdn" |
| 1656 | |
| 1657 | deployment_info = { |
| 1658 | "action_id": action_id, |
| 1659 | "nsr_id": nsr_id, |
| 1660 | "task_index": task_index, |
| 1661 | } |
| 1662 | |
| 1663 | diff_items.append( |
| 1664 | { |
| 1665 | "deployment_info": deployment_info, |
| 1666 | "target_id": target_vim, |
| 1667 | "item": item_, |
| 1668 | "action": "DELETE", |
| 1669 | "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}", |
| 1670 | "target_record_id": target_record_id, |
| 1671 | } |
| 1672 | ) |
| 1673 | task_index += 1 |
| 1674 | |
| 1675 | # step 2 items (networks,vdus,...) to be created |
| 1676 | for target_item in target_list: |
| 1677 | item_index = -1 |
| 1678 | |
| 1679 | for item_index, existing_item in enumerate(existing_list): |
| 1680 | if existing_item["id"] == target_item["id"]: |
| 1681 | break |
| 1682 | else: |
| 1683 | item_index += 1 |
| 1684 | db_nsr_update[db_path + ".{}".format(item_index)] = target_item |
| 1685 | existing_list.append(target_item) |
| 1686 | existing_item = None |
| 1687 | |
| 1688 | for target_vim, target_viminfo in target_item.get("vim_info", {}).items(): |
| 1689 | existing_viminfo = None |
| 1690 | |
| 1691 | if existing_item: |
| 1692 | existing_viminfo = existing_item.get("vim_info", {}).get(target_vim) |
| 1693 | |
| 1694 | if existing_viminfo is not None: |
| 1695 | continue |
| 1696 | |
| 1697 | target_record_id = "{}.{}".format(db_record, target_item["id"]) |
| 1698 | item_ = item |
| 1699 | |
| 1700 | if target_vim.startswith("sdn"): |
| 1701 | # item must be sdn-net instead of net if target_vim is a sdn |
| 1702 | item_ = "sdn_net" |
| 1703 | target_record_id += ".sdn" |
| 1704 | |
| 1705 | kwargs = {} |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1706 | self.logger.warning( |
| 1707 | "ns.calculate_diff_items target_item={}".format(target_item) |
| 1708 | ) |
| aticig | cf14bb1 | 2022-05-19 13:03:17 +0300 | [diff] [blame] | 1709 | if process_params == Ns._process_flavor_params: |
| 1710 | kwargs.update( |
| 1711 | { |
| 1712 | "db": self.db, |
| 1713 | } |
| 1714 | ) |
| 1715 | self.logger.warning( |
| 1716 | "calculate_diff_items for flavor kwargs={}".format(kwargs) |
| 1717 | ) |
| 1718 | |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1719 | if process_params == Ns._process_vdu_params: |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1720 | self.logger.warning( |
| 1721 | "calculate_diff_items self.fs={}".format(self.fs) |
| 1722 | ) |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1723 | kwargs.update( |
| 1724 | { |
| 1725 | "vnfr_id": vnfr_id, |
| 1726 | "nsr_id": nsr_id, |
| 1727 | "vnfr": vnfr, |
| 1728 | "vdu2cloud_init": vdu2cloud_init, |
| 1729 | "tasks_by_target_record_id": tasks_by_target_record_id, |
| 1730 | "logger": self.logger, |
| 1731 | "db": self.db, |
| 1732 | "fs": self.fs, |
| 1733 | "ro_nsr_public_key": ro_nsr_public_key, |
| 1734 | } |
| 1735 | ) |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1736 | self.logger.warning("calculate_diff_items kwargs={}".format(kwargs)) |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1737 | |
| 1738 | extra_dict = process_params( |
| 1739 | target_item, |
| 1740 | indata, |
| 1741 | target_viminfo, |
| 1742 | target_record_id, |
| 1743 | **kwargs, |
| 1744 | ) |
| 1745 | self._assign_vim(target_vim) |
| 1746 | |
| 1747 | deployment_info = { |
| 1748 | "action_id": action_id, |
| 1749 | "nsr_id": nsr_id, |
| 1750 | "task_index": task_index, |
| 1751 | } |
| 1752 | |
| gallardo | 0108e94 | 2022-03-14 18:16:41 +0000 | [diff] [blame] | 1753 | new_item = { |
| 1754 | "deployment_info": deployment_info, |
| 1755 | "target_id": target_vim, |
| 1756 | "item": item_, |
| 1757 | "action": "CREATE", |
| 1758 | "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}", |
| 1759 | "target_record_id": target_record_id, |
| 1760 | "extra_dict": extra_dict, |
| 1761 | "common_id": target_item.get("common_id", None), |
| 1762 | } |
| 1763 | diff_items.append(new_item) |
| 1764 | tasks_by_target_record_id[target_record_id] = new_item |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1765 | task_index += 1 |
| 1766 | |
| 1767 | db_nsr_update[db_path + ".{}".format(item_index)] = target_item |
| 1768 | |
| 1769 | return diff_items, task_index |
| 1770 | |
| 1771 | def calculate_all_differences_to_deploy( |
| 1772 | self, |
| 1773 | indata, |
| 1774 | nsr_id, |
| 1775 | db_nsr, |
| 1776 | db_vnfrs, |
| 1777 | db_ro_nsr, |
| 1778 | db_nsr_update, |
| 1779 | db_vnfrs_update, |
| 1780 | action_id, |
| 1781 | tasks_by_target_record_id, |
| 1782 | ): |
| 1783 | """This method calculates the ordered list of items (`changes_list`) |
| 1784 | to be created and deleted. |
| 1785 | |
| 1786 | Args: |
| 1787 | indata (Dict[str, Any]): deployment info |
| 1788 | nsr_id (str): NSR id |
| 1789 | db_nsr: NSR record from DB |
| 1790 | db_vnfrs: VNFRS record from DB |
| 1791 | db_ro_nsr (Dict[str, Any]): record from "ro_nsrs" |
| 1792 | db_nsr_update (Dict[str, Any]): NSR info to update in DB |
| 1793 | db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB |
| 1794 | action_id (str): action id |
| 1795 | tasks_by_target_record_id (Dict[str, Any]): |
| 1796 | [<target_record_id>, <task>] |
| 1797 | |
| 1798 | Returns: |
| 1799 | List: ordered list of items to be created and deleted. |
| 1800 | """ |
| 1801 | |
| 1802 | task_index = 0 |
| 1803 | # set list with diffs: |
| 1804 | changes_list = [] |
| 1805 | |
| 1806 | # NS vld, image and flavor |
| Alexis Romero | b70f4ed | 2022-03-11 18:00:49 +0100 | [diff] [blame] | 1807 | for item in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]: |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1808 | self.logger.debug("process NS={} {}".format(nsr_id, item)) |
| 1809 | diff_items, task_index = self.calculate_diff_items( |
| 1810 | indata=indata, |
| 1811 | db_nsr=db_nsr, |
| 1812 | db_ro_nsr=db_ro_nsr, |
| 1813 | db_nsr_update=db_nsr_update, |
| 1814 | item=item, |
| 1815 | tasks_by_target_record_id=tasks_by_target_record_id, |
| 1816 | action_id=action_id, |
| 1817 | nsr_id=nsr_id, |
| 1818 | task_index=task_index, |
| 1819 | vnfr_id=None, |
| 1820 | ) |
| 1821 | changes_list += diff_items |
| 1822 | |
| 1823 | # VNF vlds and vdus |
| 1824 | for vnfr_id, vnfr in db_vnfrs.items(): |
| 1825 | # vnfr_id need to be set as global variable for among others nested method _process_vdu_params |
| 1826 | for item in ["net", "vdu"]: |
| 1827 | self.logger.debug("process VNF={} {}".format(vnfr_id, item)) |
| 1828 | diff_items, task_index = self.calculate_diff_items( |
| 1829 | indata=indata, |
| 1830 | db_nsr=db_nsr, |
| 1831 | db_ro_nsr=db_ro_nsr, |
| 1832 | db_nsr_update=db_vnfrs_update[vnfr["_id"]], |
| 1833 | item=item, |
| 1834 | tasks_by_target_record_id=tasks_by_target_record_id, |
| 1835 | action_id=action_id, |
| 1836 | nsr_id=nsr_id, |
| 1837 | task_index=task_index, |
| 1838 | vnfr_id=vnfr_id, |
| 1839 | vnfr=vnfr, |
| 1840 | ) |
| 1841 | changes_list += diff_items |
| 1842 | |
| 1843 | return changes_list |
| 1844 | |
| 1845 | def define_all_tasks( |
| 1846 | self, |
| 1847 | changes_list, |
| 1848 | db_new_tasks, |
| 1849 | tasks_by_target_record_id, |
| 1850 | ): |
| 1851 | """Function to create all the task structures obtanied from |
| 1852 | the method calculate_all_differences_to_deploy |
| 1853 | |
| 1854 | Args: |
| 1855 | changes_list (List): ordered list of items to be created or deleted |
| 1856 | db_new_tasks (List): tasks list to be created |
| 1857 | action_id (str): action id |
| 1858 | tasks_by_target_record_id (Dict[str, Any]): |
| 1859 | [<target_record_id>, <task>] |
| 1860 | |
| 1861 | """ |
| 1862 | |
| 1863 | for change in changes_list: |
| 1864 | task = Ns._create_task( |
| 1865 | deployment_info=change["deployment_info"], |
| 1866 | target_id=change["target_id"], |
| 1867 | item=change["item"], |
| 1868 | action=change["action"], |
| 1869 | target_record=change["target_record"], |
| 1870 | target_record_id=change["target_record_id"], |
| 1871 | extra_dict=change.get("extra_dict", None), |
| 1872 | ) |
| 1873 | |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 1874 | self.logger.warning("ns.define_all_tasks task={}".format(task)) |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1875 | tasks_by_target_record_id[change["target_record_id"]] = task |
| 1876 | db_new_tasks.append(task) |
| 1877 | |
| 1878 | if change.get("common_id"): |
| 1879 | task["common_id"] = change["common_id"] |
| 1880 | |
| 1881 | def upload_all_tasks( |
| 1882 | self, |
| 1883 | db_new_tasks, |
| 1884 | now, |
| 1885 | ): |
| 1886 | """Function to save all tasks in the common DB |
| 1887 | |
| 1888 | Args: |
| 1889 | db_new_tasks (List): tasks list to be created |
| 1890 | now (time): current time |
| 1891 | |
| 1892 | """ |
| 1893 | |
| 1894 | nb_ro_tasks = 0 # for logging |
| 1895 | |
| 1896 | for db_task in db_new_tasks: |
| 1897 | target_id = db_task.pop("target_id") |
| 1898 | common_id = db_task.get("common_id") |
| 1899 | |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 1900 | # Do not chek tasks with vim_status DELETED |
| 1901 | # because in manual heealing there are two tasks for the same vdur: |
| 1902 | # one with vim_status deleted and the other one with the actual VM status. |
| 1903 | |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1904 | if common_id: |
| 1905 | if self.db.set_one( |
| 1906 | "ro_tasks", |
| 1907 | q_filter={ |
| 1908 | "target_id": target_id, |
| 1909 | "tasks.common_id": common_id, |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 1910 | "vim_info.vim_status.ne": "DELETED", |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1911 | }, |
| 1912 | update_dict={"to_check_at": now, "modified_at": now}, |
| 1913 | push={"tasks": db_task}, |
| 1914 | fail_on_empty=False, |
| 1915 | ): |
| 1916 | continue |
| 1917 | |
| 1918 | if not self.db.set_one( |
| 1919 | "ro_tasks", |
| 1920 | q_filter={ |
| 1921 | "target_id": target_id, |
| 1922 | "tasks.target_record": db_task["target_record"], |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 1923 | "vim_info.vim_status.ne": "DELETED", |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 1924 | }, |
| 1925 | update_dict={"to_check_at": now, "modified_at": now}, |
| 1926 | push={"tasks": db_task}, |
| 1927 | fail_on_empty=False, |
| 1928 | ): |
| 1929 | # Create a ro_task |
| 1930 | self.logger.debug("Updating database, Creating ro_tasks") |
| 1931 | db_ro_task = Ns._create_ro_task(target_id, db_task) |
| 1932 | nb_ro_tasks += 1 |
| 1933 | self.db.create("ro_tasks", db_ro_task) |
| 1934 | |
| 1935 | self.logger.debug( |
| 1936 | "Created {} ro_tasks; {} tasks - db_new_tasks={}".format( |
| 1937 | nb_ro_tasks, len(db_new_tasks), db_new_tasks |
| 1938 | ) |
| 1939 | ) |
| 1940 | |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1941 | def upload_recreate_tasks( |
| 1942 | self, |
| 1943 | db_new_tasks, |
| 1944 | now, |
| 1945 | ): |
| 1946 | """Function to save recreate tasks in the common DB |
| 1947 | |
| 1948 | Args: |
| 1949 | db_new_tasks (List): tasks list to be created |
| 1950 | now (time): current time |
| 1951 | |
| 1952 | """ |
| 1953 | |
| 1954 | nb_ro_tasks = 0 # for logging |
| 1955 | |
| 1956 | for db_task in db_new_tasks: |
| 1957 | target_id = db_task.pop("target_id") |
| 1958 | self.logger.warning("target_id={} db_task={}".format(target_id, db_task)) |
| 1959 | |
| 1960 | action = db_task.get("action", None) |
| 1961 | |
| 1962 | # Create a ro_task |
| 1963 | self.logger.debug("Updating database, Creating ro_tasks") |
| 1964 | db_ro_task = Ns._create_ro_task(target_id, db_task) |
| 1965 | |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 1966 | # If DELETE task: the associated created items should be removed |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1967 | # (except persistent volumes): |
| 1968 | if action == "DELETE": |
| 1969 | db_ro_task["vim_info"]["created"] = True |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 1970 | db_ro_task["vim_info"]["created_items"] = db_task.get( |
| 1971 | "created_items", {} |
| 1972 | ) |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 1973 | db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get( |
| 1974 | "volumes_to_hold", [] |
| 1975 | ) |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1976 | db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None) |
| 1977 | |
| 1978 | nb_ro_tasks += 1 |
| 1979 | self.logger.warning("upload_all_tasks db_ro_task={}".format(db_ro_task)) |
| 1980 | self.db.create("ro_tasks", db_ro_task) |
| 1981 | |
| 1982 | self.logger.debug( |
| 1983 | "Created {} ro_tasks; {} tasks - db_new_tasks={}".format( |
| 1984 | nb_ro_tasks, len(db_new_tasks), db_new_tasks |
| 1985 | ) |
| 1986 | ) |
| 1987 | |
| 1988 | def _prepare_created_items_for_healing( |
| 1989 | self, |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 1990 | nsr_id, |
| 1991 | target_record, |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 1992 | ): |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 1993 | created_items = {} |
| 1994 | # Get created_items from ro_task |
| 1995 | ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id}) |
| 1996 | for ro_task in ro_tasks: |
| 1997 | for task in ro_task["tasks"]: |
| 1998 | if ( |
| 1999 | task["target_record"] == target_record |
| 2000 | and task["action"] == "CREATE" |
| 2001 | and ro_task["vim_info"]["created_items"] |
| 2002 | ): |
| 2003 | created_items = ro_task["vim_info"]["created_items"] |
| 2004 | break |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2005 | |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 2006 | return created_items |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2007 | |
| 2008 | def _prepare_persistent_volumes_for_healing( |
| 2009 | self, |
| 2010 | target_id, |
| 2011 | existing_vdu, |
| 2012 | ): |
| 2013 | # The associated volumes of the VM shouldn't be removed |
| 2014 | volumes_list = [] |
| 2015 | vim_details = {} |
| 2016 | vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None) |
| 2017 | if vim_details_text: |
| 2018 | vim_details = yaml.safe_load(f"{vim_details_text}") |
| 2019 | |
| 2020 | for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []): |
| 2021 | volumes_list.append(vol_id["id"]) |
| 2022 | |
| 2023 | return volumes_list |
| 2024 | |
| 2025 | def prepare_changes_to_recreate( |
| 2026 | self, |
| 2027 | indata, |
| 2028 | nsr_id, |
| 2029 | db_nsr, |
| 2030 | db_vnfrs, |
| 2031 | db_ro_nsr, |
| 2032 | action_id, |
| 2033 | tasks_by_target_record_id, |
| 2034 | ): |
| 2035 | """This method will obtain an ordered list of items (`changes_list`) |
| 2036 | to be created and deleted to meet the recreate request. |
| 2037 | """ |
| 2038 | |
| 2039 | self.logger.debug( |
| 2040 | "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata) |
| 2041 | ) |
| 2042 | |
| 2043 | task_index = 0 |
| 2044 | # set list with diffs: |
| 2045 | changes_list = [] |
| 2046 | db_path = self.db_path_map["vdu"] |
| 2047 | target_list = indata.get("healVnfData", {}) |
| 2048 | vdu2cloud_init = indata.get("cloud_init_content") or {} |
| 2049 | ro_nsr_public_key = db_ro_nsr["public_key"] |
| 2050 | |
| 2051 | # Check each VNF of the target |
| 2052 | for target_vnf in target_list: |
| 2053 | # Find this VNF in the list from DB |
| 2054 | vnfr_id = target_vnf.get("vnfInstanceId", None) |
| 2055 | if vnfr_id: |
| 2056 | existing_vnf = db_vnfrs.get(vnfr_id) |
| 2057 | db_record = "vnfrs:{}:{}".format(vnfr_id, db_path) |
| 2058 | # vim_account_id = existing_vnf.get("vim-account-id", "") |
| 2059 | |
| 2060 | # Check each VDU of this VNF |
| 2061 | for target_vdu in target_vnf["additionalParams"].get("vdu", None): |
| 2062 | vdu_name = target_vdu.get("vdu-id", None) |
| 2063 | # For multi instance VDU count-index is mandatory |
| 2064 | # For single session VDU count-indes is 0 |
| 2065 | count_index = target_vdu.get("count-index", 0) |
| 2066 | item_index = 0 |
| 2067 | existing_instance = None |
| 2068 | for instance in existing_vnf.get("vdur", None): |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 2069 | if ( |
| 2070 | instance["vdu-name"] == vdu_name |
| 2071 | and instance["count-index"] == count_index |
| 2072 | ): |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2073 | existing_instance = instance |
| 2074 | break |
| 2075 | else: |
| 2076 | item_index += 1 |
| 2077 | |
| 2078 | target_record_id = "{}.{}".format(db_record, existing_instance["id"]) |
| 2079 | |
| 2080 | # The target VIM is the one already existing in DB to recreate |
| 2081 | for target_vim, target_viminfo in existing_instance.get( |
| 2082 | "vim_info", {} |
| 2083 | ).items(): |
| 2084 | # step 1 vdu to be deleted |
| 2085 | self._assign_vim(target_vim) |
| 2086 | deployment_info = { |
| 2087 | "action_id": action_id, |
| 2088 | "nsr_id": nsr_id, |
| 2089 | "task_index": task_index, |
| 2090 | } |
| 2091 | |
| 2092 | target_record = f"{db_record}.{item_index}.vim_info.{target_vim}" |
| 2093 | created_items = self._prepare_created_items_for_healing( |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 2094 | nsr_id, target_record |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2095 | ) |
| 2096 | |
| 2097 | volumes_to_hold = self._prepare_persistent_volumes_for_healing( |
| 2098 | target_vim, existing_instance |
| 2099 | ) |
| 2100 | |
| 2101 | # Specific extra params for recreate tasks: |
| 2102 | extra_dict = { |
| 2103 | "created_items": created_items, |
| 2104 | "vim_id": existing_instance["vim-id"], |
| 2105 | "volumes_to_hold": volumes_to_hold, |
| 2106 | } |
| 2107 | |
| 2108 | changes_list.append( |
| 2109 | { |
| 2110 | "deployment_info": deployment_info, |
| 2111 | "target_id": target_vim, |
| 2112 | "item": "vdu", |
| 2113 | "action": "DELETE", |
| 2114 | "target_record": target_record, |
| 2115 | "target_record_id": target_record_id, |
| 2116 | "extra_dict": extra_dict, |
| 2117 | } |
| 2118 | ) |
| 2119 | delete_task_id = f"{action_id}:{task_index}" |
| 2120 | task_index += 1 |
| 2121 | |
| 2122 | # step 2 vdu to be created |
| 2123 | kwargs = {} |
| 2124 | kwargs.update( |
| 2125 | { |
| 2126 | "vnfr_id": vnfr_id, |
| 2127 | "nsr_id": nsr_id, |
| 2128 | "vnfr": existing_vnf, |
| 2129 | "vdu2cloud_init": vdu2cloud_init, |
| 2130 | "tasks_by_target_record_id": tasks_by_target_record_id, |
| 2131 | "logger": self.logger, |
| 2132 | "db": self.db, |
| 2133 | "fs": self.fs, |
| 2134 | "ro_nsr_public_key": ro_nsr_public_key, |
| 2135 | } |
| 2136 | ) |
| 2137 | |
| 2138 | extra_dict = self._process_recreate_vdu_params( |
| 2139 | existing_instance, |
| 2140 | db_nsr, |
| 2141 | target_viminfo, |
| 2142 | target_record_id, |
| 2143 | target_vim, |
| 2144 | **kwargs, |
| 2145 | ) |
| 2146 | |
| 2147 | # The CREATE task depens on the DELETE task |
| 2148 | extra_dict["depends_on"] = [delete_task_id] |
| 2149 | |
| palaciosj | 42eb06f | 2022-05-05 14:59:36 +0000 | [diff] [blame] | 2150 | # Add volumes created from created_items if any |
| 2151 | # Ports should be deleted with delete task and automatically created with create task |
| 2152 | volumes = {} |
| 2153 | for k, v in created_items.items(): |
| 2154 | try: |
| 2155 | k_item, _, k_id = k.partition(":") |
| 2156 | if k_item == "volume": |
| 2157 | volumes[k] = v |
| 2158 | except Exception as e: |
| 2159 | self.logger.error( |
| 2160 | "Error evaluating created item {}: {}".format(k, e) |
| 2161 | ) |
| 2162 | extra_dict["previous_created_volumes"] = volumes |
| 2163 | |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2164 | deployment_info = { |
| 2165 | "action_id": action_id, |
| 2166 | "nsr_id": nsr_id, |
| 2167 | "task_index": task_index, |
| 2168 | } |
| 2169 | self._assign_vim(target_vim) |
| 2170 | |
| 2171 | new_item = { |
| 2172 | "deployment_info": deployment_info, |
| 2173 | "target_id": target_vim, |
| 2174 | "item": "vdu", |
| 2175 | "action": "CREATE", |
| 2176 | "target_record": target_record, |
| 2177 | "target_record_id": target_record_id, |
| 2178 | "extra_dict": extra_dict, |
| 2179 | } |
| 2180 | changes_list.append(new_item) |
| 2181 | tasks_by_target_record_id[target_record_id] = new_item |
| 2182 | task_index += 1 |
| 2183 | |
| 2184 | return changes_list |
| 2185 | |
| 2186 | def recreate(self, session, indata, version, nsr_id, *args, **kwargs): |
| 2187 | self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata)) |
| 2188 | # TODO: validate_input(indata, recreate_schema) |
| 2189 | action_id = indata.get("action_id", str(uuid4())) |
| 2190 | # get current deployment |
| 2191 | db_vnfrs = {} # vnf's info indexed by _id |
| 2192 | step = "" |
| 2193 | logging_text = "Recreate nsr_id={} action_id={} indata={}".format( |
| 2194 | nsr_id, action_id, indata |
| 2195 | ) |
| 2196 | self.logger.debug(logging_text + "Enter") |
| 2197 | |
| 2198 | try: |
| 2199 | step = "Getting ns and vnfr record from db" |
| 2200 | db_nsr = self.db.get_one("nsrs", {"_id": nsr_id}) |
| 2201 | db_new_tasks = [] |
| 2202 | tasks_by_target_record_id = {} |
| 2203 | # read from db: vnf's of this ns |
| 2204 | step = "Getting vnfrs from db" |
| 2205 | db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}) |
| 2206 | self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list)) |
| 2207 | |
| 2208 | if not db_vnfrs_list: |
| 2209 | raise NsException("Cannot obtain associated VNF for ns") |
| 2210 | |
| 2211 | for vnfr in db_vnfrs_list: |
| 2212 | db_vnfrs[vnfr["_id"]] = vnfr |
| 2213 | |
| 2214 | now = time() |
| 2215 | db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False) |
| 2216 | self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr)) |
| 2217 | |
| 2218 | if not db_ro_nsr: |
| 2219 | db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now) |
| 2220 | |
| 2221 | with self.write_lock: |
| 2222 | # NS |
| 2223 | step = "process NS elements" |
| 2224 | changes_list = self.prepare_changes_to_recreate( |
| 2225 | indata=indata, |
| 2226 | nsr_id=nsr_id, |
| 2227 | db_nsr=db_nsr, |
| 2228 | db_vnfrs=db_vnfrs, |
| 2229 | db_ro_nsr=db_ro_nsr, |
| 2230 | action_id=action_id, |
| 2231 | tasks_by_target_record_id=tasks_by_target_record_id, |
| 2232 | ) |
| 2233 | |
| 2234 | self.define_all_tasks( |
| 2235 | changes_list=changes_list, |
| 2236 | db_new_tasks=db_new_tasks, |
| 2237 | tasks_by_target_record_id=tasks_by_target_record_id, |
| 2238 | ) |
| 2239 | |
| 2240 | # Delete all ro_tasks registered for the targets vdurs (target_record) |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 2241 | # If task of type CREATE exist then vim will try to get info form deleted VMs. |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2242 | # So remove all task related to target record. |
| 2243 | ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id}) |
| 2244 | for change in changes_list: |
| 2245 | for ro_task in ro_tasks: |
| 2246 | for task in ro_task["tasks"]: |
| 2247 | if task["target_record"] == change["target_record"]: |
| 2248 | self.db.del_one( |
| 2249 | "ro_tasks", |
| 2250 | q_filter={ |
| 2251 | "_id": ro_task["_id"], |
| 2252 | "modified_at": ro_task["modified_at"], |
| 2253 | }, |
| 2254 | fail_on_empty=False, |
| 2255 | ) |
| aticig | 285185e | 2022-05-02 21:23:48 +0300 | [diff] [blame] | 2256 | |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2257 | step = "Updating database, Appending tasks to ro_tasks" |
| 2258 | self.upload_recreate_tasks( |
| 2259 | db_new_tasks=db_new_tasks, |
| 2260 | now=now, |
| 2261 | ) |
| 2262 | |
| 2263 | self.logger.debug( |
| 2264 | logging_text + "Exit. Created {} tasks".format(len(db_new_tasks)) |
| 2265 | ) |
| 2266 | |
| 2267 | return ( |
| 2268 | {"status": "ok", "nsr_id": nsr_id, "action_id": action_id}, |
| 2269 | action_id, |
| 2270 | True, |
| 2271 | ) |
| 2272 | except Exception as e: |
| 2273 | if isinstance(e, (DbException, NsException)): |
| 2274 | self.logger.error( |
| 2275 | logging_text + "Exit Exception while '{}': {}".format(step, e) |
| 2276 | ) |
| 2277 | else: |
| 2278 | e = traceback_format_exc() |
| 2279 | self.logger.critical( |
| 2280 | logging_text + "Exit Exception while '{}': {}".format(step, e), |
| 2281 | exc_info=True, |
| 2282 | ) |
| 2283 | |
| 2284 | raise NsException(e) |
| 2285 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2286 | def deploy(self, session, indata, version, nsr_id, *args, **kwargs): |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2287 | self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2288 | validate_input(indata, deploy_schema) |
| 2289 | action_id = indata.get("action_id", str(uuid4())) |
| 2290 | task_index = 0 |
| 2291 | # get current deployment |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2292 | db_nsr_update = {} # update operation on nsrs |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2293 | db_vnfrs_update = {} |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2294 | db_vnfrs = {} # vnf's info indexed by _id |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2295 | step = "" |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2296 | logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id) |
| 2297 | self.logger.debug(logging_text + "Enter") |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2298 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2299 | try: |
| 2300 | step = "Getting ns and vnfr record from db" |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2301 | db_nsr = self.db.get_one("nsrs", {"_id": nsr_id}) |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2302 | self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2303 | db_new_tasks = [] |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2304 | tasks_by_target_record_id = {} |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2305 | # read from db: vnf's of this ns |
| 2306 | step = "Getting vnfrs from db" |
| 2307 | db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2308 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2309 | if not db_vnfrs_list: |
| 2310 | raise NsException("Cannot obtain associated VNF for ns") |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2311 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2312 | for vnfr in db_vnfrs_list: |
| 2313 | db_vnfrs[vnfr["_id"]] = vnfr |
| 2314 | db_vnfrs_update[vnfr["_id"]] = {} |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2315 | self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs)) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2316 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2317 | now = time() |
| 2318 | db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2319 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2320 | if not db_ro_nsr: |
| 2321 | db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2322 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2323 | # check that action_id is not in the list of actions. Suffixed with :index |
| 2324 | if action_id in db_ro_nsr["actions"]: |
| 2325 | index = 1 |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2326 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2327 | while True: |
| 2328 | new_action_id = "{}:{}".format(action_id, index) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2329 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2330 | if new_action_id not in db_ro_nsr["actions"]: |
| 2331 | action_id = new_action_id |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2332 | self.logger.debug( |
| 2333 | logging_text |
| 2334 | + "Changing action_id in use to {}".format(action_id) |
| 2335 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2336 | break |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2337 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2338 | index += 1 |
| 2339 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2340 | def _process_action(indata): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2341 | nonlocal db_new_tasks |
| sousaedu | 89278b8 | 2021-11-19 01:01:32 +0000 | [diff] [blame] | 2342 | nonlocal action_id |
| 2343 | nonlocal nsr_id |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2344 | nonlocal task_index |
| 2345 | nonlocal db_vnfrs |
| 2346 | nonlocal db_ro_nsr |
| 2347 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2348 | if indata["action"]["action"] == "inject_ssh_key": |
| 2349 | key = indata["action"].get("key") |
| 2350 | user = indata["action"].get("user") |
| 2351 | password = indata["action"].get("password") |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2352 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2353 | for vnf in indata.get("vnf", ()): |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2354 | if vnf["_id"] not in db_vnfrs: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2355 | raise NsException("Invalid vnf={}".format(vnf["_id"])) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2356 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2357 | db_vnfr = db_vnfrs[vnf["_id"]] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2358 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2359 | for target_vdu in vnf.get("vdur", ()): |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2360 | vdu_index, vdur = next( |
| 2361 | ( |
| 2362 | i_v |
| 2363 | for i_v in enumerate(db_vnfr["vdur"]) |
| 2364 | if i_v[1]["id"] == target_vdu["id"] |
| 2365 | ), |
| 2366 | (None, None), |
| 2367 | ) |
| 2368 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2369 | if not vdur: |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2370 | raise NsException( |
| 2371 | "Invalid vdu vnf={}.{}".format( |
| 2372 | vnf["_id"], target_vdu["id"] |
| 2373 | ) |
| 2374 | ) |
| 2375 | |
| 2376 | target_vim, vim_info = next( |
| 2377 | k_v for k_v in vdur["vim_info"].items() |
| 2378 | ) |
| tierno | 8615352 | 2020-12-06 18:27:16 +0000 | [diff] [blame] | 2379 | self._assign_vim(target_vim) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2380 | target_record = "vnfrs:{}:vdur.{}.ssh_keys".format( |
| 2381 | vnf["_id"], vdu_index |
| 2382 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2383 | extra_dict = { |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2384 | "depends_on": [ |
| 2385 | "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"]) |
| 2386 | ], |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2387 | "params": { |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2388 | "ip_address": vdur.get("ip-address"), |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2389 | "user": user, |
| 2390 | "key": key, |
| 2391 | "password": password, |
| 2392 | "private_key": db_ro_nsr["private_key"], |
| 2393 | "salt": db_ro_nsr["_id"], |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2394 | "schema_version": db_ro_nsr["_admin"][ |
| 2395 | "schema_version" |
| 2396 | ], |
| 2397 | }, |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2398 | } |
| sousaedu | 89278b8 | 2021-11-19 01:01:32 +0000 | [diff] [blame] | 2399 | |
| 2400 | deployment_info = { |
| 2401 | "action_id": action_id, |
| 2402 | "nsr_id": nsr_id, |
| 2403 | "task_index": task_index, |
| 2404 | } |
| 2405 | |
| 2406 | task = Ns._create_task( |
| 2407 | deployment_info=deployment_info, |
| 2408 | target_id=target_vim, |
| 2409 | item="vdu", |
| 2410 | action="EXEC", |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2411 | target_record=target_record, |
| 2412 | target_record_id=None, |
| 2413 | extra_dict=extra_dict, |
| 2414 | ) |
| sousaedu | 89278b8 | 2021-11-19 01:01:32 +0000 | [diff] [blame] | 2415 | |
| 2416 | task_index = deployment_info.get("task_index") |
| 2417 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2418 | db_new_tasks.append(task) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2419 | |
| 2420 | with self.write_lock: |
| 2421 | if indata.get("action"): |
| 2422 | _process_action(indata) |
| 2423 | else: |
| 2424 | # compute network differences |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 2425 | # NS |
| 2426 | step = "process NS elements" |
| 2427 | changes_list = self.calculate_all_differences_to_deploy( |
| 2428 | indata=indata, |
| 2429 | nsr_id=nsr_id, |
| 2430 | db_nsr=db_nsr, |
| 2431 | db_vnfrs=db_vnfrs, |
| 2432 | db_ro_nsr=db_ro_nsr, |
| 2433 | db_nsr_update=db_nsr_update, |
| 2434 | db_vnfrs_update=db_vnfrs_update, |
| 2435 | action_id=action_id, |
| 2436 | tasks_by_target_record_id=tasks_by_target_record_id, |
| 2437 | ) |
| 2438 | self.define_all_tasks( |
| 2439 | changes_list=changes_list, |
| 2440 | db_new_tasks=db_new_tasks, |
| 2441 | tasks_by_target_record_id=tasks_by_target_record_id, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2442 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2443 | |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 2444 | step = "Updating database, Appending tasks to ro_tasks" |
| 2445 | self.upload_all_tasks( |
| 2446 | db_new_tasks=db_new_tasks, |
| 2447 | now=now, |
| 2448 | ) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2449 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2450 | step = "Updating database, nsrs" |
| 2451 | if db_nsr_update: |
| 2452 | self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2453 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2454 | for vnfr_id, db_vnfr_update in db_vnfrs_update.items(): |
| 2455 | if db_vnfr_update: |
| 2456 | step = "Updating database, vnfrs={}".format(vnfr_id) |
| 2457 | self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update) |
| 2458 | |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2459 | self.logger.debug( |
| gallardo | a1c2b40 | 2022-02-11 12:41:59 +0000 | [diff] [blame] | 2460 | logging_text + "Exit. Created {} tasks".format(len(db_new_tasks)) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2461 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2462 | |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2463 | return ( |
| 2464 | {"status": "ok", "nsr_id": nsr_id, "action_id": action_id}, |
| 2465 | action_id, |
| 2466 | True, |
| 2467 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2468 | except Exception as e: |
| 2469 | if isinstance(e, (DbException, NsException)): |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2470 | self.logger.error( |
| 2471 | logging_text + "Exit Exception while '{}': {}".format(step, e) |
| 2472 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2473 | else: |
| 2474 | e = traceback_format_exc() |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2475 | self.logger.critical( |
| 2476 | logging_text + "Exit Exception while '{}': {}".format(step, e), |
| 2477 | exc_info=True, |
| 2478 | ) |
| 2479 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2480 | raise NsException(e) |
| 2481 | |
| 2482 | def delete(self, session, indata, version, nsr_id, *args, **kwargs): |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2483 | self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2484 | # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id}) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2485 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2486 | with self.write_lock: |
| 2487 | try: |
| 2488 | NsWorker.delete_db_tasks(self.db, nsr_id, None) |
| 2489 | except NsWorkerException as e: |
| 2490 | raise NsException(e) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2491 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2492 | return None, None, True |
| 2493 | |
| 2494 | def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs): |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2495 | self.logger.debug( |
| 2496 | "ns.status version={} nsr_id={}, action_id={} indata={}".format( |
| 2497 | version, nsr_id, action_id, indata |
| 2498 | ) |
| 2499 | ) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2500 | task_list = [] |
| 2501 | done = 0 |
| 2502 | total = 0 |
| 2503 | ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id}) |
| 2504 | global_status = "DONE" |
| 2505 | details = [] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2506 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2507 | for ro_task in ro_tasks: |
| 2508 | for task in ro_task["tasks"]: |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2509 | if task and task["action_id"] == action_id: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2510 | task_list.append(task) |
| 2511 | total += 1 |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2512 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2513 | if task["status"] == "FAILED": |
| 2514 | global_status = "FAILED" |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2515 | error_text = "Error at {} {}: {}".format( |
| 2516 | task["action"].lower(), |
| 2517 | task["item"], |
| aticig | 79ac6df | 2022-05-06 16:09:52 +0300 | [diff] [blame] | 2518 | ro_task["vim_info"].get("vim_message") or "unknown", |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2519 | ) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 2520 | details.append(error_text) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2521 | elif task["status"] in ("SCHEDULED", "BUILD"): |
| 2522 | if global_status != "FAILED": |
| 2523 | global_status = "BUILD" |
| 2524 | else: |
| 2525 | done += 1 |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2526 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2527 | return_data = { |
| 2528 | "status": global_status, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2529 | "details": ". ".join(details) |
| 2530 | if details |
| 2531 | else "progress {}/{}".format(done, total), |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2532 | "nsr_id": nsr_id, |
| 2533 | "action_id": action_id, |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2534 | "tasks": task_list, |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2535 | } |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2536 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2537 | return return_data, None, True |
| 2538 | |
| palaciosj | 8f2060b | 2022-02-24 12:05:59 +0000 | [diff] [blame] | 2539 | def recreate_status( |
| 2540 | self, session, indata, version, nsr_id, action_id, *args, **kwargs |
| 2541 | ): |
| 2542 | return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs) |
| 2543 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2544 | def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs): |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2545 | print( |
| 2546 | "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format( |
| 2547 | session, indata, version, nsr_id, action_id |
| 2548 | ) |
| 2549 | ) |
| 2550 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2551 | return None, None, True |
| 2552 | |
| k4.rahul | 78f474e | 2022-05-02 15:47:57 +0000 | [diff] [blame] | 2553 | def rebuild_start_stop_task( |
| 2554 | self, |
| 2555 | vdu_id, |
| 2556 | vnf_id, |
| 2557 | vdu_index, |
| 2558 | action_id, |
| 2559 | nsr_id, |
| 2560 | task_index, |
| 2561 | target_vim, |
| 2562 | extra_dict, |
| 2563 | ): |
| 2564 | self._assign_vim(target_vim) |
| 2565 | target_record = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_index) |
| 2566 | target_record_id = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_id) |
| 2567 | deployment_info = { |
| 2568 | "action_id": action_id, |
| 2569 | "nsr_id": nsr_id, |
| 2570 | "task_index": task_index, |
| 2571 | } |
| 2572 | |
| 2573 | task = Ns._create_task( |
| 2574 | deployment_info=deployment_info, |
| 2575 | target_id=target_vim, |
| 2576 | item="update", |
| 2577 | action="EXEC", |
| 2578 | target_record=target_record, |
| 2579 | target_record_id=target_record_id, |
| 2580 | extra_dict=extra_dict, |
| 2581 | ) |
| 2582 | return task |
| 2583 | |
| 2584 | def rebuild_start_stop( |
| 2585 | self, session, action_dict, version, nsr_id, *args, **kwargs |
| 2586 | ): |
| 2587 | task_index = 0 |
| 2588 | extra_dict = {} |
| 2589 | now = time() |
| 2590 | action_id = action_dict.get("action_id", str(uuid4())) |
| 2591 | step = "" |
| 2592 | logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id) |
| 2593 | self.logger.debug(logging_text + "Enter") |
| 2594 | |
| 2595 | action = list(action_dict.keys())[0] |
| 2596 | task_dict = action_dict.get(action) |
| 2597 | vim_vm_id = action_dict.get(action).get("vim_vm_id") |
| 2598 | |
| 2599 | if action_dict.get("stop"): |
| 2600 | action = "shutoff" |
| 2601 | db_new_tasks = [] |
| 2602 | try: |
| 2603 | step = "lock the operation & do task creation" |
| 2604 | with self.write_lock: |
| 2605 | extra_dict["params"] = { |
| 2606 | "vim_vm_id": vim_vm_id, |
| 2607 | "action": action, |
| 2608 | } |
| 2609 | task = self.rebuild_start_stop_task( |
| 2610 | task_dict["vdu_id"], |
| 2611 | task_dict["vnf_id"], |
| 2612 | task_dict["vdu_index"], |
| 2613 | action_id, |
| 2614 | nsr_id, |
| 2615 | task_index, |
| 2616 | task_dict["target_vim"], |
| 2617 | extra_dict, |
| 2618 | ) |
| 2619 | db_new_tasks.append(task) |
| 2620 | step = "upload Task to db" |
| 2621 | self.upload_all_tasks( |
| 2622 | db_new_tasks=db_new_tasks, |
| 2623 | now=now, |
| 2624 | ) |
| 2625 | self.logger.debug( |
| 2626 | logging_text + "Exit. Created {} tasks".format(len(db_new_tasks)) |
| 2627 | ) |
| 2628 | return ( |
| 2629 | {"status": "ok", "nsr_id": nsr_id, "action_id": action_id}, |
| 2630 | action_id, |
| 2631 | True, |
| 2632 | ) |
| 2633 | except Exception as e: |
| 2634 | if isinstance(e, (DbException, NsException)): |
| 2635 | self.logger.error( |
| 2636 | logging_text + "Exit Exception while '{}': {}".format(step, e) |
| 2637 | ) |
| 2638 | else: |
| 2639 | e = traceback_format_exc() |
| 2640 | self.logger.critical( |
| 2641 | logging_text + "Exit Exception while '{}': {}".format(step, e), |
| 2642 | exc_info=True, |
| 2643 | ) |
| 2644 | raise NsException(e) |
| 2645 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2646 | def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs): |
| 2647 | nsrs = self.db.get_list("nsrs", {}) |
| 2648 | return_data = [] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2649 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2650 | for ns in nsrs: |
| 2651 | return_data.append({"_id": ns["_id"], "name": ns["name"]}) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2652 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2653 | return return_data, None, True |
| 2654 | |
| 2655 | def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs): |
| 2656 | ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id}) |
| 2657 | return_data = [] |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2658 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2659 | for ro_task in ro_tasks: |
| 2660 | for task in ro_task["tasks"]: |
| 2661 | if task["action_id"] not in return_data: |
| 2662 | return_data.append(task["action_id"]) |
| sousaedu | 80135b9 | 2021-02-17 15:05:18 +0100 | [diff] [blame] | 2663 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 2664 | return return_data, None, True |
| elumalai | 8658c2c | 2022-04-28 19:09:31 +0530 | [diff] [blame] | 2665 | |
| 2666 | def migrate_task( |
| 2667 | self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict |
| 2668 | ): |
| 2669 | target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items()) |
| 2670 | self._assign_vim(target_vim) |
| 2671 | target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index) |
| 2672 | target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"]) |
| 2673 | deployment_info = { |
| 2674 | "action_id": action_id, |
| 2675 | "nsr_id": nsr_id, |
| 2676 | "task_index": task_index, |
| 2677 | } |
| 2678 | |
| 2679 | task = Ns._create_task( |
| 2680 | deployment_info=deployment_info, |
| 2681 | target_id=target_vim, |
| 2682 | item="migrate", |
| 2683 | action="EXEC", |
| 2684 | target_record=target_record, |
| 2685 | target_record_id=target_record_id, |
| 2686 | extra_dict=extra_dict, |
| 2687 | ) |
| 2688 | |
| 2689 | return task |
| 2690 | |
| 2691 | def migrate(self, session, indata, version, nsr_id, *args, **kwargs): |
| 2692 | task_index = 0 |
| 2693 | extra_dict = {} |
| 2694 | now = time() |
| 2695 | action_id = indata.get("action_id", str(uuid4())) |
| 2696 | step = "" |
| 2697 | logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id) |
| 2698 | self.logger.debug(logging_text + "Enter") |
| 2699 | try: |
| 2700 | vnf_instance_id = indata["vnfInstanceId"] |
| 2701 | step = "Getting vnfrs from db" |
| 2702 | db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id}) |
| 2703 | vdu = indata.get("vdu") |
| 2704 | migrateToHost = indata.get("migrateToHost") |
| 2705 | db_new_tasks = [] |
| 2706 | |
| 2707 | with self.write_lock: |
| 2708 | if vdu is not None: |
| 2709 | vdu_id = indata["vdu"]["vduId"] |
| 2710 | vdu_count_index = indata["vdu"].get("vduCountIndex", 0) |
| 2711 | for vdu_index, vdu in enumerate(db_vnfr["vdur"]): |
| 2712 | if ( |
| 2713 | vdu["vdu-id-ref"] == vdu_id |
| 2714 | and vdu["count-index"] == vdu_count_index |
| 2715 | ): |
| 2716 | extra_dict["params"] = { |
| 2717 | "vim_vm_id": vdu["vim-id"], |
| 2718 | "migrate_host": migrateToHost, |
| 2719 | "vdu_vim_info": vdu["vim_info"], |
| 2720 | } |
| 2721 | step = "Creating migration task for vdu:{}".format(vdu) |
| 2722 | task = self.migrate_task( |
| 2723 | vdu, |
| 2724 | db_vnfr, |
| 2725 | vdu_index, |
| 2726 | action_id, |
| 2727 | nsr_id, |
| 2728 | task_index, |
| 2729 | extra_dict, |
| 2730 | ) |
| 2731 | db_new_tasks.append(task) |
| 2732 | task_index += 1 |
| 2733 | break |
| 2734 | else: |
| 2735 | |
| 2736 | for vdu_index, vdu in enumerate(db_vnfr["vdur"]): |
| 2737 | extra_dict["params"] = { |
| 2738 | "vim_vm_id": vdu["vim-id"], |
| 2739 | "migrate_host": migrateToHost, |
| 2740 | "vdu_vim_info": vdu["vim_info"], |
| 2741 | } |
| 2742 | step = "Creating migration task for vdu:{}".format(vdu) |
| 2743 | task = self.migrate_task( |
| 2744 | vdu, |
| 2745 | db_vnfr, |
| 2746 | vdu_index, |
| 2747 | action_id, |
| 2748 | nsr_id, |
| 2749 | task_index, |
| 2750 | extra_dict, |
| 2751 | ) |
| 2752 | db_new_tasks.append(task) |
| 2753 | task_index += 1 |
| 2754 | |
| 2755 | self.upload_all_tasks( |
| 2756 | db_new_tasks=db_new_tasks, |
| 2757 | now=now, |
| 2758 | ) |
| 2759 | |
| 2760 | self.logger.debug( |
| 2761 | logging_text + "Exit. Created {} tasks".format(len(db_new_tasks)) |
| 2762 | ) |
| 2763 | return ( |
| 2764 | {"status": "ok", "nsr_id": nsr_id, "action_id": action_id}, |
| 2765 | action_id, |
| 2766 | True, |
| 2767 | ) |
| 2768 | except Exception as e: |
| 2769 | if isinstance(e, (DbException, NsException)): |
| 2770 | self.logger.error( |
| 2771 | logging_text + "Exit Exception while '{}': {}".format(step, e) |
| 2772 | ) |
| 2773 | else: |
| 2774 | e = traceback_format_exc() |
| 2775 | self.logger.critical( |
| 2776 | logging_text + "Exit Exception while '{}': {}".format(step, e), |
| 2777 | exc_info=True, |
| 2778 | ) |
| 2779 | raise NsException(e) |
| sritharan | 29a4c1a | 2022-05-05 12:15:04 +0000 | [diff] [blame] | 2780 | |
| 2781 | def verticalscale_task( |
| 2782 | self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict |
| 2783 | ): |
| 2784 | target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items()) |
| 2785 | self._assign_vim(target_vim) |
| 2786 | target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index) |
| 2787 | target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"]) |
| 2788 | deployment_info = { |
| 2789 | "action_id": action_id, |
| 2790 | "nsr_id": nsr_id, |
| 2791 | "task_index": task_index, |
| 2792 | } |
| 2793 | |
| 2794 | task = Ns._create_task( |
| 2795 | deployment_info=deployment_info, |
| 2796 | target_id=target_vim, |
| 2797 | item="verticalscale", |
| 2798 | action="EXEC", |
| 2799 | target_record=target_record, |
| 2800 | target_record_id=target_record_id, |
| 2801 | extra_dict=extra_dict, |
| 2802 | ) |
| 2803 | return task |
| 2804 | |
| 2805 | def verticalscale(self, session, indata, version, nsr_id, *args, **kwargs): |
| 2806 | task_index = 0 |
| 2807 | extra_dict = {} |
| 2808 | now = time() |
| 2809 | action_id = indata.get("action_id", str(uuid4())) |
| 2810 | step = "" |
| 2811 | logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id) |
| 2812 | self.logger.debug(logging_text + "Enter") |
| 2813 | try: |
| 2814 | VnfFlavorData = indata.get("changeVnfFlavorData") |
| 2815 | vnf_instance_id = VnfFlavorData["vnfInstanceId"] |
| 2816 | step = "Getting vnfrs from db" |
| 2817 | db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id}) |
| 2818 | vduid = VnfFlavorData["additionalParams"]["vduid"] |
| 2819 | vduCountIndex = VnfFlavorData["additionalParams"]["vduCountIndex"] |
| 2820 | virtualMemory = VnfFlavorData["additionalParams"]["virtualMemory"] |
| 2821 | numVirtualCpu = VnfFlavorData["additionalParams"]["numVirtualCpu"] |
| 2822 | sizeOfStorage = VnfFlavorData["additionalParams"]["sizeOfStorage"] |
| 2823 | flavor_dict = { |
| 2824 | "name": vduid + "-flv", |
| 2825 | "ram": virtualMemory, |
| 2826 | "vcpus": numVirtualCpu, |
| 2827 | "disk": sizeOfStorage, |
| 2828 | } |
| 2829 | db_new_tasks = [] |
| 2830 | step = "Creating Tasks for vertical scaling" |
| 2831 | with self.write_lock: |
| 2832 | for vdu_index, vdu in enumerate(db_vnfr["vdur"]): |
| 2833 | if ( |
| 2834 | vdu["vdu-id-ref"] == vduid |
| 2835 | and vdu["count-index"] == vduCountIndex |
| 2836 | ): |
| 2837 | extra_dict["params"] = { |
| 2838 | "vim_vm_id": vdu["vim-id"], |
| 2839 | "flavor_dict": flavor_dict, |
| 2840 | } |
| 2841 | task = self.verticalscale_task( |
| 2842 | vdu, |
| 2843 | db_vnfr, |
| 2844 | vdu_index, |
| 2845 | action_id, |
| 2846 | nsr_id, |
| 2847 | task_index, |
| 2848 | extra_dict, |
| 2849 | ) |
| 2850 | db_new_tasks.append(task) |
| 2851 | task_index += 1 |
| 2852 | break |
| 2853 | self.upload_all_tasks( |
| 2854 | db_new_tasks=db_new_tasks, |
| 2855 | now=now, |
| 2856 | ) |
| 2857 | self.logger.debug( |
| 2858 | logging_text + "Exit. Created {} tasks".format(len(db_new_tasks)) |
| 2859 | ) |
| 2860 | return ( |
| 2861 | {"status": "ok", "nsr_id": nsr_id, "action_id": action_id}, |
| 2862 | action_id, |
| 2863 | True, |
| 2864 | ) |
| 2865 | except Exception as e: |
| 2866 | if isinstance(e, (DbException, NsException)): |
| 2867 | self.logger.error( |
| 2868 | logging_text + "Exit Exception while '{}': {}".format(step, e) |
| 2869 | ) |
| 2870 | else: |
| 2871 | e = traceback_format_exc() |
| 2872 | self.logger.critical( |
| 2873 | logging_text + "Exit Exception while '{}': {}".format(step, e), |
| 2874 | exc_info=True, |
| 2875 | ) |
| 2876 | raise NsException(e) |