| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
| tierno | 2e21551 | 2018-11-28 09:37:52 +0000 | [diff] [blame] | 3 | ## |
| 4 | # Copyright 2018 Telefonica S.A. |
| 5 | # |
| 6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 7 | # not use this file except in compliance with the License. You may obtain |
| 8 | # a copy of the License at |
| 9 | # |
| 10 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | # |
| 12 | # Unless required by applicable law or agreed to in writing, software |
| 13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 15 | # License for the specific language governing permissions and limitations |
| 16 | # under the License. |
| 17 | ## |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 18 | |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 19 | import asyncio |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 20 | import checksumdir |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 21 | from collections import OrderedDict |
| aticig | 1dda84c | 2022-09-10 01:56:58 +0300 | [diff] [blame] | 22 | import hashlib |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 23 | import os |
| aticig | 9bc63ac | 2022-07-27 09:32:06 +0300 | [diff] [blame] | 24 | import shutil |
| 25 | import traceback |
| tierno | 79cd8ad | 2019-10-18 13:03:10 +0000 | [diff] [blame] | 26 | from time import time |
| aticig | 9bc63ac | 2022-07-27 09:32:06 +0300 | [diff] [blame] | 27 | |
| 28 | from osm_common.fsbase import FsException |
| bravof | 922c417 | 2020-11-24 21:21:43 -0300 | [diff] [blame] | 29 | from osm_lcm.data_utils.database.database import Database |
| 30 | from osm_lcm.data_utils.filesystem.filesystem import Filesystem |
| aticig | 9bc63ac | 2022-07-27 09:32:06 +0300 | [diff] [blame] | 31 | import yaml |
| 32 | from zipfile import ZipFile, BadZipfile |
| bravof | 922c417 | 2020-11-24 21:21:43 -0300 | [diff] [blame] | 33 | |
| tierno | baa5110 | 2018-12-14 13:16:18 +0000 | [diff] [blame] | 34 | # from osm_common.dbbase import DbException |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 35 | |
| 36 | __author__ = "Alfonso Tierno" |
| 37 | |
| 38 | |
| 39 | class LcmException(Exception): |
| 40 | pass |
| 41 | |
| 42 | |
| gcalvino | ed7f6d4 | 2018-12-14 14:44:56 +0100 | [diff] [blame] | 43 | class LcmExceptionExit(LcmException): |
| 44 | pass |
| 45 | |
| 46 | |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 47 | def versiontuple(v): |
| tierno | 27246d8 | 2018-09-27 15:59:09 +0200 | [diff] [blame] | 48 | """utility for compare dot separate versions. Fills with zeros to proper number comparison |
| 49 | package version will be something like 4.0.1.post11+gb3f024d.dirty-1. Where 4.0.1 is the git tag, postXX is the |
| 50 | number of commits from this tag, and +XXXXXXX is the git commit short id. Total length is 16 with until 999 commits |
| 51 | """ |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 52 | filled = [] |
| 53 | for point in v.split("."): |
| tierno | e64f7fb | 2019-09-11 08:55:52 +0000 | [diff] [blame] | 54 | point, _, _ = point.partition("+") |
| 55 | point, _, _ = point.partition("-") |
| 56 | filled.append(point.zfill(20)) |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 57 | return tuple(filled) |
| 58 | |
| 59 | |
| tierno | 744303e | 2020-01-13 16:46:31 +0000 | [diff] [blame] | 60 | def deep_get(target_dict, key_list, default_value=None): |
| tierno | 626e015 | 2019-11-29 14:16:16 +0000 | [diff] [blame] | 61 | """ |
| 62 | Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None |
| 63 | Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None |
| 64 | :param target_dict: dictionary to be read |
| 65 | :param key_list: list of keys to read from target_dict |
| tierno | 744303e | 2020-01-13 16:46:31 +0000 | [diff] [blame] | 66 | :param default_value: value to return if key is not present in the nested dictionary |
| tierno | 626e015 | 2019-11-29 14:16:16 +0000 | [diff] [blame] | 67 | :return: The wanted value if exist, None otherwise |
| 68 | """ |
| 69 | for key in key_list: |
| 70 | if not isinstance(target_dict, dict) or key not in target_dict: |
| tierno | 744303e | 2020-01-13 16:46:31 +0000 | [diff] [blame] | 71 | return default_value |
| tierno | 626e015 | 2019-11-29 14:16:16 +0000 | [diff] [blame] | 72 | target_dict = target_dict[key] |
| 73 | return target_dict |
| 74 | |
| 75 | |
| tierno | 744303e | 2020-01-13 16:46:31 +0000 | [diff] [blame] | 76 | def get_iterable(in_dict, in_key): |
| 77 | """ |
| 78 | Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead |
| 79 | :param in_dict: a dictionary |
| 80 | :param in_key: the key to look for at in_dict |
| 81 | :return: in_dict[in_var] or () if it is None or not present |
| 82 | """ |
| 83 | if not in_dict.get(in_key): |
| 84 | return () |
| 85 | return in_dict[in_key] |
| 86 | |
| 87 | |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 88 | def check_juju_bundle_existence(vnfd: dict) -> str: |
| 89 | """Checks the existence of juju-bundle in the descriptor |
| 90 | |
| 91 | Args: |
| 92 | vnfd: Descriptor as a dictionary |
| 93 | |
| 94 | Returns: |
| 95 | Juju bundle if dictionary has juju-bundle else None |
| 96 | |
| 97 | """ |
| 98 | if vnfd.get("vnfd"): |
| 99 | vnfd = vnfd["vnfd"] |
| 100 | |
| 101 | for kdu in vnfd.get("kdu", []): |
| 102 | return kdu.get("juju-bundle", None) |
| 103 | |
| 104 | |
| 105 | def get_charm_artifact_path(base_folder, charm_name, charm_type, revision=str()) -> str: |
| 106 | """Finds the charm artifact paths |
| 107 | |
| 108 | Args: |
| 109 | base_folder: Main folder which will be looked up for charm |
| 110 | charm_name: Charm name |
| 111 | charm_type: Type of charm native_charm, lxc_proxy_charm or k8s_proxy_charm |
| 112 | revision: vnf package revision number if there is |
| 113 | |
| 114 | Returns: |
| 115 | artifact_path: (str) |
| 116 | |
| 117 | """ |
| 118 | extension = "" |
| 119 | if revision: |
| 120 | extension = ":" + str(revision) |
| 121 | |
| 122 | if base_folder.get("pkg-dir"): |
| 123 | artifact_path = "{}/{}/{}/{}".format( |
| aticig | d708354 | 2022-05-30 20:45:55 +0300 | [diff] [blame] | 124 | base_folder["folder"].split(":")[0] + extension, |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 125 | base_folder["pkg-dir"], |
| 126 | "charms" |
| 127 | if charm_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm") |
| 128 | else "helm-charts", |
| 129 | charm_name, |
| 130 | ) |
| 131 | |
| 132 | else: |
| 133 | # For SOL004 packages |
| 134 | artifact_path = "{}/Scripts/{}/{}".format( |
| aticig | d708354 | 2022-05-30 20:45:55 +0300 | [diff] [blame] | 135 | base_folder["folder"].split(":")[0] + extension, |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 136 | "charms" |
| 137 | if charm_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm") |
| 138 | else "helm-charts", |
| 139 | charm_name, |
| 140 | ) |
| 141 | |
| 142 | return artifact_path |
| 143 | |
| 144 | |
| tierno | 744303e | 2020-01-13 16:46:31 +0000 | [diff] [blame] | 145 | def populate_dict(target_dict, key_list, value): |
| 146 | """ |
| 147 | Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value. |
| 148 | Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}} |
| 149 | :param target_dict: dictionary to be changed |
| 150 | :param key_list: list of keys to insert at target_dict |
| 151 | :param value: |
| 152 | :return: None |
| 153 | """ |
| 154 | for key in key_list[0:-1]: |
| 155 | if key not in target_dict: |
| 156 | target_dict[key] = {} |
| 157 | target_dict = target_dict[key] |
| 158 | target_dict[key_list[-1]] = value |
| 159 | |
| 160 | |
| Gabriel Cuba | e539a8d | 2022-10-10 11:34:51 -0500 | [diff] [blame] | 161 | def get_ee_id_parts(ee_id): |
| 162 | """ |
| 163 | Parses ee_id stored at database that can be either 'version:namespace.helm_id' or only |
| 164 | namespace.helm_id for backward compatibility |
| 165 | If exists helm version can be helm-v3 or helm (helm-v2 old version) |
| 166 | """ |
| 167 | version, _, part_id = ee_id.rpartition(":") |
| 168 | namespace, _, helm_id = part_id.rpartition(".") |
| 169 | return version, namespace, helm_id |
| 170 | |
| 171 | |
| Gabriel Cuba | c773744 | 2023-02-14 13:09:18 -0500 | [diff] [blame] | 172 | def vld_to_ro_ip_profile(source_data): |
| 173 | if source_data: |
| 174 | return { |
| 175 | "ip_version": "IPv4" |
| 176 | if "v4" in source_data.get("ip-version", "ipv4") |
| 177 | else "IPv6", |
| 178 | "subnet_address": source_data.get("cidr") |
| 179 | or source_data.get("subnet-address"), |
| 180 | "gateway_address": source_data.get("gateway-ip") |
| 181 | or source_data.get("gateway-address"), |
| 182 | "dns_address": ";".join( |
| 183 | [v["address"] for v in source_data["dns-server"] if v.get("address")] |
| 184 | ) |
| 185 | if source_data.get("dns-server") |
| 186 | else None, |
| 187 | "dhcp_enabled": source_data.get("dhcp-params", {}).get("enabled", False) |
| 188 | or source_data.get("dhcp-enabled", False), |
| 189 | "dhcp_start_address": source_data["dhcp-params"].get("start-address") |
| 190 | if source_data.get("dhcp-params") |
| 191 | else None, |
| 192 | "dhcp_count": source_data["dhcp-params"].get("count") |
| 193 | if source_data.get("dhcp-params") |
| 194 | else None, |
| Gabriel Cuba | f0af5e6 | 2023-03-14 00:27:49 -0500 | [diff] [blame] | 195 | "ipv6_address_mode": source_data["ipv6-address-mode"] |
| 196 | if "ipv6-address-mode" in source_data |
| 197 | else None, |
| Gabriel Cuba | c773744 | 2023-02-14 13:09:18 -0500 | [diff] [blame] | 198 | } |
| 199 | |
| 200 | |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 201 | class LcmBase: |
| bravof | 922c417 | 2020-11-24 21:21:43 -0300 | [diff] [blame] | 202 | def __init__(self, msg, logger): |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 203 | """ |
| 204 | |
| 205 | :param db: database connection |
| 206 | """ |
| bravof | 922c417 | 2020-11-24 21:21:43 -0300 | [diff] [blame] | 207 | self.db = Database().instance.db |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 208 | self.msg = msg |
| bravof | 922c417 | 2020-11-24 21:21:43 -0300 | [diff] [blame] | 209 | self.fs = Filesystem().instance.fs |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 210 | self.logger = logger |
| 211 | |
| 212 | def update_db_2(self, item, _id, _desc): |
| 213 | """ |
| 214 | Updates database with _desc information. If success _desc is cleared |
| Pedro Escaleira | da21d26 | 2022-04-21 16:31:06 +0100 | [diff] [blame] | 215 | :param item: collection |
| 216 | :param _id: the _id to use in the query filter |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 217 | :param _desc: dictionary with the content to update. Keys are dot separated keys for |
| 218 | :return: None. Exception is raised on error |
| 219 | """ |
| 220 | if not _desc: |
| 221 | return |
| tierno | 79cd8ad | 2019-10-18 13:03:10 +0000 | [diff] [blame] | 222 | now = time() |
| 223 | _desc["_admin.modified"] = now |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 224 | self.logger.info("Desc: {} Item: {} _id: {}".format(_desc, item, _id)) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 225 | self.db.set_one(item, {"_id": _id}, _desc) |
| 226 | _desc.clear() |
| 227 | # except DbException as e: |
| 228 | # self.logger.error("Updating {} _id={} with '{}'. Error: {}".format(item, _id, _desc, e)) |
| 229 | |
| aticig | 1dda84c | 2022-09-10 01:56:58 +0300 | [diff] [blame] | 230 | @staticmethod |
| 231 | def calculate_charm_hash(zipped_file): |
| 232 | """Calculate the hash of charm files which ends with .charm |
| 233 | |
| 234 | Args: |
| 235 | zipped_file (str): Existing charm package full path |
| 236 | |
| 237 | Returns: |
| 238 | hex digest (str): The hash of the charm file |
| 239 | """ |
| Gabriel Cuba | 4c0e680 | 2023-10-09 13:22:38 -0500 | [diff] [blame] | 240 | filehash = hashlib.sha256() |
| aticig | 1dda84c | 2022-09-10 01:56:58 +0300 | [diff] [blame] | 241 | with open(zipped_file, mode="rb") as file: |
| 242 | contents = file.read() |
| 243 | filehash.update(contents) |
| 244 | return filehash.hexdigest() |
| 245 | |
| 246 | @staticmethod |
| 247 | def compare_charm_hash(current_charm, target_charm): |
| 248 | """Compare the existing charm and the target charm if the charms |
| 249 | are given as zip files ends with .charm |
| 250 | |
| 251 | Args: |
| 252 | current_charm (str): Existing charm package full path |
| 253 | target_charm (str): Target charm package full path |
| 254 | |
| 255 | Returns: |
| 256 | True/False (bool): if charm has changed it returns True |
| 257 | """ |
| 258 | return LcmBase.calculate_charm_hash( |
| 259 | current_charm |
| 260 | ) != LcmBase.calculate_charm_hash(target_charm) |
| 261 | |
| 262 | @staticmethod |
| 263 | def compare_charmdir_hash(current_charm_dir, target_charm_dir): |
| 264 | """Compare the existing charm and the target charm if the charms |
| 265 | are given as directories |
| 266 | |
| 267 | Args: |
| 268 | current_charm_dir (str): Existing charm package directory path |
| 269 | target_charm_dir (str): Target charm package directory path |
| 270 | |
| 271 | Returns: |
| 272 | True/False (bool): if charm has changed it returns True |
| 273 | """ |
| 274 | return checksumdir.dirhash(current_charm_dir) != checksumdir.dirhash( |
| 275 | target_charm_dir |
| 276 | ) |
| 277 | |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 278 | def check_charm_hash_changed( |
| 279 | self, current_charm_path: str, target_charm_path: str |
| 280 | ) -> bool: |
| 281 | """Find the target charm has changed or not by checking the hash of |
| 282 | old and new charm packages |
| 283 | |
| 284 | Args: |
| 285 | current_charm_path (str): Existing charm package artifact path |
| 286 | target_charm_path (str): Target charm package artifact path |
| 287 | |
| 288 | Returns: |
| 289 | True/False (bool): if charm has changed it returns True |
| 290 | |
| 291 | """ |
| aticig | 1dda84c | 2022-09-10 01:56:58 +0300 | [diff] [blame] | 292 | try: |
| 293 | # Check if the charm artifacts are available |
| 294 | current_charm = self.fs.path + current_charm_path |
| 295 | target_charm = self.fs.path + target_charm_path |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 296 | |
| aticig | 1dda84c | 2022-09-10 01:56:58 +0300 | [diff] [blame] | 297 | if os.path.exists(current_charm) and os.path.exists(target_charm): |
| aticig | 1dda84c | 2022-09-10 01:56:58 +0300 | [diff] [blame] | 298 | # Compare the hash of .charm files |
| 299 | if current_charm.endswith(".charm"): |
| 300 | return LcmBase.compare_charm_hash(current_charm, target_charm) |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 301 | |
| aticig | 1dda84c | 2022-09-10 01:56:58 +0300 | [diff] [blame] | 302 | # Compare the hash of charm folders |
| 303 | return LcmBase.compare_charmdir_hash(current_charm, target_charm) |
| 304 | |
| 305 | else: |
| 306 | raise LcmException( |
| 307 | "Charm artifact {} does not exist in the VNF Package".format( |
| 308 | self.fs.path + target_charm_path |
| 309 | ) |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 310 | ) |
| aticig | 1dda84c | 2022-09-10 01:56:58 +0300 | [diff] [blame] | 311 | except (IOError, OSError, TypeError) as error: |
| 312 | self.logger.debug(traceback.format_exc()) |
| 313 | self.logger.error(f"{error} occured while checking the charm hashes") |
| 314 | raise LcmException(error) |
| aticig | dffa621 | 2022-04-12 15:27:53 +0300 | [diff] [blame] | 315 | |
| aticig | 9bc63ac | 2022-07-27 09:32:06 +0300 | [diff] [blame] | 316 | @staticmethod |
| 317 | def get_charm_name(charm_metadata_file: str) -> str: |
| 318 | """Get the charm name from metadata file. |
| 319 | |
| 320 | Args: |
| 321 | charm_metadata_file (str): charm metadata file full path |
| 322 | |
| 323 | Returns: |
| 324 | charm_name (str): charm name |
| 325 | |
| 326 | """ |
| 327 | # Read charm metadata.yaml to get the charm name |
| 328 | with open(charm_metadata_file, "r") as metadata_file: |
| 329 | content = yaml.safe_load(metadata_file) |
| 330 | charm_name = content["name"] |
| 331 | return str(charm_name) |
| 332 | |
| 333 | def _get_charm_path( |
| 334 | self, nsd_package_path: str, nsd_package_name: str, charm_folder_name: str |
| 335 | ) -> str: |
| 336 | """Get the full path of charm folder. |
| 337 | |
| 338 | Args: |
| 339 | nsd_package_path (str): NSD package full path |
| 340 | nsd_package_name (str): NSD package name |
| 341 | charm_folder_name (str): folder name |
| 342 | |
| 343 | Returns: |
| 344 | charm_path (str): charm folder full path |
| 345 | """ |
| 346 | charm_path = ( |
| 347 | self.fs.path |
| 348 | + nsd_package_path |
| 349 | + "/" |
| 350 | + nsd_package_name |
| 351 | + "/charms/" |
| 352 | + charm_folder_name |
| 353 | ) |
| 354 | return charm_path |
| 355 | |
| 356 | def _get_charm_metadata_file( |
| 357 | self, |
| 358 | charm_folder_name: str, |
| 359 | nsd_package_path: str, |
| 360 | nsd_package_name: str, |
| 361 | charm_path: str = None, |
| 362 | ) -> str: |
| 363 | """Get the path of charm metadata file. |
| 364 | |
| 365 | Args: |
| 366 | charm_folder_name (str): folder name |
| 367 | nsd_package_path (str): NSD package full path |
| 368 | nsd_package_name (str): NSD package name |
| 369 | charm_path (str): Charm full path |
| 370 | |
| 371 | Returns: |
| 372 | charm_metadata_file_path (str): charm metadata file full path |
| 373 | |
| 374 | """ |
| 375 | # Locate the charm metadata.yaml |
| 376 | if charm_folder_name.endswith(".charm"): |
| 377 | extract_path = ( |
| 378 | self.fs.path |
| 379 | + nsd_package_path |
| 380 | + "/" |
| 381 | + nsd_package_name |
| 382 | + "/charms/" |
| aticig | a37c6ff | 2022-08-20 20:56:19 +0300 | [diff] [blame] | 383 | + charm_folder_name.replace(".charm", "") |
| aticig | 9bc63ac | 2022-07-27 09:32:06 +0300 | [diff] [blame] | 384 | ) |
| 385 | # Extract .charm to extract path |
| 386 | with ZipFile(charm_path, "r") as zipfile: |
| 387 | zipfile.extractall(extract_path) |
| 388 | return extract_path + "/metadata.yaml" |
| 389 | else: |
| 390 | return charm_path + "/metadata.yaml" |
| 391 | |
| 392 | def find_charm_name(self, db_nsr: dict, charm_folder_name: str) -> str: |
| 393 | """Get the charm name from metadata.yaml of charm package. |
| 394 | |
| 395 | Args: |
| 396 | db_nsr (dict): NS record as a dictionary |
| 397 | charm_folder_name (str): charm folder name |
| 398 | |
| 399 | Returns: |
| 400 | charm_name (str): charm name |
| 401 | """ |
| 402 | try: |
| 403 | if not charm_folder_name: |
| 404 | raise LcmException("charm_folder_name should be provided.") |
| 405 | |
| 406 | # Find nsd_package details: path, name |
| 407 | revision = db_nsr.get("revision", "") |
| aticig | a37c6ff | 2022-08-20 20:56:19 +0300 | [diff] [blame] | 408 | |
| 409 | # Get the NSD package path |
| 410 | if revision: |
| preethika.p | 28b0bf8 | 2022-09-23 07:36:28 +0000 | [diff] [blame] | 411 | nsd_package_path = db_nsr["nsd-id"] + ":" + str(revision) |
| aticig | a37c6ff | 2022-08-20 20:56:19 +0300 | [diff] [blame] | 412 | db_nsd = self.db.get_one("nsds_revisions", {"_id": nsd_package_path}) |
| 413 | |
| 414 | else: |
| 415 | nsd_package_path = db_nsr["nsd-id"] |
| 416 | |
| 417 | db_nsd = self.db.get_one("nsds", {"_id": nsd_package_path}) |
| 418 | |
| 419 | # Get the NSD package name |
| 420 | nsd_package_name = db_nsd["_admin"]["storage"]["pkg-dir"] |
| aticig | 9bc63ac | 2022-07-27 09:32:06 +0300 | [diff] [blame] | 421 | |
| 422 | # Remove the existing nsd package and sync from FsMongo |
| 423 | shutil.rmtree(self.fs.path + nsd_package_path, ignore_errors=True) |
| 424 | self.fs.sync(from_path=nsd_package_path) |
| 425 | |
| 426 | # Get the charm path |
| 427 | charm_path = self._get_charm_path( |
| 428 | nsd_package_path, nsd_package_name, charm_folder_name |
| 429 | ) |
| 430 | |
| 431 | # Find charm metadata file full path |
| 432 | charm_metadata_file = self._get_charm_metadata_file( |
| 433 | charm_folder_name, nsd_package_path, nsd_package_name, charm_path |
| 434 | ) |
| 435 | |
| 436 | # Return charm name |
| 437 | return self.get_charm_name(charm_metadata_file) |
| 438 | |
| 439 | except ( |
| 440 | yaml.YAMLError, |
| 441 | IOError, |
| 442 | FsException, |
| 443 | KeyError, |
| 444 | TypeError, |
| 445 | FileNotFoundError, |
| 446 | BadZipfile, |
| 447 | ) as error: |
| 448 | self.logger.debug(traceback.format_exc()) |
| 449 | self.logger.error(f"{error} occured while getting the charm name") |
| 450 | raise LcmException(error) |
| 451 | |
| Gabriel Cuba | 879483e | 2024-03-19 18:01:13 -0500 | [diff] [blame] | 452 | def get_vca_info(self, ee_item, db_nsr, get_charm_name: bool): |
| 453 | vca_name = charm_name = vca_type = None |
| 454 | if ee_item.get("juju"): |
| 455 | vca_name = ee_item["juju"].get("charm") |
| 456 | if get_charm_name: |
| 457 | charm_name = self.find_charm_name(db_nsr, str(vca_name)) |
| 458 | vca_type = ( |
| 459 | "lxc_proxy_charm" |
| 460 | if ee_item["juju"].get("charm") is not None |
| 461 | else "native_charm" |
| 462 | ) |
| 463 | if ee_item["juju"].get("cloud") == "k8s": |
| 464 | vca_type = "k8s_proxy_charm" |
| 465 | elif ee_item["juju"].get("proxy") is False: |
| 466 | vca_type = "native_charm" |
| 467 | elif ee_item.get("helm-chart"): |
| 468 | vca_name = ee_item["helm-chart"] |
| 469 | vca_type = "helm-v3" |
| 470 | return vca_name, charm_name, vca_type |
| 471 | |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 472 | |
| 473 | class TaskRegistry(LcmBase): |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 474 | """ |
| 475 | Implements a registry of task needed for later cancelation, look for related tasks that must be completed before |
| 476 | etc. It stores a four level dict |
| 477 | First level is the topic, ns, vim_account, sdn |
| 478 | Second level is the _id |
| 479 | Third level is the operation id |
| 480 | Fourth level is a descriptive name, the value is the task class |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 481 | |
| 482 | The HA (High-Availability) methods are used when more than one LCM instance is running. |
| 483 | To register the current task in the external DB, use LcmBase as base class, to be able |
| 484 | to reuse LcmBase.update_db_2() |
| 485 | The DB registry uses the following fields to distinguish a task: |
| 486 | - op_type: operation type ("nslcmops" or "nsilcmops") |
| 487 | - op_id: operation ID |
| 488 | - worker: the worker ID for this process |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 489 | """ |
| 490 | |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 491 | # NS/NSI: "services" VIM/WIM/SDN: "accounts" |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 492 | topic_service_list = ["ns", "nsi"] |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 493 | topic_account_list = [ |
| 494 | "vim", |
| 495 | "wim", |
| 496 | "sdn", |
| 497 | "k8scluster", |
| 498 | "vca", |
| 499 | "k8srepo", |
| 500 | "cluster", |
| 501 | "k8s_app", |
| 502 | "k8s_resource", |
| 503 | "k8s_infra_controller", |
| 504 | "k8s_infra_config", |
| yshah | 771dea8 | 2024-07-05 15:11:49 +0000 | [diff] [blame] | 505 | "oka", |
| 506 | "ksu", |
| garciadeblas | 61a4c69 | 2025-07-17 13:04:13 +0200 | [diff] [blame] | 507 | "appinstance", |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 508 | ] |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 509 | |
| 510 | # Map topic to InstanceID |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 511 | topic2instid_dict = {"ns": "nsInstanceId", "nsi": "netsliceInstanceId"} |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 512 | |
| 513 | # Map topic to DB table name |
| 514 | topic2dbtable_dict = { |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 515 | "ns": "nslcmops", |
| 516 | "nsi": "nsilcmops", |
| 517 | "vim": "vim_accounts", |
| 518 | "wim": "wim_accounts", |
| 519 | "sdn": "sdns", |
| 520 | "k8scluster": "k8sclusters", |
| 521 | "vca": "vca", |
| 522 | "k8srepo": "k8srepos", |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 523 | "cluster": "k8sclusters", |
| 524 | "k8s_app": "k8sapp", |
| 525 | "k8s_resource": "k8sresource", |
| 526 | "k8s_infra_controller": "k8sinfra_controller", |
| 527 | "k8s_infra_config": "k8sinfra_config", |
| yshah | 771dea8 | 2024-07-05 15:11:49 +0000 | [diff] [blame] | 528 | "oka": "oka", |
| 529 | "ksu": "ksus", |
| garciadeblas | 61a4c69 | 2025-07-17 13:04:13 +0200 | [diff] [blame] | 530 | "appinstance": "appinstances", |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 531 | } |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 532 | |
| bravof | 922c417 | 2020-11-24 21:21:43 -0300 | [diff] [blame] | 533 | def __init__(self, worker_id=None, logger=None): |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 534 | self.task_registry = { |
| 535 | "ns": {}, |
| Felipe Vicens | c2033f2 | 2018-11-15 15:09:58 +0100 | [diff] [blame] | 536 | "nsi": {}, |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 537 | "vim_account": {}, |
| tierno | e37b57d | 2018-12-11 17:22:51 +0000 | [diff] [blame] | 538 | "wim_account": {}, |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 539 | "sdn": {}, |
| calvinosanch | 9f9c6f2 | 2019-11-04 13:37:39 +0100 | [diff] [blame] | 540 | "k8scluster": {}, |
| David Garcia | c1fe90a | 2021-03-31 19:12:02 +0200 | [diff] [blame] | 541 | "vca": {}, |
| calvinosanch | 9f9c6f2 | 2019-11-04 13:37:39 +0100 | [diff] [blame] | 542 | "k8srepo": {}, |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 543 | "cluster": {}, |
| 544 | "k8s_app": {}, |
| 545 | "k8s_resource": {}, |
| 546 | "k8s_infra_controller": {}, |
| 547 | "k8s_infra_config": {}, |
| yshah | 771dea8 | 2024-07-05 15:11:49 +0000 | [diff] [blame] | 548 | "oka": {}, |
| 549 | "ksu": {}, |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 550 | "odu": {}, |
| garciadeblas | 61a4c69 | 2025-07-17 13:04:13 +0200 | [diff] [blame] | 551 | "appinstance": {}, |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 552 | } |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 553 | self.worker_id = worker_id |
| bravof | 922c417 | 2020-11-24 21:21:43 -0300 | [diff] [blame] | 554 | self.db = Database().instance.db |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 555 | self.logger = logger |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 556 | # self.logger.info("Task registry: {}".format(self.task_registry)) |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 557 | |
| 558 | def register(self, topic, _id, op_id, task_name, task): |
| 559 | """ |
| 560 | Register a new task |
| Felipe Vicens | c2033f2 | 2018-11-15 15:09:58 +0100 | [diff] [blame] | 561 | :param topic: Can be "ns", "nsi", "vim_account", "sdn" |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 562 | :param _id: _id of the related item |
| 563 | :param op_id: id of the operation of the related item |
| 564 | :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id |
| 565 | :param task: Task class |
| 566 | :return: none |
| 567 | """ |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 568 | self.logger.info( |
| 569 | "topic : {}, _id:{}, op_id:{}, taskname:{}, task:{}".format( |
| 570 | topic, _id, op_id, task_name, task |
| 571 | ) |
| 572 | ) |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 573 | if _id not in self.task_registry[topic]: |
| 574 | self.task_registry[topic][_id] = OrderedDict() |
| 575 | if op_id not in self.task_registry[topic][_id]: |
| 576 | self.task_registry[topic][_id][op_id] = {task_name: task} |
| 577 | else: |
| 578 | self.task_registry[topic][_id][op_id][task_name] = task |
| garciadeblas | 6d8acf3 | 2025-02-06 13:34:37 +0100 | [diff] [blame] | 579 | self.logger.info("Task registry: {}".format(self.task_registry)) |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 580 | # print("registering task", topic, _id, op_id, task_name, task) |
| 581 | |
| 582 | def remove(self, topic, _id, op_id, task_name=None): |
| 583 | """ |
| tierno | baa5110 | 2018-12-14 13:16:18 +0000 | [diff] [blame] | 584 | When task is ended, it should be removed. It ignores missing tasks. It also removes tasks done with this _id |
| Felipe Vicens | c2033f2 | 2018-11-15 15:09:58 +0100 | [diff] [blame] | 585 | :param topic: Can be "ns", "nsi", "vim_account", "sdn" |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 586 | :param _id: _id of the related item |
| 587 | :param op_id: id of the operation of the related item |
| tierno | baa5110 | 2018-12-14 13:16:18 +0000 | [diff] [blame] | 588 | :param task_name: Task descriptive name. If none it deletes all tasks with same _id and op_id |
| 589 | :return: None |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 590 | """ |
| tierno | baa5110 | 2018-12-14 13:16:18 +0000 | [diff] [blame] | 591 | if not self.task_registry[topic].get(_id): |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 592 | return |
| 593 | if not task_name: |
| tierno | baa5110 | 2018-12-14 13:16:18 +0000 | [diff] [blame] | 594 | self.task_registry[topic][_id].pop(op_id, None) |
| 595 | elif self.task_registry[topic][_id].get(op_id): |
| 596 | self.task_registry[topic][_id][op_id].pop(task_name, None) |
| 597 | |
| 598 | # delete done tasks |
| 599 | for op_id_ in list(self.task_registry[topic][_id]): |
| 600 | for name, task in self.task_registry[topic][_id][op_id_].items(): |
| 601 | if not task.done(): |
| 602 | break |
| 603 | else: |
| 604 | del self.task_registry[topic][_id][op_id_] |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 605 | if not self.task_registry[topic][_id]: |
| 606 | del self.task_registry[topic][_id] |
| 607 | |
| 608 | def lookfor_related(self, topic, _id, my_op_id=None): |
| 609 | task_list = [] |
| 610 | task_name_list = [] |
| 611 | if _id not in self.task_registry[topic]: |
| 612 | return "", task_name_list |
| 613 | for op_id in reversed(self.task_registry[topic][_id]): |
| 614 | if my_op_id: |
| 615 | if my_op_id == op_id: |
| 616 | my_op_id = None # so that the next task is taken |
| 617 | continue |
| 618 | |
| 619 | for task_name, task in self.task_registry[topic][_id][op_id].items(): |
| tierno | baa5110 | 2018-12-14 13:16:18 +0000 | [diff] [blame] | 620 | if not task.done(): |
| 621 | task_list.append(task) |
| 622 | task_name_list.append(task_name) |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 623 | break |
| 624 | return ", ".join(task_name_list), task_list |
| 625 | |
| 626 | def cancel(self, topic, _id, target_op_id=None, target_task_name=None): |
| 627 | """ |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 628 | Cancel all active tasks of a concrete ns, nsi, vim_account, sdn identified for _id. If op_id is supplied only |
| Felipe Vicens | c2033f2 | 2018-11-15 15:09:58 +0100 | [diff] [blame] | 629 | this is cancelled, and the same with task_name |
| Gabriel Cuba | b6049d3 | 2023-10-30 13:44:49 -0500 | [diff] [blame] | 630 | :return: cancelled task to be awaited if needed |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 631 | """ |
| 632 | if not self.task_registry[topic].get(_id): |
| 633 | return |
| 634 | for op_id in reversed(self.task_registry[topic][_id]): |
| 635 | if target_op_id and target_op_id != op_id: |
| 636 | continue |
| Gabriel Cuba | b6049d3 | 2023-10-30 13:44:49 -0500 | [diff] [blame] | 637 | for task_name, task in list(self.task_registry[topic][_id][op_id].items()): |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 638 | if target_task_name and target_task_name != task_name: |
| 639 | continue |
| 640 | # result = |
| 641 | task.cancel() |
| Gabriel Cuba | b6049d3 | 2023-10-30 13:44:49 -0500 | [diff] [blame] | 642 | yield task |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 643 | # if result: |
| 644 | # self.logger.debug("{} _id={} order_id={} task={} cancelled".format(topic, _id, op_id, task_name)) |
| 645 | |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 646 | # Is topic NS/NSI? |
| 647 | def _is_service_type_HA(self, topic): |
| 648 | return topic in self.topic_service_list |
| 649 | |
| 650 | # Is topic VIM/WIM/SDN? |
| 651 | def _is_account_type_HA(self, topic): |
| 652 | return topic in self.topic_account_list |
| 653 | |
| 654 | # Input: op_id, example: 'abc123def:3' Output: account_id='abc123def', op_index=3 |
| 655 | def _get_account_and_op_HA(self, op_id): |
| 656 | if not op_id: |
| tierno | fa076c3 | 2020-08-13 14:25:47 +0000 | [diff] [blame] | 657 | return None, None |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 658 | account_id, _, op_index = op_id.rpartition(":") |
| tierno | fa076c3 | 2020-08-13 14:25:47 +0000 | [diff] [blame] | 659 | if not account_id or not op_index.isdigit(): |
| 660 | return None, None |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 661 | return account_id, op_index |
| 662 | |
| 663 | # Get '_id' for any topic and operation |
| 664 | def _get_instance_id_HA(self, topic, op_type, op_id): |
| 665 | _id = None |
| 666 | # Special operation 'ANY', for SDN account associated to a VIM account: op_id as '_id' |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 667 | if op_type == "ANY": |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 668 | _id = op_id |
| 669 | # NS/NSI: Use op_id as '_id' |
| 670 | elif self._is_service_type_HA(topic): |
| 671 | _id = op_id |
| calvinosanch | 9f9c6f2 | 2019-11-04 13:37:39 +0100 | [diff] [blame] | 672 | # VIM/SDN/WIM/K8SCLUSTER: Split op_id to get Account ID and Operation Index, use Account ID as '_id' |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 673 | elif self._is_account_type_HA(topic): |
| 674 | _id, _ = self._get_account_and_op_HA(op_id) |
| 675 | return _id |
| 676 | |
| 677 | # Set DB _filter for querying any related process state |
| 678 | def _get_waitfor_filter_HA(self, db_lcmop, topic, op_type, op_id): |
| 679 | _filter = {} |
| 680 | # Special operation 'ANY', for SDN account associated to a VIM account: op_id as '_id' |
| 681 | # In this special case, the timestamp is ignored |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 682 | if op_type == "ANY": |
| 683 | _filter = {"operationState": "PROCESSING"} |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 684 | # Otherwise, get 'startTime' timestamp for this operation |
| 685 | else: |
| 686 | # NS/NSI |
| 687 | if self._is_service_type_HA(topic): |
| tierno | 79cd8ad | 2019-10-18 13:03:10 +0000 | [diff] [blame] | 688 | now = time() |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 689 | starttime_this_op = db_lcmop.get("startTime") |
| 690 | instance_id_label = self.topic2instid_dict.get(topic) |
| 691 | instance_id = db_lcmop.get(instance_id_label) |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 692 | _filter = { |
| 693 | instance_id_label: instance_id, |
| 694 | "operationState": "PROCESSING", |
| 695 | "startTime.lt": starttime_this_op, |
| 696 | "_admin.modified.gt": now |
| 697 | - 2 * 3600, # ignore if tow hours of inactivity |
| 698 | } |
| calvinosanch | 9f9c6f2 | 2019-11-04 13:37:39 +0100 | [diff] [blame] | 699 | # VIM/WIM/SDN/K8scluster |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 700 | elif self._is_account_type_HA(topic): |
| 701 | _, op_index = self._get_account_and_op_HA(op_id) |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 702 | _ops = db_lcmop["_admin"]["operations"] |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 703 | _this_op = _ops[int(op_index)] |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 704 | starttime_this_op = _this_op.get("startTime", None) |
| 705 | _filter = { |
| 706 | "operationState": "PROCESSING", |
| 707 | "startTime.lt": starttime_this_op, |
| 708 | } |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 709 | return _filter |
| 710 | |
| 711 | # Get DB params for any topic and operation |
| 712 | def _get_dbparams_for_lock_HA(self, topic, op_type, op_id): |
| 713 | q_filter = {} |
| 714 | update_dict = {} |
| 715 | # NS/NSI |
| 716 | if self._is_service_type_HA(topic): |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 717 | q_filter = {"_id": op_id, "_admin.worker": None} |
| 718 | update_dict = {"_admin.worker": self.worker_id} |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 719 | # VIM/WIM/SDN |
| 720 | elif self._is_account_type_HA(topic): |
| 721 | account_id, op_index = self._get_account_and_op_HA(op_id) |
| 722 | if not account_id: |
| 723 | return None, None |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 724 | if op_type == "create": |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 725 | # Creating a VIM/WIM/SDN account implies setting '_admin.current_operation' = 0 |
| 726 | op_index = 0 |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 727 | q_filter = { |
| 728 | "_id": account_id, |
| 729 | "_admin.operations.{}.worker".format(op_index): None, |
| 730 | } |
| 731 | update_dict = { |
| 732 | "_admin.operations.{}.worker".format(op_index): self.worker_id, |
| 733 | "_admin.current_operation": op_index, |
| 734 | } |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 735 | return q_filter, update_dict |
| 736 | |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 737 | def lock_HA(self, topic, op_type, op_id): |
| 738 | """ |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 739 | Lock a task, if possible, to indicate to the HA system that |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 740 | the task will be executed in this LCM instance. |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 741 | :param topic: Can be "ns", "nsi", "vim", "wim", or "sdn" |
| 742 | :param op_type: Operation type, can be "nslcmops", "nsilcmops", "create", "edit", "delete" |
| 743 | :param op_id: NS, NSI: Operation ID VIM,WIM,SDN: Account ID + ':' + Operation Index |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 744 | :return: |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 745 | True=lock was successful => execute the task (not registered by any other LCM instance) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 746 | False=lock failed => do NOT execute the task (already registered by another LCM instance) |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 747 | |
| 748 | HA tasks and backward compatibility: |
| 749 | If topic is "account type" (VIM/WIM/SDN) and op_id is None, 'op_id' was not provided by NBI. |
| 750 | This means that the running NBI instance does not support HA. |
| 751 | In such a case this method should always return True, to always execute |
| 752 | the task in this instance of LCM, without querying the DB. |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 753 | """ |
| 754 | |
| calvinosanch | 9f9c6f2 | 2019-11-04 13:37:39 +0100 | [diff] [blame] | 755 | # Backward compatibility for VIM/WIM/SDN/k8scluster without op_id |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 756 | self.logger.info("Lock_HA") |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 757 | if self._is_account_type_HA(topic) and op_id is None: |
| 758 | return True |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 759 | |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 760 | # Try to lock this task |
| tierno | fa076c3 | 2020-08-13 14:25:47 +0000 | [diff] [blame] | 761 | db_table_name = self.topic2dbtable_dict[topic] |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 762 | q_filter, update_dict = self._get_dbparams_for_lock_HA(topic, op_type, op_id) |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 763 | self.logger.info( |
| 764 | "db table name: {} update dict: {}".format(db_table_name, update_dict) |
| 765 | ) |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 766 | db_lock_task = self.db.set_one( |
| 767 | db_table_name, |
| 768 | q_filter=q_filter, |
| 769 | update_dict=update_dict, |
| 770 | fail_on_empty=False, |
| 771 | ) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 772 | if db_lock_task is None: |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 773 | self.logger.debug( |
| 774 | "Task {} operation={} already locked by another worker".format( |
| 775 | topic, op_id |
| 776 | ) |
| 777 | ) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 778 | return False |
| 779 | else: |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 780 | # Set 'detailed-status' to 'In progress' for VIM/WIM/SDN operations |
| 781 | if self._is_account_type_HA(topic): |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 782 | detailed_status = "In progress" |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 783 | account_id, op_index = self._get_account_and_op_HA(op_id) |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 784 | q_filter = {"_id": account_id} |
| 785 | update_dict = { |
| 786 | "_admin.operations.{}.detailed-status".format( |
| 787 | op_index |
| 788 | ): detailed_status |
| 789 | } |
| 790 | self.db.set_one( |
| 791 | db_table_name, |
| 792 | q_filter=q_filter, |
| 793 | update_dict=update_dict, |
| 794 | fail_on_empty=False, |
| 795 | ) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 796 | return True |
| 797 | |
| tierno | fa076c3 | 2020-08-13 14:25:47 +0000 | [diff] [blame] | 798 | def unlock_HA(self, topic, op_type, op_id, operationState, detailed_status): |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 799 | """ |
| 800 | Register a task, done when finished a VIM/WIM/SDN 'create' operation. |
| 801 | :param topic: Can be "vim", "wim", or "sdn" |
| 802 | :param op_type: Operation type, can be "create", "edit", "delete" |
| 803 | :param op_id: Account ID + ':' + Operation Index |
| 804 | :return: nothing |
| 805 | """ |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 806 | self.logger.info("Unlock HA") |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 807 | # Backward compatibility |
| tierno | fa076c3 | 2020-08-13 14:25:47 +0000 | [diff] [blame] | 808 | if not self._is_account_type_HA(topic) or not op_id: |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 809 | return |
| 810 | |
| 811 | # Get Account ID and Operation Index |
| 812 | account_id, op_index = self._get_account_and_op_HA(op_id) |
| tierno | fa076c3 | 2020-08-13 14:25:47 +0000 | [diff] [blame] | 813 | db_table_name = self.topic2dbtable_dict[topic] |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 814 | self.logger.info("db_table_name: {}".format(db_table_name)) |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 815 | # If this is a 'delete' operation, the account may have been deleted (SUCCESS) or may still exist (FAILED) |
| 816 | # If the account exist, register the HA task. |
| 817 | # Update DB for HA tasks |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 818 | q_filter = {"_id": account_id} |
| 819 | update_dict = { |
| 820 | "_admin.operations.{}.operationState".format(op_index): operationState, |
| 821 | "_admin.operations.{}.detailed-status".format(op_index): detailed_status, |
| 822 | "_admin.operations.{}.worker".format(op_index): None, |
| 823 | "_admin.current_operation": None, |
| 824 | } |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 825 | self.logger.info("Update dict: {}".format(update_dict)) |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 826 | self.db.set_one( |
| 827 | db_table_name, |
| 828 | q_filter=q_filter, |
| 829 | update_dict=update_dict, |
| 830 | fail_on_empty=False, |
| 831 | ) |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 832 | return |
| 833 | |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 834 | async def waitfor_related_HA(self, topic, op_type, op_id=None): |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 835 | """ |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 836 | Wait for any pending related HA tasks |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 837 | """ |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 838 | |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 839 | # Backward compatibility |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 840 | if not ( |
| 841 | self._is_service_type_HA(topic) or self._is_account_type_HA(topic) |
| 842 | ) and (op_id is None): |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 843 | return |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 844 | |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 845 | # Get DB table name |
| 846 | db_table_name = self.topic2dbtable_dict.get(topic) |
| 847 | |
| 848 | # Get instance ID |
| 849 | _id = self._get_instance_id_HA(topic, op_type, op_id) |
| 850 | _filter = {"_id": _id} |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 851 | db_lcmop = self.db.get_one(db_table_name, _filter, fail_on_empty=False) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 852 | if not db_lcmop: |
| tierno | 59d22d2 | 2018-09-25 18:10:19 +0200 | [diff] [blame] | 853 | return |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 854 | |
| 855 | # Set DB _filter for querying any related process state |
| 856 | _filter = self._get_waitfor_filter_HA(db_lcmop, topic, op_type, op_id) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 857 | |
| 858 | # For HA, get list of tasks from DB instead of from dictionary (in-memory) variable. |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 859 | timeout_wait_for_task = ( |
| 860 | 3600 # Max time (seconds) to wait for a related task to finish |
| 861 | ) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 862 | # interval_wait_for_task = 30 # A too long polling interval slows things down considerably |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 863 | interval_wait_for_task = 10 # Interval in seconds for polling related tasks |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 864 | time_left = timeout_wait_for_task |
| 865 | old_num_related_tasks = 0 |
| 866 | while True: |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 867 | # Get related tasks (operations within the same instance as this) which are |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 868 | # still running (operationState='PROCESSING') and which were started before this task. |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 869 | # In the case of op_type='ANY', get any related tasks with operationState='PROCESSING', ignore timestamps. |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 870 | db_waitfor_related_task = self.db.get_list(db_table_name, q_filter=_filter) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 871 | new_num_related_tasks = len(db_waitfor_related_task) |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 872 | # If there are no related tasks, there is nothing to wait for, so return. |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 873 | if not new_num_related_tasks: |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 874 | return |
| 875 | # If number of pending related tasks have changed, |
| 876 | # update the 'detailed-status' field and log the change. |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 877 | # Do NOT update the 'detailed-status' for SDNC-associated-to-VIM operations ('ANY'). |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 878 | if (op_type != "ANY") and (new_num_related_tasks != old_num_related_tasks): |
| 879 | step = "Waiting for {} related tasks to be completed.".format( |
| 880 | new_num_related_tasks |
| 881 | ) |
| rshri | 932105f | 2024-07-05 15:11:55 +0000 | [diff] [blame] | 882 | self.logger.info("{}".format(step)) |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 883 | update_dict = {} |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 884 | q_filter = {"_id": _id} |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 885 | # NS/NSI |
| 886 | if self._is_service_type_HA(topic): |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 887 | update_dict = { |
| 888 | "detailed-status": step, |
| 889 | "queuePosition": new_num_related_tasks, |
| 890 | } |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 891 | # VIM/WIM/SDN |
| 892 | elif self._is_account_type_HA(topic): |
| 893 | _, op_index = self._get_account_and_op_HA(op_id) |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 894 | update_dict = { |
| 895 | "_admin.operations.{}.detailed-status".format(op_index): step |
| 896 | } |
| kuuse | 6a470c6 | 2019-07-10 13:52:45 +0200 | [diff] [blame] | 897 | self.logger.debug("Task {} operation={} {}".format(topic, _id, step)) |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 898 | self.db.set_one( |
| 899 | db_table_name, |
| 900 | q_filter=q_filter, |
| 901 | update_dict=update_dict, |
| 902 | fail_on_empty=False, |
| 903 | ) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 904 | old_num_related_tasks = new_num_related_tasks |
| 905 | time_left -= interval_wait_for_task |
| 906 | if time_left < 0: |
| 907 | raise LcmException( |
| 908 | "Timeout ({}) when waiting for related tasks to be completed".format( |
| garciadeblas | 5697b8b | 2021-03-24 09:17:02 +0100 | [diff] [blame] | 909 | timeout_wait_for_task |
| 910 | ) |
| 911 | ) |
| kuuse | d124bfe | 2019-06-18 12:09:24 +0200 | [diff] [blame] | 912 | await asyncio.sleep(interval_wait_for_task) |
| 913 | |
| 914 | return |