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