blob: 925fd2d5a6235076abb01b65f987e17d74b20d04 [file] [log] [blame]
tierno59d22d22018-09-25 18:10:19 +02001# -*- coding: utf-8 -*-
2
tierno2e215512018-11-28 09:37:52 +00003##
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##
tierno59d22d22018-09-25 18:10:19 +020018
kuused124bfe2019-06-18 12:09:24 +020019import asyncio
aticigdffa6212022-04-12 15:27:53 +030020import checksumdir
tierno59d22d22018-09-25 18:10:19 +020021from collections import OrderedDict
aticig1dda84c2022-09-10 01:56:58 +030022import hashlib
aticigdffa6212022-04-12 15:27:53 +030023import os
aticig9bc63ac2022-07-27 09:32:06 +030024import shutil
25import traceback
tierno79cd8ad2019-10-18 13:03:10 +000026from time import time
aticig9bc63ac2022-07-27 09:32:06 +030027
28from osm_common.fsbase import FsException
bravof922c4172020-11-24 21:21:43 -030029from osm_lcm.data_utils.database.database import Database
30from osm_lcm.data_utils.filesystem.filesystem import Filesystem
aticig9bc63ac2022-07-27 09:32:06 +030031import yaml
32from zipfile import ZipFile, BadZipfile
bravof922c4172020-11-24 21:21:43 -030033
tiernobaa51102018-12-14 13:16:18 +000034# from osm_common.dbbase import DbException
tierno59d22d22018-09-25 18:10:19 +020035
36__author__ = "Alfonso Tierno"
37
38
39class LcmException(Exception):
40 pass
41
42
gcalvinoed7f6d42018-12-14 14:44:56 +010043class LcmExceptionExit(LcmException):
44 pass
45
46
tierno59d22d22018-09-25 18:10:19 +020047def versiontuple(v):
tierno27246d82018-09-27 15:59:09 +020048 """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 """
tierno59d22d22018-09-25 18:10:19 +020052 filled = []
53 for point in v.split("."):
tiernoe64f7fb2019-09-11 08:55:52 +000054 point, _, _ = point.partition("+")
55 point, _, _ = point.partition("-")
56 filled.append(point.zfill(20))
tierno59d22d22018-09-25 18:10:19 +020057 return tuple(filled)
58
59
tierno744303e2020-01-13 16:46:31 +000060def deep_get(target_dict, key_list, default_value=None):
tierno626e0152019-11-29 14:16:16 +000061 """
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
tierno744303e2020-01-13 16:46:31 +000066 :param default_value: value to return if key is not present in the nested dictionary
tierno626e0152019-11-29 14:16:16 +000067 :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:
tierno744303e2020-01-13 16:46:31 +000071 return default_value
tierno626e0152019-11-29 14:16:16 +000072 target_dict = target_dict[key]
73 return target_dict
74
75
tierno744303e2020-01-13 16:46:31 +000076def 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
aticigdffa6212022-04-12 15:27:53 +030088def 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
105def 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(
aticigd7083542022-05-30 20:45:55 +0300124 base_folder["folder"].split(":")[0] + extension,
aticigdffa6212022-04-12 15:27:53 +0300125 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(
aticigd7083542022-05-30 20:45:55 +0300135 base_folder["folder"].split(":")[0] + extension,
aticigdffa6212022-04-12 15:27:53 +0300136 "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
tierno744303e2020-01-13 16:46:31 +0000145def 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 Cubae539a8d2022-10-10 11:34:51 -0500161def 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 Cubac7737442023-02-14 13:09:18 -0500172def 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 Cubaf0af5e62023-03-14 00:27:49 -0500195 "ipv6_address_mode": source_data["ipv6-address-mode"]
196 if "ipv6-address-mode" in source_data
197 else None,
Gabriel Cubac7737442023-02-14 13:09:18 -0500198 }
199
200
kuused124bfe2019-06-18 12:09:24 +0200201class LcmBase:
bravof922c4172020-11-24 21:21:43 -0300202 def __init__(self, msg, logger):
kuused124bfe2019-06-18 12:09:24 +0200203 """
204
205 :param db: database connection
206 """
bravof922c4172020-11-24 21:21:43 -0300207 self.db = Database().instance.db
kuused124bfe2019-06-18 12:09:24 +0200208 self.msg = msg
bravof922c4172020-11-24 21:21:43 -0300209 self.fs = Filesystem().instance.fs
kuused124bfe2019-06-18 12:09:24 +0200210 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 Escaleirada21d262022-04-21 16:31:06 +0100215 :param item: collection
216 :param _id: the _id to use in the query filter
kuused124bfe2019-06-18 12:09:24 +0200217 :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
tierno79cd8ad2019-10-18 13:03:10 +0000222 now = time()
223 _desc["_admin.modified"] = now
rshri932105f2024-07-05 15:11:55 +0000224 self.logger.info("Desc: {} Item: {} _id: {}".format(_desc, item, _id))
kuused124bfe2019-06-18 12:09:24 +0200225 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
rshri932105f2024-07-05 15:11:55 +0000230 def update_operation_history(
231 self, content, workflow_status=None, resource_status=None
232 ):
233 self.logger.info("Update Operation History in LcmBase")
234 self.logger.info(
235 "Content: {} Workflow Status: {} Resource Status: {}".format(
236 content, workflow_status, resource_status
237 )
238 )
239
240 op_id = content["current_operation"]
garciadeblase547e712024-10-22 13:59:45 +0200241 self.logger.debug("OP_id: {}".format(op_id))
242 op_num = 0
garciadeblas96b94f52024-07-08 16:18:21 +0200243 for operation in content["operationHistory"]:
garciadeblase547e712024-10-22 13:59:45 +0200244 self.logger.debug("Operations: {}".format(operation))
garciadeblas96b94f52024-07-08 16:18:21 +0200245 if operation["op_id"] == op_id:
garciadeblase547e712024-10-22 13:59:45 +0200246 self.logger.debug("Found operation number: {}".format(op_num))
rshri932105f2024-07-05 15:11:55 +0000247 now = time()
248 if workflow_status:
garciadeblase547e712024-10-22 13:59:45 +0200249 content["operationHistory"][op_num]["workflowState"] = "COMPLETED"
shahithya56e18db2024-11-07 09:39:07 +0000250 content["operationHistory"][op_num]["result"] = True
rshri932105f2024-07-05 15:11:55 +0000251 else:
garciadeblase547e712024-10-22 13:59:45 +0200252 content["operationHistory"][op_num]["workflowState"] = "ERROR"
shahithya56e18db2024-11-07 09:39:07 +0000253 content["operationHistory"][op_num]["operationState"] = "FAILED"
254 content["operationHistory"][op_num]["result"] = False
rshri932105f2024-07-05 15:11:55 +0000255
256 if resource_status:
garciadeblase547e712024-10-22 13:59:45 +0200257 content["operationHistory"][op_num]["resourceState"] = "READY"
shahithya56e18db2024-11-07 09:39:07 +0000258 content["operationHistory"][op_num]["operationState"] = "COMPLETED"
259 content["operationHistory"][op_num]["result"] = True
rshri932105f2024-07-05 15:11:55 +0000260 else:
garciadeblase547e712024-10-22 13:59:45 +0200261 content["operationHistory"][op_num]["resourceState"] = "NOT_READY"
shahithya56e18db2024-11-07 09:39:07 +0000262 content["operationHistory"][op_num]["operationState"] = "FAILED"
263 content["operationHistory"][op_num]["result"] = False
rshri932105f2024-07-05 15:11:55 +0000264
garciadeblase547e712024-10-22 13:59:45 +0200265 content["operationHistory"][op_num]["endDate"] = now
rshri932105f2024-07-05 15:11:55 +0000266 break
garciadeblase547e712024-10-22 13:59:45 +0200267 op_num += 1
268 self.logger.debug("content: {}".format(content))
rshri932105f2024-07-05 15:11:55 +0000269
270 return content
271
aticig1dda84c2022-09-10 01:56:58 +0300272 @staticmethod
273 def calculate_charm_hash(zipped_file):
274 """Calculate the hash of charm files which ends with .charm
275
276 Args:
277 zipped_file (str): Existing charm package full path
278
279 Returns:
280 hex digest (str): The hash of the charm file
281 """
Gabriel Cuba4c0e6802023-10-09 13:22:38 -0500282 filehash = hashlib.sha256()
aticig1dda84c2022-09-10 01:56:58 +0300283 with open(zipped_file, mode="rb") as file:
284 contents = file.read()
285 filehash.update(contents)
286 return filehash.hexdigest()
287
288 @staticmethod
289 def compare_charm_hash(current_charm, target_charm):
290 """Compare the existing charm and the target charm if the charms
291 are given as zip files ends with .charm
292
293 Args:
294 current_charm (str): Existing charm package full path
295 target_charm (str): Target charm package full path
296
297 Returns:
298 True/False (bool): if charm has changed it returns True
299 """
300 return LcmBase.calculate_charm_hash(
301 current_charm
302 ) != LcmBase.calculate_charm_hash(target_charm)
303
304 @staticmethod
305 def compare_charmdir_hash(current_charm_dir, target_charm_dir):
306 """Compare the existing charm and the target charm if the charms
307 are given as directories
308
309 Args:
310 current_charm_dir (str): Existing charm package directory path
311 target_charm_dir (str): Target charm package directory path
312
313 Returns:
314 True/False (bool): if charm has changed it returns True
315 """
316 return checksumdir.dirhash(current_charm_dir) != checksumdir.dirhash(
317 target_charm_dir
318 )
319
aticigdffa6212022-04-12 15:27:53 +0300320 def check_charm_hash_changed(
321 self, current_charm_path: str, target_charm_path: str
322 ) -> bool:
323 """Find the target charm has changed or not by checking the hash of
324 old and new charm packages
325
326 Args:
327 current_charm_path (str): Existing charm package artifact path
328 target_charm_path (str): Target charm package artifact path
329
330 Returns:
331 True/False (bool): if charm has changed it returns True
332
333 """
aticig1dda84c2022-09-10 01:56:58 +0300334 try:
335 # Check if the charm artifacts are available
336 current_charm = self.fs.path + current_charm_path
337 target_charm = self.fs.path + target_charm_path
aticigdffa6212022-04-12 15:27:53 +0300338
aticig1dda84c2022-09-10 01:56:58 +0300339 if os.path.exists(current_charm) and os.path.exists(target_charm):
aticig1dda84c2022-09-10 01:56:58 +0300340 # Compare the hash of .charm files
341 if current_charm.endswith(".charm"):
342 return LcmBase.compare_charm_hash(current_charm, target_charm)
aticigdffa6212022-04-12 15:27:53 +0300343
aticig1dda84c2022-09-10 01:56:58 +0300344 # Compare the hash of charm folders
345 return LcmBase.compare_charmdir_hash(current_charm, target_charm)
346
347 else:
348 raise LcmException(
349 "Charm artifact {} does not exist in the VNF Package".format(
350 self.fs.path + target_charm_path
351 )
aticigdffa6212022-04-12 15:27:53 +0300352 )
aticig1dda84c2022-09-10 01:56:58 +0300353 except (IOError, OSError, TypeError) as error:
354 self.logger.debug(traceback.format_exc())
355 self.logger.error(f"{error} occured while checking the charm hashes")
356 raise LcmException(error)
aticigdffa6212022-04-12 15:27:53 +0300357
aticig9bc63ac2022-07-27 09:32:06 +0300358 @staticmethod
359 def get_charm_name(charm_metadata_file: str) -> str:
360 """Get the charm name from metadata file.
361
362 Args:
363 charm_metadata_file (str): charm metadata file full path
364
365 Returns:
366 charm_name (str): charm name
367
368 """
369 # Read charm metadata.yaml to get the charm name
370 with open(charm_metadata_file, "r") as metadata_file:
371 content = yaml.safe_load(metadata_file)
372 charm_name = content["name"]
373 return str(charm_name)
374
375 def _get_charm_path(
376 self, nsd_package_path: str, nsd_package_name: str, charm_folder_name: str
377 ) -> str:
378 """Get the full path of charm folder.
379
380 Args:
381 nsd_package_path (str): NSD package full path
382 nsd_package_name (str): NSD package name
383 charm_folder_name (str): folder name
384
385 Returns:
386 charm_path (str): charm folder full path
387 """
388 charm_path = (
389 self.fs.path
390 + nsd_package_path
391 + "/"
392 + nsd_package_name
393 + "/charms/"
394 + charm_folder_name
395 )
396 return charm_path
397
398 def _get_charm_metadata_file(
399 self,
400 charm_folder_name: str,
401 nsd_package_path: str,
402 nsd_package_name: str,
403 charm_path: str = None,
404 ) -> str:
405 """Get the path of charm metadata file.
406
407 Args:
408 charm_folder_name (str): folder name
409 nsd_package_path (str): NSD package full path
410 nsd_package_name (str): NSD package name
411 charm_path (str): Charm full path
412
413 Returns:
414 charm_metadata_file_path (str): charm metadata file full path
415
416 """
417 # Locate the charm metadata.yaml
418 if charm_folder_name.endswith(".charm"):
419 extract_path = (
420 self.fs.path
421 + nsd_package_path
422 + "/"
423 + nsd_package_name
424 + "/charms/"
aticiga37c6ff2022-08-20 20:56:19 +0300425 + charm_folder_name.replace(".charm", "")
aticig9bc63ac2022-07-27 09:32:06 +0300426 )
427 # Extract .charm to extract path
428 with ZipFile(charm_path, "r") as zipfile:
429 zipfile.extractall(extract_path)
430 return extract_path + "/metadata.yaml"
431 else:
432 return charm_path + "/metadata.yaml"
433
434 def find_charm_name(self, db_nsr: dict, charm_folder_name: str) -> str:
435 """Get the charm name from metadata.yaml of charm package.
436
437 Args:
438 db_nsr (dict): NS record as a dictionary
439 charm_folder_name (str): charm folder name
440
441 Returns:
442 charm_name (str): charm name
443 """
444 try:
445 if not charm_folder_name:
446 raise LcmException("charm_folder_name should be provided.")
447
448 # Find nsd_package details: path, name
449 revision = db_nsr.get("revision", "")
aticiga37c6ff2022-08-20 20:56:19 +0300450
451 # Get the NSD package path
452 if revision:
preethika.p28b0bf82022-09-23 07:36:28 +0000453 nsd_package_path = db_nsr["nsd-id"] + ":" + str(revision)
aticiga37c6ff2022-08-20 20:56:19 +0300454 db_nsd = self.db.get_one("nsds_revisions", {"_id": nsd_package_path})
455
456 else:
457 nsd_package_path = db_nsr["nsd-id"]
458
459 db_nsd = self.db.get_one("nsds", {"_id": nsd_package_path})
460
461 # Get the NSD package name
462 nsd_package_name = db_nsd["_admin"]["storage"]["pkg-dir"]
aticig9bc63ac2022-07-27 09:32:06 +0300463
464 # Remove the existing nsd package and sync from FsMongo
465 shutil.rmtree(self.fs.path + nsd_package_path, ignore_errors=True)
466 self.fs.sync(from_path=nsd_package_path)
467
468 # Get the charm path
469 charm_path = self._get_charm_path(
470 nsd_package_path, nsd_package_name, charm_folder_name
471 )
472
473 # Find charm metadata file full path
474 charm_metadata_file = self._get_charm_metadata_file(
475 charm_folder_name, nsd_package_path, nsd_package_name, charm_path
476 )
477
478 # Return charm name
479 return self.get_charm_name(charm_metadata_file)
480
481 except (
482 yaml.YAMLError,
483 IOError,
484 FsException,
485 KeyError,
486 TypeError,
487 FileNotFoundError,
488 BadZipfile,
489 ) as error:
490 self.logger.debug(traceback.format_exc())
491 self.logger.error(f"{error} occured while getting the charm name")
492 raise LcmException(error)
493
Gabriel Cuba879483e2024-03-19 18:01:13 -0500494 def get_vca_info(self, ee_item, db_nsr, get_charm_name: bool):
495 vca_name = charm_name = vca_type = None
496 if ee_item.get("juju"):
497 vca_name = ee_item["juju"].get("charm")
498 if get_charm_name:
499 charm_name = self.find_charm_name(db_nsr, str(vca_name))
500 vca_type = (
501 "lxc_proxy_charm"
502 if ee_item["juju"].get("charm") is not None
503 else "native_charm"
504 )
505 if ee_item["juju"].get("cloud") == "k8s":
506 vca_type = "k8s_proxy_charm"
507 elif ee_item["juju"].get("proxy") is False:
508 vca_type = "native_charm"
509 elif ee_item.get("helm-chart"):
510 vca_name = ee_item["helm-chart"]
511 vca_type = "helm-v3"
512 return vca_name, charm_name, vca_type
513
kuused124bfe2019-06-18 12:09:24 +0200514
515class TaskRegistry(LcmBase):
tierno59d22d22018-09-25 18:10:19 +0200516 """
517 Implements a registry of task needed for later cancelation, look for related tasks that must be completed before
518 etc. It stores a four level dict
519 First level is the topic, ns, vim_account, sdn
520 Second level is the _id
521 Third level is the operation id
522 Fourth level is a descriptive name, the value is the task class
kuused124bfe2019-06-18 12:09:24 +0200523
524 The HA (High-Availability) methods are used when more than one LCM instance is running.
525 To register the current task in the external DB, use LcmBase as base class, to be able
526 to reuse LcmBase.update_db_2()
527 The DB registry uses the following fields to distinguish a task:
528 - op_type: operation type ("nslcmops" or "nsilcmops")
529 - op_id: operation ID
530 - worker: the worker ID for this process
tierno59d22d22018-09-25 18:10:19 +0200531 """
532
kuuse6a470c62019-07-10 13:52:45 +0200533 # NS/NSI: "services" VIM/WIM/SDN: "accounts"
garciadeblas5697b8b2021-03-24 09:17:02 +0100534 topic_service_list = ["ns", "nsi"]
rshri932105f2024-07-05 15:11:55 +0000535 topic_account_list = [
536 "vim",
537 "wim",
538 "sdn",
539 "k8scluster",
540 "vca",
541 "k8srepo",
542 "cluster",
543 "k8s_app",
544 "k8s_resource",
545 "k8s_infra_controller",
546 "k8s_infra_config",
yshah771dea82024-07-05 15:11:49 +0000547 "oka",
548 "ksu",
rshri932105f2024-07-05 15:11:55 +0000549 ]
kuuse6a470c62019-07-10 13:52:45 +0200550
551 # Map topic to InstanceID
garciadeblas5697b8b2021-03-24 09:17:02 +0100552 topic2instid_dict = {"ns": "nsInstanceId", "nsi": "netsliceInstanceId"}
kuuse6a470c62019-07-10 13:52:45 +0200553
554 # Map topic to DB table name
555 topic2dbtable_dict = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100556 "ns": "nslcmops",
557 "nsi": "nsilcmops",
558 "vim": "vim_accounts",
559 "wim": "wim_accounts",
560 "sdn": "sdns",
561 "k8scluster": "k8sclusters",
562 "vca": "vca",
563 "k8srepo": "k8srepos",
rshri932105f2024-07-05 15:11:55 +0000564 "cluster": "k8sclusters",
565 "k8s_app": "k8sapp",
566 "k8s_resource": "k8sresource",
567 "k8s_infra_controller": "k8sinfra_controller",
568 "k8s_infra_config": "k8sinfra_config",
yshah771dea82024-07-05 15:11:49 +0000569 "oka": "oka",
570 "ksu": "ksus",
garciadeblas5697b8b2021-03-24 09:17:02 +0100571 }
kuused124bfe2019-06-18 12:09:24 +0200572
bravof922c4172020-11-24 21:21:43 -0300573 def __init__(self, worker_id=None, logger=None):
tierno59d22d22018-09-25 18:10:19 +0200574 self.task_registry = {
575 "ns": {},
Felipe Vicensc2033f22018-11-15 15:09:58 +0100576 "nsi": {},
tierno59d22d22018-09-25 18:10:19 +0200577 "vim_account": {},
tiernoe37b57d2018-12-11 17:22:51 +0000578 "wim_account": {},
tierno59d22d22018-09-25 18:10:19 +0200579 "sdn": {},
calvinosanch9f9c6f22019-11-04 13:37:39 +0100580 "k8scluster": {},
David Garciac1fe90a2021-03-31 19:12:02 +0200581 "vca": {},
calvinosanch9f9c6f22019-11-04 13:37:39 +0100582 "k8srepo": {},
rshri932105f2024-07-05 15:11:55 +0000583 "cluster": {},
584 "k8s_app": {},
585 "k8s_resource": {},
586 "k8s_infra_controller": {},
587 "k8s_infra_config": {},
yshah771dea82024-07-05 15:11:49 +0000588 "oka": {},
589 "ksu": {},
rshri932105f2024-07-05 15:11:55 +0000590 "odu": {},
tierno59d22d22018-09-25 18:10:19 +0200591 }
kuused124bfe2019-06-18 12:09:24 +0200592 self.worker_id = worker_id
bravof922c4172020-11-24 21:21:43 -0300593 self.db = Database().instance.db
kuused124bfe2019-06-18 12:09:24 +0200594 self.logger = logger
rshri932105f2024-07-05 15:11:55 +0000595 # self.logger.info("Task registry: {}".format(self.task_registry))
tierno59d22d22018-09-25 18:10:19 +0200596
597 def register(self, topic, _id, op_id, task_name, task):
598 """
599 Register a new task
Felipe Vicensc2033f22018-11-15 15:09:58 +0100600 :param topic: Can be "ns", "nsi", "vim_account", "sdn"
tierno59d22d22018-09-25 18:10:19 +0200601 :param _id: _id of the related item
602 :param op_id: id of the operation of the related item
603 :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id
604 :param task: Task class
605 :return: none
606 """
rshri932105f2024-07-05 15:11:55 +0000607 self.logger.info(
608 "topic : {}, _id:{}, op_id:{}, taskname:{}, task:{}".format(
609 topic, _id, op_id, task_name, task
610 )
611 )
tierno59d22d22018-09-25 18:10:19 +0200612 if _id not in self.task_registry[topic]:
613 self.task_registry[topic][_id] = OrderedDict()
614 if op_id not in self.task_registry[topic][_id]:
615 self.task_registry[topic][_id][op_id] = {task_name: task}
616 else:
617 self.task_registry[topic][_id][op_id][task_name] = task
rshri932105f2024-07-05 15:11:55 +0000618 self.logger.info("Task resgistry: {}".format(self.task_registry))
tierno59d22d22018-09-25 18:10:19 +0200619 # print("registering task", topic, _id, op_id, task_name, task)
620
621 def remove(self, topic, _id, op_id, task_name=None):
622 """
tiernobaa51102018-12-14 13:16:18 +0000623 When task is ended, it should be removed. It ignores missing tasks. It also removes tasks done with this _id
Felipe Vicensc2033f22018-11-15 15:09:58 +0100624 :param topic: Can be "ns", "nsi", "vim_account", "sdn"
tierno59d22d22018-09-25 18:10:19 +0200625 :param _id: _id of the related item
626 :param op_id: id of the operation of the related item
tiernobaa51102018-12-14 13:16:18 +0000627 :param task_name: Task descriptive name. If none it deletes all tasks with same _id and op_id
628 :return: None
tierno59d22d22018-09-25 18:10:19 +0200629 """
tiernobaa51102018-12-14 13:16:18 +0000630 if not self.task_registry[topic].get(_id):
tierno59d22d22018-09-25 18:10:19 +0200631 return
632 if not task_name:
tiernobaa51102018-12-14 13:16:18 +0000633 self.task_registry[topic][_id].pop(op_id, None)
634 elif self.task_registry[topic][_id].get(op_id):
635 self.task_registry[topic][_id][op_id].pop(task_name, None)
636
637 # delete done tasks
638 for op_id_ in list(self.task_registry[topic][_id]):
639 for name, task in self.task_registry[topic][_id][op_id_].items():
640 if not task.done():
641 break
642 else:
643 del self.task_registry[topic][_id][op_id_]
tierno59d22d22018-09-25 18:10:19 +0200644 if not self.task_registry[topic][_id]:
645 del self.task_registry[topic][_id]
646
647 def lookfor_related(self, topic, _id, my_op_id=None):
648 task_list = []
649 task_name_list = []
650 if _id not in self.task_registry[topic]:
651 return "", task_name_list
652 for op_id in reversed(self.task_registry[topic][_id]):
653 if my_op_id:
654 if my_op_id == op_id:
655 my_op_id = None # so that the next task is taken
656 continue
657
658 for task_name, task in self.task_registry[topic][_id][op_id].items():
tiernobaa51102018-12-14 13:16:18 +0000659 if not task.done():
660 task_list.append(task)
661 task_name_list.append(task_name)
tierno59d22d22018-09-25 18:10:19 +0200662 break
663 return ", ".join(task_name_list), task_list
664
665 def cancel(self, topic, _id, target_op_id=None, target_task_name=None):
666 """
kuused124bfe2019-06-18 12:09:24 +0200667 Cancel all active tasks of a concrete ns, nsi, vim_account, sdn identified for _id. If op_id is supplied only
Felipe Vicensc2033f22018-11-15 15:09:58 +0100668 this is cancelled, and the same with task_name
Gabriel Cubab6049d32023-10-30 13:44:49 -0500669 :return: cancelled task to be awaited if needed
tierno59d22d22018-09-25 18:10:19 +0200670 """
671 if not self.task_registry[topic].get(_id):
672 return
673 for op_id in reversed(self.task_registry[topic][_id]):
674 if target_op_id and target_op_id != op_id:
675 continue
Gabriel Cubab6049d32023-10-30 13:44:49 -0500676 for task_name, task in list(self.task_registry[topic][_id][op_id].items()):
tierno59d22d22018-09-25 18:10:19 +0200677 if target_task_name and target_task_name != task_name:
678 continue
679 # result =
680 task.cancel()
Gabriel Cubab6049d32023-10-30 13:44:49 -0500681 yield task
tierno59d22d22018-09-25 18:10:19 +0200682 # if result:
683 # self.logger.debug("{} _id={} order_id={} task={} cancelled".format(topic, _id, op_id, task_name))
684
kuuse6a470c62019-07-10 13:52:45 +0200685 # Is topic NS/NSI?
686 def _is_service_type_HA(self, topic):
687 return topic in self.topic_service_list
688
689 # Is topic VIM/WIM/SDN?
690 def _is_account_type_HA(self, topic):
691 return topic in self.topic_account_list
692
693 # Input: op_id, example: 'abc123def:3' Output: account_id='abc123def', op_index=3
694 def _get_account_and_op_HA(self, op_id):
695 if not op_id:
tiernofa076c32020-08-13 14:25:47 +0000696 return None, None
garciadeblas5697b8b2021-03-24 09:17:02 +0100697 account_id, _, op_index = op_id.rpartition(":")
tiernofa076c32020-08-13 14:25:47 +0000698 if not account_id or not op_index.isdigit():
699 return None, None
kuuse6a470c62019-07-10 13:52:45 +0200700 return account_id, op_index
701
702 # Get '_id' for any topic and operation
703 def _get_instance_id_HA(self, topic, op_type, op_id):
704 _id = None
705 # Special operation 'ANY', for SDN account associated to a VIM account: op_id as '_id'
garciadeblas5697b8b2021-03-24 09:17:02 +0100706 if op_type == "ANY":
kuuse6a470c62019-07-10 13:52:45 +0200707 _id = op_id
708 # NS/NSI: Use op_id as '_id'
709 elif self._is_service_type_HA(topic):
710 _id = op_id
calvinosanch9f9c6f22019-11-04 13:37:39 +0100711 # VIM/SDN/WIM/K8SCLUSTER: Split op_id to get Account ID and Operation Index, use Account ID as '_id'
kuuse6a470c62019-07-10 13:52:45 +0200712 elif self._is_account_type_HA(topic):
713 _id, _ = self._get_account_and_op_HA(op_id)
714 return _id
715
716 # Set DB _filter for querying any related process state
717 def _get_waitfor_filter_HA(self, db_lcmop, topic, op_type, op_id):
718 _filter = {}
719 # Special operation 'ANY', for SDN account associated to a VIM account: op_id as '_id'
720 # In this special case, the timestamp is ignored
garciadeblas5697b8b2021-03-24 09:17:02 +0100721 if op_type == "ANY":
722 _filter = {"operationState": "PROCESSING"}
kuuse6a470c62019-07-10 13:52:45 +0200723 # Otherwise, get 'startTime' timestamp for this operation
724 else:
725 # NS/NSI
726 if self._is_service_type_HA(topic):
tierno79cd8ad2019-10-18 13:03:10 +0000727 now = time()
kuuse6a470c62019-07-10 13:52:45 +0200728 starttime_this_op = db_lcmop.get("startTime")
729 instance_id_label = self.topic2instid_dict.get(topic)
730 instance_id = db_lcmop.get(instance_id_label)
garciadeblas5697b8b2021-03-24 09:17:02 +0100731 _filter = {
732 instance_id_label: instance_id,
733 "operationState": "PROCESSING",
734 "startTime.lt": starttime_this_op,
735 "_admin.modified.gt": now
736 - 2 * 3600, # ignore if tow hours of inactivity
737 }
calvinosanch9f9c6f22019-11-04 13:37:39 +0100738 # VIM/WIM/SDN/K8scluster
kuuse6a470c62019-07-10 13:52:45 +0200739 elif self._is_account_type_HA(topic):
740 _, op_index = self._get_account_and_op_HA(op_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100741 _ops = db_lcmop["_admin"]["operations"]
kuuse6a470c62019-07-10 13:52:45 +0200742 _this_op = _ops[int(op_index)]
garciadeblas5697b8b2021-03-24 09:17:02 +0100743 starttime_this_op = _this_op.get("startTime", None)
744 _filter = {
745 "operationState": "PROCESSING",
746 "startTime.lt": starttime_this_op,
747 }
kuuse6a470c62019-07-10 13:52:45 +0200748 return _filter
749
750 # Get DB params for any topic and operation
751 def _get_dbparams_for_lock_HA(self, topic, op_type, op_id):
752 q_filter = {}
753 update_dict = {}
754 # NS/NSI
755 if self._is_service_type_HA(topic):
garciadeblas5697b8b2021-03-24 09:17:02 +0100756 q_filter = {"_id": op_id, "_admin.worker": None}
757 update_dict = {"_admin.worker": self.worker_id}
kuuse6a470c62019-07-10 13:52:45 +0200758 # VIM/WIM/SDN
759 elif self._is_account_type_HA(topic):
760 account_id, op_index = self._get_account_and_op_HA(op_id)
761 if not account_id:
762 return None, None
garciadeblas5697b8b2021-03-24 09:17:02 +0100763 if op_type == "create":
kuuse6a470c62019-07-10 13:52:45 +0200764 # Creating a VIM/WIM/SDN account implies setting '_admin.current_operation' = 0
765 op_index = 0
garciadeblas5697b8b2021-03-24 09:17:02 +0100766 q_filter = {
767 "_id": account_id,
768 "_admin.operations.{}.worker".format(op_index): None,
769 }
770 update_dict = {
771 "_admin.operations.{}.worker".format(op_index): self.worker_id,
772 "_admin.current_operation": op_index,
773 }
kuuse6a470c62019-07-10 13:52:45 +0200774 return q_filter, update_dict
775
kuused124bfe2019-06-18 12:09:24 +0200776 def lock_HA(self, topic, op_type, op_id):
777 """
kuuse6a470c62019-07-10 13:52:45 +0200778 Lock a task, if possible, to indicate to the HA system that
kuused124bfe2019-06-18 12:09:24 +0200779 the task will be executed in this LCM instance.
kuuse6a470c62019-07-10 13:52:45 +0200780 :param topic: Can be "ns", "nsi", "vim", "wim", or "sdn"
781 :param op_type: Operation type, can be "nslcmops", "nsilcmops", "create", "edit", "delete"
782 :param op_id: NS, NSI: Operation ID VIM,WIM,SDN: Account ID + ':' + Operation Index
kuused124bfe2019-06-18 12:09:24 +0200783 :return:
kuuse6a470c62019-07-10 13:52:45 +0200784 True=lock was successful => execute the task (not registered by any other LCM instance)
kuused124bfe2019-06-18 12:09:24 +0200785 False=lock failed => do NOT execute the task (already registered by another LCM instance)
kuuse6a470c62019-07-10 13:52:45 +0200786
787 HA tasks and backward compatibility:
788 If topic is "account type" (VIM/WIM/SDN) and op_id is None, 'op_id' was not provided by NBI.
789 This means that the running NBI instance does not support HA.
790 In such a case this method should always return True, to always execute
791 the task in this instance of LCM, without querying the DB.
tierno59d22d22018-09-25 18:10:19 +0200792 """
793
calvinosanch9f9c6f22019-11-04 13:37:39 +0100794 # Backward compatibility for VIM/WIM/SDN/k8scluster without op_id
rshri932105f2024-07-05 15:11:55 +0000795 self.logger.info("Lock_HA")
kuuse6a470c62019-07-10 13:52:45 +0200796 if self._is_account_type_HA(topic) and op_id is None:
797 return True
tierno59d22d22018-09-25 18:10:19 +0200798
kuuse6a470c62019-07-10 13:52:45 +0200799 # Try to lock this task
tiernofa076c32020-08-13 14:25:47 +0000800 db_table_name = self.topic2dbtable_dict[topic]
kuuse6a470c62019-07-10 13:52:45 +0200801 q_filter, update_dict = self._get_dbparams_for_lock_HA(topic, op_type, op_id)
rshri932105f2024-07-05 15:11:55 +0000802 self.logger.info(
803 "db table name: {} update dict: {}".format(db_table_name, update_dict)
804 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100805 db_lock_task = self.db.set_one(
806 db_table_name,
807 q_filter=q_filter,
808 update_dict=update_dict,
809 fail_on_empty=False,
810 )
kuused124bfe2019-06-18 12:09:24 +0200811 if db_lock_task is None:
garciadeblas5697b8b2021-03-24 09:17:02 +0100812 self.logger.debug(
813 "Task {} operation={} already locked by another worker".format(
814 topic, op_id
815 )
816 )
kuused124bfe2019-06-18 12:09:24 +0200817 return False
818 else:
kuuse6a470c62019-07-10 13:52:45 +0200819 # Set 'detailed-status' to 'In progress' for VIM/WIM/SDN operations
820 if self._is_account_type_HA(topic):
garciadeblas5697b8b2021-03-24 09:17:02 +0100821 detailed_status = "In progress"
kuuse6a470c62019-07-10 13:52:45 +0200822 account_id, op_index = self._get_account_and_op_HA(op_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100823 q_filter = {"_id": account_id}
824 update_dict = {
825 "_admin.operations.{}.detailed-status".format(
826 op_index
827 ): detailed_status
828 }
829 self.db.set_one(
830 db_table_name,
831 q_filter=q_filter,
832 update_dict=update_dict,
833 fail_on_empty=False,
834 )
kuused124bfe2019-06-18 12:09:24 +0200835 return True
836
tiernofa076c32020-08-13 14:25:47 +0000837 def unlock_HA(self, topic, op_type, op_id, operationState, detailed_status):
kuuse6a470c62019-07-10 13:52:45 +0200838 """
839 Register a task, done when finished a VIM/WIM/SDN 'create' operation.
840 :param topic: Can be "vim", "wim", or "sdn"
841 :param op_type: Operation type, can be "create", "edit", "delete"
842 :param op_id: Account ID + ':' + Operation Index
843 :return: nothing
844 """
rshri932105f2024-07-05 15:11:55 +0000845 self.logger.info("Unlock HA")
kuuse6a470c62019-07-10 13:52:45 +0200846 # Backward compatibility
tiernofa076c32020-08-13 14:25:47 +0000847 if not self._is_account_type_HA(topic) or not op_id:
kuuse6a470c62019-07-10 13:52:45 +0200848 return
849
850 # Get Account ID and Operation Index
851 account_id, op_index = self._get_account_and_op_HA(op_id)
tiernofa076c32020-08-13 14:25:47 +0000852 db_table_name = self.topic2dbtable_dict[topic]
rshri932105f2024-07-05 15:11:55 +0000853 self.logger.info("db_table_name: {}".format(db_table_name))
kuuse6a470c62019-07-10 13:52:45 +0200854 # If this is a 'delete' operation, the account may have been deleted (SUCCESS) or may still exist (FAILED)
855 # If the account exist, register the HA task.
856 # Update DB for HA tasks
garciadeblas5697b8b2021-03-24 09:17:02 +0100857 q_filter = {"_id": account_id}
858 update_dict = {
859 "_admin.operations.{}.operationState".format(op_index): operationState,
860 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
861 "_admin.operations.{}.worker".format(op_index): None,
862 "_admin.current_operation": None,
863 }
rshri932105f2024-07-05 15:11:55 +0000864 self.logger.info("Update dict: {}".format(update_dict))
garciadeblas5697b8b2021-03-24 09:17:02 +0100865 self.db.set_one(
866 db_table_name,
867 q_filter=q_filter,
868 update_dict=update_dict,
869 fail_on_empty=False,
870 )
kuuse6a470c62019-07-10 13:52:45 +0200871 return
872
kuused124bfe2019-06-18 12:09:24 +0200873 async def waitfor_related_HA(self, topic, op_type, op_id=None):
tierno59d22d22018-09-25 18:10:19 +0200874 """
kuused124bfe2019-06-18 12:09:24 +0200875 Wait for any pending related HA tasks
tierno59d22d22018-09-25 18:10:19 +0200876 """
kuused124bfe2019-06-18 12:09:24 +0200877
kuuse6a470c62019-07-10 13:52:45 +0200878 # Backward compatibility
garciadeblas5697b8b2021-03-24 09:17:02 +0100879 if not (
880 self._is_service_type_HA(topic) or self._is_account_type_HA(topic)
881 ) and (op_id is None):
kuuse6a470c62019-07-10 13:52:45 +0200882 return
kuused124bfe2019-06-18 12:09:24 +0200883
kuuse6a470c62019-07-10 13:52:45 +0200884 # Get DB table name
885 db_table_name = self.topic2dbtable_dict.get(topic)
886
887 # Get instance ID
888 _id = self._get_instance_id_HA(topic, op_type, op_id)
889 _filter = {"_id": _id}
garciadeblas5697b8b2021-03-24 09:17:02 +0100890 db_lcmop = self.db.get_one(db_table_name, _filter, fail_on_empty=False)
kuused124bfe2019-06-18 12:09:24 +0200891 if not db_lcmop:
tierno59d22d22018-09-25 18:10:19 +0200892 return
kuuse6a470c62019-07-10 13:52:45 +0200893
894 # Set DB _filter for querying any related process state
895 _filter = self._get_waitfor_filter_HA(db_lcmop, topic, op_type, op_id)
kuused124bfe2019-06-18 12:09:24 +0200896
897 # For HA, get list of tasks from DB instead of from dictionary (in-memory) variable.
garciadeblas5697b8b2021-03-24 09:17:02 +0100898 timeout_wait_for_task = (
899 3600 # Max time (seconds) to wait for a related task to finish
900 )
kuused124bfe2019-06-18 12:09:24 +0200901 # interval_wait_for_task = 30 # A too long polling interval slows things down considerably
garciadeblas5697b8b2021-03-24 09:17:02 +0100902 interval_wait_for_task = 10 # Interval in seconds for polling related tasks
kuused124bfe2019-06-18 12:09:24 +0200903 time_left = timeout_wait_for_task
904 old_num_related_tasks = 0
905 while True:
kuuse6a470c62019-07-10 13:52:45 +0200906 # Get related tasks (operations within the same instance as this) which are
kuused124bfe2019-06-18 12:09:24 +0200907 # still running (operationState='PROCESSING') and which were started before this task.
kuuse6a470c62019-07-10 13:52:45 +0200908 # In the case of op_type='ANY', get any related tasks with operationState='PROCESSING', ignore timestamps.
garciadeblas5697b8b2021-03-24 09:17:02 +0100909 db_waitfor_related_task = self.db.get_list(db_table_name, q_filter=_filter)
kuused124bfe2019-06-18 12:09:24 +0200910 new_num_related_tasks = len(db_waitfor_related_task)
kuuse6a470c62019-07-10 13:52:45 +0200911 # If there are no related tasks, there is nothing to wait for, so return.
kuused124bfe2019-06-18 12:09:24 +0200912 if not new_num_related_tasks:
kuused124bfe2019-06-18 12:09:24 +0200913 return
914 # If number of pending related tasks have changed,
915 # update the 'detailed-status' field and log the change.
kuuse6a470c62019-07-10 13:52:45 +0200916 # Do NOT update the 'detailed-status' for SDNC-associated-to-VIM operations ('ANY').
garciadeblas5697b8b2021-03-24 09:17:02 +0100917 if (op_type != "ANY") and (new_num_related_tasks != old_num_related_tasks):
918 step = "Waiting for {} related tasks to be completed.".format(
919 new_num_related_tasks
920 )
rshri932105f2024-07-05 15:11:55 +0000921 self.logger.info("{}".format(step))
kuuse6a470c62019-07-10 13:52:45 +0200922 update_dict = {}
garciadeblas5697b8b2021-03-24 09:17:02 +0100923 q_filter = {"_id": _id}
kuuse6a470c62019-07-10 13:52:45 +0200924 # NS/NSI
925 if self._is_service_type_HA(topic):
garciadeblas5697b8b2021-03-24 09:17:02 +0100926 update_dict = {
927 "detailed-status": step,
928 "queuePosition": new_num_related_tasks,
929 }
kuuse6a470c62019-07-10 13:52:45 +0200930 # VIM/WIM/SDN
931 elif self._is_account_type_HA(topic):
932 _, op_index = self._get_account_and_op_HA(op_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100933 update_dict = {
934 "_admin.operations.{}.detailed-status".format(op_index): step
935 }
kuuse6a470c62019-07-10 13:52:45 +0200936 self.logger.debug("Task {} operation={} {}".format(topic, _id, step))
garciadeblas5697b8b2021-03-24 09:17:02 +0100937 self.db.set_one(
938 db_table_name,
939 q_filter=q_filter,
940 update_dict=update_dict,
941 fail_on_empty=False,
942 )
kuused124bfe2019-06-18 12:09:24 +0200943 old_num_related_tasks = new_num_related_tasks
944 time_left -= interval_wait_for_task
945 if time_left < 0:
946 raise LcmException(
947 "Timeout ({}) when waiting for related tasks to be completed".format(
garciadeblas5697b8b2021-03-24 09:17:02 +0100948 timeout_wait_for_task
949 )
950 )
kuused124bfe2019-06-18 12:09:24 +0200951 await asyncio.sleep(interval_wait_for_task)
952
953 return