retries.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. import functools
  19. import logging
  20. from inspect import signature
  21. from typing import Callable, TypeVar, overload
  22. from sqlalchemy.exc import DBAPIError
  23. from airflow.configuration import conf
  24. F = TypeVar("F", bound=Callable)
  25. MAX_DB_RETRIES = conf.getint("database", "max_db_retries", fallback=3)
  26. def run_with_db_retries(max_retries: int = MAX_DB_RETRIES, logger: logging.Logger | None = None, **kwargs):
  27. """Return Tenacity Retrying object with project specific default."""
  28. import tenacity
  29. # Default kwargs
  30. retry_kwargs = dict(
  31. retry=tenacity.retry_if_exception_type(exception_types=(DBAPIError)),
  32. wait=tenacity.wait_random_exponential(multiplier=0.5, max=5),
  33. stop=tenacity.stop_after_attempt(max_retries),
  34. reraise=True,
  35. **kwargs,
  36. )
  37. if logger and isinstance(logger, logging.Logger):
  38. retry_kwargs["before_sleep"] = tenacity.before_sleep_log(logger, logging.DEBUG, True)
  39. return tenacity.Retrying(**retry_kwargs)
  40. @overload
  41. def retry_db_transaction(*, retries: int = MAX_DB_RETRIES) -> Callable[[F], F]: ...
  42. @overload
  43. def retry_db_transaction(_func: F) -> F: ...
  44. def retry_db_transaction(_func: Callable | None = None, *, retries: int = MAX_DB_RETRIES, **retry_kwargs):
  45. """
  46. Retry functions in case of ``DBAPIError`` from DB.
  47. It should not be used with ``@provide_session``.
  48. """
  49. def retry_decorator(func: Callable) -> Callable:
  50. # Get Positional argument for 'session'
  51. func_params = signature(func).parameters
  52. try:
  53. # func_params is an ordered dict -- this is the "recommended" way of getting the position
  54. session_args_idx = tuple(func_params).index("session")
  55. except ValueError:
  56. raise ValueError(f"Function {func.__qualname__} has no `session` argument")
  57. # We don't need this anymore -- ensure we don't keep a reference to it by mistake
  58. del func_params
  59. @functools.wraps(func)
  60. def wrapped_function(*args, **kwargs):
  61. if args and hasattr(args[0], "logger"):
  62. logger = args[0].logger()
  63. elif args and hasattr(args[0], "log"):
  64. logger = args[0].log
  65. else:
  66. logger = logging.getLogger(func.__module__)
  67. # Get session from args or kwargs
  68. if "session" in kwargs:
  69. session = kwargs["session"]
  70. elif len(args) > session_args_idx:
  71. session = args[session_args_idx]
  72. else:
  73. raise TypeError(f"session is a required argument for {func.__qualname__}")
  74. for attempt in run_with_db_retries(max_retries=retries, logger=logger, **retry_kwargs):
  75. with attempt:
  76. logger.debug(
  77. "Running %s with retries. Try %d of %d",
  78. func.__qualname__,
  79. attempt.retry_state.attempt_number,
  80. retries,
  81. )
  82. try:
  83. return func(*args, **kwargs)
  84. except DBAPIError:
  85. session.rollback()
  86. raise
  87. return wrapped_function
  88. # Allow using decorator with and without arguments
  89. if _func is None:
  90. return retry_decorator
  91. else:
  92. return retry_decorator(_func)