apache-airflow-providers-standard 1.0.0.dev1__py3-none-any.whl → 1.0.0rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of apache-airflow-providers-standard might be problematic. Click here for more details.

Files changed (50) hide show
  1. airflow/providers/standard/LICENSE +0 -52
  2. airflow/providers/standard/__init__.py +23 -1
  3. airflow/providers/standard/decorators/__init__.py +16 -0
  4. airflow/providers/standard/decorators/bash.py +121 -0
  5. airflow/providers/standard/decorators/branch_external_python.py +63 -0
  6. airflow/providers/standard/decorators/branch_python.py +62 -0
  7. airflow/providers/standard/decorators/branch_virtualenv.py +62 -0
  8. airflow/providers/standard/decorators/external_python.py +70 -0
  9. airflow/providers/standard/decorators/python.py +86 -0
  10. airflow/providers/standard/decorators/python_virtualenv.py +67 -0
  11. airflow/providers/standard/decorators/sensor.py +83 -0
  12. airflow/providers/standard/decorators/short_circuit.py +65 -0
  13. airflow/providers/standard/get_provider_info.py +78 -7
  14. airflow/providers/standard/hooks/__init__.py +16 -0
  15. airflow/providers/standard/hooks/filesystem.py +89 -0
  16. airflow/providers/standard/hooks/package_index.py +95 -0
  17. airflow/providers/standard/hooks/subprocess.py +119 -0
  18. airflow/providers/standard/operators/bash.py +73 -56
  19. airflow/providers/standard/operators/branch.py +105 -0
  20. airflow/providers/standard/operators/datetime.py +15 -5
  21. airflow/providers/standard/operators/empty.py +39 -0
  22. airflow/providers/standard/operators/latest_only.py +115 -0
  23. airflow/providers/standard/operators/python.py +1143 -0
  24. airflow/providers/standard/operators/smooth.py +38 -0
  25. airflow/providers/standard/operators/trigger_dagrun.py +370 -0
  26. airflow/providers/standard/operators/weekday.py +19 -9
  27. airflow/providers/standard/sensors/bash.py +15 -11
  28. airflow/providers/standard/sensors/date_time.py +32 -8
  29. airflow/providers/standard/sensors/external_task.py +593 -0
  30. airflow/providers/standard/sensors/filesystem.py +158 -0
  31. airflow/providers/standard/sensors/python.py +84 -0
  32. airflow/providers/standard/sensors/time.py +28 -5
  33. airflow/providers/standard/sensors/time_delta.py +68 -15
  34. airflow/providers/standard/sensors/weekday.py +25 -7
  35. airflow/providers/standard/triggers/__init__.py +16 -0
  36. airflow/providers/standard/triggers/external_task.py +288 -0
  37. airflow/providers/standard/triggers/file.py +131 -0
  38. airflow/providers/standard/triggers/temporal.py +113 -0
  39. airflow/providers/standard/utils/__init__.py +16 -0
  40. airflow/providers/standard/utils/python_virtualenv.py +209 -0
  41. airflow/providers/standard/utils/python_virtualenv_script.jinja2 +82 -0
  42. airflow/providers/standard/utils/sensor_helper.py +137 -0
  43. airflow/providers/standard/utils/skipmixin.py +192 -0
  44. airflow/providers/standard/utils/weekday.py +77 -0
  45. airflow/providers/standard/version_compat.py +36 -0
  46. {apache_airflow_providers_standard-1.0.0.dev1.dist-info → apache_airflow_providers_standard-1.0.0rc1.dist-info}/METADATA +12 -31
  47. apache_airflow_providers_standard-1.0.0rc1.dist-info/RECORD +51 -0
  48. {apache_airflow_providers_standard-1.0.0.dev1.dist-info → apache_airflow_providers_standard-1.0.0rc1.dist-info}/WHEEL +1 -1
  49. apache_airflow_providers_standard-1.0.0.dev1.dist-info/RECORD +0 -17
  50. {apache_airflow_providers_standard-1.0.0.dev1.dist-info → apache_airflow_providers_standard-1.0.0rc1.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,1143 @@
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
+
20
+ import inspect
21
+ import json
22
+ import logging
23
+ import os
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ import textwrap
28
+ import types
29
+ from abc import ABCMeta, abstractmethod
30
+ from collections.abc import Collection, Container, Iterable, Mapping, Sequence
31
+ from functools import cache
32
+ from pathlib import Path
33
+ from tempfile import TemporaryDirectory
34
+ from typing import TYPE_CHECKING, Any, Callable, NamedTuple, cast
35
+
36
+ import lazy_object_proxy
37
+
38
+ from airflow.exceptions import (
39
+ AirflowConfigException,
40
+ AirflowException,
41
+ AirflowSkipException,
42
+ DeserializingResultError,
43
+ )
44
+ from airflow.models.baseoperator import BaseOperator
45
+ from airflow.models.variable import Variable
46
+ from airflow.providers.standard.utils.python_virtualenv import prepare_virtualenv, write_python_script
47
+ from airflow.providers.standard.version_compat import AIRFLOW_V_2_10_PLUS, AIRFLOW_V_3_0_PLUS
48
+ from airflow.utils import hashlib_wrapper
49
+ from airflow.utils.context import context_copy_partial, context_merge
50
+ from airflow.utils.file import get_unique_dag_module_name
51
+ from airflow.utils.operator_helpers import KeywordParameters
52
+ from airflow.utils.process_utils import execute_in_subprocess, execute_in_subprocess_with_kwargs
53
+
54
+ if AIRFLOW_V_3_0_PLUS:
55
+ from airflow.providers.standard.operators.branch import BranchMixIn
56
+ from airflow.providers.standard.utils.skipmixin import SkipMixin
57
+ else:
58
+ from airflow.models.skipmixin import SkipMixin
59
+ from airflow.operators.branch import BranchMixIn # type: ignore[no-redef]
60
+
61
+
62
+ log = logging.getLogger(__name__)
63
+
64
+ if TYPE_CHECKING:
65
+ from typing import Literal
66
+
67
+ from pendulum.datetime import DateTime
68
+
69
+ from airflow.sdk.execution_time.callback_runner import ExecutionCallableRunner
70
+ from airflow.sdk.execution_time.context import OutletEventAccessorsProtocol
71
+
72
+ try:
73
+ from airflow.sdk.definitions.context import Context
74
+ except ImportError: # TODO: Remove once provider drops support for Airflow 2
75
+ from airflow.utils.context import Context
76
+
77
+ _SerializerTypeDef = Literal["pickle", "cloudpickle", "dill"]
78
+
79
+
80
+ @cache
81
+ def _parse_version_info(text: str) -> tuple[int, int, int, str, int]:
82
+ """Parse python version info from a text."""
83
+ parts = text.strip().split(".")
84
+ if len(parts) != 5:
85
+ msg = f"Invalid Python version info, expected 5 components separated by '.', but got {text!r}."
86
+ raise ValueError(msg)
87
+ try:
88
+ return int(parts[0]), int(parts[1]), int(parts[2]), parts[3], int(parts[4])
89
+ except ValueError:
90
+ msg = f"Unable to convert parts {parts} parsed from {text!r} to (int, int, int, str, int)."
91
+ raise ValueError(msg) from None
92
+
93
+
94
+ class _PythonVersionInfo(NamedTuple):
95
+ """Provide the same interface as ``sys.version_info``."""
96
+
97
+ major: int
98
+ minor: int
99
+ micro: int
100
+ releaselevel: str
101
+ serial: int
102
+
103
+ @classmethod
104
+ def from_executable(cls, executable: str) -> _PythonVersionInfo:
105
+ """Parse python version info from an executable."""
106
+ cmd = [executable, "-c", 'import sys; print(".".join(map(str, sys.version_info)))']
107
+ try:
108
+ result = subprocess.check_output(cmd, text=True)
109
+ except Exception as e:
110
+ raise ValueError(f"Error while executing command {cmd}: {e}")
111
+ return cls(*_parse_version_info(result.strip()))
112
+
113
+
114
+ class PythonOperator(BaseOperator):
115
+ """
116
+ Executes a Python callable.
117
+
118
+ .. seealso::
119
+ For more information on how to use this operator, take a look at the guide:
120
+ :ref:`howto/operator:PythonOperator`
121
+
122
+ When running your callable, Airflow will pass a set of keyword arguments that can be used in your
123
+ function. This set of kwargs correspond exactly to what you can use in your jinja templates.
124
+ For this to work, you need to define ``**kwargs`` in your function header, or you can add directly the
125
+ keyword arguments you would like to get - for example with the below code your callable will get
126
+ the values of ``ti`` context variables.
127
+
128
+ With explicit arguments:
129
+
130
+ .. code-block:: python
131
+
132
+ def my_python_callable(ti):
133
+ pass
134
+
135
+ With kwargs:
136
+
137
+ .. code-block:: python
138
+
139
+ def my_python_callable(**kwargs):
140
+ ti = kwargs["ti"]
141
+
142
+
143
+ :param python_callable: A reference to an object that is callable
144
+ :param op_args: a list of positional arguments that will get unpacked when
145
+ calling your callable
146
+ :param op_kwargs: a dictionary of keyword arguments that will get unpacked
147
+ in your function
148
+ :param templates_dict: a dictionary where the values are templates that
149
+ will get templated by the Airflow engine sometime between
150
+ ``__init__`` and ``execute`` takes place and are made available
151
+ in your callable's context after the template has been applied. (templated)
152
+ :param templates_exts: a list of file extensions to resolve while
153
+ processing templated fields, for examples ``['.sql', '.hql']``
154
+ :param show_return_value_in_logs: a bool value whether to show return_value
155
+ logs. Defaults to True, which allows return value log output.
156
+ It can be set to False to prevent log output of return value when you return huge data
157
+ such as transmission a large amount of XCom to TaskAPI.
158
+ """
159
+
160
+ template_fields: Sequence[str] = ("templates_dict", "op_args", "op_kwargs")
161
+ template_fields_renderers = {"templates_dict": "json", "op_args": "py", "op_kwargs": "py"}
162
+ BLUE = "#ffefeb"
163
+ ui_color = BLUE
164
+
165
+ # since we won't mutate the arguments, we should just do the shallow copy
166
+ # there are some cases we can't deepcopy the objects(e.g protobuf).
167
+ shallow_copy_attrs: Sequence[str] = ("python_callable", "op_kwargs")
168
+
169
+ def __init__(
170
+ self,
171
+ *,
172
+ python_callable: Callable,
173
+ op_args: Collection[Any] | None = None,
174
+ op_kwargs: Mapping[str, Any] | None = None,
175
+ templates_dict: dict[str, Any] | None = None,
176
+ templates_exts: Sequence[str] | None = None,
177
+ show_return_value_in_logs: bool = True,
178
+ **kwargs,
179
+ ) -> None:
180
+ super().__init__(**kwargs)
181
+ if not callable(python_callable):
182
+ raise AirflowException("`python_callable` param must be callable")
183
+ self.python_callable = python_callable
184
+ self.op_args = op_args or ()
185
+ self.op_kwargs = op_kwargs or {}
186
+ self.templates_dict = templates_dict
187
+ if templates_exts:
188
+ self.template_ext = templates_exts
189
+ self.show_return_value_in_logs = show_return_value_in_logs
190
+
191
+ def execute(self, context: Context) -> Any:
192
+ context_merge(context, self.op_kwargs, templates_dict=self.templates_dict)
193
+ self.op_kwargs = self.determine_kwargs(context)
194
+
195
+ # This needs to be lazy because subclasses may implement execute_callable
196
+ # by running a separate process that can't use the eager result.
197
+ def __prepare_execution() -> tuple[ExecutionCallableRunner, OutletEventAccessorsProtocol] | None:
198
+ if AIRFLOW_V_3_0_PLUS:
199
+ from airflow.sdk.execution_time.callback_runner import create_executable_runner
200
+ from airflow.sdk.execution_time.context import context_get_outlet_events
201
+
202
+ return create_executable_runner, context_get_outlet_events(context)
203
+ if AIRFLOW_V_2_10_PLUS:
204
+ from airflow.utils.context import context_get_outlet_events # type: ignore
205
+ from airflow.utils.operator_helpers import ExecutionCallableRunner # type: ignore
206
+
207
+ return ExecutionCallableRunner, context_get_outlet_events(context)
208
+ return None
209
+
210
+ self.__prepare_execution = __prepare_execution
211
+
212
+ return_value = self.execute_callable()
213
+ if self.show_return_value_in_logs:
214
+ self.log.info("Done. Returned value was: %s", return_value)
215
+ else:
216
+ self.log.info("Done. Returned value not shown")
217
+
218
+ return return_value
219
+
220
+ def determine_kwargs(self, context: Mapping[str, Any]) -> Mapping[str, Any]:
221
+ return KeywordParameters.determine(self.python_callable, self.op_args, context).unpacking()
222
+
223
+ __prepare_execution: Callable[[], tuple[ExecutionCallableRunner, OutletEventAccessorsProtocol] | None]
224
+
225
+ def execute_callable(self) -> Any:
226
+ """
227
+ Call the python callable with the given arguments.
228
+
229
+ :return: the return value of the call.
230
+ """
231
+ if (execution_preparation := self.__prepare_execution()) is None:
232
+ return self.python_callable(*self.op_args, **self.op_kwargs)
233
+ create_execution_runner, asset_events = execution_preparation
234
+ runner = create_execution_runner(self.python_callable, asset_events, logger=self.log)
235
+ return runner.run(*self.op_args, **self.op_kwargs)
236
+
237
+
238
+ class BranchPythonOperator(PythonOperator, BranchMixIn):
239
+ """
240
+ A workflow can "branch" or follow a path after the execution of this task.
241
+
242
+ It derives the PythonOperator and expects a Python function that returns
243
+ a single task_id, a single task_group_id, or a list of task_ids and/or
244
+ task_group_ids to follow. The task_id(s) and/or task_group_id(s) returned
245
+ should point to a task or task group directly downstream from {self}. All
246
+ other "branches" or directly downstream tasks are marked with a state of
247
+ ``skipped`` so that these paths can't move forward. The ``skipped`` states
248
+ are propagated downstream to allow for the DAG state to fill up and
249
+ the DAG run's state to be inferred.
250
+ """
251
+
252
+ inherits_from_skipmixin = True
253
+
254
+ def execute(self, context: Context) -> Any:
255
+ return self.do_branch(context, super().execute(context))
256
+
257
+
258
+ class ShortCircuitOperator(PythonOperator, SkipMixin):
259
+ """
260
+ Allows a pipeline to continue based on the result of a ``python_callable``.
261
+
262
+ The ShortCircuitOperator is derived from the PythonOperator and evaluates the result of a
263
+ ``python_callable``. If the returned result is False or a falsy value, the pipeline will be
264
+ short-circuited. Downstream tasks will be marked with a state of "skipped" based on the short-circuiting
265
+ mode configured. If the returned result is True or a truthy value, downstream tasks proceed as normal and
266
+ an ``XCom`` of the returned result is pushed.
267
+
268
+ The short-circuiting can be configured to either respect or ignore the ``trigger_rule`` set for
269
+ downstream tasks. If ``ignore_downstream_trigger_rules`` is set to True, the default setting, all
270
+ downstream tasks are skipped without considering the ``trigger_rule`` defined for tasks. However, if this
271
+ parameter is set to False, the direct downstream tasks are skipped but the specified ``trigger_rule`` for
272
+ other subsequent downstream tasks are respected. In this mode, the operator assumes the direct downstream
273
+ tasks were purposely meant to be skipped but perhaps not other subsequent tasks.
274
+
275
+ .. seealso::
276
+ For more information on how to use this operator, take a look at the guide:
277
+ :ref:`howto/operator:ShortCircuitOperator`
278
+
279
+ :param ignore_downstream_trigger_rules: If set to True, all downstream tasks from this operator task will
280
+ be skipped. This is the default behavior. If set to False, the direct, downstream task(s) will be
281
+ skipped but the ``trigger_rule`` defined for all other downstream tasks will be respected.
282
+ """
283
+
284
+ inherits_from_skipmixin = True
285
+
286
+ def __init__(self, *, ignore_downstream_trigger_rules: bool = True, **kwargs) -> None:
287
+ super().__init__(**kwargs)
288
+ self.ignore_downstream_trigger_rules = ignore_downstream_trigger_rules
289
+
290
+ def execute(self, context: Context) -> Any:
291
+ condition = super().execute(context)
292
+ self.log.info("Condition result is %s", condition)
293
+
294
+ if condition:
295
+ self.log.info("Proceeding with downstream tasks...")
296
+ return condition
297
+
298
+ if not self.downstream_task_ids:
299
+ self.log.info("No downstream tasks; nothing to do.")
300
+ return condition
301
+
302
+ dag_run = context["dag_run"]
303
+
304
+ def get_tasks_to_skip():
305
+ if self.ignore_downstream_trigger_rules is True:
306
+ tasks = context["task"].get_flat_relatives(upstream=False)
307
+ else:
308
+ tasks = context["task"].get_direct_relatives(upstream=False)
309
+ for t in tasks:
310
+ if not t.is_teardown:
311
+ yield t
312
+
313
+ to_skip = get_tasks_to_skip()
314
+
315
+ # this lets us avoid an intermediate list unless debug logging
316
+ if self.log.getEffectiveLevel() <= logging.DEBUG:
317
+ self.log.debug("Downstream task IDs %s", to_skip := list(get_tasks_to_skip()))
318
+
319
+ self.log.info("Skipping downstream tasks")
320
+ if AIRFLOW_V_3_0_PLUS:
321
+ self.skip(
322
+ ti=context["ti"],
323
+ tasks=to_skip,
324
+ )
325
+ else:
326
+ if to_skip:
327
+ self.skip(
328
+ dag_run=context["dag_run"],
329
+ tasks=to_skip,
330
+ execution_date=cast("DateTime", dag_run.logical_date), # type: ignore[call-arg, union-attr]
331
+ map_index=context["ti"].map_index,
332
+ )
333
+
334
+ self.log.info("Done.")
335
+ # returns the result of the super execute method as it is instead of returning None
336
+ return condition
337
+
338
+
339
+ def _load_pickle():
340
+ import pickle
341
+
342
+ return pickle
343
+
344
+
345
+ def _load_dill():
346
+ try:
347
+ import dill
348
+ except ModuleNotFoundError:
349
+ log.error("Unable to import `dill` module. Please please make sure that it installed.")
350
+ raise
351
+ return dill
352
+
353
+
354
+ def _load_cloudpickle():
355
+ try:
356
+ import cloudpickle
357
+ except ModuleNotFoundError:
358
+ log.error(
359
+ "Unable to import `cloudpickle` module. "
360
+ "Please install it with: pip install 'apache-airflow[cloudpickle]'"
361
+ )
362
+ raise
363
+ return cloudpickle
364
+
365
+
366
+ _SERIALIZERS: dict[_SerializerTypeDef, Any] = {
367
+ "pickle": lazy_object_proxy.Proxy(_load_pickle),
368
+ "dill": lazy_object_proxy.Proxy(_load_dill),
369
+ "cloudpickle": lazy_object_proxy.Proxy(_load_cloudpickle),
370
+ }
371
+
372
+
373
+ class _BasePythonVirtualenvOperator(PythonOperator, metaclass=ABCMeta):
374
+ BASE_SERIALIZABLE_CONTEXT_KEYS = {
375
+ "ds",
376
+ "ds_nodash",
377
+ "expanded_ti_count",
378
+ "inlets",
379
+ "outlets",
380
+ "run_id",
381
+ "task_instance_key_str",
382
+ "test_mode",
383
+ "ts",
384
+ "ts_nodash",
385
+ "ts_nodash_with_tz",
386
+ # The following should be removed when Airflow 2 support is dropped.
387
+ "next_ds",
388
+ "next_ds_nodash",
389
+ "prev_ds",
390
+ "prev_ds_nodash",
391
+ "tomorrow_ds",
392
+ "tomorrow_ds_nodash",
393
+ "yesterday_ds",
394
+ "yesterday_ds_nodash",
395
+ }
396
+ if AIRFLOW_V_3_0_PLUS:
397
+ BASE_SERIALIZABLE_CONTEXT_KEYS.add("task_reschedule_count")
398
+
399
+ PENDULUM_SERIALIZABLE_CONTEXT_KEYS = {
400
+ "data_interval_end",
401
+ "data_interval_start",
402
+ "logical_date",
403
+ "prev_data_interval_end_success",
404
+ "prev_data_interval_start_success",
405
+ "prev_start_date_success",
406
+ "prev_end_date_success",
407
+ # The following should be removed when Airflow 2 support is dropped.
408
+ "execution_date",
409
+ "next_execution_date",
410
+ "prev_execution_date",
411
+ "prev_execution_date_success",
412
+ }
413
+
414
+ AIRFLOW_SERIALIZABLE_CONTEXT_KEYS = {
415
+ "macros",
416
+ "conf",
417
+ "dag",
418
+ "dag_run",
419
+ "task",
420
+ "params",
421
+ "triggering_asset_events",
422
+ # The following should be removed when Airflow 2 support is dropped.
423
+ "triggering_dataset_events",
424
+ }
425
+
426
+ def __init__(
427
+ self,
428
+ *,
429
+ python_callable: Callable,
430
+ serializer: _SerializerTypeDef | None = None,
431
+ op_args: Collection[Any] | None = None,
432
+ op_kwargs: Mapping[str, Any] | None = None,
433
+ string_args: Iterable[str] | None = None,
434
+ templates_dict: dict | None = None,
435
+ templates_exts: list[str] | None = None,
436
+ expect_airflow: bool = True,
437
+ skip_on_exit_code: int | Container[int] | None = None,
438
+ env_vars: dict[str, str] | None = None,
439
+ inherit_env: bool = True,
440
+ **kwargs,
441
+ ):
442
+ if (
443
+ not isinstance(python_callable, types.FunctionType)
444
+ or isinstance(python_callable, types.LambdaType)
445
+ and python_callable.__name__ == "<lambda>"
446
+ ):
447
+ raise ValueError(f"{type(self).__name__} only supports functions for python_callable arg")
448
+ if inspect.isgeneratorfunction(python_callable):
449
+ raise ValueError(f"{type(self).__name__} does not support using 'yield' in python_callable")
450
+ super().__init__(
451
+ python_callable=python_callable,
452
+ op_args=op_args,
453
+ op_kwargs=op_kwargs,
454
+ templates_dict=templates_dict,
455
+ templates_exts=templates_exts,
456
+ **kwargs,
457
+ )
458
+ self.string_args = string_args or []
459
+
460
+ serializer = serializer or "pickle"
461
+ if serializer not in _SERIALIZERS:
462
+ msg = (
463
+ f"Unsupported serializer {serializer!r}. Expected one of {', '.join(map(repr, _SERIALIZERS))}"
464
+ )
465
+ raise AirflowException(msg)
466
+
467
+ self.pickling_library = _SERIALIZERS[serializer]
468
+ self.serializer: _SerializerTypeDef = serializer
469
+
470
+ self.expect_airflow = expect_airflow
471
+ self.skip_on_exit_code = (
472
+ skip_on_exit_code
473
+ if isinstance(skip_on_exit_code, Container)
474
+ else [skip_on_exit_code]
475
+ if skip_on_exit_code is not None
476
+ else []
477
+ )
478
+ self.env_vars = env_vars
479
+ self.inherit_env = inherit_env
480
+
481
+ @abstractmethod
482
+ def _iter_serializable_context_keys(self):
483
+ pass
484
+
485
+ def execute(self, context: Context) -> Any:
486
+ serializable_keys = set(self._iter_serializable_context_keys())
487
+ serializable_context = context_copy_partial(context, serializable_keys)
488
+ return super().execute(context=serializable_context)
489
+
490
+ def get_python_source(self):
491
+ """Return the source of self.python_callable."""
492
+ return textwrap.dedent(inspect.getsource(self.python_callable))
493
+
494
+ def _write_args(self, file: Path):
495
+ if self.op_args or self.op_kwargs:
496
+ self.log.info("Use %r as serializer.", self.serializer)
497
+ file.write_bytes(self.pickling_library.dumps({"args": self.op_args, "kwargs": self.op_kwargs}))
498
+
499
+ def _write_string_args(self, file: Path):
500
+ file.write_text("\n".join(map(str, self.string_args)))
501
+
502
+ def _read_result(self, path: Path):
503
+ if path.stat().st_size == 0:
504
+ return None
505
+ try:
506
+ return self.pickling_library.loads(path.read_bytes())
507
+ except ValueError as value_error:
508
+ raise DeserializingResultError() from value_error
509
+
510
+ def __deepcopy__(self, memo):
511
+ # module objects can't be copied _at all__
512
+ memo[id(self.pickling_library)] = self.pickling_library
513
+ return super().__deepcopy__(memo)
514
+
515
+ def _execute_python_callable_in_subprocess(self, python_path: Path):
516
+ with TemporaryDirectory(prefix="venv-call") as tmp:
517
+ tmp_dir = Path(tmp)
518
+ op_kwargs: dict[str, Any] = dict(self.op_kwargs)
519
+ if self.templates_dict:
520
+ op_kwargs["templates_dict"] = self.templates_dict
521
+ input_path = tmp_dir / "script.in"
522
+ output_path = tmp_dir / "script.out"
523
+ string_args_path = tmp_dir / "string_args.txt"
524
+ script_path = tmp_dir / "script.py"
525
+ termination_log_path = tmp_dir / "termination.log"
526
+ airflow_context_path = tmp_dir / "airflow_context.json"
527
+
528
+ self._write_args(input_path)
529
+ self._write_string_args(string_args_path)
530
+
531
+ jinja_context = {
532
+ "op_args": self.op_args,
533
+ "op_kwargs": op_kwargs,
534
+ "expect_airflow": self.expect_airflow,
535
+ "pickling_library": self.serializer,
536
+ "python_callable": self.python_callable.__name__,
537
+ "python_callable_source": self.get_python_source(),
538
+ }
539
+
540
+ if inspect.getfile(self.python_callable) == self.dag.fileloc:
541
+ jinja_context["modified_dag_module_name"] = get_unique_dag_module_name(self.dag.fileloc)
542
+
543
+ write_python_script(
544
+ jinja_context=jinja_context,
545
+ filename=os.fspath(script_path),
546
+ render_template_as_native_obj=self.dag.render_template_as_native_obj,
547
+ )
548
+
549
+ env_vars = dict(os.environ) if self.inherit_env else {}
550
+ if self.env_vars:
551
+ env_vars.update(self.env_vars)
552
+
553
+ try:
554
+ cmd: list[str] = [
555
+ os.fspath(python_path),
556
+ os.fspath(script_path),
557
+ os.fspath(input_path),
558
+ os.fspath(output_path),
559
+ os.fspath(string_args_path),
560
+ os.fspath(termination_log_path),
561
+ os.fspath(airflow_context_path),
562
+ ]
563
+ if AIRFLOW_V_2_10_PLUS:
564
+ execute_in_subprocess(
565
+ cmd=cmd,
566
+ env=env_vars,
567
+ )
568
+ else:
569
+ execute_in_subprocess_with_kwargs(
570
+ cmd=cmd,
571
+ env=env_vars,
572
+ )
573
+ except subprocess.CalledProcessError as e:
574
+ if e.returncode in self.skip_on_exit_code:
575
+ raise AirflowSkipException(f"Process exited with code {e.returncode}. Skipping.")
576
+ if termination_log_path.exists() and termination_log_path.stat().st_size > 0:
577
+ error_msg = f"Process returned non-zero exit status {e.returncode}.\n"
578
+ with open(termination_log_path) as file:
579
+ error_msg += file.read()
580
+ raise AirflowException(error_msg) from None
581
+ raise
582
+
583
+ if 0 in self.skip_on_exit_code:
584
+ raise AirflowSkipException("Process exited with code 0. Skipping.")
585
+
586
+ return self._read_result(output_path)
587
+
588
+ def determine_kwargs(self, context: Mapping[str, Any]) -> Mapping[str, Any]:
589
+ keyword_params = KeywordParameters.determine(self.python_callable, self.op_args, context)
590
+ if AIRFLOW_V_3_0_PLUS:
591
+ return keyword_params.unpacking()
592
+ return keyword_params.serializing() # type: ignore[attr-defined]
593
+
594
+
595
+ class PythonVirtualenvOperator(_BasePythonVirtualenvOperator):
596
+ """
597
+ Run a function in a virtualenv that is created and destroyed automatically.
598
+
599
+ The function (has certain caveats) must be defined using def, and not be
600
+ part of a class. All imports must happen inside the function
601
+ and no variables outside the scope may be referenced. A global scope
602
+ variable named virtualenv_string_args will be available (populated by
603
+ string_args). In addition, one can pass stuff through op_args and op_kwargs, and one
604
+ can use a return value.
605
+ Note that if your virtualenv runs in a different Python major version than Airflow,
606
+ you cannot use return values, op_args, op_kwargs, or use any macros that are being provided to
607
+ Airflow through plugins. You can use string_args though.
608
+
609
+ .. seealso::
610
+ For more information on how to use this operator, take a look at the guide:
611
+ :ref:`howto/operator:PythonVirtualenvOperator`
612
+
613
+ :param python_callable: A python function with no references to outside variables,
614
+ defined with def, which will be run in a virtual environment.
615
+ :param requirements: Either a list of requirement strings, or a (templated)
616
+ "requirements file" as specified by pip.
617
+ :param python_version: The Python version to run the virtual environment with. Note that
618
+ both 2 and 2.7 are acceptable forms.
619
+ :param serializer: Which serializer use to serialize the args and result. It can be one of the following:
620
+
621
+ - ``"pickle"``: (default) Use pickle for serialization. Included in the Python Standard Library.
622
+ - ``"cloudpickle"``: Use cloudpickle for serialize more complex types,
623
+ this requires to include cloudpickle in your requirements.
624
+ - ``"dill"``: Use dill for serialize more complex types,
625
+ this requires to include dill in your requirements.
626
+ :param system_site_packages: Whether to include
627
+ system_site_packages in your virtual environment.
628
+ See virtualenv documentation for more information.
629
+ :param pip_install_options: a list of pip install options when installing requirements
630
+ See 'pip install -h' for available options
631
+ :param op_args: A list of positional arguments to pass to python_callable.
632
+ :param op_kwargs: A dict of keyword arguments to pass to python_callable.
633
+ :param string_args: Strings that are present in the global var virtualenv_string_args,
634
+ available to python_callable at runtime as a list[str]. Note that args are split
635
+ by newline.
636
+ :param templates_dict: a dictionary where the values are templates that
637
+ will get templated by the Airflow engine sometime between
638
+ ``__init__`` and ``execute`` takes place and are made available
639
+ in your callable's context after the template has been applied
640
+ :param templates_exts: a list of file extensions to resolve while
641
+ processing templated fields, for examples ``['.sql', '.hql']``
642
+ :param expect_airflow: expect Airflow to be installed in the target environment. If true, the operator
643
+ will raise warning if Airflow is not installed, and it will attempt to load Airflow
644
+ macros when starting.
645
+ :param skip_on_exit_code: If python_callable exits with this exit code, leave the task
646
+ in ``skipped`` state (default: None). If set to ``None``, any non-zero
647
+ exit code will be treated as a failure.
648
+ :param index_urls: an optional list of index urls to load Python packages from.
649
+ If not provided the system pip conf will be used to source packages from.
650
+ :param venv_cache_path: Optional path to the virtual environment parent folder in which the
651
+ virtual environment will be cached, creates a sub-folder venv-{hash} whereas hash will be replaced
652
+ with a checksum of requirements. If not provided the virtual environment will be created and deleted
653
+ in a temp folder for every execution.
654
+ :param env_vars: A dictionary containing additional environment variables to set for the virtual
655
+ environment when it is executed.
656
+ :param inherit_env: Whether to inherit the current environment variables when executing the virtual
657
+ environment. If set to ``True``, the virtual environment will inherit the environment variables
658
+ of the parent process (``os.environ``). If set to ``False``, the virtual environment will be
659
+ executed with a clean environment.
660
+ """
661
+
662
+ template_fields: Sequence[str] = tuple(
663
+ {"requirements", "index_urls", "venv_cache_path"}.union(PythonOperator.template_fields)
664
+ )
665
+ template_ext: Sequence[str] = (".txt",)
666
+
667
+ def __init__(
668
+ self,
669
+ *,
670
+ python_callable: Callable,
671
+ requirements: None | Iterable[str] | str = None,
672
+ python_version: str | None = None,
673
+ serializer: _SerializerTypeDef | None = None,
674
+ system_site_packages: bool = True,
675
+ pip_install_options: list[str] | None = None,
676
+ op_args: Collection[Any] | None = None,
677
+ op_kwargs: Mapping[str, Any] | None = None,
678
+ string_args: Iterable[str] | None = None,
679
+ templates_dict: dict | None = None,
680
+ templates_exts: list[str] | None = None,
681
+ expect_airflow: bool = True,
682
+ skip_on_exit_code: int | Container[int] | None = None,
683
+ index_urls: None | Collection[str] | str = None,
684
+ venv_cache_path: None | os.PathLike[str] = None,
685
+ env_vars: dict[str, str] | None = None,
686
+ inherit_env: bool = True,
687
+ **kwargs,
688
+ ):
689
+ if (
690
+ python_version
691
+ and str(python_version)[0] != str(sys.version_info.major)
692
+ and (op_args or op_kwargs)
693
+ ):
694
+ raise AirflowException(
695
+ "Passing op_args or op_kwargs is not supported across different Python "
696
+ "major versions for PythonVirtualenvOperator. Please use string_args."
697
+ f"Sys version: {sys.version_info}. Virtual environment version: {python_version}"
698
+ )
699
+ if python_version is not None and not isinstance(python_version, str):
700
+ raise AirflowException(
701
+ "Passing non-string types (e.g. int or float) as python_version not supported"
702
+ )
703
+ if not requirements:
704
+ self.requirements: list[str] = []
705
+ elif isinstance(requirements, str):
706
+ self.requirements = [requirements]
707
+ else:
708
+ self.requirements = list(requirements)
709
+ self.python_version = python_version
710
+ self.system_site_packages = system_site_packages
711
+ self.pip_install_options = pip_install_options
712
+ if isinstance(index_urls, str):
713
+ self.index_urls: list[str] | None = [index_urls]
714
+ elif isinstance(index_urls, Collection):
715
+ self.index_urls = list(index_urls)
716
+ else:
717
+ self.index_urls = None
718
+ self.venv_cache_path = venv_cache_path
719
+ super().__init__(
720
+ python_callable=python_callable,
721
+ serializer=serializer,
722
+ op_args=op_args,
723
+ op_kwargs=op_kwargs,
724
+ string_args=string_args,
725
+ templates_dict=templates_dict,
726
+ templates_exts=templates_exts,
727
+ expect_airflow=expect_airflow,
728
+ skip_on_exit_code=skip_on_exit_code,
729
+ env_vars=env_vars,
730
+ inherit_env=inherit_env,
731
+ **kwargs,
732
+ )
733
+
734
+ def _requirements_list(self, exclude_cloudpickle: bool = False) -> list[str]:
735
+ """Prepare a list of requirements that need to be installed for the virtual environment."""
736
+ requirements = [str(dependency) for dependency in self.requirements]
737
+ if not self.system_site_packages:
738
+ if (
739
+ self.serializer == "cloudpickle"
740
+ and not exclude_cloudpickle
741
+ and "cloudpickle" not in requirements
742
+ ):
743
+ requirements.append("cloudpickle")
744
+ elif self.serializer == "dill" and "dill" not in requirements:
745
+ requirements.append("dill")
746
+ requirements.sort() # Ensure a hash is stable
747
+ return requirements
748
+
749
+ def _prepare_venv(self, venv_path: Path) -> None:
750
+ """Prepare the requirements and installs the virtual environment."""
751
+ requirements_file = venv_path / "requirements.txt"
752
+ requirements_file.write_text("\n".join(self._requirements_list()))
753
+ prepare_virtualenv(
754
+ venv_directory=str(venv_path),
755
+ python_bin=f"python{self.python_version}" if self.python_version else "python",
756
+ system_site_packages=self.system_site_packages,
757
+ requirements_file_path=str(requirements_file),
758
+ pip_install_options=self.pip_install_options,
759
+ index_urls=self.index_urls,
760
+ )
761
+
762
+ def _calculate_cache_hash(self, exclude_cloudpickle: bool = False) -> tuple[str, str]:
763
+ """
764
+ Generate the hash of the cache folder to use.
765
+
766
+ The following factors are used as input for the hash:
767
+ - (sorted) list of requirements
768
+ - pip install options
769
+ - flag of system site packages
770
+ - python version
771
+ - Variable to override the hash with a cache key
772
+ - Index URLs
773
+
774
+ Returns a hash and the data dict which is the base for the hash as text.
775
+ """
776
+ hash_dict = {
777
+ "requirements_list": self._requirements_list(exclude_cloudpickle=exclude_cloudpickle),
778
+ "pip_install_options": self.pip_install_options,
779
+ "index_urls": self.index_urls,
780
+ "cache_key": str(Variable.get("PythonVirtualenvOperator.cache_key", "")),
781
+ "python_version": self.python_version,
782
+ "system_site_packages": self.system_site_packages,
783
+ }
784
+ hash_text = json.dumps(hash_dict, sort_keys=True)
785
+ hash_object = hashlib_wrapper.md5(hash_text.encode())
786
+ requirements_hash = hash_object.hexdigest()
787
+ return requirements_hash[:8], hash_text
788
+
789
+ def _ensure_venv_cache_exists(self, venv_cache_path: Path) -> Path:
790
+ """Ensure a valid virtual environment is set up and will create inplace."""
791
+ cache_hash, hash_data = self._calculate_cache_hash()
792
+ venv_path = venv_cache_path / f"venv-{cache_hash}"
793
+ self.log.info("Python virtual environment will be cached in %s", venv_path)
794
+ venv_path.parent.mkdir(parents=True, exist_ok=True)
795
+ with open(f"{venv_path}.lock", "w") as f:
796
+ # Ensure that cache is not build by parallel workers
797
+ import fcntl
798
+
799
+ fcntl.flock(f, fcntl.LOCK_EX)
800
+
801
+ hash_marker = venv_path / "install_complete_marker.json"
802
+ try:
803
+ if venv_path.exists():
804
+ if hash_marker.exists():
805
+ previous_hash_data = hash_marker.read_text(encoding="utf8")
806
+ if previous_hash_data == hash_data:
807
+ self.log.info("Reusing cached Python virtual environment in %s", venv_path)
808
+ return venv_path
809
+
810
+ _, hash_data_before_upgrade = self._calculate_cache_hash(exclude_cloudpickle=True)
811
+ if previous_hash_data == hash_data_before_upgrade:
812
+ self.log.warning(
813
+ "Found a previous virtual environment in with outdated dependencies %s, "
814
+ "deleting and re-creating.",
815
+ venv_path,
816
+ )
817
+ else:
818
+ self.log.error(
819
+ "Unicorn alert: Found a previous virtual environment in %s "
820
+ "with the same hash but different parameters. Previous setup: '%s' / "
821
+ "Requested venv setup: '%s'. Please report a bug to airflow!",
822
+ venv_path,
823
+ previous_hash_data,
824
+ hash_data,
825
+ )
826
+ else:
827
+ self.log.warning(
828
+ "Found a previous (probably partial installed) virtual environment in %s, "
829
+ "deleting and re-creating.",
830
+ venv_path,
831
+ )
832
+
833
+ shutil.rmtree(venv_path)
834
+
835
+ venv_path.mkdir(parents=True)
836
+ self._prepare_venv(venv_path)
837
+ hash_marker.write_text(hash_data, encoding="utf8")
838
+ except Exception as e:
839
+ shutil.rmtree(venv_path)
840
+ raise AirflowException(f"Unable to create new virtual environment in {venv_path}") from e
841
+ self.log.info("New Python virtual environment created in %s", venv_path)
842
+ return venv_path
843
+
844
+ def execute_callable(self):
845
+ if self.venv_cache_path:
846
+ venv_path = self._ensure_venv_cache_exists(Path(self.venv_cache_path))
847
+ python_path = venv_path / "bin" / "python"
848
+ return self._execute_python_callable_in_subprocess(python_path)
849
+
850
+ with TemporaryDirectory(prefix="venv") as tmp_dir:
851
+ tmp_path = Path(tmp_dir)
852
+ self._prepare_venv(tmp_path)
853
+ python_path = tmp_path / "bin" / "python"
854
+ result = self._execute_python_callable_in_subprocess(python_path)
855
+ return result
856
+
857
+ def _iter_serializable_context_keys(self):
858
+ yield from self.BASE_SERIALIZABLE_CONTEXT_KEYS
859
+ if self.system_site_packages or "apache-airflow" in self.requirements:
860
+ yield from self.AIRFLOW_SERIALIZABLE_CONTEXT_KEYS
861
+ yield from self.PENDULUM_SERIALIZABLE_CONTEXT_KEYS
862
+ elif "pendulum" in self.requirements:
863
+ yield from self.PENDULUM_SERIALIZABLE_CONTEXT_KEYS
864
+
865
+
866
+ class BranchPythonVirtualenvOperator(PythonVirtualenvOperator, BranchMixIn):
867
+ """
868
+ A workflow can "branch" or follow a path after the execution of this task in a virtual environment.
869
+
870
+ It derives the PythonVirtualenvOperator and expects a Python function that returns
871
+ a single task_id, a single task_group_id, or a list of task_ids and/or
872
+ task_group_ids to follow. The task_id(s) and/or task_group_id(s) returned
873
+ should point to a task or task group directly downstream from {self}. All
874
+ other "branches" or directly downstream tasks are marked with a state of
875
+ ``skipped`` so that these paths can't move forward. The ``skipped`` states
876
+ are propagated downstream to allow for the DAG state to fill up and
877
+ the DAG run's state to be inferred.
878
+
879
+ .. seealso::
880
+ For more information on how to use this operator, take a look at the guide:
881
+ :ref:`howto/operator:BranchPythonVirtualenvOperator`
882
+ """
883
+
884
+ inherits_from_skipmixin = True
885
+
886
+ def execute(self, context: Context) -> Any:
887
+ return self.do_branch(context, super().execute(context))
888
+
889
+
890
+ class ExternalPythonOperator(_BasePythonVirtualenvOperator):
891
+ """
892
+ Run a function in a virtualenv that is not re-created.
893
+
894
+ Reused as is without the overhead of creating the virtual environment (with certain caveats).
895
+
896
+ The function must be defined using def, and not be
897
+ part of a class. All imports must happen inside the function
898
+ and no variables outside the scope may be referenced. A global scope
899
+ variable named virtualenv_string_args will be available (populated by
900
+ string_args). In addition, one can pass stuff through op_args and op_kwargs, and one
901
+ can use a return value.
902
+ Note that if your virtual environment runs in a different Python major version than Airflow,
903
+ you cannot use return values, op_args, op_kwargs, or use any macros that are being provided to
904
+ Airflow through plugins. You can use string_args though.
905
+
906
+ If Airflow is installed in the external environment in different version that the version
907
+ used by the operator, the operator will fail.,
908
+
909
+ .. seealso::
910
+ For more information on how to use this operator, take a look at the guide:
911
+ :ref:`howto/operator:ExternalPythonOperator`
912
+
913
+ :param python: Full path string (file-system specific) that points to a Python binary inside
914
+ a virtual environment that should be used (in ``VENV/bin`` folder). Should be absolute path
915
+ (so usually start with "/" or "X:/" depending on the filesystem/os used).
916
+ :param python_callable: A python function with no references to outside variables,
917
+ defined with def, which will be run in a virtual environment.
918
+ :param serializer: Which serializer use to serialize the args and result. It can be one of the following:
919
+
920
+ - ``"pickle"``: (default) Use pickle for serialization. Included in the Python Standard Library.
921
+ - ``"cloudpickle"``: Use cloudpickle for serialize more complex types,
922
+ this requires to include cloudpickle in your requirements.
923
+ - ``"dill"``: Use dill for serialize more complex types,
924
+ this requires to include dill in your requirements.
925
+ :param op_args: A list of positional arguments to pass to python_callable.
926
+ :param op_kwargs: A dict of keyword arguments to pass to python_callable.
927
+ :param string_args: Strings that are present in the global var virtualenv_string_args,
928
+ available to python_callable at runtime as a list[str]. Note that args are split
929
+ by newline.
930
+ :param templates_dict: a dictionary where the values are templates that
931
+ will get templated by the Airflow engine sometime between
932
+ ``__init__`` and ``execute`` takes place and are made available
933
+ in your callable's context after the template has been applied
934
+ :param templates_exts: a list of file extensions to resolve while
935
+ processing templated fields, for examples ``['.sql', '.hql']``
936
+ :param expect_airflow: expect Airflow to be installed in the target environment. If true, the operator
937
+ will raise warning if Airflow is not installed, and it will attempt to load Airflow
938
+ macros when starting.
939
+ :param skip_on_exit_code: If python_callable exits with this exit code, leave the task
940
+ in ``skipped`` state (default: None). If set to ``None``, any non-zero
941
+ exit code will be treated as a failure.
942
+ :param env_vars: A dictionary containing additional environment variables to set for the virtual
943
+ environment when it is executed.
944
+ :param inherit_env: Whether to inherit the current environment variables when executing the virtual
945
+ environment. If set to ``True``, the virtual environment will inherit the environment variables
946
+ of the parent process (``os.environ``). If set to ``False``, the virtual environment will be
947
+ executed with a clean environment.
948
+ """
949
+
950
+ template_fields: Sequence[str] = tuple({"python"}.union(PythonOperator.template_fields))
951
+
952
+ def __init__(
953
+ self,
954
+ *,
955
+ python: str,
956
+ python_callable: Callable,
957
+ serializer: _SerializerTypeDef | None = None,
958
+ op_args: Collection[Any] | None = None,
959
+ op_kwargs: Mapping[str, Any] | None = None,
960
+ string_args: Iterable[str] | None = None,
961
+ templates_dict: dict | None = None,
962
+ templates_exts: list[str] | None = None,
963
+ expect_airflow: bool = True,
964
+ expect_pendulum: bool = False,
965
+ skip_on_exit_code: int | Container[int] | None = None,
966
+ env_vars: dict[str, str] | None = None,
967
+ inherit_env: bool = True,
968
+ **kwargs,
969
+ ):
970
+ if not python:
971
+ raise ValueError("Python Path must be defined in ExternalPythonOperator")
972
+ self.python = python
973
+ self.expect_pendulum = expect_pendulum
974
+ super().__init__(
975
+ python_callable=python_callable,
976
+ serializer=serializer,
977
+ op_args=op_args,
978
+ op_kwargs=op_kwargs,
979
+ string_args=string_args,
980
+ templates_dict=templates_dict,
981
+ templates_exts=templates_exts,
982
+ expect_airflow=expect_airflow,
983
+ skip_on_exit_code=skip_on_exit_code,
984
+ env_vars=env_vars,
985
+ inherit_env=inherit_env,
986
+ **kwargs,
987
+ )
988
+
989
+ def execute_callable(self):
990
+ python_path = Path(self.python)
991
+ if not python_path.exists():
992
+ raise ValueError(f"Python Path '{python_path}' must exists")
993
+ if not python_path.is_file():
994
+ raise ValueError(f"Python Path '{python_path}' must be a file")
995
+ if not python_path.is_absolute():
996
+ raise ValueError(f"Python Path '{python_path}' must be an absolute path.")
997
+ python_version = _PythonVersionInfo.from_executable(self.python)
998
+ if python_version.major != sys.version_info.major and (self.op_args or self.op_kwargs):
999
+ raise AirflowException(
1000
+ "Passing op_args or op_kwargs is not supported across different Python "
1001
+ "major versions for ExternalPythonOperator. Please use string_args."
1002
+ f"Sys version: {sys.version_info}. "
1003
+ f"Virtual environment version: {python_version}"
1004
+ )
1005
+ return self._execute_python_callable_in_subprocess(python_path)
1006
+
1007
+ def _iter_serializable_context_keys(self):
1008
+ yield from self.BASE_SERIALIZABLE_CONTEXT_KEYS
1009
+ if self._get_airflow_version_from_target_env():
1010
+ yield from self.AIRFLOW_SERIALIZABLE_CONTEXT_KEYS
1011
+ yield from self.PENDULUM_SERIALIZABLE_CONTEXT_KEYS
1012
+ elif self._is_pendulum_installed_in_target_env():
1013
+ yield from self.PENDULUM_SERIALIZABLE_CONTEXT_KEYS
1014
+
1015
+ def _is_pendulum_installed_in_target_env(self) -> bool:
1016
+ try:
1017
+ subprocess.check_call([self.python, "-c", "import pendulum"])
1018
+ return True
1019
+ except Exception as e:
1020
+ if self.expect_pendulum:
1021
+ self.log.warning("When checking for Pendulum installed in virtual environment got %s", e)
1022
+ self.log.warning(
1023
+ "Pendulum is not properly installed in the virtual environment "
1024
+ "Pendulum context keys will not be available. "
1025
+ "Please Install Pendulum or Airflow in your virtual environment to access them."
1026
+ )
1027
+ return False
1028
+
1029
+ @property
1030
+ def _external_airflow_version_script(self):
1031
+ """
1032
+ Return python script which determines the version of the Apache Airflow.
1033
+
1034
+ Import airflow as a module might take a while as a result,
1035
+ obtaining a version would take up to 1 second.
1036
+ On the other hand, `importlib.metadata.version` will retrieve the package version pretty fast
1037
+ something below 100ms; this includes new subprocess overhead.
1038
+
1039
+ Possible side effect: It might be a situation that `importlib.metadata` is not available (Python < 3.8),
1040
+ as well as backport `importlib_metadata` which might indicate that venv doesn't contain an `apache-airflow`
1041
+ or something wrong with the environment.
1042
+ """
1043
+ return textwrap.dedent(
1044
+ """
1045
+ try:
1046
+ from importlib.metadata import version
1047
+ except ImportError:
1048
+ from importlib_metadata import version
1049
+ print(version("apache-airflow"))
1050
+ """
1051
+ )
1052
+
1053
+ def _get_airflow_version_from_target_env(self) -> str | None:
1054
+ from airflow import __version__ as airflow_version
1055
+
1056
+ try:
1057
+ result = subprocess.check_output(
1058
+ [self.python, "-c", self._external_airflow_version_script],
1059
+ text=True,
1060
+ )
1061
+ target_airflow_version = result.strip()
1062
+ if target_airflow_version != airflow_version:
1063
+ raise AirflowConfigException(
1064
+ f"The version of Airflow installed for the {self.python} "
1065
+ f"({target_airflow_version}) is different than the runtime Airflow version: "
1066
+ f"{airflow_version}. Make sure your environment has the same Airflow version "
1067
+ f"installed as the Airflow runtime."
1068
+ )
1069
+ return target_airflow_version
1070
+ except Exception as e:
1071
+ if self.expect_airflow:
1072
+ self.log.warning("When checking for Airflow installed in virtual environment got %s", e)
1073
+ self.log.warning(
1074
+ "This means that Airflow is not properly installed by %s. "
1075
+ "Airflow context keys will not be available. "
1076
+ "Please Install Airflow %s in your environment to access them.",
1077
+ self.python,
1078
+ airflow_version,
1079
+ )
1080
+ return None
1081
+
1082
+
1083
+ class BranchExternalPythonOperator(ExternalPythonOperator, BranchMixIn):
1084
+ """
1085
+ A workflow can "branch" or follow a path after the execution of this task.
1086
+
1087
+ Extends ExternalPythonOperator, so expects to get Python:
1088
+ virtual environment that should be used (in ``VENV/bin`` folder). Should be absolute path,
1089
+ so it can run on separate virtual environment similarly to ExternalPythonOperator.
1090
+
1091
+ .. seealso::
1092
+ For more information on how to use this operator, take a look at the guide:
1093
+ :ref:`howto/operator:BranchExternalPythonOperator`
1094
+ """
1095
+
1096
+ def execute(self, context: Context) -> Any:
1097
+ return self.do_branch(context, super().execute(context))
1098
+
1099
+
1100
+ def get_current_context() -> Mapping[str, Any]:
1101
+ """
1102
+ Retrieve the execution context dictionary without altering user method's signature.
1103
+
1104
+ This is the simplest method of retrieving the execution context dictionary.
1105
+
1106
+ **Old style:**
1107
+
1108
+ .. code:: python
1109
+
1110
+ def my_task(**context):
1111
+ ti = context["ti"]
1112
+
1113
+ **New style:**
1114
+
1115
+ .. code:: python
1116
+
1117
+ from airflow.providers.standard.operators.python import get_current_context
1118
+
1119
+
1120
+ def my_task():
1121
+ context = get_current_context()
1122
+ ti = context["ti"]
1123
+
1124
+ Current context will only have value if this method was called after an operator
1125
+ was starting to execute.
1126
+ """
1127
+ if AIRFLOW_V_3_0_PLUS:
1128
+ from airflow.sdk import get_current_context
1129
+
1130
+ return get_current_context()
1131
+ return _get_current_context()
1132
+
1133
+
1134
+ def _get_current_context() -> Mapping[str, Any]:
1135
+ # Airflow 2.x
1136
+ # TODO: To be removed when Airflow 2 support is dropped
1137
+ from airflow.models.taskinstance import _CURRENT_CONTEXT # type: ignore[attr-defined]
1138
+
1139
+ if not _CURRENT_CONTEXT:
1140
+ raise RuntimeError(
1141
+ "Current context was requested but no context was found! Are you running within an Airflow task?"
1142
+ )
1143
+ return _CURRENT_CONTEXT[-1]