blob: d91eaed76813aca3bfcc993ebe5a12f0bf7da89b [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
tiernof578e552018-11-08 19:07:20 +010043class LcmExceptionNoMgmtIP(LcmException):
44 pass
45
46
gcalvinoed7f6d42018-12-14 14:44:56 +010047class LcmExceptionExit(LcmException):
48 pass
49
50
tierno59d22d22018-09-25 18:10:19 +020051def versiontuple(v):
tierno27246d82018-09-27 15:59:09 +020052 """utility for compare dot separate versions. Fills with zeros to proper number comparison
53 package version will be something like 4.0.1.post11+gb3f024d.dirty-1. Where 4.0.1 is the git tag, postXX is the
54 number of commits from this tag, and +XXXXXXX is the git commit short id. Total length is 16 with until 999 commits
55 """
tierno59d22d22018-09-25 18:10:19 +020056 filled = []
57 for point in v.split("."):
tiernoe64f7fb2019-09-11 08:55:52 +000058 point, _, _ = point.partition("+")
59 point, _, _ = point.partition("-")
60 filled.append(point.zfill(20))
tierno59d22d22018-09-25 18:10:19 +020061 return tuple(filled)
62
63
tierno744303e2020-01-13 16:46:31 +000064def deep_get(target_dict, key_list, default_value=None):
tierno626e0152019-11-29 14:16:16 +000065 """
66 Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
67 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
68 :param target_dict: dictionary to be read
69 :param key_list: list of keys to read from target_dict
tierno744303e2020-01-13 16:46:31 +000070 :param default_value: value to return if key is not present in the nested dictionary
tierno626e0152019-11-29 14:16:16 +000071 :return: The wanted value if exist, None otherwise
72 """
73 for key in key_list:
74 if not isinstance(target_dict, dict) or key not in target_dict:
tierno744303e2020-01-13 16:46:31 +000075 return default_value
tierno626e0152019-11-29 14:16:16 +000076 target_dict = target_dict[key]
77 return target_dict
78
79
tierno744303e2020-01-13 16:46:31 +000080def get_iterable(in_dict, in_key):
81 """
82 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
83 :param in_dict: a dictionary
84 :param in_key: the key to look for at in_dict
85 :return: in_dict[in_var] or () if it is None or not present
86 """
87 if not in_dict.get(in_key):
88 return ()
89 return in_dict[in_key]
90
91
aticigdffa6212022-04-12 15:27:53 +030092def check_juju_bundle_existence(vnfd: dict) -> str:
93 """Checks the existence of juju-bundle in the descriptor
94
95 Args:
96 vnfd: Descriptor as a dictionary
97
98 Returns:
99 Juju bundle if dictionary has juju-bundle else None
100
101 """
102 if vnfd.get("vnfd"):
103 vnfd = vnfd["vnfd"]
104
105 for kdu in vnfd.get("kdu", []):
106 return kdu.get("juju-bundle", None)
107
108
109def get_charm_artifact_path(base_folder, charm_name, charm_type, revision=str()) -> str:
110 """Finds the charm artifact paths
111
112 Args:
113 base_folder: Main folder which will be looked up for charm
114 charm_name: Charm name
115 charm_type: Type of charm native_charm, lxc_proxy_charm or k8s_proxy_charm
116 revision: vnf package revision number if there is
117
118 Returns:
119 artifact_path: (str)
120
121 """
122 extension = ""
123 if revision:
124 extension = ":" + str(revision)
125
126 if base_folder.get("pkg-dir"):
127 artifact_path = "{}/{}/{}/{}".format(
aticigd7083542022-05-30 20:45:55 +0300128 base_folder["folder"].split(":")[0] + extension,
aticigdffa6212022-04-12 15:27:53 +0300129 base_folder["pkg-dir"],
130 "charms"
131 if charm_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
132 else "helm-charts",
133 charm_name,
134 )
135
136 else:
137 # For SOL004 packages
138 artifact_path = "{}/Scripts/{}/{}".format(
aticigd7083542022-05-30 20:45:55 +0300139 base_folder["folder"].split(":")[0] + extension,
aticigdffa6212022-04-12 15:27:53 +0300140 "charms"
141 if charm_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
142 else "helm-charts",
143 charm_name,
144 )
145
146 return artifact_path
147
148
tierno744303e2020-01-13 16:46:31 +0000149def populate_dict(target_dict, key_list, value):
150 """
151 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
152 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
153 :param target_dict: dictionary to be changed
154 :param key_list: list of keys to insert at target_dict
155 :param value:
156 :return: None
157 """
158 for key in key_list[0:-1]:
159 if key not in target_dict:
160 target_dict[key] = {}
161 target_dict = target_dict[key]
162 target_dict[key_list[-1]] = value
163
164
Gabriel Cubae539a8d2022-10-10 11:34:51 -0500165def get_ee_id_parts(ee_id):
166 """
167 Parses ee_id stored at database that can be either 'version:namespace.helm_id' or only
168 namespace.helm_id for backward compatibility
169 If exists helm version can be helm-v3 or helm (helm-v2 old version)
170 """
171 version, _, part_id = ee_id.rpartition(":")
172 namespace, _, helm_id = part_id.rpartition(".")
173 return version, namespace, helm_id
174
175
Gabriel Cubac7737442023-02-14 13:09:18 -0500176def vld_to_ro_ip_profile(source_data):
177 if source_data:
178 return {
179 "ip_version": "IPv4"
180 if "v4" in source_data.get("ip-version", "ipv4")
181 else "IPv6",
182 "subnet_address": source_data.get("cidr")
183 or source_data.get("subnet-address"),
184 "gateway_address": source_data.get("gateway-ip")
185 or source_data.get("gateway-address"),
186 "dns_address": ";".join(
187 [v["address"] for v in source_data["dns-server"] if v.get("address")]
188 )
189 if source_data.get("dns-server")
190 else None,
191 "dhcp_enabled": source_data.get("dhcp-params", {}).get("enabled", False)
192 or source_data.get("dhcp-enabled", False),
193 "dhcp_start_address": source_data["dhcp-params"].get("start-address")
194 if source_data.get("dhcp-params")
195 else None,
196 "dhcp_count": source_data["dhcp-params"].get("count")
197 if source_data.get("dhcp-params")
198 else None,
Gabriel Cubaf0af5e62023-03-14 00:27:49 -0500199 "ipv6_address_mode": source_data["ipv6-address-mode"]
200 if "ipv6-address-mode" in source_data
201 else None,
Gabriel Cubac7737442023-02-14 13:09:18 -0500202 }
203
204
kuused124bfe2019-06-18 12:09:24 +0200205class LcmBase:
bravof922c4172020-11-24 21:21:43 -0300206 def __init__(self, msg, logger):
kuused124bfe2019-06-18 12:09:24 +0200207 """
208
209 :param db: database connection
210 """
bravof922c4172020-11-24 21:21:43 -0300211 self.db = Database().instance.db
kuused124bfe2019-06-18 12:09:24 +0200212 self.msg = msg
bravof922c4172020-11-24 21:21:43 -0300213 self.fs = Filesystem().instance.fs
kuused124bfe2019-06-18 12:09:24 +0200214 self.logger = logger
215
216 def update_db_2(self, item, _id, _desc):
217 """
218 Updates database with _desc information. If success _desc is cleared
Pedro Escaleirada21d262022-04-21 16:31:06 +0100219 :param item: collection
220 :param _id: the _id to use in the query filter
kuused124bfe2019-06-18 12:09:24 +0200221 :param _desc: dictionary with the content to update. Keys are dot separated keys for
222 :return: None. Exception is raised on error
223 """
224 if not _desc:
225 return
tierno79cd8ad2019-10-18 13:03:10 +0000226 now = time()
227 _desc["_admin.modified"] = now
kuused124bfe2019-06-18 12:09:24 +0200228 self.db.set_one(item, {"_id": _id}, _desc)
229 _desc.clear()
230 # except DbException as e:
231 # self.logger.error("Updating {} _id={} with '{}'. Error: {}".format(item, _id, _desc, e))
232
aticig1dda84c2022-09-10 01:56:58 +0300233 @staticmethod
234 def calculate_charm_hash(zipped_file):
235 """Calculate the hash of charm files which ends with .charm
236
237 Args:
238 zipped_file (str): Existing charm package full path
239
240 Returns:
241 hex digest (str): The hash of the charm file
242 """
243 filehash = hashlib.md5()
244 with open(zipped_file, mode="rb") as file:
245 contents = file.read()
246 filehash.update(contents)
247 return filehash.hexdigest()
248
249 @staticmethod
250 def compare_charm_hash(current_charm, target_charm):
251 """Compare the existing charm and the target charm if the charms
252 are given as zip files ends with .charm
253
254 Args:
255 current_charm (str): Existing charm package full path
256 target_charm (str): Target charm package full path
257
258 Returns:
259 True/False (bool): if charm has changed it returns True
260 """
261 return LcmBase.calculate_charm_hash(
262 current_charm
263 ) != LcmBase.calculate_charm_hash(target_charm)
264
265 @staticmethod
266 def compare_charmdir_hash(current_charm_dir, target_charm_dir):
267 """Compare the existing charm and the target charm if the charms
268 are given as directories
269
270 Args:
271 current_charm_dir (str): Existing charm package directory path
272 target_charm_dir (str): Target charm package directory path
273
274 Returns:
275 True/False (bool): if charm has changed it returns True
276 """
277 return checksumdir.dirhash(current_charm_dir) != checksumdir.dirhash(
278 target_charm_dir
279 )
280
aticigdffa6212022-04-12 15:27:53 +0300281 def check_charm_hash_changed(
282 self, current_charm_path: str, target_charm_path: str
283 ) -> bool:
284 """Find the target charm has changed or not by checking the hash of
285 old and new charm packages
286
287 Args:
288 current_charm_path (str): Existing charm package artifact path
289 target_charm_path (str): Target charm package artifact path
290
291 Returns:
292 True/False (bool): if charm has changed it returns True
293
294 """
aticig1dda84c2022-09-10 01:56:58 +0300295 try:
296 # Check if the charm artifacts are available
297 current_charm = self.fs.path + current_charm_path
298 target_charm = self.fs.path + target_charm_path
aticigdffa6212022-04-12 15:27:53 +0300299
aticig1dda84c2022-09-10 01:56:58 +0300300 if os.path.exists(current_charm) and os.path.exists(target_charm):
aticig1dda84c2022-09-10 01:56:58 +0300301 # Compare the hash of .charm files
302 if current_charm.endswith(".charm"):
303 return LcmBase.compare_charm_hash(current_charm, target_charm)
aticigdffa6212022-04-12 15:27:53 +0300304
aticig1dda84c2022-09-10 01:56:58 +0300305 # Compare the hash of charm folders
306 return LcmBase.compare_charmdir_hash(current_charm, target_charm)
307
308 else:
309 raise LcmException(
310 "Charm artifact {} does not exist in the VNF Package".format(
311 self.fs.path + target_charm_path
312 )
aticigdffa6212022-04-12 15:27:53 +0300313 )
aticig1dda84c2022-09-10 01:56:58 +0300314 except (IOError, OSError, TypeError) as error:
315 self.logger.debug(traceback.format_exc())
316 self.logger.error(f"{error} occured while checking the charm hashes")
317 raise LcmException(error)
aticigdffa6212022-04-12 15:27:53 +0300318
aticig9bc63ac2022-07-27 09:32:06 +0300319 @staticmethod
320 def get_charm_name(charm_metadata_file: str) -> str:
321 """Get the charm name from metadata file.
322
323 Args:
324 charm_metadata_file (str): charm metadata file full path
325
326 Returns:
327 charm_name (str): charm name
328
329 """
330 # Read charm metadata.yaml to get the charm name
331 with open(charm_metadata_file, "r") as metadata_file:
332 content = yaml.safe_load(metadata_file)
333 charm_name = content["name"]
334 return str(charm_name)
335
336 def _get_charm_path(
337 self, nsd_package_path: str, nsd_package_name: str, charm_folder_name: str
338 ) -> str:
339 """Get the full path of charm folder.
340
341 Args:
342 nsd_package_path (str): NSD package full path
343 nsd_package_name (str): NSD package name
344 charm_folder_name (str): folder name
345
346 Returns:
347 charm_path (str): charm folder full path
348 """
349 charm_path = (
350 self.fs.path
351 + nsd_package_path
352 + "/"
353 + nsd_package_name
354 + "/charms/"
355 + charm_folder_name
356 )
357 return charm_path
358
359 def _get_charm_metadata_file(
360 self,
361 charm_folder_name: str,
362 nsd_package_path: str,
363 nsd_package_name: str,
364 charm_path: str = None,
365 ) -> str:
366 """Get the path of charm metadata file.
367
368 Args:
369 charm_folder_name (str): folder name
370 nsd_package_path (str): NSD package full path
371 nsd_package_name (str): NSD package name
372 charm_path (str): Charm full path
373
374 Returns:
375 charm_metadata_file_path (str): charm metadata file full path
376
377 """
378 # Locate the charm metadata.yaml
379 if charm_folder_name.endswith(".charm"):
380 extract_path = (
381 self.fs.path
382 + nsd_package_path
383 + "/"
384 + nsd_package_name
385 + "/charms/"
aticiga37c6ff2022-08-20 20:56:19 +0300386 + charm_folder_name.replace(".charm", "")
aticig9bc63ac2022-07-27 09:32:06 +0300387 )
388 # Extract .charm to extract path
389 with ZipFile(charm_path, "r") as zipfile:
390 zipfile.extractall(extract_path)
391 return extract_path + "/metadata.yaml"
392 else:
393 return charm_path + "/metadata.yaml"
394
395 def find_charm_name(self, db_nsr: dict, charm_folder_name: str) -> str:
396 """Get the charm name from metadata.yaml of charm package.
397
398 Args:
399 db_nsr (dict): NS record as a dictionary
400 charm_folder_name (str): charm folder name
401
402 Returns:
403 charm_name (str): charm name
404 """
405 try:
406 if not charm_folder_name:
407 raise LcmException("charm_folder_name should be provided.")
408
409 # Find nsd_package details: path, name
410 revision = db_nsr.get("revision", "")
aticiga37c6ff2022-08-20 20:56:19 +0300411
412 # Get the NSD package path
413 if revision:
preethika.p28b0bf82022-09-23 07:36:28 +0000414 nsd_package_path = db_nsr["nsd-id"] + ":" + str(revision)
aticiga37c6ff2022-08-20 20:56:19 +0300415 db_nsd = self.db.get_one("nsds_revisions", {"_id": nsd_package_path})
416
417 else:
418 nsd_package_path = db_nsr["nsd-id"]
419
420 db_nsd = self.db.get_one("nsds", {"_id": nsd_package_path})
421
422 # Get the NSD package name
423 nsd_package_name = db_nsd["_admin"]["storage"]["pkg-dir"]
aticig9bc63ac2022-07-27 09:32:06 +0300424
425 # Remove the existing nsd package and sync from FsMongo
426 shutil.rmtree(self.fs.path + nsd_package_path, ignore_errors=True)
427 self.fs.sync(from_path=nsd_package_path)
428
429 # Get the charm path
430 charm_path = self._get_charm_path(
431 nsd_package_path, nsd_package_name, charm_folder_name
432 )
433
434 # Find charm metadata file full path
435 charm_metadata_file = self._get_charm_metadata_file(
436 charm_folder_name, nsd_package_path, nsd_package_name, charm_path
437 )
438
439 # Return charm name
440 return self.get_charm_name(charm_metadata_file)
441
442 except (
443 yaml.YAMLError,
444 IOError,
445 FsException,
446 KeyError,
447 TypeError,
448 FileNotFoundError,
449 BadZipfile,
450 ) as error:
451 self.logger.debug(traceback.format_exc())
452 self.logger.error(f"{error} occured while getting the charm name")
453 raise LcmException(error)
454
kuused124bfe2019-06-18 12:09:24 +0200455
456class TaskRegistry(LcmBase):
tierno59d22d22018-09-25 18:10:19 +0200457 """
458 Implements a registry of task needed for later cancelation, look for related tasks that must be completed before
459 etc. It stores a four level dict
460 First level is the topic, ns, vim_account, sdn
461 Second level is the _id
462 Third level is the operation id
463 Fourth level is a descriptive name, the value is the task class
kuused124bfe2019-06-18 12:09:24 +0200464
465 The HA (High-Availability) methods are used when more than one LCM instance is running.
466 To register the current task in the external DB, use LcmBase as base class, to be able
467 to reuse LcmBase.update_db_2()
468 The DB registry uses the following fields to distinguish a task:
469 - op_type: operation type ("nslcmops" or "nsilcmops")
470 - op_id: operation ID
471 - worker: the worker ID for this process
tierno59d22d22018-09-25 18:10:19 +0200472 """
473
kuuse6a470c62019-07-10 13:52:45 +0200474 # NS/NSI: "services" VIM/WIM/SDN: "accounts"
garciadeblas5697b8b2021-03-24 09:17:02 +0100475 topic_service_list = ["ns", "nsi"]
476 topic_account_list = ["vim", "wim", "sdn", "k8scluster", "vca", "k8srepo"]
kuuse6a470c62019-07-10 13:52:45 +0200477
478 # Map topic to InstanceID
garciadeblas5697b8b2021-03-24 09:17:02 +0100479 topic2instid_dict = {"ns": "nsInstanceId", "nsi": "netsliceInstanceId"}
kuuse6a470c62019-07-10 13:52:45 +0200480
481 # Map topic to DB table name
482 topic2dbtable_dict = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100483 "ns": "nslcmops",
484 "nsi": "nsilcmops",
485 "vim": "vim_accounts",
486 "wim": "wim_accounts",
487 "sdn": "sdns",
488 "k8scluster": "k8sclusters",
489 "vca": "vca",
490 "k8srepo": "k8srepos",
491 }
kuused124bfe2019-06-18 12:09:24 +0200492
bravof922c4172020-11-24 21:21:43 -0300493 def __init__(self, worker_id=None, logger=None):
tierno59d22d22018-09-25 18:10:19 +0200494 self.task_registry = {
495 "ns": {},
Felipe Vicensc2033f22018-11-15 15:09:58 +0100496 "nsi": {},
tierno59d22d22018-09-25 18:10:19 +0200497 "vim_account": {},
tiernoe37b57d2018-12-11 17:22:51 +0000498 "wim_account": {},
tierno59d22d22018-09-25 18:10:19 +0200499 "sdn": {},
calvinosanch9f9c6f22019-11-04 13:37:39 +0100500 "k8scluster": {},
David Garciac1fe90a2021-03-31 19:12:02 +0200501 "vca": {},
calvinosanch9f9c6f22019-11-04 13:37:39 +0100502 "k8srepo": {},
tierno59d22d22018-09-25 18:10:19 +0200503 }
kuused124bfe2019-06-18 12:09:24 +0200504 self.worker_id = worker_id
bravof922c4172020-11-24 21:21:43 -0300505 self.db = Database().instance.db
kuused124bfe2019-06-18 12:09:24 +0200506 self.logger = logger
tierno59d22d22018-09-25 18:10:19 +0200507
508 def register(self, topic, _id, op_id, task_name, task):
509 """
510 Register a new task
Felipe Vicensc2033f22018-11-15 15:09:58 +0100511 :param topic: Can be "ns", "nsi", "vim_account", "sdn"
tierno59d22d22018-09-25 18:10:19 +0200512 :param _id: _id of the related item
513 :param op_id: id of the operation of the related item
514 :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id
515 :param task: Task class
516 :return: none
517 """
518 if _id not in self.task_registry[topic]:
519 self.task_registry[topic][_id] = OrderedDict()
520 if op_id not in self.task_registry[topic][_id]:
521 self.task_registry[topic][_id][op_id] = {task_name: task}
522 else:
523 self.task_registry[topic][_id][op_id][task_name] = task
524 # print("registering task", topic, _id, op_id, task_name, task)
525
526 def remove(self, topic, _id, op_id, task_name=None):
527 """
tiernobaa51102018-12-14 13:16:18 +0000528 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 +0100529 :param topic: Can be "ns", "nsi", "vim_account", "sdn"
tierno59d22d22018-09-25 18:10:19 +0200530 :param _id: _id of the related item
531 :param op_id: id of the operation of the related item
tiernobaa51102018-12-14 13:16:18 +0000532 :param task_name: Task descriptive name. If none it deletes all tasks with same _id and op_id
533 :return: None
tierno59d22d22018-09-25 18:10:19 +0200534 """
tiernobaa51102018-12-14 13:16:18 +0000535 if not self.task_registry[topic].get(_id):
tierno59d22d22018-09-25 18:10:19 +0200536 return
537 if not task_name:
tiernobaa51102018-12-14 13:16:18 +0000538 self.task_registry[topic][_id].pop(op_id, None)
539 elif self.task_registry[topic][_id].get(op_id):
540 self.task_registry[topic][_id][op_id].pop(task_name, None)
541
542 # delete done tasks
543 for op_id_ in list(self.task_registry[topic][_id]):
544 for name, task in self.task_registry[topic][_id][op_id_].items():
545 if not task.done():
546 break
547 else:
548 del self.task_registry[topic][_id][op_id_]
tierno59d22d22018-09-25 18:10:19 +0200549 if not self.task_registry[topic][_id]:
550 del self.task_registry[topic][_id]
551
552 def lookfor_related(self, topic, _id, my_op_id=None):
553 task_list = []
554 task_name_list = []
555 if _id not in self.task_registry[topic]:
556 return "", task_name_list
557 for op_id in reversed(self.task_registry[topic][_id]):
558 if my_op_id:
559 if my_op_id == op_id:
560 my_op_id = None # so that the next task is taken
561 continue
562
563 for task_name, task in self.task_registry[topic][_id][op_id].items():
tiernobaa51102018-12-14 13:16:18 +0000564 if not task.done():
565 task_list.append(task)
566 task_name_list.append(task_name)
tierno59d22d22018-09-25 18:10:19 +0200567 break
568 return ", ".join(task_name_list), task_list
569
570 def cancel(self, topic, _id, target_op_id=None, target_task_name=None):
571 """
kuused124bfe2019-06-18 12:09:24 +0200572 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 +0100573 this is cancelled, and the same with task_name
tierno59d22d22018-09-25 18:10:19 +0200574 """
575 if not self.task_registry[topic].get(_id):
576 return
577 for op_id in reversed(self.task_registry[topic][_id]):
578 if target_op_id and target_op_id != op_id:
579 continue
580 for task_name, task in self.task_registry[topic][_id][op_id].items():
581 if target_task_name and target_task_name != task_name:
582 continue
583 # result =
584 task.cancel()
585 # if result:
586 # self.logger.debug("{} _id={} order_id={} task={} cancelled".format(topic, _id, op_id, task_name))
587
kuuse6a470c62019-07-10 13:52:45 +0200588 # Is topic NS/NSI?
589 def _is_service_type_HA(self, topic):
590 return topic in self.topic_service_list
591
592 # Is topic VIM/WIM/SDN?
593 def _is_account_type_HA(self, topic):
594 return topic in self.topic_account_list
595
596 # Input: op_id, example: 'abc123def:3' Output: account_id='abc123def', op_index=3
597 def _get_account_and_op_HA(self, op_id):
598 if not op_id:
tiernofa076c32020-08-13 14:25:47 +0000599 return None, None
garciadeblas5697b8b2021-03-24 09:17:02 +0100600 account_id, _, op_index = op_id.rpartition(":")
tiernofa076c32020-08-13 14:25:47 +0000601 if not account_id or not op_index.isdigit():
602 return None, None
kuuse6a470c62019-07-10 13:52:45 +0200603 return account_id, op_index
604
605 # Get '_id' for any topic and operation
606 def _get_instance_id_HA(self, topic, op_type, op_id):
607 _id = None
608 # Special operation 'ANY', for SDN account associated to a VIM account: op_id as '_id'
garciadeblas5697b8b2021-03-24 09:17:02 +0100609 if op_type == "ANY":
kuuse6a470c62019-07-10 13:52:45 +0200610 _id = op_id
611 # NS/NSI: Use op_id as '_id'
612 elif self._is_service_type_HA(topic):
613 _id = op_id
calvinosanch9f9c6f22019-11-04 13:37:39 +0100614 # 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 +0200615 elif self._is_account_type_HA(topic):
616 _id, _ = self._get_account_and_op_HA(op_id)
617 return _id
618
619 # Set DB _filter for querying any related process state
620 def _get_waitfor_filter_HA(self, db_lcmop, topic, op_type, op_id):
621 _filter = {}
622 # Special operation 'ANY', for SDN account associated to a VIM account: op_id as '_id'
623 # In this special case, the timestamp is ignored
garciadeblas5697b8b2021-03-24 09:17:02 +0100624 if op_type == "ANY":
625 _filter = {"operationState": "PROCESSING"}
kuuse6a470c62019-07-10 13:52:45 +0200626 # Otherwise, get 'startTime' timestamp for this operation
627 else:
628 # NS/NSI
629 if self._is_service_type_HA(topic):
tierno79cd8ad2019-10-18 13:03:10 +0000630 now = time()
kuuse6a470c62019-07-10 13:52:45 +0200631 starttime_this_op = db_lcmop.get("startTime")
632 instance_id_label = self.topic2instid_dict.get(topic)
633 instance_id = db_lcmop.get(instance_id_label)
garciadeblas5697b8b2021-03-24 09:17:02 +0100634 _filter = {
635 instance_id_label: instance_id,
636 "operationState": "PROCESSING",
637 "startTime.lt": starttime_this_op,
638 "_admin.modified.gt": now
639 - 2 * 3600, # ignore if tow hours of inactivity
640 }
calvinosanch9f9c6f22019-11-04 13:37:39 +0100641 # VIM/WIM/SDN/K8scluster
kuuse6a470c62019-07-10 13:52:45 +0200642 elif self._is_account_type_HA(topic):
643 _, op_index = self._get_account_and_op_HA(op_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100644 _ops = db_lcmop["_admin"]["operations"]
kuuse6a470c62019-07-10 13:52:45 +0200645 _this_op = _ops[int(op_index)]
garciadeblas5697b8b2021-03-24 09:17:02 +0100646 starttime_this_op = _this_op.get("startTime", None)
647 _filter = {
648 "operationState": "PROCESSING",
649 "startTime.lt": starttime_this_op,
650 }
kuuse6a470c62019-07-10 13:52:45 +0200651 return _filter
652
653 # Get DB params for any topic and operation
654 def _get_dbparams_for_lock_HA(self, topic, op_type, op_id):
655 q_filter = {}
656 update_dict = {}
657 # NS/NSI
658 if self._is_service_type_HA(topic):
garciadeblas5697b8b2021-03-24 09:17:02 +0100659 q_filter = {"_id": op_id, "_admin.worker": None}
660 update_dict = {"_admin.worker": self.worker_id}
kuuse6a470c62019-07-10 13:52:45 +0200661 # VIM/WIM/SDN
662 elif self._is_account_type_HA(topic):
663 account_id, op_index = self._get_account_and_op_HA(op_id)
664 if not account_id:
665 return None, None
garciadeblas5697b8b2021-03-24 09:17:02 +0100666 if op_type == "create":
kuuse6a470c62019-07-10 13:52:45 +0200667 # Creating a VIM/WIM/SDN account implies setting '_admin.current_operation' = 0
668 op_index = 0
garciadeblas5697b8b2021-03-24 09:17:02 +0100669 q_filter = {
670 "_id": account_id,
671 "_admin.operations.{}.worker".format(op_index): None,
672 }
673 update_dict = {
674 "_admin.operations.{}.worker".format(op_index): self.worker_id,
675 "_admin.current_operation": op_index,
676 }
kuuse6a470c62019-07-10 13:52:45 +0200677 return q_filter, update_dict
678
kuused124bfe2019-06-18 12:09:24 +0200679 def lock_HA(self, topic, op_type, op_id):
680 """
kuuse6a470c62019-07-10 13:52:45 +0200681 Lock a task, if possible, to indicate to the HA system that
kuused124bfe2019-06-18 12:09:24 +0200682 the task will be executed in this LCM instance.
kuuse6a470c62019-07-10 13:52:45 +0200683 :param topic: Can be "ns", "nsi", "vim", "wim", or "sdn"
684 :param op_type: Operation type, can be "nslcmops", "nsilcmops", "create", "edit", "delete"
685 :param op_id: NS, NSI: Operation ID VIM,WIM,SDN: Account ID + ':' + Operation Index
kuused124bfe2019-06-18 12:09:24 +0200686 :return:
kuuse6a470c62019-07-10 13:52:45 +0200687 True=lock was successful => execute the task (not registered by any other LCM instance)
kuused124bfe2019-06-18 12:09:24 +0200688 False=lock failed => do NOT execute the task (already registered by another LCM instance)
kuuse6a470c62019-07-10 13:52:45 +0200689
690 HA tasks and backward compatibility:
691 If topic is "account type" (VIM/WIM/SDN) and op_id is None, 'op_id' was not provided by NBI.
692 This means that the running NBI instance does not support HA.
693 In such a case this method should always return True, to always execute
694 the task in this instance of LCM, without querying the DB.
tierno59d22d22018-09-25 18:10:19 +0200695 """
696
calvinosanch9f9c6f22019-11-04 13:37:39 +0100697 # Backward compatibility for VIM/WIM/SDN/k8scluster without op_id
kuuse6a470c62019-07-10 13:52:45 +0200698 if self._is_account_type_HA(topic) and op_id is None:
699 return True
tierno59d22d22018-09-25 18:10:19 +0200700
kuuse6a470c62019-07-10 13:52:45 +0200701 # Try to lock this task
tiernofa076c32020-08-13 14:25:47 +0000702 db_table_name = self.topic2dbtable_dict[topic]
kuuse6a470c62019-07-10 13:52:45 +0200703 q_filter, update_dict = self._get_dbparams_for_lock_HA(topic, op_type, op_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100704 db_lock_task = self.db.set_one(
705 db_table_name,
706 q_filter=q_filter,
707 update_dict=update_dict,
708 fail_on_empty=False,
709 )
kuused124bfe2019-06-18 12:09:24 +0200710 if db_lock_task is None:
garciadeblas5697b8b2021-03-24 09:17:02 +0100711 self.logger.debug(
712 "Task {} operation={} already locked by another worker".format(
713 topic, op_id
714 )
715 )
kuused124bfe2019-06-18 12:09:24 +0200716 return False
717 else:
kuuse6a470c62019-07-10 13:52:45 +0200718 # Set 'detailed-status' to 'In progress' for VIM/WIM/SDN operations
719 if self._is_account_type_HA(topic):
garciadeblas5697b8b2021-03-24 09:17:02 +0100720 detailed_status = "In progress"
kuuse6a470c62019-07-10 13:52:45 +0200721 account_id, op_index = self._get_account_and_op_HA(op_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100722 q_filter = {"_id": account_id}
723 update_dict = {
724 "_admin.operations.{}.detailed-status".format(
725 op_index
726 ): detailed_status
727 }
728 self.db.set_one(
729 db_table_name,
730 q_filter=q_filter,
731 update_dict=update_dict,
732 fail_on_empty=False,
733 )
kuused124bfe2019-06-18 12:09:24 +0200734 return True
735
tiernofa076c32020-08-13 14:25:47 +0000736 def unlock_HA(self, topic, op_type, op_id, operationState, detailed_status):
kuuse6a470c62019-07-10 13:52:45 +0200737 """
738 Register a task, done when finished a VIM/WIM/SDN 'create' operation.
739 :param topic: Can be "vim", "wim", or "sdn"
740 :param op_type: Operation type, can be "create", "edit", "delete"
741 :param op_id: Account ID + ':' + Operation Index
742 :return: nothing
743 """
744
745 # Backward compatibility
tiernofa076c32020-08-13 14:25:47 +0000746 if not self._is_account_type_HA(topic) or not op_id:
kuuse6a470c62019-07-10 13:52:45 +0200747 return
748
749 # Get Account ID and Operation Index
750 account_id, op_index = self._get_account_and_op_HA(op_id)
tiernofa076c32020-08-13 14:25:47 +0000751 db_table_name = self.topic2dbtable_dict[topic]
kuuse6a470c62019-07-10 13:52:45 +0200752
753 # If this is a 'delete' operation, the account may have been deleted (SUCCESS) or may still exist (FAILED)
754 # If the account exist, register the HA task.
755 # Update DB for HA tasks
garciadeblas5697b8b2021-03-24 09:17:02 +0100756 q_filter = {"_id": account_id}
757 update_dict = {
758 "_admin.operations.{}.operationState".format(op_index): operationState,
759 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
760 "_admin.operations.{}.worker".format(op_index): None,
761 "_admin.current_operation": None,
762 }
763 self.db.set_one(
764 db_table_name,
765 q_filter=q_filter,
766 update_dict=update_dict,
767 fail_on_empty=False,
768 )
kuuse6a470c62019-07-10 13:52:45 +0200769 return
770
kuused124bfe2019-06-18 12:09:24 +0200771 async def waitfor_related_HA(self, topic, op_type, op_id=None):
tierno59d22d22018-09-25 18:10:19 +0200772 """
kuused124bfe2019-06-18 12:09:24 +0200773 Wait for any pending related HA tasks
tierno59d22d22018-09-25 18:10:19 +0200774 """
kuused124bfe2019-06-18 12:09:24 +0200775
kuuse6a470c62019-07-10 13:52:45 +0200776 # Backward compatibility
garciadeblas5697b8b2021-03-24 09:17:02 +0100777 if not (
778 self._is_service_type_HA(topic) or self._is_account_type_HA(topic)
779 ) and (op_id is None):
kuuse6a470c62019-07-10 13:52:45 +0200780 return
kuused124bfe2019-06-18 12:09:24 +0200781
kuuse6a470c62019-07-10 13:52:45 +0200782 # Get DB table name
783 db_table_name = self.topic2dbtable_dict.get(topic)
784
785 # Get instance ID
786 _id = self._get_instance_id_HA(topic, op_type, op_id)
787 _filter = {"_id": _id}
garciadeblas5697b8b2021-03-24 09:17:02 +0100788 db_lcmop = self.db.get_one(db_table_name, _filter, fail_on_empty=False)
kuused124bfe2019-06-18 12:09:24 +0200789 if not db_lcmop:
tierno59d22d22018-09-25 18:10:19 +0200790 return
kuuse6a470c62019-07-10 13:52:45 +0200791
792 # Set DB _filter for querying any related process state
793 _filter = self._get_waitfor_filter_HA(db_lcmop, topic, op_type, op_id)
kuused124bfe2019-06-18 12:09:24 +0200794
795 # For HA, get list of tasks from DB instead of from dictionary (in-memory) variable.
garciadeblas5697b8b2021-03-24 09:17:02 +0100796 timeout_wait_for_task = (
797 3600 # Max time (seconds) to wait for a related task to finish
798 )
kuused124bfe2019-06-18 12:09:24 +0200799 # interval_wait_for_task = 30 # A too long polling interval slows things down considerably
garciadeblas5697b8b2021-03-24 09:17:02 +0100800 interval_wait_for_task = 10 # Interval in seconds for polling related tasks
kuused124bfe2019-06-18 12:09:24 +0200801 time_left = timeout_wait_for_task
802 old_num_related_tasks = 0
803 while True:
kuuse6a470c62019-07-10 13:52:45 +0200804 # Get related tasks (operations within the same instance as this) which are
kuused124bfe2019-06-18 12:09:24 +0200805 # still running (operationState='PROCESSING') and which were started before this task.
kuuse6a470c62019-07-10 13:52:45 +0200806 # In the case of op_type='ANY', get any related tasks with operationState='PROCESSING', ignore timestamps.
garciadeblas5697b8b2021-03-24 09:17:02 +0100807 db_waitfor_related_task = self.db.get_list(db_table_name, q_filter=_filter)
kuused124bfe2019-06-18 12:09:24 +0200808 new_num_related_tasks = len(db_waitfor_related_task)
kuuse6a470c62019-07-10 13:52:45 +0200809 # If there are no related tasks, there is nothing to wait for, so return.
kuused124bfe2019-06-18 12:09:24 +0200810 if not new_num_related_tasks:
kuused124bfe2019-06-18 12:09:24 +0200811 return
812 # If number of pending related tasks have changed,
813 # update the 'detailed-status' field and log the change.
kuuse6a470c62019-07-10 13:52:45 +0200814 # Do NOT update the 'detailed-status' for SDNC-associated-to-VIM operations ('ANY').
garciadeblas5697b8b2021-03-24 09:17:02 +0100815 if (op_type != "ANY") and (new_num_related_tasks != old_num_related_tasks):
816 step = "Waiting for {} related tasks to be completed.".format(
817 new_num_related_tasks
818 )
kuuse6a470c62019-07-10 13:52:45 +0200819 update_dict = {}
garciadeblas5697b8b2021-03-24 09:17:02 +0100820 q_filter = {"_id": _id}
kuuse6a470c62019-07-10 13:52:45 +0200821 # NS/NSI
822 if self._is_service_type_HA(topic):
garciadeblas5697b8b2021-03-24 09:17:02 +0100823 update_dict = {
824 "detailed-status": step,
825 "queuePosition": new_num_related_tasks,
826 }
kuuse6a470c62019-07-10 13:52:45 +0200827 # VIM/WIM/SDN
828 elif self._is_account_type_HA(topic):
829 _, op_index = self._get_account_and_op_HA(op_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100830 update_dict = {
831 "_admin.operations.{}.detailed-status".format(op_index): step
832 }
kuuse6a470c62019-07-10 13:52:45 +0200833 self.logger.debug("Task {} operation={} {}".format(topic, _id, step))
garciadeblas5697b8b2021-03-24 09:17:02 +0100834 self.db.set_one(
835 db_table_name,
836 q_filter=q_filter,
837 update_dict=update_dict,
838 fail_on_empty=False,
839 )
kuused124bfe2019-06-18 12:09:24 +0200840 old_num_related_tasks = new_num_related_tasks
841 time_left -= interval_wait_for_task
842 if time_left < 0:
843 raise LcmException(
844 "Timeout ({}) when waiting for related tasks to be completed".format(
garciadeblas5697b8b2021-03-24 09:17:02 +0100845 timeout_wait_for_task
846 )
847 )
kuused124bfe2019-06-18 12:09:24 +0200848 await asyncio.sleep(interval_wait_for_task)
849
850 return