|
| 1 | +# This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | +# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | +# file, you can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 | +import asyncio |
| 5 | +import functools |
| 6 | +import inspect |
| 7 | +import logging |
| 8 | +from dataclasses import dataclass |
| 9 | +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple |
| 10 | + |
| 11 | +from .messages import CheckMessage, level_to_text |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | +CheckFn = Callable[..., List[CheckMessage]] |
| 16 | + |
| 17 | +_REGISTERED_CHECKS = {} |
| 18 | + |
| 19 | + |
| 20 | +def _iscoroutinefunction_or_partial(obj): |
| 21 | + """ |
| 22 | + Determine if the provided object is a coroutine function or a partial function |
| 23 | + that wraps a coroutine function. |
| 24 | +
|
| 25 | + This function should be removed when we drop support for Python 3.7, as this is |
| 26 | + handled directly by `inspect.iscoroutinefunction` in Python 3.8. |
| 27 | + """ |
| 28 | + while isinstance(obj, functools.partial): |
| 29 | + obj = obj.func |
| 30 | + return inspect.iscoroutinefunction(obj) |
| 31 | + |
| 32 | + |
| 33 | +def register(func=None, name=None): |
| 34 | + """ |
| 35 | + Register a check callback to be executed from |
| 36 | + the heartbeat endpoint. |
| 37 | + """ |
| 38 | + if func is None: |
| 39 | + return functools.partial(register, name=name) |
| 40 | + |
| 41 | + if name is None: |
| 42 | + name = func.__name__ |
| 43 | + |
| 44 | + logger.debug("Register Dockerflow check %s", name) |
| 45 | + |
| 46 | + if _iscoroutinefunction_or_partial(func): |
| 47 | + |
| 48 | + @functools.wraps(func) |
| 49 | + async def decorated_function_asyc(*args, **kwargs): |
| 50 | + logger.debug("Called Dockerflow check %s", name) |
| 51 | + return await func(*args, **kwargs) |
| 52 | + |
| 53 | + _REGISTERED_CHECKS[name] = decorated_function_asyc |
| 54 | + return decorated_function_asyc |
| 55 | + |
| 56 | + @functools.wraps(func) |
| 57 | + def decorated_function(*args, **kwargs): |
| 58 | + logger.debug("Called Dockerflow check %s", name) |
| 59 | + return func(*args, **kwargs) |
| 60 | + |
| 61 | + _REGISTERED_CHECKS[name] = decorated_function |
| 62 | + return decorated_function |
| 63 | + |
| 64 | + |
| 65 | +def register_partial(func, *args, name=None): |
| 66 | + """ |
| 67 | + Registers a given check callback that will be called with the provided |
| 68 | + arguments using `functools.partial()`. For example: |
| 69 | +
|
| 70 | + .. code-block:: python |
| 71 | +
|
| 72 | + dockerflow.register_partial(check_redis_connected, redis) |
| 73 | +
|
| 74 | + """ |
| 75 | + if name is None: |
| 76 | + name = func.__name__ |
| 77 | + |
| 78 | + logger.debug("Register Dockerflow check %s with partially applied arguments" % name) |
| 79 | + partial = functools.wraps(func)(functools.partial(func, *args)) |
| 80 | + return register(func=partial, name=name) |
| 81 | + |
| 82 | + |
| 83 | +def get_checks(): |
| 84 | + return _REGISTERED_CHECKS |
| 85 | + |
| 86 | + |
| 87 | +def clear_checks(): |
| 88 | + global _REGISTERED_CHECKS |
| 89 | + _REGISTERED_CHECKS = dict() |
| 90 | + |
| 91 | + |
| 92 | +@dataclass |
| 93 | +class ChecksResults: |
| 94 | + """ |
| 95 | + Represents the results of running checks. |
| 96 | +
|
| 97 | + This data class holds the results of running a collection of checks. It includes |
| 98 | + details about each check's outcome, their statuses, and the overall result level. |
| 99 | +
|
| 100 | + :param details: A dictionary containing detailed information about each check's |
| 101 | + outcome, with check names as keys and dictionaries of details as values. |
| 102 | + :type details: Dict[str, Dict[str, Any]] |
| 103 | +
|
| 104 | + :param statuses: A dictionary containing the status of each check, with check names |
| 105 | + as keys and statuses as values (e.g., 'pass', 'fail', 'warning'). |
| 106 | + :type statuses: Dict[str, str] |
| 107 | +
|
| 108 | + :param level: An integer representing the overall result level of the checks |
| 109 | + :type level: int |
| 110 | + """ |
| 111 | + |
| 112 | + details: Dict[str, Dict[str, Any]] |
| 113 | + statuses: Dict[str, str] |
| 114 | + level: int |
| 115 | + |
| 116 | + |
| 117 | +async def _run_check_async(check): |
| 118 | + name, check_fn = check |
| 119 | + if _iscoroutinefunction_or_partial(check_fn): |
| 120 | + errors = await check_fn() |
| 121 | + else: |
| 122 | + loop = asyncio.get_event_loop() |
| 123 | + errors = await loop.run_in_executor(None, check_fn) |
| 124 | + |
| 125 | + return (name, errors) |
| 126 | + |
| 127 | + |
| 128 | +async def run_checks_async( |
| 129 | + checks: Iterable[Tuple[str, CheckFn]], |
| 130 | + silenced_check_ids: Optional[Iterable[str]] = None, |
| 131 | +) -> ChecksResults: |
| 132 | + """ |
| 133 | + Run checks concurrently and return the results. |
| 134 | +
|
| 135 | + Executes a collection of checks concurrently, supporting both synchronous and |
| 136 | + asynchronous checks. The results include the outcome of each check and can be |
| 137 | + further processed. |
| 138 | +
|
| 139 | + :param checks: An iterable of tuples where each tuple contains a check name and a |
| 140 | + check function. |
| 141 | + :type checks: Iterable[Tuple[str, CheckFn]] |
| 142 | +
|
| 143 | + :param silenced_check_ids: A list of check IDs that should be omitted from the |
| 144 | + results. |
| 145 | + :type silenced_check_ids: List[str] |
| 146 | +
|
| 147 | + :return: An instance of ChecksResults containing detailed information about each |
| 148 | + check's outcome, their statuses, and the overall result level. |
| 149 | + :rtype: ChecksResults |
| 150 | + """ |
| 151 | + if silenced_check_ids is None: |
| 152 | + silenced_check_ids = [] |
| 153 | + |
| 154 | + tasks = (_run_check_async(check) for check in checks) |
| 155 | + results = await asyncio.gather(*tasks) |
| 156 | + return _build_results_payload(results, silenced_check_ids) |
| 157 | + |
| 158 | + |
| 159 | +def run_checks( |
| 160 | + checks: Iterable[Tuple[str, CheckFn]], |
| 161 | + silenced_check_ids: Optional[Iterable[str]] = None, |
| 162 | +) -> ChecksResults: |
| 163 | + """ |
| 164 | + Run checks synchronously and return the results. |
| 165 | +
|
| 166 | + Executes a collection of checks and returns the results. The results include the |
| 167 | + outcome of each check and can be further processed. |
| 168 | +
|
| 169 | + :param checks: An iterable of tuples where each tuple contains a check name and a |
| 170 | + check function. |
| 171 | + :type checks: Iterable[Tuple[str, CheckFn]] |
| 172 | +
|
| 173 | + :param silenced_check_ids: A list of check IDs that should be omitted from the |
| 174 | + results. |
| 175 | + :type silenced_check_ids: List[str] |
| 176 | +
|
| 177 | + :return: An instance of ChecksResults containing detailed information about each |
| 178 | + check's outcome, their statuses, and the overall result level. |
| 179 | + :rtype: ChecksResults |
| 180 | + """ |
| 181 | + if silenced_check_ids is None: |
| 182 | + silenced_check_ids = [] |
| 183 | + results = [(name, check()) for name, check in checks] |
| 184 | + return _build_results_payload(results, silenced_check_ids) |
| 185 | + |
| 186 | + |
| 187 | +def _build_results_payload( |
| 188 | + checks_results: Iterable[Tuple[str, Iterable[CheckMessage]]], |
| 189 | + silenced_check_ids, |
| 190 | +): |
| 191 | + details = {} |
| 192 | + statuses = {} |
| 193 | + max_level = 0 |
| 194 | + |
| 195 | + for name, errors in checks_results: |
| 196 | + # Log check results with appropriate level. |
| 197 | + for error in errors: |
| 198 | + logger.log(error.level, "%s: %s", error.id, error.msg) |
| 199 | + |
| 200 | + errors = [e for e in errors if e.id not in silenced_check_ids] |
| 201 | + level = max([0] + [e.level for e in errors]) |
| 202 | + |
| 203 | + detail = { |
| 204 | + "status": level_to_text(level), |
| 205 | + "level": level, |
| 206 | + "messages": {e.id: e.msg for e in errors}, |
| 207 | + } |
| 208 | + statuses[name] = level_to_text(level) |
| 209 | + max_level = max(max_level, level) |
| 210 | + if level > 0: |
| 211 | + details[name] = detail |
| 212 | + |
| 213 | + return ChecksResults(statuses=statuses, details=details, level=max_level) |
0 commit comments