apache-airflow-providers-standard 1.0.0.dev1__py3-none-any.whl → 1.1.0__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 +89 -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 +127 -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 +391 -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.1.0.dist-info}/METADATA +16 -35
  47. apache_airflow_providers_standard-1.1.0.dist-info/RECORD +51 -0
  48. {apache_airflow_providers_standard-1.0.0.dev1.dist-info → apache_airflow_providers_standard-1.1.0.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.1.0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,593 @@
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 datetime
21
+ import os
22
+ import warnings
23
+ from collections.abc import Collection, Iterable
24
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar
25
+
26
+ from airflow.configuration import conf
27
+ from airflow.exceptions import AirflowException, AirflowSkipException
28
+ from airflow.models.dag import DagModel
29
+ from airflow.models.dagbag import DagBag
30
+ from airflow.providers.standard.operators.empty import EmptyOperator
31
+ from airflow.providers.standard.triggers.external_task import WorkflowTrigger
32
+ from airflow.providers.standard.utils.sensor_helper import _get_count, _get_external_task_group_task_ids
33
+ from airflow.providers.standard.version_compat import AIRFLOW_V_3_0_PLUS
34
+ from airflow.utils.file import correct_maybe_zipped
35
+ from airflow.utils.state import State, TaskInstanceState
36
+
37
+ if AIRFLOW_V_3_0_PLUS:
38
+ from airflow.sdk.bases.sensor import BaseSensorOperator
39
+ else:
40
+ from airflow.sensors.base import BaseSensorOperator
41
+ from airflow.utils.session import NEW_SESSION, provide_session
42
+
43
+ if TYPE_CHECKING:
44
+ from sqlalchemy.orm import Session
45
+
46
+ from airflow.models.taskinstancekey import TaskInstanceKey
47
+
48
+ try:
49
+ from airflow.sdk import BaseOperator
50
+ from airflow.sdk.definitions.context import Context
51
+ except ImportError:
52
+ # TODO: Remove once provider drops support for Airflow 2
53
+ from airflow.models.baseoperator import BaseOperator
54
+ from airflow.utils.context import Context
55
+
56
+
57
+ if AIRFLOW_V_3_0_PLUS:
58
+ from airflow.sdk import BaseOperatorLink
59
+ else:
60
+ from airflow.models.baseoperatorlink import BaseOperatorLink # type: ignore[no-redef]
61
+
62
+
63
+ class ExternalDagLink(BaseOperatorLink):
64
+ """
65
+ Operator link for ExternalTaskSensor and ExternalTaskMarker.
66
+
67
+ It allows users to access DAG waited with ExternalTaskSensor or cleared by ExternalTaskMarker.
68
+ """
69
+
70
+ name = "External DAG"
71
+
72
+ def get_link(self, operator: BaseOperator, *, ti_key: TaskInstanceKey) -> str:
73
+ if TYPE_CHECKING:
74
+ assert isinstance(operator, (ExternalTaskMarker, ExternalTaskSensor))
75
+
76
+ external_dag_id = operator.external_dag_id
77
+
78
+ if not AIRFLOW_V_3_0_PLUS:
79
+ from airflow.models.renderedtifields import RenderedTaskInstanceFields
80
+
81
+ if template_fields := RenderedTaskInstanceFields.get_templated_fields(ti_key):
82
+ external_dag_id: str = template_fields.get("external_dag_id", operator.external_dag_id) # type: ignore[no-redef]
83
+
84
+ if AIRFLOW_V_3_0_PLUS:
85
+ from airflow.utils.helpers import build_airflow_dagrun_url
86
+
87
+ return build_airflow_dagrun_url(dag_id=external_dag_id, run_id=ti_key.run_id)
88
+ from airflow.utils.helpers import build_airflow_url_with_query # type:ignore[attr-defined]
89
+
90
+ query = {"dag_id": external_dag_id, "run_id": ti_key.run_id}
91
+ return build_airflow_url_with_query(query)
92
+
93
+
94
+ class ExternalTaskSensor(BaseSensorOperator):
95
+ """
96
+ Waits for a different DAG, task group, or task to complete for a specific logical date.
97
+
98
+ If both `external_task_group_id` and `external_task_id` are ``None`` (default), the sensor
99
+ waits for the DAG.
100
+ Values for `external_task_group_id` and `external_task_id` can't be set at the same time.
101
+
102
+ By default, the ExternalTaskSensor will wait for the external task to
103
+ succeed, at which point it will also succeed. However, by default it will
104
+ *not* fail if the external task fails, but will continue to check the status
105
+ until the sensor times out (thus giving you time to retry the external task
106
+ without also having to clear the sensor).
107
+
108
+ By default, the ExternalTaskSensor will not skip if the external task skips.
109
+ To change this, simply set ``skipped_states=[TaskInstanceState.SKIPPED]``.
110
+ Note that if you are monitoring multiple tasks, and one enters error state
111
+ and the other enters a skipped state, then the external task will react to
112
+ whichever one it sees first. If both happen together, then the failed state
113
+ takes priority.
114
+
115
+ It is possible to alter the default behavior by setting states which
116
+ cause the sensor to fail, e.g. by setting ``allowed_states=[DagRunState.FAILED]``
117
+ and ``failed_states=[DagRunState.SUCCESS]`` you will flip the behaviour to
118
+ get a sensor which goes green when the external task *fails* and immediately
119
+ goes red if the external task *succeeds*!
120
+
121
+ Note that ``soft_fail`` is respected when examining the failed_states. Thus
122
+ if the external task enters a failed state and ``soft_fail == True`` the
123
+ sensor will _skip_ rather than fail. As a result, setting ``soft_fail=True``
124
+ and ``failed_states=[DagRunState.SKIPPED]`` will result in the sensor
125
+ skipping if the external task skips. However, this is a contrived
126
+ example---consider using ``skipped_states`` if you would like this
127
+ behaviour. Using ``skipped_states`` allows the sensor to skip if the target
128
+ fails, but still enter failed state on timeout. Using ``soft_fail == True``
129
+ as above will cause the sensor to skip if the target fails, but also if it
130
+ times out.
131
+
132
+ :param external_dag_id: The dag_id that contains the task you want to
133
+ wait for. (templated)
134
+ :param external_task_id: The task_id that contains the task you want to
135
+ wait for. (templated)
136
+ :param external_task_ids: The list of task_ids that you want to wait for. (templated)
137
+ If ``None`` (default value) the sensor waits for the DAG. Either
138
+ external_task_id or external_task_ids can be passed to
139
+ ExternalTaskSensor, but not both.
140
+ :param external_task_group_id: The task_group_id that contains the task you want to
141
+ wait for. (templated)
142
+ :param allowed_states: Iterable of allowed states, default is ``['success']``
143
+ :param skipped_states: Iterable of states to make this task mark as skipped, default is ``None``
144
+ :param failed_states: Iterable of failed or dis-allowed states, default is ``None``
145
+ :param execution_delta: time difference with the previous execution to
146
+ look at, the default is the same logical date as the current task or DAG.
147
+ For yesterday, use [positive!] datetime.timedelta(days=1). Either
148
+ execution_delta or execution_date_fn can be passed to
149
+ ExternalTaskSensor, but not both.
150
+ :param execution_date_fn: function that receives the current execution's logical date as the first
151
+ positional argument and optionally any number of keyword arguments available in the
152
+ context dictionary, and returns the desired logical dates to query.
153
+ Either execution_delta or execution_date_fn can be passed to ExternalTaskSensor,
154
+ but not both.
155
+ :param check_existence: Set to `True` to check if the external task exists (when
156
+ external_task_id is not None) or check if the DAG to wait for exists (when
157
+ external_task_id is None), and immediately cease waiting if the external task
158
+ or DAG does not exist (default value: False).
159
+ :param poll_interval: polling period in seconds to check for the status
160
+ :param deferrable: Run sensor in deferrable mode
161
+ """
162
+
163
+ template_fields = ["external_dag_id", "external_task_id", "external_task_ids", "external_task_group_id"]
164
+ ui_color = "#4db7db"
165
+ operator_extra_links = [ExternalDagLink()]
166
+
167
+ def __init__(
168
+ self,
169
+ *,
170
+ external_dag_id: str,
171
+ external_task_id: str | None = None,
172
+ external_task_ids: Collection[str] | None = None,
173
+ external_task_group_id: str | None = None,
174
+ allowed_states: Iterable[str] | None = None,
175
+ skipped_states: Iterable[str] | None = None,
176
+ failed_states: Iterable[str] | None = None,
177
+ execution_delta: datetime.timedelta | None = None,
178
+ execution_date_fn: Callable | None = None,
179
+ check_existence: bool = False,
180
+ poll_interval: float = 2.0,
181
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
182
+ **kwargs,
183
+ ):
184
+ super().__init__(**kwargs)
185
+
186
+ self.allowed_states = list(allowed_states) if allowed_states else [TaskInstanceState.SUCCESS.value]
187
+ self.skipped_states = list(skipped_states) if skipped_states else []
188
+ self.failed_states = list(failed_states) if failed_states else []
189
+
190
+ total_states = set(self.allowed_states + self.skipped_states + self.failed_states)
191
+
192
+ if len(total_states) != len(self.allowed_states) + len(self.skipped_states) + len(self.failed_states):
193
+ raise AirflowException(
194
+ "Duplicate values provided across allowed_states, skipped_states and failed_states."
195
+ )
196
+
197
+ # convert [] to None
198
+ if not external_task_ids:
199
+ external_task_ids = None
200
+
201
+ # can't set both single task id and a list of task ids
202
+ if external_task_id is not None and external_task_ids is not None:
203
+ raise ValueError(
204
+ "Only one of `external_task_id` or `external_task_ids` may "
205
+ "be provided to ExternalTaskSensor; "
206
+ "use external_task_id or external_task_ids or external_task_group_id."
207
+ )
208
+
209
+ # since both not set, convert the single id to a 1-elt list - from here on, we only consider the list
210
+ if external_task_id is not None:
211
+ external_task_ids = [external_task_id]
212
+
213
+ if external_task_group_id is not None and external_task_ids is not None:
214
+ raise ValueError(
215
+ "Only one of `external_task_group_id` or `external_task_ids` may "
216
+ "be provided to ExternalTaskSensor; "
217
+ "use external_task_id or external_task_ids or external_task_group_id."
218
+ )
219
+
220
+ # check the requested states are all valid states for the target type, be it dag or task
221
+ if external_task_ids or external_task_group_id:
222
+ if not total_states <= set(State.task_states):
223
+ raise ValueError(
224
+ "Valid values for `allowed_states`, `skipped_states` and `failed_states` "
225
+ "when `external_task_id` or `external_task_ids` or `external_task_group_id` "
226
+ f"is not `None`: {State.task_states}"
227
+ )
228
+
229
+ elif not total_states <= set(State.dag_states):
230
+ raise ValueError(
231
+ "Valid values for `allowed_states`, `skipped_states` and `failed_states` "
232
+ f"when `external_task_id` and `external_task_group_id` is `None`: {State.dag_states}"
233
+ )
234
+
235
+ if execution_delta is not None and execution_date_fn is not None:
236
+ raise ValueError(
237
+ "Only one of `execution_delta` or `execution_date_fn` may "
238
+ "be provided to ExternalTaskSensor; not both."
239
+ )
240
+
241
+ self.execution_delta = execution_delta
242
+ self.execution_date_fn = execution_date_fn
243
+ self.external_dag_id = external_dag_id
244
+ self.external_task_id = external_task_id
245
+ self.external_task_ids = external_task_ids
246
+ self.external_task_group_id = external_task_group_id
247
+ self.check_existence = check_existence
248
+ self._has_checked_existence = False
249
+ self.deferrable = deferrable
250
+ self.poll_interval = poll_interval
251
+
252
+ def _get_dttm_filter(self, context):
253
+ logical_date = context.get("logical_date")
254
+ if logical_date is None:
255
+ dag_run = context.get("dag_run")
256
+ if TYPE_CHECKING:
257
+ assert dag_run
258
+
259
+ logical_date = dag_run.run_after
260
+ if self.execution_delta:
261
+ dttm = logical_date - self.execution_delta
262
+ elif self.execution_date_fn:
263
+ dttm = self._handle_execution_date_fn(context=context)
264
+ else:
265
+ dttm = logical_date
266
+ return dttm if isinstance(dttm, list) else [dttm]
267
+
268
+ def poke(self, context: Context) -> bool:
269
+ # delay check to poke rather than __init__ in case it was supplied as XComArgs
270
+ if self.external_task_ids and len(self.external_task_ids) > len(set(self.external_task_ids)):
271
+ raise ValueError("Duplicate task_ids passed in external_task_ids parameter")
272
+
273
+ dttm_filter = self._get_dttm_filter(context)
274
+ serialized_dttm_filter = ",".join(dt.isoformat() for dt in dttm_filter)
275
+
276
+ if self.external_task_ids:
277
+ self.log.info(
278
+ "Poking for tasks %s in dag %s on %s ... ",
279
+ self.external_task_ids,
280
+ self.external_dag_id,
281
+ serialized_dttm_filter,
282
+ )
283
+
284
+ if self.external_task_group_id:
285
+ self.log.info(
286
+ "Poking for task_group '%s' in dag '%s' on %s ... ",
287
+ self.external_task_group_id,
288
+ self.external_dag_id,
289
+ serialized_dttm_filter,
290
+ )
291
+
292
+ if self.external_dag_id and not self.external_task_group_id and not self.external_task_ids:
293
+ self.log.info(
294
+ "Poking for DAG '%s' on %s ... ",
295
+ self.external_dag_id,
296
+ serialized_dttm_filter,
297
+ )
298
+
299
+ if AIRFLOW_V_3_0_PLUS:
300
+ return self._poke_af3(context, dttm_filter)
301
+ return self._poke_af2(dttm_filter)
302
+
303
+ def _poke_af3(self, context: Context, dttm_filter: list[datetime.datetime]) -> bool:
304
+ from airflow.providers.standard.utils.sensor_helper import _get_count_by_matched_states
305
+
306
+ self._has_checked_existence = True
307
+ ti = context["ti"]
308
+
309
+ def _get_count(states: list[str]) -> int:
310
+ if self.external_task_ids:
311
+ return ti.get_ti_count(
312
+ dag_id=self.external_dag_id,
313
+ task_ids=self.external_task_ids, # type: ignore[arg-type]
314
+ logical_dates=dttm_filter,
315
+ states=states,
316
+ )
317
+ if self.external_task_group_id:
318
+ run_id_task_state_map = ti.get_task_states(
319
+ dag_id=self.external_dag_id,
320
+ task_group_id=self.external_task_group_id,
321
+ logical_dates=dttm_filter,
322
+ )
323
+ return _get_count_by_matched_states(run_id_task_state_map, states)
324
+ return ti.get_dr_count(
325
+ dag_id=self.external_dag_id,
326
+ logical_dates=dttm_filter,
327
+ states=states,
328
+ )
329
+
330
+ if self.failed_states:
331
+ count = _get_count(self.failed_states)
332
+ count_failed = self._calculate_count(count, dttm_filter)
333
+ self._handle_failed_states(count_failed)
334
+
335
+ if self.skipped_states:
336
+ count = _get_count(self.skipped_states)
337
+ count_skipped = self._calculate_count(count, dttm_filter)
338
+ self._handle_skipped_states(count_skipped)
339
+
340
+ count = _get_count(self.allowed_states)
341
+ count_allowed = self._calculate_count(count, dttm_filter)
342
+ return count_allowed == len(dttm_filter)
343
+
344
+ def _calculate_count(self, count: int, dttm_filter: list[datetime.datetime]) -> float | int:
345
+ """Calculate the normalized count based on the type of check."""
346
+ if self.external_task_ids:
347
+ return count / len(self.external_task_ids)
348
+ return count
349
+
350
+ def _handle_failed_states(self, count_failed: float | int) -> None:
351
+ """Handle failed states and raise appropriate exceptions."""
352
+ if count_failed > 0:
353
+ if self.external_task_ids:
354
+ if self.soft_fail:
355
+ raise AirflowSkipException(
356
+ f"Some of the external tasks {self.external_task_ids} "
357
+ f"in DAG {self.external_dag_id} failed. Skipping due to soft_fail."
358
+ )
359
+ raise AirflowException(
360
+ f"Some of the external tasks {self.external_task_ids} "
361
+ f"in DAG {self.external_dag_id} failed."
362
+ )
363
+ if self.external_task_group_id:
364
+ if self.soft_fail:
365
+ raise AirflowSkipException(
366
+ f"The external task_group '{self.external_task_group_id}' "
367
+ f"in DAG '{self.external_dag_id}' failed. Skipping due to soft_fail."
368
+ )
369
+ raise AirflowException(
370
+ f"The external task_group '{self.external_task_group_id}' "
371
+ f"in DAG '{self.external_dag_id}' failed."
372
+ )
373
+ if self.soft_fail:
374
+ raise AirflowSkipException(
375
+ f"The external DAG {self.external_dag_id} failed. Skipping due to soft_fail."
376
+ )
377
+ raise AirflowException(f"The external DAG {self.external_dag_id} failed.")
378
+
379
+ def _handle_skipped_states(self, count_skipped: float | int) -> None:
380
+ """Handle skipped states and raise appropriate exceptions."""
381
+ if count_skipped > 0:
382
+ if self.external_task_ids:
383
+ raise AirflowSkipException(
384
+ f"Some of the external tasks {self.external_task_ids} "
385
+ f"in DAG {self.external_dag_id} reached a state in our states-to-skip-on list. Skipping."
386
+ )
387
+ if self.external_task_group_id:
388
+ raise AirflowSkipException(
389
+ f"The external task_group '{self.external_task_group_id}' "
390
+ f"in DAG {self.external_dag_id} reached a state in our states-to-skip-on list. Skipping."
391
+ )
392
+ raise AirflowSkipException(
393
+ f"The external DAG {self.external_dag_id} reached a state in our states-to-skip-on list. "
394
+ "Skipping."
395
+ )
396
+
397
+ if not AIRFLOW_V_3_0_PLUS:
398
+
399
+ @provide_session
400
+ def _poke_af2(self, dttm_filter: list[datetime.datetime], session: Session = NEW_SESSION) -> bool:
401
+ if self.check_existence and not self._has_checked_existence:
402
+ self._check_for_existence(session=session)
403
+
404
+ if self.failed_states:
405
+ count_failed = self.get_count(dttm_filter, session, self.failed_states)
406
+ self._handle_failed_states(count_failed)
407
+
408
+ if self.skipped_states:
409
+ count_skipped = self.get_count(dttm_filter, session, self.skipped_states)
410
+ self._handle_skipped_states(count_skipped)
411
+
412
+ count_allowed = self.get_count(dttm_filter, session, self.allowed_states)
413
+ return count_allowed == len(dttm_filter)
414
+
415
+ def execute(self, context: Context) -> None:
416
+ """Run on the worker and defer using the triggers if deferrable is set to True."""
417
+ if not self.deferrable:
418
+ super().execute(context)
419
+ else:
420
+ dttm_filter = self._get_dttm_filter(context)
421
+ logical_or_execution_dates = (
422
+ {"logical_dates": dttm_filter} if AIRFLOW_V_3_0_PLUS else {"execution_date": dttm_filter}
423
+ )
424
+ self.defer(
425
+ timeout=self.execution_timeout,
426
+ trigger=WorkflowTrigger(
427
+ external_dag_id=self.external_dag_id,
428
+ external_task_group_id=self.external_task_group_id,
429
+ external_task_ids=self.external_task_ids,
430
+ allowed_states=self.allowed_states,
431
+ failed_states=self.failed_states,
432
+ skipped_states=self.skipped_states,
433
+ poke_interval=self.poll_interval,
434
+ soft_fail=self.soft_fail,
435
+ **logical_or_execution_dates,
436
+ ),
437
+ method_name="execute_complete",
438
+ )
439
+
440
+ def execute_complete(self, context, event=None):
441
+ """Execute when the trigger fires - return immediately."""
442
+ if event["status"] == "success":
443
+ self.log.info("External tasks %s has executed successfully.", self.external_task_ids)
444
+ elif event["status"] == "skipped":
445
+ raise AirflowSkipException("External job has skipped skipping.")
446
+ else:
447
+ if self.soft_fail:
448
+ raise AirflowSkipException("External job has failed skipping.")
449
+ raise AirflowException(
450
+ "Error occurred while trying to retrieve task status. Please, check the "
451
+ "name of executed task and Dag."
452
+ )
453
+
454
+ def _check_for_existence(self, session) -> None:
455
+ dag_to_wait = DagModel.get_current(self.external_dag_id, session)
456
+
457
+ if not dag_to_wait:
458
+ raise AirflowException(f"The external DAG {self.external_dag_id} does not exist.")
459
+
460
+ if not os.path.exists(correct_maybe_zipped(dag_to_wait.fileloc)):
461
+ raise AirflowException(f"The external DAG {self.external_dag_id} was deleted.")
462
+
463
+ if self.external_task_ids:
464
+ refreshed_dag_info = DagBag(dag_to_wait.fileloc).get_dag(self.external_dag_id)
465
+ for external_task_id in self.external_task_ids:
466
+ if not refreshed_dag_info.has_task(external_task_id):
467
+ raise AirflowException(
468
+ f"The external task {external_task_id} in DAG {self.external_dag_id} does not exist."
469
+ )
470
+
471
+ if self.external_task_group_id:
472
+ refreshed_dag_info = DagBag(dag_to_wait.fileloc).get_dag(self.external_dag_id)
473
+ if not refreshed_dag_info.has_task_group(self.external_task_group_id):
474
+ raise AirflowException(
475
+ f"The external task group '{self.external_task_group_id}' in "
476
+ f"DAG '{self.external_dag_id}' does not exist."
477
+ )
478
+
479
+ self._has_checked_existence = True
480
+
481
+ def get_count(self, dttm_filter, session, states) -> int:
482
+ """
483
+ Get the count of records against dttm filter and states.
484
+
485
+ :param dttm_filter: date time filter for logical date
486
+ :param session: airflow session object
487
+ :param states: task or dag states
488
+ :return: count of record against the filters
489
+ """
490
+ warnings.warn(
491
+ "This method is deprecated and will be removed in future.", DeprecationWarning, stacklevel=2
492
+ )
493
+ return _get_count(
494
+ dttm_filter,
495
+ self.external_task_ids,
496
+ self.external_task_group_id,
497
+ self.external_dag_id,
498
+ states,
499
+ session,
500
+ )
501
+
502
+ def get_external_task_group_task_ids(self, session, dttm_filter):
503
+ warnings.warn(
504
+ "This method is deprecated and will be removed in future.", DeprecationWarning, stacklevel=2
505
+ )
506
+ return _get_external_task_group_task_ids(
507
+ dttm_filter, self.external_task_group_id, self.external_dag_id, session
508
+ )
509
+
510
+ def _handle_execution_date_fn(self, context) -> Any:
511
+ """
512
+ Handle backward compatibility.
513
+
514
+ This function is to handle backwards compatibility with how this operator was
515
+ previously where it only passes the logical date, but also allow for the newer
516
+ implementation to pass all context variables as keyword arguments, to allow
517
+ for more sophisticated returns of dates to return.
518
+ """
519
+ from airflow.utils.operator_helpers import make_kwargs_callable
520
+
521
+ # Remove "logical_date" because it is already a mandatory positional argument
522
+ logical_date = context["logical_date"]
523
+ kwargs = {k: v for k, v in context.items() if k not in {"execution_date", "logical_date"}}
524
+ # Add "context" in the kwargs for backward compatibility (because context used to be
525
+ # an acceptable argument of execution_date_fn)
526
+ kwargs["context"] = context
527
+ if TYPE_CHECKING:
528
+ assert self.execution_date_fn is not None
529
+ kwargs_callable = make_kwargs_callable(self.execution_date_fn)
530
+ return kwargs_callable(logical_date, **kwargs)
531
+
532
+
533
+ class ExternalTaskMarker(EmptyOperator):
534
+ """
535
+ Use this operator to indicate that a task on a different DAG depends on this task.
536
+
537
+ When this task is cleared with "Recursive" selected, Airflow will clear the task on
538
+ the other DAG and its downstream tasks recursively. Transitive dependencies are followed
539
+ until the recursion_depth is reached.
540
+
541
+ :param external_dag_id: The dag_id that contains the dependent task that needs to be cleared.
542
+ :param external_task_id: The task_id of the dependent task that needs to be cleared.
543
+ :param logical_date: The logical date of the dependent task execution that needs to be cleared.
544
+ :param recursion_depth: The maximum level of transitive dependencies allowed. Default is 10.
545
+ This is mostly used for preventing cyclic dependencies. It is fine to increase
546
+ this number if necessary. However, too many levels of transitive dependencies will make
547
+ it slower to clear tasks in the web UI.
548
+ """
549
+
550
+ template_fields = ["external_dag_id", "external_task_id", "logical_date"]
551
+ if not AIRFLOW_V_3_0_PLUS:
552
+ template_fields.append("execution_date")
553
+
554
+ ui_color = "#4db7db"
555
+ operator_extra_links = [ExternalDagLink()]
556
+
557
+ # The _serialized_fields are lazily loaded when get_serialized_fields() method is called
558
+ __serialized_fields: ClassVar[frozenset[str] | None] = None
559
+
560
+ def __init__(
561
+ self,
562
+ *,
563
+ external_dag_id: str,
564
+ external_task_id: str,
565
+ logical_date: str | datetime.datetime | None = "{{ logical_date.isoformat() }}",
566
+ recursion_depth: int = 10,
567
+ **kwargs,
568
+ ):
569
+ super().__init__(**kwargs)
570
+ self.external_dag_id = external_dag_id
571
+ self.external_task_id = external_task_id
572
+ if isinstance(logical_date, datetime.datetime):
573
+ self.logical_date = logical_date.isoformat()
574
+ elif isinstance(logical_date, str):
575
+ self.logical_date = logical_date
576
+ else:
577
+ raise TypeError(
578
+ f"Expected str or datetime.datetime type for logical_date. Got {type(logical_date)}"
579
+ )
580
+
581
+ if not AIRFLOW_V_3_0_PLUS:
582
+ self.execution_date = self.logical_date
583
+
584
+ if recursion_depth <= 0:
585
+ raise ValueError("recursion_depth should be a positive integer")
586
+ self.recursion_depth = recursion_depth
587
+
588
+ @classmethod
589
+ def get_serialized_fields(cls):
590
+ """Serialize ExternalTaskMarker to contain exactly these fields + templated_fields ."""
591
+ if not cls.__serialized_fields:
592
+ cls.__serialized_fields = frozenset(super().get_serialized_fields() | {"recursion_depth"})
593
+ return cls.__serialized_fields