helpers.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain 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,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. from __future__ import annotations
  19. import copy
  20. import itertools
  21. import re
  22. import signal
  23. import warnings
  24. from datetime import datetime
  25. from functools import reduce
  26. from typing import TYPE_CHECKING, Any, Callable, Generator, Iterable, Mapping, MutableMapping, TypeVar, cast
  27. from lazy_object_proxy import Proxy
  28. from airflow.configuration import conf
  29. from airflow.exceptions import AirflowException, RemovedInAirflow3Warning
  30. from airflow.utils.module_loading import import_string
  31. from airflow.utils.types import NOTSET
  32. if TYPE_CHECKING:
  33. import jinja2
  34. from airflow.models.taskinstance import TaskInstance
  35. from airflow.utils.context import Context
  36. KEY_REGEX = re.compile(r"^[\w.-]+$")
  37. GROUP_KEY_REGEX = re.compile(r"^[\w-]+$")
  38. CAMELCASE_TO_SNAKE_CASE_REGEX = re.compile(r"(?!^)([A-Z]+)")
  39. T = TypeVar("T")
  40. S = TypeVar("S")
  41. def validate_key(k: str, max_length: int = 250):
  42. """Validate value used as a key."""
  43. if not isinstance(k, str):
  44. raise TypeError(f"The key has to be a string and is {type(k)}:{k}")
  45. if len(k) > max_length:
  46. raise AirflowException(f"The key has to be less than {max_length} characters")
  47. if not KEY_REGEX.match(k):
  48. raise AirflowException(
  49. f"The key {k!r} has to be made of alphanumeric characters, dashes, "
  50. f"dots and underscores exclusively"
  51. )
  52. def validate_instance_args(instance: object, expected_arg_types: dict[str, Any]) -> None:
  53. """Validate that the instance has the expected types for the arguments."""
  54. for arg_name, expected_arg_type in expected_arg_types.items():
  55. instance_arg_value = getattr(instance, arg_name, None)
  56. if instance_arg_value is not None and not isinstance(instance_arg_value, expected_arg_type):
  57. raise TypeError(
  58. f"'{arg_name}' has an invalid type {type(instance_arg_value)} with value "
  59. f"{instance_arg_value}, expected type is {expected_arg_type}"
  60. )
  61. def validate_group_key(k: str, max_length: int = 200):
  62. """Validate value used as a group key."""
  63. if not isinstance(k, str):
  64. raise TypeError(f"The key has to be a string and is {type(k)}:{k}")
  65. if len(k) > max_length:
  66. raise AirflowException(f"The key has to be less than {max_length} characters")
  67. if not GROUP_KEY_REGEX.match(k):
  68. raise AirflowException(
  69. f"The key {k!r} has to be made of alphanumeric characters, dashes and underscores exclusively"
  70. )
  71. def alchemy_to_dict(obj: Any) -> dict | None:
  72. """Transform a SQLAlchemy model instance into a dictionary."""
  73. if not obj:
  74. return None
  75. output = {}
  76. for col in obj.__table__.columns:
  77. value = getattr(obj, col.name)
  78. if isinstance(value, datetime):
  79. value = value.isoformat()
  80. output[col.name] = value
  81. return output
  82. def ask_yesno(question: str, default: bool | None = None) -> bool:
  83. """Get a yes or no answer from the user."""
  84. yes = {"yes", "y"}
  85. no = {"no", "n"}
  86. print(question)
  87. while True:
  88. choice = input().lower()
  89. if choice == "" and default is not None:
  90. return default
  91. if choice in yes:
  92. return True
  93. if choice in no:
  94. return False
  95. print("Please respond with y/yes or n/no.")
  96. def prompt_with_timeout(question: str, timeout: int, default: bool | None = None) -> bool:
  97. """Ask the user a question and timeout if they don't respond."""
  98. def handler(signum, frame):
  99. raise AirflowException(f"Timeout {timeout}s reached")
  100. signal.signal(signal.SIGALRM, handler)
  101. signal.alarm(timeout)
  102. try:
  103. return ask_yesno(question, default)
  104. finally:
  105. signal.alarm(0)
  106. def is_container(obj: Any) -> bool:
  107. """Test if an object is a container (iterable) but not a string."""
  108. if isinstance(obj, Proxy):
  109. # Proxy of any object is considered a container because it implements __iter__
  110. # to forward the call to the lazily initialized object
  111. # Unwrap Proxy before checking __iter__ to evaluate the proxied object
  112. obj = obj.__wrapped__
  113. return hasattr(obj, "__iter__") and not isinstance(obj, str)
  114. def as_tuple(obj: Any) -> tuple:
  115. """Return obj as a tuple if obj is a container, otherwise return a tuple containing obj."""
  116. if is_container(obj):
  117. return tuple(obj)
  118. else:
  119. return tuple([obj])
  120. def chunks(items: list[T], chunk_size: int) -> Generator[list[T], None, None]:
  121. """Yield successive chunks of a given size from a list of items."""
  122. if chunk_size <= 0:
  123. raise ValueError("Chunk size must be a positive integer")
  124. for i in range(0, len(items), chunk_size):
  125. yield items[i : i + chunk_size]
  126. def reduce_in_chunks(fn: Callable[[S, list[T]], S], iterable: list[T], initializer: S, chunk_size: int = 0):
  127. """Split the list of items into chunks of a given size and pass each chunk through the reducer."""
  128. if not iterable:
  129. return initializer
  130. if chunk_size == 0:
  131. chunk_size = len(iterable)
  132. return reduce(fn, chunks(iterable, chunk_size), initializer)
  133. def as_flattened_list(iterable: Iterable[Iterable[T]]) -> list[T]:
  134. """
  135. Return an iterable with one level flattened.
  136. >>> as_flattened_list((("blue", "red"), ("green", "yellow", "pink")))
  137. ['blue', 'red', 'green', 'yellow', 'pink']
  138. """
  139. return [e for i in iterable for e in i]
  140. def parse_template_string(template_string: str) -> tuple[str | None, jinja2.Template | None]:
  141. """Parse Jinja template string."""
  142. import jinja2
  143. if "{{" in template_string: # jinja mode
  144. return None, jinja2.Template(template_string)
  145. else:
  146. return template_string, None
  147. def render_log_filename(ti: TaskInstance, try_number, filename_template) -> str:
  148. """
  149. Given task instance, try_number, filename_template, return the rendered log filename.
  150. :param ti: task instance
  151. :param try_number: try_number of the task
  152. :param filename_template: filename template, which can be jinja template or
  153. python string template
  154. """
  155. filename_template, filename_jinja_template = parse_template_string(filename_template)
  156. if filename_jinja_template:
  157. jinja_context = ti.get_template_context()
  158. jinja_context["try_number"] = try_number
  159. return render_template_to_string(filename_jinja_template, jinja_context)
  160. return filename_template.format(
  161. dag_id=ti.dag_id,
  162. task_id=ti.task_id,
  163. execution_date=ti.execution_date.isoformat(),
  164. try_number=try_number,
  165. )
  166. def convert_camel_to_snake(camel_str: str) -> str:
  167. """Convert CamelCase to snake_case."""
  168. return CAMELCASE_TO_SNAKE_CASE_REGEX.sub(r"_\1", camel_str).lower()
  169. def merge_dicts(dict1: dict, dict2: dict) -> dict:
  170. """
  171. Merge two dicts recursively, returning new dict (input dict is not mutated).
  172. Lists are not concatenated. Items in dict2 overwrite those also found in dict1.
  173. """
  174. merged = dict1.copy()
  175. for k, v in dict2.items():
  176. if k in merged and isinstance(v, dict):
  177. merged[k] = merge_dicts(merged.get(k, {}), v)
  178. else:
  179. merged[k] = v
  180. return merged
  181. def partition(pred: Callable[[T], bool], iterable: Iterable[T]) -> tuple[Iterable[T], Iterable[T]]:
  182. """Use a predicate to partition entries into false entries and true entries."""
  183. iter_1, iter_2 = itertools.tee(iterable)
  184. return itertools.filterfalse(pred, iter_1), filter(pred, iter_2)
  185. def chain(*args, **kwargs):
  186. """Use `airflow.models.baseoperator.chain`, this function is deprecated."""
  187. warnings.warn(
  188. "This function is deprecated. Please use `airflow.models.baseoperator.chain`.",
  189. RemovedInAirflow3Warning,
  190. stacklevel=2,
  191. )
  192. return import_string("airflow.models.baseoperator.chain")(*args, **kwargs)
  193. def cross_downstream(*args, **kwargs):
  194. """Use `airflow.models.baseoperator.cross_downstream`, this function is deprecated."""
  195. warnings.warn(
  196. "This function is deprecated. Please use `airflow.models.baseoperator.cross_downstream`.",
  197. RemovedInAirflow3Warning,
  198. stacklevel=2,
  199. )
  200. return import_string("airflow.models.baseoperator.cross_downstream")(*args, **kwargs)
  201. def build_airflow_url_with_query(query: dict[str, Any]) -> str:
  202. """
  203. Build airflow url using base_url and default_view and provided query.
  204. For example:
  205. http://0.0.0.0:8000/base/graph?dag_id=my-task&root=&execution_date=2020-10-27T10%3A59%3A25.615587
  206. """
  207. import flask
  208. view = conf.get_mandatory_value("webserver", "dag_default_view").lower()
  209. return flask.url_for(f"Airflow.{view}", **query)
  210. # The 'template' argument is typed as Any because the jinja2.Template is too
  211. # dynamic to be effectively type-checked.
  212. def render_template(template: Any, context: MutableMapping[str, Any], *, native: bool) -> Any:
  213. """
  214. Render a Jinja2 template with given Airflow context.
  215. The default implementation of ``jinja2.Template.render()`` converts the
  216. input context into dict eagerly many times, which triggers deprecation
  217. messages in our custom context class. This takes the implementation apart
  218. and retain the context mapping without resolving instead.
  219. :param template: A Jinja2 template to render.
  220. :param context: The Airflow task context to render the template with.
  221. :param native: If set to *True*, render the template into a native type. A
  222. DAG can enable this with ``render_template_as_native_obj=True``.
  223. :returns: The render result.
  224. """
  225. context = copy.copy(context)
  226. env = template.environment
  227. if template.globals:
  228. context.update((k, v) for k, v in template.globals.items() if k not in context)
  229. try:
  230. nodes = template.root_render_func(env.context_class(env, context, template.name, template.blocks))
  231. except Exception:
  232. env.handle_exception() # Rewrite traceback to point to the template.
  233. if native:
  234. import jinja2.nativetypes
  235. return jinja2.nativetypes.native_concat(nodes)
  236. return "".join(nodes)
  237. def render_template_to_string(template: jinja2.Template, context: Context) -> str:
  238. """Shorthand to ``render_template(native=False)`` with better typing support."""
  239. return render_template(template, cast(MutableMapping[str, Any], context), native=False)
  240. def render_template_as_native(template: jinja2.Template, context: Context) -> Any:
  241. """Shorthand to ``render_template(native=True)`` with better typing support."""
  242. return render_template(template, cast(MutableMapping[str, Any], context), native=True)
  243. def exactly_one(*args) -> bool:
  244. """
  245. Return True if exactly one of *args is "truthy", and False otherwise.
  246. If user supplies an iterable, we raise ValueError and force them to unpack.
  247. """
  248. if is_container(args[0]):
  249. raise ValueError(
  250. "Not supported for iterable args. Use `*` to unpack your iterable in the function call."
  251. )
  252. return sum(map(bool, args)) == 1
  253. def at_most_one(*args) -> bool:
  254. """
  255. Return True if at most one of *args is "truthy", and False otherwise.
  256. NOTSET is treated the same as None.
  257. If user supplies an iterable, we raise ValueError and force them to unpack.
  258. """
  259. def is_set(val):
  260. if val is NOTSET:
  261. return False
  262. else:
  263. return bool(val)
  264. return sum(map(is_set, args)) in (0, 1)
  265. def prune_dict(val: Any, mode="strict"):
  266. """
  267. Given dict ``val``, returns new dict based on ``val`` with all empty elements removed.
  268. What constitutes "empty" is controlled by the ``mode`` parameter. If mode is 'strict'
  269. then only ``None`` elements will be removed. If mode is ``truthy``, then element ``x``
  270. will be removed if ``bool(x) is False``.
  271. """
  272. def is_empty(x):
  273. if mode == "strict":
  274. return x is None
  275. elif mode == "truthy":
  276. return bool(x) is False
  277. raise ValueError("allowable values for `mode` include 'truthy' and 'strict'")
  278. if isinstance(val, dict):
  279. new_dict = {}
  280. for k, v in val.items():
  281. if is_empty(v):
  282. continue
  283. elif isinstance(v, (list, dict)):
  284. new_val = prune_dict(v, mode=mode)
  285. if not is_empty(new_val):
  286. new_dict[k] = new_val
  287. else:
  288. new_dict[k] = v
  289. return new_dict
  290. elif isinstance(val, list):
  291. new_list = []
  292. for v in val:
  293. if is_empty(v):
  294. continue
  295. elif isinstance(v, (list, dict)):
  296. new_val = prune_dict(v, mode=mode)
  297. if not is_empty(new_val):
  298. new_list.append(new_val)
  299. else:
  300. new_list.append(v)
  301. return new_list
  302. else:
  303. return val
  304. def prevent_duplicates(kwargs1: dict[str, Any], kwargs2: Mapping[str, Any], *, fail_reason: str) -> None:
  305. """
  306. Ensure *kwargs1* and *kwargs2* do not contain common keys.
  307. :raises TypeError: If common keys are found.
  308. """
  309. duplicated_keys = set(kwargs1).intersection(kwargs2)
  310. if not duplicated_keys:
  311. return
  312. if len(duplicated_keys) == 1:
  313. raise TypeError(f"{fail_reason} argument: {duplicated_keys.pop()}")
  314. duplicated_keys_display = ", ".join(sorted(duplicated_keys))
  315. raise TypeError(f"{fail_reason} arguments: {duplicated_keys_display}")