| 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 | |
| 19 | import logging |
| 20 | # import yaml |
| 21 | from traceback import format_exc as traceback_format_exc |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 22 | from osm_ng_ro.ns_thread import NsWorker, NsWorkerException, deep_get |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 23 | from osm_ng_ro.validation import validate_input, deploy_schema |
| 24 | from osm_common import dbmongo, dbmemory, fslocal, fsmongo, msglocal, msgkafka, version as common_version |
| 25 | from osm_common.dbbase import DbException |
| 26 | from osm_common.fsbase import FsException |
| 27 | from osm_common.msgbase import MsgException |
| 28 | from http import HTTPStatus |
| 29 | from uuid import uuid4 |
| 30 | from threading import Lock |
| 31 | from random import choice as random_choice |
| 32 | from time import time |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 33 | from jinja2 import Environment, TemplateError, TemplateNotFound, StrictUndefined, UndefinedError |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 34 | from cryptography.hazmat.primitives import serialization as crypto_serialization |
| 35 | from cryptography.hazmat.primitives.asymmetric import rsa |
| 36 | from cryptography.hazmat.backends import default_backend as crypto_default_backend |
| 37 | |
| 38 | __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>" |
| 39 | min_common_version = "0.1.16" |
| 40 | |
| 41 | |
| 42 | class NsException(Exception): |
| 43 | |
| 44 | def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST): |
| 45 | self.http_code = http_code |
| 46 | super(Exception, self).__init__(message) |
| 47 | |
| 48 | |
| 49 | def get_process_id(): |
| 50 | """ |
| 51 | Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it |
| 52 | will provide a random one |
| 53 | :return: Obtained ID |
| 54 | """ |
| 55 | # Try getting docker id. If fails, get pid |
| 56 | try: |
| 57 | with open("/proc/self/cgroup", "r") as f: |
| 58 | text_id_ = f.readline() |
| 59 | _, _, text_id = text_id_.rpartition("/") |
| 60 | text_id = text_id.replace("\n", "")[:12] |
| 61 | if text_id: |
| 62 | return text_id |
| 63 | except Exception: |
| 64 | pass |
| 65 | # Return a random id |
| 66 | return "".join(random_choice("0123456789abcdef") for _ in range(12)) |
| 67 | |
| 68 | |
| 69 | def versiontuple(v): |
| 70 | """utility for compare dot separate versions. Fills with zeros to proper number comparison""" |
| 71 | filled = [] |
| 72 | for point in v.split("."): |
| 73 | filled.append(point.zfill(8)) |
| 74 | return tuple(filled) |
| 75 | |
| 76 | |
| 77 | class Ns(object): |
| 78 | |
| 79 | def __init__(self): |
| 80 | self.db = None |
| 81 | self.fs = None |
| 82 | self.msg = None |
| 83 | self.config = None |
| 84 | # self.operations = None |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 85 | self.logger = None |
| 86 | # ^ Getting logger inside method self.start because parent logger (ro) is not available yet. |
| 87 | # 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] | 88 | self.map_topic = {} |
| 89 | self.write_lock = None |
| 90 | self.assignment = {} |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 91 | self.assignment_list = [] |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 92 | self.next_worker = 0 |
| 93 | self.plugins = {} |
| 94 | self.workers = [] |
| 95 | |
| 96 | def init_db(self, target_version): |
| 97 | pass |
| 98 | |
| 99 | def start(self, config): |
| 100 | """ |
| 101 | Connect to database, filesystem storage, and messaging |
| 102 | :param config: two level dictionary with configuration. Top level should contain 'database', 'storage', |
| 103 | :param config: Configuration of db, storage, etc |
| 104 | :return: None |
| 105 | """ |
| 106 | self.config = config |
| 107 | self.config["process_id"] = get_process_id() # used for HA identity |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 108 | self.logger = logging.getLogger("ro.ns") |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 109 | # check right version of common |
| 110 | if versiontuple(common_version) < versiontuple(min_common_version): |
| 111 | raise NsException("Not compatible osm/common version '{}'. Needed '{}' or higher".format( |
| 112 | common_version, min_common_version)) |
| 113 | |
| 114 | try: |
| 115 | if not self.db: |
| 116 | if config["database"]["driver"] == "mongo": |
| 117 | self.db = dbmongo.DbMongo() |
| 118 | self.db.db_connect(config["database"]) |
| 119 | elif config["database"]["driver"] == "memory": |
| 120 | self.db = dbmemory.DbMemory() |
| 121 | self.db.db_connect(config["database"]) |
| 122 | else: |
| 123 | raise NsException("Invalid configuration param '{}' at '[database]':'driver'".format( |
| 124 | config["database"]["driver"])) |
| 125 | if not self.fs: |
| 126 | if config["storage"]["driver"] == "local": |
| 127 | self.fs = fslocal.FsLocal() |
| 128 | self.fs.fs_connect(config["storage"]) |
| 129 | elif config["storage"]["driver"] == "mongo": |
| 130 | self.fs = fsmongo.FsMongo() |
| 131 | self.fs.fs_connect(config["storage"]) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 132 | elif config["storage"]["driver"] is None: |
| 133 | pass |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 134 | else: |
| 135 | raise NsException("Invalid configuration param '{}' at '[storage]':'driver'".format( |
| 136 | config["storage"]["driver"])) |
| 137 | if not self.msg: |
| 138 | if config["message"]["driver"] == "local": |
| 139 | self.msg = msglocal.MsgLocal() |
| 140 | self.msg.connect(config["message"]) |
| 141 | elif config["message"]["driver"] == "kafka": |
| 142 | self.msg = msgkafka.MsgKafka() |
| 143 | self.msg.connect(config["message"]) |
| 144 | else: |
| 145 | raise NsException("Invalid configuration param '{}' at '[message]':'driver'".format( |
| 146 | config["message"]["driver"])) |
| 147 | |
| 148 | # TODO load workers to deal with exising database tasks |
| 149 | |
| 150 | self.write_lock = Lock() |
| 151 | except (DbException, FsException, MsgException) as e: |
| 152 | raise NsException(str(e), http_code=e.http_code) |
| 153 | |
| 154 | def stop(self): |
| 155 | try: |
| 156 | if self.db: |
| 157 | self.db.db_disconnect() |
| 158 | if self.fs: |
| 159 | self.fs.fs_disconnect() |
| 160 | if self.msg: |
| 161 | self.msg.disconnect() |
| 162 | self.write_lock = None |
| 163 | except (DbException, FsException, MsgException) as e: |
| 164 | raise NsException(str(e), http_code=e.http_code) |
| 165 | for worker in self.workers: |
| 166 | worker.insert_task(("terminate",)) |
| 167 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 168 | def _create_worker(self, target_id, load=True): |
| 169 | # Look for a thread not alive |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 170 | worker_id = next((i for i in range(len(self.workers)) if not self.workers[i].is_alive()), None) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 171 | if worker_id: |
| 172 | # re-start worker |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 173 | self.workers[worker_id].start() |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 174 | else: |
| 175 | worker_id = len(self.workers) |
| 176 | if worker_id < self.config["global"]["server.ns_threads"]: |
| 177 | # create a new worker |
| 178 | self.workers.append(NsWorker(worker_id, self.config, self.plugins, self.db)) |
| 179 | self.workers[worker_id].start() |
| 180 | else: |
| 181 | # reached maximum number of threads, assign VIM to an existing one |
| 182 | worker_id = self.next_worker |
| 183 | self.next_worker = (self.next_worker + 1) % self.config["global"]["server.ns_threads"] |
| 184 | if load: |
| 185 | self.workers[worker_id].insert_task(("load_vim", target_id)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 186 | return worker_id |
| 187 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 188 | def assign_vim(self, target_id): |
| 189 | if target_id not in self.assignment: |
| 190 | self.assignment[target_id] = self._create_worker(target_id) |
| 191 | self.assignment_list.append(target_id) |
| 192 | |
| 193 | def reload_vim(self, target_id): |
| 194 | # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed, |
| 195 | # this is because database VIM information is cached for threads working with SDN |
| 196 | # if target_id in self.assignment: |
| 197 | # worker_id = self.assignment[target_id] |
| 198 | # self.workers[worker_id].insert_task(("reload_vim", target_id)) |
| 199 | for worker in self.workers: |
| 200 | if worker.is_alive(): |
| 201 | worker.insert_task(("reload_vim", target_id)) |
| 202 | |
| 203 | def unload_vim(self, target_id): |
| 204 | if target_id in self.assignment: |
| 205 | worker_id = self.assignment[target_id] |
| 206 | self.workers[worker_id].insert_task(("unload_vim", target_id)) |
| 207 | del self.assignment[target_id] |
| 208 | self.assignment_list.remove(target_id) |
| 209 | |
| 210 | def check_vim(self, target_id): |
| 211 | if target_id in self.assignment: |
| 212 | worker_id = self.assignment[target_id] |
| 213 | else: |
| 214 | worker_id = self._create_worker(target_id, load=False) |
| 215 | |
| 216 | worker = self.workers[worker_id] |
| 217 | worker.insert_task(("check_vim", target_id)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 218 | |
| 219 | def _get_cloud_init(self, where): |
| 220 | """ |
| 221 | |
| 222 | :param where: can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex' |
| 223 | :return: |
| 224 | """ |
| 225 | vnfd_id, _, other = where.partition(":") |
| 226 | _type, _, name = other.partition(":") |
| 227 | vnfd = self.db.get_one("vnfds", {"_id": vnfd_id}) |
| 228 | if _type == "file": |
| 229 | base_folder = vnfd["_admin"]["storage"] |
| 230 | cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"], name) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 231 | if not self.fs: |
| 232 | raise NsException("Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver" |
| 233 | .format(cloud_init_file)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 234 | with self.fs.file_open(cloud_init_file, "r") as ci_file: |
| 235 | cloud_init_content = ci_file.read() |
| 236 | elif _type == "vdu": |
| 237 | cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"] |
| 238 | else: |
| 239 | raise NsException("Mismatch descriptor for cloud init: {}".format(where)) |
| 240 | return cloud_init_content |
| 241 | |
| 242 | def _parse_jinja2(self, cloud_init_content, params, context): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 243 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 244 | try: |
| 245 | env = Environment(undefined=StrictUndefined) |
| 246 | template = env.from_string(cloud_init_content) |
| 247 | return template.render(params or {}) |
| 248 | except UndefinedError as e: |
| 249 | raise NsException( |
| 250 | "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters" |
| 251 | "inside the 'additionalParamsForVnf' block".format(e, context)) |
| 252 | except (TemplateError, TemplateNotFound) as e: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 253 | raise NsException("Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(context, e)) |
| 254 | |
| 255 | def _create_db_ro_nsrs(self, nsr_id, now): |
| 256 | try: |
| 257 | key = rsa.generate_private_key( |
| 258 | backend=crypto_default_backend(), |
| 259 | public_exponent=65537, |
| 260 | key_size=2048 |
| 261 | ) |
| 262 | private_key = key.private_bytes( |
| 263 | crypto_serialization.Encoding.PEM, |
| 264 | crypto_serialization.PrivateFormat.PKCS8, |
| 265 | crypto_serialization.NoEncryption()) |
| 266 | public_key = key.public_key().public_bytes( |
| 267 | crypto_serialization.Encoding.OpenSSH, |
| 268 | crypto_serialization.PublicFormat.OpenSSH |
| 269 | ) |
| 270 | private_key = private_key.decode('utf8') |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 271 | # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY' |
| 272 | i = private_key.find("\n") |
| 273 | private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:] |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 274 | public_key = public_key.decode('utf8') |
| 275 | except Exception as e: |
| 276 | raise NsException("Cannot create ssh-keys: {}".format(e)) |
| 277 | |
| 278 | schema_version = "1.1" |
| 279 | private_key_encrypted = self.db.encrypt(private_key, schema_version=schema_version, salt=nsr_id) |
| 280 | db_content = { |
| 281 | "_id": nsr_id, |
| 282 | "_admin": { |
| 283 | "created": now, |
| 284 | "modified": now, |
| 285 | "schema_version": schema_version |
| 286 | }, |
| 287 | "public_key": public_key, |
| 288 | "private_key": private_key_encrypted, |
| 289 | "actions": [], |
| 290 | } |
| 291 | self.db.create("ro_nsrs", db_content) |
| 292 | return db_content |
| 293 | |
| 294 | def deploy(self, session, indata, version, nsr_id, *args, **kwargs): |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 295 | self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 296 | validate_input(indata, deploy_schema) |
| 297 | action_id = indata.get("action_id", str(uuid4())) |
| 298 | task_index = 0 |
| 299 | # get current deployment |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 300 | db_nsr_update = {} # update operation on nsrs |
| 301 | db_vnfrs_update = {} |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 302 | db_vnfrs = {} # vnf's info indexed by _id |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 303 | nb_ro_tasks = 0 # for logging |
| 304 | vdu2cloud_init = indata.get("cloud_init_content") or {} |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 305 | step = '' |
| 306 | logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id) |
| 307 | self.logger.debug(logging_text + "Enter") |
| 308 | try: |
| 309 | step = "Getting ns and vnfr record from db" |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 310 | db_nsr = self.db.get_one("nsrs", {"_id": nsr_id}) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 311 | db_new_tasks = [] |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 312 | tasks_by_target_record_id = {} |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 313 | # read from db: vnf's of this ns |
| 314 | step = "Getting vnfrs from db" |
| 315 | db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}) |
| 316 | if not db_vnfrs_list: |
| 317 | raise NsException("Cannot obtain associated VNF for ns") |
| 318 | for vnfr in db_vnfrs_list: |
| 319 | db_vnfrs[vnfr["_id"]] = vnfr |
| 320 | db_vnfrs_update[vnfr["_id"]] = {} |
| 321 | now = time() |
| 322 | db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False) |
| 323 | if not db_ro_nsr: |
| 324 | db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now) |
| 325 | ro_nsr_public_key = db_ro_nsr["public_key"] |
| 326 | |
| 327 | # check that action_id is not in the list of actions. Suffixed with :index |
| 328 | if action_id in db_ro_nsr["actions"]: |
| 329 | index = 1 |
| 330 | while True: |
| 331 | new_action_id = "{}:{}".format(action_id, index) |
| 332 | if new_action_id not in db_ro_nsr["actions"]: |
| 333 | action_id = new_action_id |
| 334 | self.logger.debug(logging_text + "Changing action_id in use to {}".format(action_id)) |
| 335 | break |
| 336 | index += 1 |
| 337 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 338 | def _create_task(target_id, item, action, target_record, target_record_id, extra_dict=None): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 339 | nonlocal task_index |
| 340 | nonlocal action_id |
| 341 | nonlocal nsr_id |
| 342 | |
| 343 | task = { |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 344 | "target_id": target_id, # it will be removed before pushing at database |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 345 | "action_id": action_id, |
| 346 | "nsr_id": nsr_id, |
| 347 | "task_id": "{}:{}".format(action_id, task_index), |
| 348 | "status": "SCHEDULED", |
| 349 | "action": action, |
| 350 | "item": item, |
| 351 | "target_record": target_record, |
| 352 | "target_record_id": target_record_id, |
| 353 | } |
| 354 | if extra_dict: |
| 355 | task.update(extra_dict) # params, find_params, depends_on |
| 356 | task_index += 1 |
| 357 | return task |
| 358 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 359 | def _create_ro_task(target_id, task): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 360 | nonlocal action_id |
| 361 | nonlocal task_index |
| 362 | nonlocal now |
| 363 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 364 | _id = task["task_id"] |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 365 | db_ro_task = { |
| 366 | "_id": _id, |
| 367 | "locked_by": None, |
| 368 | "locked_at": 0.0, |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 369 | "target_id": target_id, |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 370 | "vim_info": { |
| 371 | "created": False, |
| 372 | "created_items": None, |
| 373 | "vim_id": None, |
| 374 | "vim_name": None, |
| 375 | "vim_status": None, |
| 376 | "vim_details": None, |
| 377 | "refresh_at": None, |
| 378 | }, |
| 379 | "modified_at": now, |
| 380 | "created_at": now, |
| 381 | "to_check_at": now, |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 382 | "tasks": [task], |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 383 | } |
| 384 | return db_ro_task |
| 385 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 386 | def _process_image_params(target_image, vim_info, target_record_id): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 387 | find_params = {} |
| 388 | if target_image.get("image"): |
| 389 | find_params["filter_dict"] = {"name": target_image.get("image")} |
| 390 | if target_image.get("vim_image_id"): |
| 391 | find_params["filter_dict"] = {"id": target_image.get("vim_image_id")} |
| 392 | if target_image.get("image_checksum"): |
| 393 | find_params["filter_dict"] = {"checksum": target_image.get("image_checksum")} |
| 394 | return {"find_params": find_params} |
| 395 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 396 | def _process_flavor_params(target_flavor, vim_info, target_record_id): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 397 | |
| 398 | def _get_resource_allocation_params(quota_descriptor): |
| 399 | """ |
| 400 | read the quota_descriptor from vnfd and fetch the resource allocation properties from the |
| 401 | descriptor object |
| 402 | :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor |
| 403 | :return: quota params for limit, reserve, shares from the descriptor object |
| 404 | """ |
| 405 | quota = {} |
| 406 | if quota_descriptor.get("limit"): |
| 407 | quota["limit"] = int(quota_descriptor["limit"]) |
| 408 | if quota_descriptor.get("reserve"): |
| 409 | quota["reserve"] = int(quota_descriptor["reserve"]) |
| 410 | if quota_descriptor.get("shares"): |
| 411 | quota["shares"] = int(quota_descriptor["shares"]) |
| 412 | return quota |
| 413 | |
| 414 | flavor_data = { |
| 415 | "disk": int(target_flavor["storage-gb"]), |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 416 | "ram": int(target_flavor["memory-mb"]), |
| tierno | fb13d2e | 2020-11-26 15:55:20 +0000 | [diff] [blame^] | 417 | "vcpus": int(target_flavor["vcpu-count"]), |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 418 | } |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 419 | numa = {} |
| 420 | extended = {} |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 421 | if target_flavor.get("guest-epa"): |
| 422 | extended = {} |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 423 | epa_vcpu_set = False |
| 424 | if target_flavor["guest-epa"].get("numa-node-policy"): |
| 425 | numa_node_policy = target_flavor["guest-epa"].get("numa-node-policy") |
| 426 | if numa_node_policy.get("node"): |
| 427 | numa_node = numa_node_policy["node"][0] |
| 428 | if numa_node.get("num-cores"): |
| 429 | numa["cores"] = numa_node["num-cores"] |
| 430 | epa_vcpu_set = True |
| 431 | if numa_node.get("paired-threads"): |
| 432 | if numa_node["paired-threads"].get("num-paired-threads"): |
| 433 | numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"]) |
| 434 | epa_vcpu_set = True |
| 435 | if len(numa_node["paired-threads"].get("paired-thread-ids")): |
| 436 | numa["paired-threads-id"] = [] |
| 437 | for pair in numa_node["paired-threads"]["paired-thread-ids"]: |
| 438 | numa["paired-threads-id"].append( |
| 439 | (str(pair["thread-a"]), str(pair["thread-b"])) |
| 440 | ) |
| 441 | if numa_node.get("num-threads"): |
| 442 | numa["threads"] = int(numa_node["num-threads"]) |
| 443 | epa_vcpu_set = True |
| 444 | if numa_node.get("memory-mb"): |
| 445 | numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1) |
| 446 | if target_flavor["guest-epa"].get("mempage-size"): |
| 447 | extended["mempage-size"] = target_flavor["guest-epa"].get("mempage-size") |
| 448 | if target_flavor["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set: |
| 449 | if target_flavor["guest-epa"]["cpu-pinning-policy"] == "DEDICATED": |
| 450 | if target_flavor["guest-epa"].get("cpu-thread-pinning-policy") and \ |
| 451 | target_flavor["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER": |
| 452 | numa["cores"] = max(flavor_data["vcpus"], 1) |
| 453 | else: |
| 454 | numa["threads"] = max(flavor_data["vcpus"], 1) |
| 455 | epa_vcpu_set = True |
| 456 | if target_flavor["guest-epa"].get("cpu-quota") and not epa_vcpu_set: |
| 457 | cpuquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("cpu-quota")) |
| 458 | if cpuquota: |
| 459 | extended["cpu-quota"] = cpuquota |
| 460 | if target_flavor["guest-epa"].get("mem-quota"): |
| 461 | vduquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("mem-quota")) |
| 462 | if vduquota: |
| 463 | extended["mem-quota"] = vduquota |
| 464 | if target_flavor["guest-epa"].get("disk-io-quota"): |
| 465 | diskioquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("disk-io-quota")) |
| 466 | if diskioquota: |
| 467 | extended["disk-io-quota"] = diskioquota |
| 468 | if target_flavor["guest-epa"].get("vif-quota"): |
| 469 | vifquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("vif-quota")) |
| 470 | if vifquota: |
| 471 | extended["vif-quota"] = vifquota |
| 472 | if numa: |
| 473 | extended["numas"] = [numa] |
| 474 | if extended: |
| 475 | flavor_data["extended"] = extended |
| 476 | |
| 477 | extra_dict = {"find_params": {"flavor_data": flavor_data}} |
| 478 | flavor_data_name = flavor_data.copy() |
| 479 | flavor_data_name["name"] = target_flavor["name"] |
| 480 | extra_dict["params"] = {"flavor_data": flavor_data_name} |
| 481 | return extra_dict |
| 482 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 483 | def _ip_profile_2_ro(ip_profile): |
| 484 | if not ip_profile: |
| 485 | return None |
| 486 | ro_ip_profile = { |
| 487 | "ip_version": "IPv4" if "v4" in ip_profile.get("ip-version", "ipv4") else "IPv6", |
| 488 | "subnet_address": ip_profile.get("subnet-address"), |
| 489 | "gateway_address": ip_profile.get("gateway-address"), |
| 490 | "dhcp_enabled": ip_profile["dhcp-params"].get("enabled", True), |
| 491 | "dhcp_start_address": ip_profile["dhcp-params"].get("start-address"), |
| 492 | "dhcp_count": ip_profile["dhcp-params"].get("count"), |
| 493 | |
| 494 | } |
| 495 | if ip_profile.get("dns-server"): |
| 496 | ro_ip_profile["dns_address"] = ";".join([v["address"] for v in ip_profile["dns-server"]]) |
| 497 | if ip_profile.get('security-group'): |
| 498 | ro_ip_profile["security_group"] = ip_profile['security-group'] |
| 499 | return ro_ip_profile |
| 500 | |
| 501 | def _process_net_params(target_vld, vim_info, target_record_id): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 502 | nonlocal indata |
| 503 | extra_dict = {} |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 504 | |
| 505 | if vim_info.get("sdn"): |
| 506 | # vnf_preffix = "vnfrs:{}".format(vnfr_id) |
| 507 | # ns_preffix = "nsrs:{}".format(nsr_id) |
| 508 | vld_target_record_id, _, _ = target_record_id.rpartition(".") # remove the ending ".sdn |
| 509 | extra_dict["params"] = {k: vim_info[k] for k in ("sdn-ports", "target_vim", "vlds", "type") |
| 510 | if vim_info.get(k)} |
| 511 | # TODO needed to add target_id in the dependency. |
| 512 | if vim_info.get("target_vim"): |
| 513 | extra_dict["depends_on"] = [vim_info.get("target_vim") + " " + vld_target_record_id] |
| 514 | return extra_dict |
| 515 | |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 516 | if vim_info.get("vim_network_name"): |
| 517 | extra_dict["find_params"] = {"filter_dict": {"name": vim_info.get("vim_network_name")}} |
| 518 | elif vim_info.get("vim_network_id"): |
| 519 | extra_dict["find_params"] = {"filter_dict": {"id": vim_info.get("vim_network_id")}} |
| 520 | elif target_vld.get("mgmt-network"): |
| 521 | extra_dict["find_params"] = {"mgmt": True, "name": target_vld["id"]} |
| 522 | else: |
| 523 | # create |
| 524 | extra_dict["params"] = { |
| 525 | "net_name": "{}-{}".format(indata["name"][:16], target_vld.get("name", target_vld["id"])[:16]), |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 526 | "ip_profile": _ip_profile_2_ro(vim_info.get('ip_profile')), |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 527 | "provider_network_profile": vim_info.get('provider_network'), |
| 528 | } |
| 529 | if not target_vld.get("underlay"): |
| 530 | extra_dict["params"]["net_type"] = "bridge" |
| 531 | else: |
| 532 | extra_dict["params"]["net_type"] = "ptp" if target_vld.get("type") == "ELINE" else "data" |
| 533 | return extra_dict |
| 534 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 535 | def _process_vdu_params(target_vdu, vim_info, target_record_id): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 536 | nonlocal vnfr_id |
| 537 | nonlocal nsr_id |
| 538 | nonlocal indata |
| 539 | nonlocal vnfr |
| 540 | nonlocal vdu2cloud_init |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 541 | nonlocal tasks_by_target_record_id |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 542 | vnf_preffix = "vnfrs:{}".format(vnfr_id) |
| 543 | ns_preffix = "nsrs:{}".format(nsr_id) |
| 544 | image_text = ns_preffix + ":image." + target_vdu["ns-image-id"] |
| 545 | flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"] |
| 546 | extra_dict = {"depends_on": [image_text, flavor_text]} |
| 547 | net_list = [] |
| 548 | for iface_index, interface in enumerate(target_vdu["interfaces"]): |
| 549 | if interface.get("ns-vld-id"): |
| 550 | net_text = ns_preffix + ":vld." + interface["ns-vld-id"] |
| 551 | else: |
| 552 | net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"] |
| 553 | extra_dict["depends_on"].append(net_text) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 554 | net_item = {x: v for x, v in interface.items() if x in |
| 555 | ("name", "vpci", "port_security", "port_security_disable_strategy", "floating_ip")} |
| 556 | net_item["net_id"] = "TASK-" + net_text |
| 557 | net_item["type"] = "virtual" |
| 558 | # TODO mac_address: used for SR-IOV ifaces #TODO for other types |
| 559 | # TODO floating_ip: True/False (or it can be None) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 560 | if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"): |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 561 | # mark the net create task as type data |
| 562 | if deep_get(tasks_by_target_record_id, net_text, "params", "net_type"): |
| 563 | tasks_by_target_record_id[net_text]["params"]["net_type"] = "data" |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 564 | net_item["use"] = "data" |
| 565 | net_item["model"] = interface["type"] |
| 566 | net_item["type"] = interface["type"] |
| 567 | elif interface.get("type") == "OM-MGMT" or interface.get("mgmt-interface") or \ |
| 568 | interface.get("mgmt-vnf"): |
| 569 | net_item["use"] = "mgmt" |
| 570 | else: # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"): |
| 571 | net_item["use"] = "bridge" |
| 572 | net_item["model"] = interface.get("type") |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 573 | if interface.get("ip-address"): |
| 574 | net_item["ip_address"] = interface["ip-address"] |
| 575 | if interface.get("mac-address"): |
| 576 | net_item["mac_address"] = interface["mac-address"] |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 577 | net_list.append(net_item) |
| 578 | if interface.get("mgmt-vnf"): |
| 579 | extra_dict["mgmt_vnf_interface"] = iface_index |
| 580 | elif interface.get("mgmt-interface"): |
| 581 | extra_dict["mgmt_vdu_interface"] = iface_index |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 582 | # cloud config |
| 583 | cloud_config = {} |
| 584 | if target_vdu.get("cloud-init"): |
| 585 | if target_vdu["cloud-init"] not in vdu2cloud_init: |
| 586 | vdu2cloud_init[target_vdu["cloud-init"]] = self._get_cloud_init(target_vdu["cloud-init"]) |
| 587 | cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]] |
| 588 | cloud_config["user-data"] = self._parse_jinja2(cloud_content_, target_vdu.get("additionalParams"), |
| 589 | target_vdu["cloud-init"]) |
| 590 | if target_vdu.get("boot-data-drive"): |
| 591 | cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive") |
| 592 | ssh_keys = [] |
| 593 | if target_vdu.get("ssh-keys"): |
| 594 | ssh_keys += target_vdu.get("ssh-keys") |
| 595 | if target_vdu.get("ssh-access-required"): |
| 596 | ssh_keys.append(ro_nsr_public_key) |
| 597 | if ssh_keys: |
| 598 | cloud_config["key-pairs"] = ssh_keys |
| 599 | |
| 600 | extra_dict["params"] = { |
| 601 | "name": "{}-{}-{}-{}".format(indata["name"][:16], vnfr["member-vnf-index-ref"][:16], |
| 602 | target_vdu["vdu-name"][:32], target_vdu.get("count-index") or 0), |
| 603 | "description": target_vdu["vdu-name"], |
| 604 | "start": True, |
| 605 | "image_id": "TASK-" + image_text, |
| 606 | "flavor_id": "TASK-" + flavor_text, |
| 607 | "net_list": net_list, |
| 608 | "cloud_config": cloud_config or None, |
| 609 | "disk_list": None, # TODO |
| 610 | "availability_zone_index": None, # TODO |
| 611 | "availability_zone_list": None, # TODO |
| 612 | } |
| 613 | return extra_dict |
| 614 | |
| 615 | def _process_items(target_list, existing_list, db_record, db_update, db_path, item, process_params): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 616 | nonlocal db_new_tasks |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 617 | nonlocal tasks_by_target_record_id |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 618 | nonlocal task_index |
| 619 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 620 | # ensure all the target_list elements has an "id". If not assign the index as id |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 621 | for target_index, tl in enumerate(target_list): |
| 622 | if tl and not tl.get("id"): |
| 623 | tl["id"] = str(target_index) |
| 624 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 625 | # step 1 items (networks,vdus,...) to be deleted/updated |
| 626 | for item_index, existing_item in enumerate(existing_list): |
| 627 | target_item = next((t for t in target_list if t["id"] == existing_item["id"]), None) |
| 628 | for target_vim, existing_viminfo in existing_item.get("vim_info", {}).items(): |
| 629 | if existing_viminfo is None: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 630 | continue |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 631 | if target_item: |
| 632 | target_viminfo = target_item.get("vim_info", {}).get(target_vim) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 633 | else: |
| 634 | target_viminfo = None |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 635 | if target_viminfo is None: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 636 | # must be deleted |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 637 | self.assign_vim(target_vim) |
| 638 | target_record_id = "{}.{}".format(db_record, existing_item["id"]) |
| 639 | item_ = item |
| 640 | if target_vim.startswith("sdn"): |
| 641 | # item must be sdn-net instead of net if target_vim is a sdn |
| 642 | item_ = "sdn_net" |
| 643 | target_record_id += ".sdn" |
| 644 | task = _create_task( |
| 645 | target_vim, item_, "DELETE", |
| 646 | target_record="{}.{}.vim_info.{}".format(db_record, item_index, target_vim), |
| 647 | target_record_id=target_record_id) |
| 648 | tasks_by_target_record_id[target_record_id] = task |
| 649 | db_new_tasks.append(task) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 650 | # TODO delete |
| 651 | # TODO check one by one the vims to be created/deleted |
| 652 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 653 | # step 2 items (networks,vdus,...) to be created |
| 654 | for target_item in target_list: |
| 655 | item_index = -1 |
| 656 | for item_index, existing_item in enumerate(existing_list): |
| 657 | if existing_item["id"] == target_item["id"]: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 658 | break |
| 659 | else: |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 660 | item_index += 1 |
| 661 | db_update[db_path + ".{}".format(item_index)] = target_item |
| 662 | existing_list.append(target_item) |
| 663 | existing_item = None |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 664 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 665 | for target_vim, target_viminfo in target_item.get("vim_info", {}).items(): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 666 | existing_viminfo = None |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 667 | if existing_item: |
| 668 | existing_viminfo = existing_item.get("vim_info", {}).get(target_vim) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 669 | # TODO check if different. Delete and create??? |
| 670 | # TODO delete if not exist |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 671 | if existing_viminfo is not None: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 672 | continue |
| 673 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 674 | target_record_id = "{}.{}".format(db_record, target_item["id"]) |
| 675 | item_ = item |
| 676 | if target_vim.startswith("sdn"): |
| 677 | # item must be sdn-net instead of net if target_vim is a sdn |
| 678 | item_ = "sdn_net" |
| 679 | target_record_id += ".sdn" |
| 680 | extra_dict = process_params(target_item, target_viminfo, target_record_id) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 681 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 682 | self.assign_vim(target_vim) |
| 683 | task = _create_task( |
| 684 | target_vim, item_, "CREATE", |
| 685 | target_record="{}.{}.vim_info.{}".format(db_record, item_index, target_vim), |
| 686 | target_record_id=target_record_id, |
| 687 | extra_dict=extra_dict) |
| 688 | tasks_by_target_record_id[target_record_id] = task |
| 689 | db_new_tasks.append(task) |
| 690 | if target_item.get("common_id"): |
| 691 | task["common_id"] = target_item["common_id"] |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 692 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 693 | db_update[db_path + ".{}".format(item_index)] = target_item |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 694 | |
| 695 | def _process_action(indata): |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 696 | nonlocal db_new_tasks |
| 697 | nonlocal task_index |
| 698 | nonlocal db_vnfrs |
| 699 | nonlocal db_ro_nsr |
| 700 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 701 | if indata["action"]["action"] == "inject_ssh_key": |
| 702 | key = indata["action"].get("key") |
| 703 | user = indata["action"].get("user") |
| 704 | password = indata["action"].get("password") |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 705 | for vnf in indata.get("vnf", ()): |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 706 | if vnf["_id"] not in db_vnfrs: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 707 | raise NsException("Invalid vnf={}".format(vnf["_id"])) |
| 708 | db_vnfr = db_vnfrs[vnf["_id"]] |
| 709 | for target_vdu in vnf.get("vdur", ()): |
| 710 | vdu_index, vdur = next((i_v for i_v in enumerate(db_vnfr["vdur"]) if |
| 711 | i_v[1]["id"] == target_vdu["id"]), (None, None)) |
| 712 | if not vdur: |
| 713 | raise NsException("Invalid vdu vnf={}.{}".format(vnf["_id"], target_vdu["id"])) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 714 | target_vim, vim_info = next(k_v for k_v in vdur["vim_info"].items()) |
| 715 | self.assign_vim(target_vim) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 716 | target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(vnf["_id"], vdu_index) |
| 717 | extra_dict = { |
| 718 | "depends_on": ["vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])], |
| 719 | "params": { |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 720 | "ip_address": vdur.get("ip-address"), |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 721 | "user": user, |
| 722 | "key": key, |
| 723 | "password": password, |
| 724 | "private_key": db_ro_nsr["private_key"], |
| 725 | "salt": db_ro_nsr["_id"], |
| 726 | "schema_version": db_ro_nsr["_admin"]["schema_version"] |
| 727 | } |
| 728 | } |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 729 | task = _create_task(target_vim, "vdu", "EXEC", |
| 730 | target_record=target_record, |
| 731 | target_record_id=None, |
| 732 | extra_dict=extra_dict) |
| 733 | db_new_tasks.append(task) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 734 | |
| 735 | with self.write_lock: |
| 736 | if indata.get("action"): |
| 737 | _process_action(indata) |
| 738 | else: |
| 739 | # compute network differences |
| 740 | # NS.vld |
| 741 | step = "process NS VLDs" |
| 742 | _process_items(target_list=indata["ns"]["vld"] or [], existing_list=db_nsr.get("vld") or [], |
| 743 | db_record="nsrs:{}:vld".format(nsr_id), db_update=db_nsr_update, |
| 744 | db_path="vld", item="net", process_params=_process_net_params) |
| 745 | |
| 746 | step = "process NS images" |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 747 | _process_items(target_list=indata.get("image") or [], existing_list=db_nsr.get("image") or [], |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 748 | db_record="nsrs:{}:image".format(nsr_id), |
| 749 | db_update=db_nsr_update, db_path="image", item="image", |
| 750 | process_params=_process_image_params) |
| 751 | |
| 752 | step = "process NS flavors" |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 753 | _process_items(target_list=indata.get("flavor") or [], existing_list=db_nsr.get("flavor") or [], |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 754 | db_record="nsrs:{}:flavor".format(nsr_id), |
| 755 | db_update=db_nsr_update, db_path="flavor", item="flavor", |
| 756 | process_params=_process_flavor_params) |
| 757 | |
| 758 | # VNF.vld |
| 759 | for vnfr_id, vnfr in db_vnfrs.items(): |
| 760 | # vnfr_id need to be set as global variable for among others nested method _process_vdu_params |
| 761 | step = "process VNF={} VLDs".format(vnfr_id) |
| 762 | target_vnf = next((vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id), None) |
| 763 | target_list = target_vnf.get("vld") if target_vnf else None |
| 764 | _process_items(target_list=target_list or [], existing_list=vnfr.get("vld") or [], |
| 765 | db_record="vnfrs:{}:vld".format(vnfr_id), db_update=db_vnfrs_update[vnfr["_id"]], |
| 766 | db_path="vld", item="net", process_params=_process_net_params) |
| 767 | |
| 768 | target_list = target_vnf.get("vdur") if target_vnf else None |
| 769 | step = "process VNF={} VDUs".format(vnfr_id) |
| 770 | _process_items(target_list=target_list or [], existing_list=vnfr.get("vdur") or [], |
| 771 | db_record="vnfrs:{}:vdur".format(vnfr_id), |
| 772 | db_update=db_vnfrs_update[vnfr["_id"]], db_path="vdur", item="vdu", |
| 773 | process_params=_process_vdu_params) |
| 774 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 775 | for db_task in db_new_tasks: |
| 776 | step = "Updating database, Appending tasks to ro_tasks" |
| 777 | target_id = db_task.pop("target_id") |
| 778 | common_id = db_task.get("common_id") |
| 779 | if common_id: |
| 780 | if self.db.set_one("ro_tasks", |
| 781 | q_filter={"target_id": target_id, |
| 782 | "tasks.common_id": common_id}, |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 783 | update_dict={"to_check_at": now, "modified_at": now}, |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 784 | push={"tasks": db_task}, fail_on_empty=False): |
| 785 | continue |
| 786 | if not self.db.set_one("ro_tasks", |
| 787 | q_filter={"target_id": target_id, |
| 788 | "tasks.target_record": db_task["target_record"]}, |
| 789 | update_dict={"to_check_at": now, "modified_at": now}, |
| 790 | push={"tasks": db_task}, fail_on_empty=False): |
| 791 | # Create a ro_task |
| 792 | step = "Updating database, Creating ro_tasks" |
| 793 | db_ro_task = _create_ro_task(target_id, db_task) |
| 794 | nb_ro_tasks += 1 |
| 795 | self.db.create("ro_tasks", db_ro_task) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 796 | step = "Updating database, nsrs" |
| 797 | if db_nsr_update: |
| 798 | self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update) |
| 799 | for vnfr_id, db_vnfr_update in db_vnfrs_update.items(): |
| 800 | if db_vnfr_update: |
| 801 | step = "Updating database, vnfrs={}".format(vnfr_id) |
| 802 | self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update) |
| 803 | |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 804 | self.logger.debug(logging_text + "Exit. Created {} ro_tasks; {} tasks".format(nb_ro_tasks, |
| 805 | len(db_new_tasks))) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 806 | return {"status": "ok", "nsr_id": nsr_id, "action_id": action_id}, action_id, True |
| 807 | |
| 808 | except Exception as e: |
| 809 | if isinstance(e, (DbException, NsException)): |
| 810 | self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e)) |
| 811 | else: |
| 812 | e = traceback_format_exc() |
| 813 | self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(step, e), exc_info=True) |
| 814 | raise NsException(e) |
| 815 | |
| 816 | def delete(self, session, indata, version, nsr_id, *args, **kwargs): |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 817 | self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 818 | # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id}) |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 819 | with self.write_lock: |
| 820 | try: |
| 821 | NsWorker.delete_db_tasks(self.db, nsr_id, None) |
| 822 | except NsWorkerException as e: |
| 823 | raise NsException(e) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 824 | return None, None, True |
| 825 | |
| 826 | def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs): |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 827 | # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}" |
| 828 | # .format(version, nsr_id, action_id, indata)) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 829 | task_list = [] |
| 830 | done = 0 |
| 831 | total = 0 |
| 832 | ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id}) |
| 833 | global_status = "DONE" |
| 834 | details = [] |
| 835 | for ro_task in ro_tasks: |
| 836 | for task in ro_task["tasks"]: |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 837 | if task and task["action_id"] == action_id: |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 838 | task_list.append(task) |
| 839 | total += 1 |
| 840 | if task["status"] == "FAILED": |
| 841 | global_status = "FAILED" |
| tierno | 70eeb18 | 2020-10-19 16:38:00 +0000 | [diff] [blame] | 842 | error_text = "Error at {} {}: {}".format(task["action"].lower(), task["item"], |
| 843 | ro_task["vim_info"].get("vim_details") or "unknown") |
| 844 | details.append(error_text) |
| tierno | 1d213f4 | 2020-04-24 14:02:51 +0000 | [diff] [blame] | 845 | elif task["status"] in ("SCHEDULED", "BUILD"): |
| 846 | if global_status != "FAILED": |
| 847 | global_status = "BUILD" |
| 848 | else: |
| 849 | done += 1 |
| 850 | return_data = { |
| 851 | "status": global_status, |
| 852 | "details": ". ".join(details) if details else "progress {}/{}".format(done, total), |
| 853 | "nsr_id": nsr_id, |
| 854 | "action_id": action_id, |
| 855 | "tasks": task_list |
| 856 | } |
| 857 | return return_data, None, True |
| 858 | |
| 859 | def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs): |
| 860 | print("ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(session, indata, version, |
| 861 | nsr_id, action_id)) |
| 862 | return None, None, True |
| 863 | |
| 864 | def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs): |
| 865 | nsrs = self.db.get_list("nsrs", {}) |
| 866 | return_data = [] |
| 867 | for ns in nsrs: |
| 868 | return_data.append({"_id": ns["_id"], "name": ns["name"]}) |
| 869 | return return_data, None, True |
| 870 | |
| 871 | def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs): |
| 872 | ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id}) |
| 873 | return_data = [] |
| 874 | for ro_task in ro_tasks: |
| 875 | for task in ro_task["tasks"]: |
| 876 | if task["action_id"] not in return_data: |
| 877 | return_data.append(task["action_id"]) |
| 878 | return return_data, None, True |