-
Notifications
You must be signed in to change notification settings - Fork 14.7k
/
Copy pathbaseoperator.py
1933 lines (1638 loc) · 74.1 KB
/
baseoperator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Base operator for all operators.
:sphinx-autoapi-skip:
"""
from __future__ import annotations
import abc
import collections.abc
import contextlib
import copy
import functools
import logging
import sys
import warnings
from datetime import datetime, timedelta
from inspect import signature
from types import FunctionType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Collection,
Iterable,
Sequence,
TypeVar,
Union,
cast,
)
import attr
import pendulum
from dateutil.relativedelta import relativedelta
from sqlalchemy import select
from sqlalchemy.orm.exc import NoResultFound
from airflow.configuration import conf
from airflow.exceptions import (
AirflowException,
FailStopDagInvalidTriggerRule,
RemovedInAirflow3Warning,
TaskDeferralError,
TaskDeferred,
)
from airflow.lineage import apply_lineage, prepare_lineage
from airflow.models.abstractoperator import (
DEFAULT_IGNORE_FIRST_DEPENDS_ON_PAST,
DEFAULT_OWNER,
DEFAULT_POOL_SLOTS,
DEFAULT_PRIORITY_WEIGHT,
DEFAULT_QUEUE,
DEFAULT_RETRIES,
DEFAULT_RETRY_DELAY,
DEFAULT_TASK_EXECUTION_TIMEOUT,
DEFAULT_TRIGGER_RULE,
DEFAULT_WAIT_FOR_PAST_DEPENDS_BEFORE_SKIPPING,
DEFAULT_WEIGHT_RULE,
AbstractOperator,
)
from airflow.models.mappedoperator import OperatorPartial, validate_mapping_kwargs
from airflow.models.param import ParamsDict
from airflow.models.pool import Pool
from airflow.models.taskinstance import TaskInstance, clear_task_instances
from airflow.models.taskmixin import DependencyMixin
from airflow.serialization.enums import DagAttributeTypes
from airflow.ti_deps.deps.not_in_retry_period_dep import NotInRetryPeriodDep
from airflow.ti_deps.deps.not_previously_skipped_dep import NotPreviouslySkippedDep
from airflow.ti_deps.deps.prev_dagrun_dep import PrevDagrunDep
from airflow.ti_deps.deps.trigger_rule_dep import TriggerRuleDep
from airflow.utils import timezone
from airflow.utils.context import Context
from airflow.utils.decorators import fixup_decorator_warning_stack
from airflow.utils.edgemodifier import EdgeModifier
from airflow.utils.helpers import validate_key
from airflow.utils.operator_resources import Resources
from airflow.utils.session import NEW_SESSION, provide_session
from airflow.utils.setup_teardown import SetupTeardownContext
from airflow.utils.trigger_rule import TriggerRule
from airflow.utils.types import NOTSET
from airflow.utils.weight_rule import WeightRule
from airflow.utils.xcom import XCOM_RETURN_KEY
if TYPE_CHECKING:
from types import ClassMethodDescriptorType
import jinja2 # Slow import.
from sqlalchemy.orm import Session
from airflow.models.abstractoperator import TaskStateChangeCallback
from airflow.models.baseoperatorlink import BaseOperatorLink
from airflow.models.dag import DAG
from airflow.models.operator import Operator
from airflow.models.xcom_arg import XComArg
from airflow.ti_deps.deps.base_ti_dep import BaseTIDep
from airflow.triggers.base import BaseTrigger
from airflow.utils.task_group import TaskGroup
from airflow.utils.types import ArgNotSet
ScheduleInterval = Union[str, timedelta, relativedelta]
TaskPreExecuteHook = Callable[[Context], None]
TaskPostExecuteHook = Callable[[Context, Any], None]
T = TypeVar("T", bound=FunctionType)
logger = logging.getLogger("airflow.models.baseoperator.BaseOperator")
def parse_retries(retries: Any) -> int | None:
if retries is None or type(retries) == int: # noqa: E721
return retries
try:
parsed_retries = int(retries)
except (TypeError, ValueError):
raise AirflowException(f"'retries' type must be int, not {type(retries).__name__}")
logger.warning("Implicitly converting 'retries' from %r to int", retries)
return parsed_retries
def coerce_timedelta(value: float | timedelta, *, key: str) -> timedelta:
if isinstance(value, timedelta):
return value
logger.debug("%s isn't a timedelta object, assuming secs", key)
return timedelta(seconds=value)
def coerce_resources(resources: dict[str, Any] | None) -> Resources | None:
if resources is None:
return None
return Resources(**resources)
def _get_parent_defaults(dag: DAG | None, task_group: TaskGroup | None) -> tuple[dict, ParamsDict]:
if not dag:
return {}, ParamsDict()
dag_args = copy.copy(dag.default_args)
dag_params = copy.deepcopy(dag.params)
if task_group:
if task_group.default_args and not isinstance(task_group.default_args, collections.abc.Mapping):
raise TypeError("default_args must be a mapping")
dag_args.update(task_group.default_args)
return dag_args, dag_params
def get_merged_defaults(
dag: DAG | None,
task_group: TaskGroup | None,
task_params: collections.abc.MutableMapping | None,
task_default_args: dict | None,
) -> tuple[dict, ParamsDict]:
args, params = _get_parent_defaults(dag, task_group)
if task_params:
if not isinstance(task_params, collections.abc.Mapping):
raise TypeError("params must be a mapping")
params.update(task_params)
if task_default_args:
if not isinstance(task_default_args, collections.abc.Mapping):
raise TypeError("default_args must be a mapping")
args.update(task_default_args)
with contextlib.suppress(KeyError):
params.update(task_default_args["params"] or {})
return args, params
class _PartialDescriptor:
"""A descriptor that guards against ``.partial`` being called on Task objects."""
class_method: ClassMethodDescriptorType | None = None
def __get__(
self, obj: BaseOperator, cls: type[BaseOperator] | None = None
) -> Callable[..., OperatorPartial]:
# Call this "partial" so it looks nicer in stack traces.
def partial(**kwargs):
raise TypeError("partial can only be called on Operator classes, not Tasks themselves")
if obj is not None:
return partial
return self.class_method.__get__(cls, cls)
_PARTIAL_DEFAULTS = {
"owner": DEFAULT_OWNER,
"trigger_rule": DEFAULT_TRIGGER_RULE,
"depends_on_past": False,
"ignore_first_depends_on_past": DEFAULT_IGNORE_FIRST_DEPENDS_ON_PAST,
"wait_for_past_depends_before_skipping": DEFAULT_WAIT_FOR_PAST_DEPENDS_BEFORE_SKIPPING,
"wait_for_downstream": False,
"retries": DEFAULT_RETRIES,
"queue": DEFAULT_QUEUE,
"pool_slots": DEFAULT_POOL_SLOTS,
"execution_timeout": DEFAULT_TASK_EXECUTION_TIMEOUT,
"retry_delay": DEFAULT_RETRY_DELAY,
"retry_exponential_backoff": False,
"priority_weight": DEFAULT_PRIORITY_WEIGHT,
"weight_rule": DEFAULT_WEIGHT_RULE,
"inlets": [],
"outlets": [],
}
# This is what handles the actual mapping.
def partial(
operator_class: type[BaseOperator],
*,
task_id: str,
dag: DAG | None = None,
task_group: TaskGroup | None = None,
start_date: datetime | ArgNotSet = NOTSET,
end_date: datetime | ArgNotSet = NOTSET,
owner: str | ArgNotSet = NOTSET,
email: None | str | Iterable[str] | ArgNotSet = NOTSET,
params: collections.abc.MutableMapping | None = None,
resources: dict[str, Any] | None | ArgNotSet = NOTSET,
trigger_rule: str | ArgNotSet = NOTSET,
depends_on_past: bool | ArgNotSet = NOTSET,
ignore_first_depends_on_past: bool | ArgNotSet = NOTSET,
wait_for_past_depends_before_skipping: bool | ArgNotSet = NOTSET,
wait_for_downstream: bool | ArgNotSet = NOTSET,
retries: int | None | ArgNotSet = NOTSET,
queue: str | ArgNotSet = NOTSET,
pool: str | ArgNotSet = NOTSET,
pool_slots: int | ArgNotSet = NOTSET,
execution_timeout: timedelta | None | ArgNotSet = NOTSET,
max_retry_delay: None | timedelta | float | ArgNotSet = NOTSET,
retry_delay: timedelta | float | ArgNotSet = NOTSET,
retry_exponential_backoff: bool | ArgNotSet = NOTSET,
priority_weight: int | ArgNotSet = NOTSET,
weight_rule: str | ArgNotSet = NOTSET,
sla: timedelta | None | ArgNotSet = NOTSET,
map_index_template: str | None | ArgNotSet = NOTSET,
max_active_tis_per_dag: int | None | ArgNotSet = NOTSET,
max_active_tis_per_dagrun: int | None | ArgNotSet = NOTSET,
on_execute_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] | ArgNotSet = NOTSET,
on_failure_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] | ArgNotSet = NOTSET,
on_success_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] | ArgNotSet = NOTSET,
on_retry_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] | ArgNotSet = NOTSET,
on_skipped_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] | ArgNotSet = NOTSET,
run_as_user: str | None | ArgNotSet = NOTSET,
executor_config: dict | None | ArgNotSet = NOTSET,
inlets: Any | None | ArgNotSet = NOTSET,
outlets: Any | None | ArgNotSet = NOTSET,
doc: str | None | ArgNotSet = NOTSET,
doc_md: str | None | ArgNotSet = NOTSET,
doc_json: str | None | ArgNotSet = NOTSET,
doc_yaml: str | None | ArgNotSet = NOTSET,
doc_rst: str | None | ArgNotSet = NOTSET,
logger_name: str | None | ArgNotSet = NOTSET,
**kwargs,
) -> OperatorPartial:
from airflow.models.dag import DagContext
from airflow.utils.task_group import TaskGroupContext
validate_mapping_kwargs(operator_class, "partial", kwargs)
dag = dag or DagContext.get_current_dag()
if dag:
task_group = task_group or TaskGroupContext.get_current_task_group(dag)
if task_group:
task_id = task_group.child_id(task_id)
# Merge DAG and task group level defaults into user-supplied values.
dag_default_args, partial_params = get_merged_defaults(
dag=dag,
task_group=task_group,
task_params=params,
task_default_args=kwargs.pop("default_args", None),
)
# Create partial_kwargs from args and kwargs
partial_kwargs: dict[str, Any] = {
**kwargs,
"dag": dag,
"task_group": task_group,
"task_id": task_id,
"map_index_template": map_index_template,
"start_date": start_date,
"end_date": end_date,
"owner": owner,
"email": email,
"trigger_rule": trigger_rule,
"depends_on_past": depends_on_past,
"ignore_first_depends_on_past": ignore_first_depends_on_past,
"wait_for_past_depends_before_skipping": wait_for_past_depends_before_skipping,
"wait_for_downstream": wait_for_downstream,
"retries": retries,
"queue": queue,
"pool": pool,
"pool_slots": pool_slots,
"execution_timeout": execution_timeout,
"max_retry_delay": max_retry_delay,
"retry_delay": retry_delay,
"retry_exponential_backoff": retry_exponential_backoff,
"priority_weight": priority_weight,
"weight_rule": weight_rule,
"sla": sla,
"max_active_tis_per_dag": max_active_tis_per_dag,
"max_active_tis_per_dagrun": max_active_tis_per_dagrun,
"on_execute_callback": on_execute_callback,
"on_failure_callback": on_failure_callback,
"on_retry_callback": on_retry_callback,
"on_success_callback": on_success_callback,
"on_skipped_callback": on_skipped_callback,
"run_as_user": run_as_user,
"executor_config": executor_config,
"inlets": inlets,
"outlets": outlets,
"resources": resources,
"doc": doc,
"doc_json": doc_json,
"doc_md": doc_md,
"doc_rst": doc_rst,
"doc_yaml": doc_yaml,
"logger_name": logger_name,
}
# Inject DAG-level default args into args provided to this function.
partial_kwargs.update((k, v) for k, v in dag_default_args.items() if partial_kwargs.get(k) is NOTSET)
# Fill fields not provided by the user with default values.
partial_kwargs = {k: _PARTIAL_DEFAULTS.get(k) if v is NOTSET else v for k, v in partial_kwargs.items()}
# Post-process arguments. Should be kept in sync with _TaskDecorator.expand().
if "task_concurrency" in kwargs: # Reject deprecated option.
raise TypeError("unexpected argument: task_concurrency")
if partial_kwargs["wait_for_downstream"]:
partial_kwargs["depends_on_past"] = True
partial_kwargs["start_date"] = timezone.convert_to_utc(partial_kwargs["start_date"])
partial_kwargs["end_date"] = timezone.convert_to_utc(partial_kwargs["end_date"])
if partial_kwargs["pool"] is None:
partial_kwargs["pool"] = Pool.DEFAULT_POOL_NAME
partial_kwargs["retries"] = parse_retries(partial_kwargs["retries"])
partial_kwargs["retry_delay"] = coerce_timedelta(partial_kwargs["retry_delay"], key="retry_delay")
if partial_kwargs["max_retry_delay"] is not None:
partial_kwargs["max_retry_delay"] = coerce_timedelta(
partial_kwargs["max_retry_delay"],
key="max_retry_delay",
)
partial_kwargs["executor_config"] = partial_kwargs["executor_config"] or {}
partial_kwargs["resources"] = coerce_resources(partial_kwargs["resources"])
return OperatorPartial(
operator_class=operator_class,
kwargs=partial_kwargs,
params=partial_params,
)
class BaseOperatorMeta(abc.ABCMeta):
"""Metaclass of BaseOperator."""
@classmethod
def _apply_defaults(cls, func: T) -> T:
"""
Look for an argument named "default_args", and fill the unspecified arguments from it.
Since python2.* isn't clear about which arguments are missing when
calling a function, and that this can be quite confusing with multi-level
inheritance and argument defaults, this decorator also alerts with
specific information about the missing arguments.
"""
# Cache inspect.signature for the wrapper closure to avoid calling it
# at every decorated invocation. This is separate sig_cache created
# per decoration, i.e. each function decorated using apply_defaults will
# have a different sig_cache.
sig_cache = signature(func)
non_variadic_params = {
name: param
for (name, param) in sig_cache.parameters.items()
if param.name != "self" and param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)
}
non_optional_args = {
name
for name, param in non_variadic_params.items()
if param.default == param.empty and name != "task_id"
}
fixup_decorator_warning_stack(func)
@functools.wraps(func)
def apply_defaults(self: BaseOperator, *args: Any, **kwargs: Any) -> Any:
from airflow.models.dag import DagContext
from airflow.utils.task_group import TaskGroupContext
if args:
raise AirflowException("Use keyword arguments when initializing operators")
instantiated_from_mapped = kwargs.pop(
"_airflow_from_mapped",
getattr(self, "_BaseOperator__from_mapped", False),
)
dag: DAG | None = kwargs.get("dag") or DagContext.get_current_dag()
task_group: TaskGroup | None = kwargs.get("task_group")
if dag and not task_group:
task_group = TaskGroupContext.get_current_task_group(dag)
default_args, merged_params = get_merged_defaults(
dag=dag,
task_group=task_group,
task_params=kwargs.pop("params", None),
task_default_args=kwargs.pop("default_args", None),
)
for arg in sig_cache.parameters:
if arg not in kwargs and arg in default_args:
kwargs[arg] = default_args[arg]
missing_args = non_optional_args.difference(kwargs)
if len(missing_args) == 1:
raise AirflowException(f"missing keyword argument {missing_args.pop()!r}")
elif missing_args:
display = ", ".join(repr(a) for a in sorted(missing_args))
raise AirflowException(f"missing keyword arguments {display}")
if merged_params:
kwargs["params"] = merged_params
hook = getattr(self, "_hook_apply_defaults", None)
if hook:
args, kwargs = hook(**kwargs, default_args=default_args)
default_args = kwargs.pop("default_args", {})
if not hasattr(self, "_BaseOperator__init_kwargs"):
self._BaseOperator__init_kwargs = {}
self._BaseOperator__from_mapped = instantiated_from_mapped
result = func(self, **kwargs, default_args=default_args)
# Store the args passed to init -- we need them to support task.map serialization!
self._BaseOperator__init_kwargs.update(kwargs) # type: ignore
# Set upstream task defined by XComArgs passed to template fields of the operator.
# BUT: only do this _ONCE_, not once for each class in the hierarchy
if not instantiated_from_mapped and func == self.__init__.__wrapped__: # type: ignore[misc]
self.set_xcomargs_dependencies()
# Mark instance as instantiated.
self._BaseOperator__instantiated = True
return result
apply_defaults.__non_optional_args = non_optional_args # type: ignore
apply_defaults.__param_names = set(non_variadic_params) # type: ignore
return cast(T, apply_defaults)
def __new__(cls, name, bases, namespace, **kwargs):
new_cls = super().__new__(cls, name, bases, namespace, **kwargs)
with contextlib.suppress(KeyError):
# Update the partial descriptor with the class method, so it calls the actual function
# (but let subclasses override it if they need to)
partial_desc = vars(new_cls)["partial"]
if isinstance(partial_desc, _PartialDescriptor):
partial_desc.class_method = classmethod(partial)
new_cls.__init__ = cls._apply_defaults(new_cls.__init__)
return new_cls
@functools.total_ordering
class BaseOperator(AbstractOperator, metaclass=BaseOperatorMeta):
"""
Abstract base class for all operators.
Since operators create objects that become nodes in the DAG, BaseOperator
contains many recursive methods for DAG crawling behavior. To derive from
this class, you are expected to override the constructor and the 'execute'
method.
Operators derived from this class should perform or trigger certain tasks
synchronously (wait for completion). Example of operators could be an
operator that runs a Pig job (PigOperator), a sensor operator that
waits for a partition to land in Hive (HiveSensorOperator), or one that
moves data from Hive to MySQL (Hive2MySqlOperator). Instances of these
operators (tasks) target specific operations, running specific scripts,
functions or data transfers.
This class is abstract and shouldn't be instantiated. Instantiating a
class derived from this one results in the creation of a task object,
which ultimately becomes a node in DAG objects. Task dependencies should
be set by using the set_upstream and/or set_downstream methods.
:param task_id: a unique, meaningful id for the task
:param owner: the owner of the task. Using a meaningful description
(e.g. user/person/team/role name) to clarify ownership is recommended.
:param email: the 'to' email address(es) used in email alerts. This can be a
single email or multiple ones. Multiple addresses can be specified as a
comma or semicolon separated string or by passing a list of strings.
:param email_on_retry: Indicates whether email alerts should be sent when a
task is retried
:param email_on_failure: Indicates whether email alerts should be sent when
a task failed
:param retries: the number of retries that should be performed before
failing the task
:param retry_delay: delay between retries, can be set as ``timedelta`` or
``float`` seconds, which will be converted into ``timedelta``,
the default is ``timedelta(seconds=300)``.
:param retry_exponential_backoff: allow progressively longer waits between
retries by using exponential backoff algorithm on retry delay (delay
will be converted into seconds)
:param max_retry_delay: maximum delay interval between retries, can be set as
``timedelta`` or ``float`` seconds, which will be converted into ``timedelta``.
:param start_date: The ``start_date`` for the task, determines
the ``execution_date`` for the first task instance. The best practice
is to have the start_date rounded
to your DAG's ``schedule_interval``. Daily jobs have their start_date
some day at 00:00:00, hourly jobs have their start_date at 00:00
of a specific hour. Note that Airflow simply looks at the latest
``execution_date`` and adds the ``schedule_interval`` to determine
the next ``execution_date``. It is also very important
to note that different tasks' dependencies
need to line up in time. If task A depends on task B and their
start_date are offset in a way that their execution_date don't line
up, A's dependencies will never be met. If you are looking to delay
a task, for example running a daily task at 2AM, look into the
``TimeSensor`` and ``TimeDeltaSensor``. We advise against using
dynamic ``start_date`` and recommend using fixed ones. Read the
FAQ entry about start_date for more information.
:param end_date: if specified, the scheduler won't go beyond this date
:param depends_on_past: when set to true, task instances will run
sequentially and only if the previous instance has succeeded or has been skipped.
The task instance for the start_date is allowed to run.
:param wait_for_past_depends_before_skipping: when set to true, if the task instance
should be marked as skipped, and depends_on_past is true, the ti will stay on None state
waiting the task of the previous run
:param wait_for_downstream: when set to true, an instance of task
X will wait for tasks immediately downstream of the previous instance
of task X to finish successfully or be skipped before it runs. This is useful if the
different instances of a task X alter the same asset, and this asset
is used by tasks downstream of task X. Note that depends_on_past
is forced to True wherever wait_for_downstream is used. Also note that
only tasks *immediately* downstream of the previous task instance are waited
for; the statuses of any tasks further downstream are ignored.
:param dag: a reference to the dag the task is attached to (if any)
:param priority_weight: priority weight of this task against other task.
This allows the executor to trigger higher priority tasks before
others when things get backed up. Set priority_weight as a higher
number for more important tasks.
:param weight_rule: weighting method used for the effective total
priority weight of the task. Options are:
``{ downstream | upstream | absolute }`` default is ``downstream``
When set to ``downstream`` the effective weight of the task is the
aggregate sum of all downstream descendants. As a result, upstream
tasks will have higher weight and will be scheduled more aggressively
when using positive weight values. This is useful when you have
multiple dag run instances and desire to have all upstream tasks to
complete for all runs before each dag can continue processing
downstream tasks. When set to ``upstream`` the effective weight is the
aggregate sum of all upstream ancestors. This is the opposite where
downstream tasks have higher weight and will be scheduled more
aggressively when using positive weight values. This is useful when you
have multiple dag run instances and prefer to have each dag complete
before starting upstream tasks of other dags. When set to
``absolute``, the effective weight is the exact ``priority_weight``
specified without additional weighting. You may want to do this when
you know exactly what priority weight each task should have.
Additionally, when set to ``absolute``, there is bonus effect of
significantly speeding up the task creation process as for very large
DAGs. Options can be set as string or using the constants defined in
the static class ``airflow.utils.WeightRule``
:param queue: which queue to target when running this job. Not
all executors implement queue management, the CeleryExecutor
does support targeting specific queues.
:param pool: the slot pool this task should run in, slot pools are a
way to limit concurrency for certain tasks
:param pool_slots: the number of pool slots this task should use (>= 1)
Values less than 1 are not allowed.
:param sla: time by which the job is expected to succeed. Note that
this represents the ``timedelta`` after the period is closed. For
example if you set an SLA of 1 hour, the scheduler would send an email
soon after 1:00AM on the ``2016-01-02`` if the ``2016-01-01`` instance
has not succeeded yet.
The scheduler pays special attention for jobs with an SLA and
sends alert
emails for SLA misses. SLA misses are also recorded in the database
for future reference. All tasks that share the same SLA time
get bundled in a single email, sent soon after that time. SLA
notification are sent once and only once for each task instance.
:param execution_timeout: max time allowed for the execution of
this task instance, if it goes beyond it will raise and fail.
:param on_failure_callback: a function or list of functions to be called when a task instance
of this task fails. a context dictionary is passed as a single
parameter to this function. Context contains references to related
objects to the task instance and is documented under the macros
section of the API.
:param on_execute_callback: much like the ``on_failure_callback`` except
that it is executed right before the task is executed.
:param on_retry_callback: much like the ``on_failure_callback`` except
that it is executed when retries occur.
:param on_success_callback: much like the ``on_failure_callback`` except
that it is executed when the task succeeds.
:param on_skipped_callback: much like the ``on_failure_callback`` except
that it is executed when skipped occur; this callback will be called only if AirflowSkipException get raised.
Explicitly it is NOT called if a task is not started to be executed because of a preceding branching
decision in the DAG or a trigger rule which causes execution to skip so that the task execution
is never scheduled.
:param pre_execute: a function to be called immediately before task
execution, receiving a context dictionary; raising an exception will
prevent the task from being executed.
|experimental|
:param post_execute: a function to be called immediately after task
execution, receiving a context dictionary and task result; raising an
exception will prevent the task from succeeding.
|experimental|
:param trigger_rule: defines the rule by which dependencies are applied
for the task to get triggered. Options are:
``{ all_success | all_failed | all_done | all_skipped | one_success | one_done |
one_failed | none_failed | none_failed_min_one_success | none_skipped | always}``
default is ``all_success``. Options can be set as string or
using the constants defined in the static class
``airflow.utils.TriggerRule``
:param resources: A map of resource parameter names (the argument names of the
Resources constructor) to their values.
:param run_as_user: unix username to impersonate while running the task
:param max_active_tis_per_dag: When set, a task will be able to limit the concurrent
runs across execution_dates.
:param max_active_tis_per_dagrun: When set, a task will be able to limit the concurrent
task instances per DAG run.
:param executor_config: Additional task-level configuration parameters that are
interpreted by a specific executor. Parameters are namespaced by the name of
executor.
**Example**: to run this task in a specific docker container through
the KubernetesExecutor ::
MyOperator(..., executor_config={"KubernetesExecutor": {"image": "myCustomDockerImage"}})
:param do_xcom_push: if True, an XCom is pushed containing the Operator's
result
:param multiple_outputs: if True and do_xcom_push is True, pushes multiple XComs, one for each
key in the returned dictionary result. If False and do_xcom_push is True, pushes a single XCom.
:param task_group: The TaskGroup to which the task should belong. This is typically provided when not
using a TaskGroup as a context manager.
:param doc: Add documentation or notes to your Task objects that is visible in
Task Instance details View in the Webserver
:param doc_md: Add documentation (in Markdown format) or notes to your Task objects
that is visible in Task Instance details View in the Webserver
:param doc_rst: Add documentation (in RST format) or notes to your Task objects
that is visible in Task Instance details View in the Webserver
:param doc_json: Add documentation (in JSON format) or notes to your Task objects
that is visible in Task Instance details View in the Webserver
:param doc_yaml: Add documentation (in YAML format) or notes to your Task objects
that is visible in Task Instance details View in the Webserver
:param logger_name: Name of the logger used by the Operator to emit logs.
If set to `None` (default), the logger name will fall back to
`airflow.task.operators.{class.__module__}.{class.__name__}` (e.g. SimpleHttpOperator will have
*airflow.task.operators.airflow.providers.http.operators.http.SimpleHttpOperator* as logger).
"""
# Implementing Operator.
template_fields: Sequence[str] = ()
template_ext: Sequence[str] = ()
template_fields_renderers: dict[str, str] = {}
# Defines the color in the UI
ui_color: str = "#fff"
ui_fgcolor: str = "#000"
pool: str = ""
# base list which includes all the attrs that don't need deep copy.
_base_operator_shallow_copy_attrs: tuple[str, ...] = (
"user_defined_macros",
"user_defined_filters",
"params",
)
# each operator should override this class attr for shallow copy attrs.
shallow_copy_attrs: Sequence[str] = ()
# Defines the operator level extra links
operator_extra_links: Collection[BaseOperatorLink] = ()
# The _serialized_fields are lazily loaded when get_serialized_fields() method is called
__serialized_fields: frozenset[str] | None = None
partial: Callable[..., OperatorPartial] = _PartialDescriptor() # type: ignore
_comps = {
"task_id",
"dag_id",
"owner",
"email",
"email_on_retry",
"retry_delay",
"retry_exponential_backoff",
"max_retry_delay",
"start_date",
"end_date",
"depends_on_past",
"wait_for_downstream",
"priority_weight",
"sla",
"execution_timeout",
"on_execute_callback",
"on_failure_callback",
"on_success_callback",
"on_retry_callback",
"on_skipped_callback",
"do_xcom_push",
"multiple_outputs",
}
# Defines if the operator supports lineage without manual definitions
supports_lineage = False
# If True then the class constructor was called
__instantiated = False
# List of args as passed to `init()`, after apply_defaults() has been updated. Used to "recreate" the task
# when mapping
__init_kwargs: dict[str, Any]
# Set to True before calling execute method
_lock_for_execution = False
_dag: DAG | None = None
task_group: TaskGroup | None = None
# subdag parameter is only set for SubDagOperator.
# Setting it to None by default as other Operators do not have that field
subdag: DAG | None = None
start_date: pendulum.DateTime | None = None
end_date: pendulum.DateTime | None = None
# Set to True for an operator instantiated by a mapped operator.
__from_mapped = False
def __init__(
self,
task_id: str,
owner: str = DEFAULT_OWNER,
email: str | Iterable[str] | None = None,
email_on_retry: bool = conf.getboolean("email", "default_email_on_retry", fallback=True),
email_on_failure: bool = conf.getboolean("email", "default_email_on_failure", fallback=True),
retries: int | None = DEFAULT_RETRIES,
retry_delay: timedelta | float = DEFAULT_RETRY_DELAY,
retry_exponential_backoff: bool = False,
max_retry_delay: timedelta | float | None = None,
start_date: datetime | None = None,
end_date: datetime | None = None,
depends_on_past: bool = False,
ignore_first_depends_on_past: bool = DEFAULT_IGNORE_FIRST_DEPENDS_ON_PAST,
wait_for_past_depends_before_skipping: bool = DEFAULT_WAIT_FOR_PAST_DEPENDS_BEFORE_SKIPPING,
wait_for_downstream: bool = False,
dag: DAG | None = None,
params: collections.abc.MutableMapping | None = None,
default_args: dict | None = None,
priority_weight: int = DEFAULT_PRIORITY_WEIGHT,
weight_rule: str = DEFAULT_WEIGHT_RULE,
queue: str = DEFAULT_QUEUE,
pool: str | None = None,
pool_slots: int = DEFAULT_POOL_SLOTS,
sla: timedelta | None = None,
execution_timeout: timedelta | None = DEFAULT_TASK_EXECUTION_TIMEOUT,
on_execute_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = None,
on_failure_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = None,
on_success_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = None,
on_retry_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = None,
on_skipped_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = None,
pre_execute: TaskPreExecuteHook | None = None,
post_execute: TaskPostExecuteHook | None = None,
trigger_rule: str = DEFAULT_TRIGGER_RULE,
resources: dict[str, Any] | None = None,
run_as_user: str | None = None,
task_concurrency: int | None = None,
map_index_template: str | None = None,
max_active_tis_per_dag: int | None = None,
max_active_tis_per_dagrun: int | None = None,
executor_config: dict | None = None,
do_xcom_push: bool = True,
multiple_outputs: bool = False,
inlets: Any | None = None,
outlets: Any | None = None,
task_group: TaskGroup | None = None,
doc: str | None = None,
doc_md: str | None = None,
doc_json: str | None = None,
doc_yaml: str | None = None,
doc_rst: str | None = None,
logger_name: str | None = None,
**kwargs,
):
from airflow.models.dag import DagContext
from airflow.utils.task_group import TaskGroupContext
self.__init_kwargs = {}
super().__init__()
kwargs.pop("_airflow_mapped_validation_only", None)
if kwargs:
if not conf.getboolean("operators", "ALLOW_ILLEGAL_ARGUMENTS"):
raise AirflowException(
f"Invalid arguments were passed to {self.__class__.__name__} (task_id: {task_id}). "
f"Invalid arguments were:\n**kwargs: {kwargs}",
)
warnings.warn(
f"Invalid arguments were passed to {self.__class__.__name__} (task_id: {task_id}). "
"Support for passing such arguments will be dropped in future. "
f"Invalid arguments were:\n**kwargs: {kwargs}",
category=RemovedInAirflow3Warning,
stacklevel=3,
)
validate_key(task_id)
dag = dag or DagContext.get_current_dag()
task_group = task_group or TaskGroupContext.get_current_task_group(dag)
self.task_id = task_group.child_id(task_id) if task_group else task_id
if not self.__from_mapped and task_group:
task_group.add(self)
self.owner = owner
self.email = email
self.email_on_retry = email_on_retry
self.email_on_failure = email_on_failure
if execution_timeout is not None and not isinstance(execution_timeout, timedelta):
raise ValueError(
f"execution_timeout must be timedelta object but passed as type: {type(execution_timeout)}"
)
self.execution_timeout = execution_timeout
self.on_execute_callback = on_execute_callback
self.on_failure_callback = on_failure_callback
self.on_success_callback = on_success_callback
self.on_retry_callback = on_retry_callback
self.on_skipped_callback = on_skipped_callback
self._pre_execute_hook = pre_execute
self._post_execute_hook = post_execute
if start_date and not isinstance(start_date, datetime):
self.log.warning("start_date for %s isn't datetime.datetime", self)
elif start_date:
self.start_date = timezone.convert_to_utc(start_date)
if end_date:
self.end_date = timezone.convert_to_utc(end_date)
self.executor_config = executor_config or {}
self.run_as_user = run_as_user
self.retries = parse_retries(retries)
self.queue = queue
self.pool = Pool.DEFAULT_POOL_NAME if pool is None else pool
self.pool_slots = pool_slots
if self.pool_slots < 1:
dag_str = f" in dag {dag.dag_id}" if dag else ""
raise ValueError(f"pool slots for {self.task_id}{dag_str} cannot be less than 1")
self.sla = sla
if trigger_rule == "dummy":
warnings.warn(
"dummy Trigger Rule is deprecated. Please use `TriggerRule.ALWAYS`.",
RemovedInAirflow3Warning,
stacklevel=2,
)
trigger_rule = TriggerRule.ALWAYS
if trigger_rule == "none_failed_or_skipped":
warnings.warn(
"none_failed_or_skipped Trigger Rule is deprecated. "
"Please use `none_failed_min_one_success`.",
RemovedInAirflow3Warning,
stacklevel=2,
)
trigger_rule = TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS
if not TriggerRule.is_valid(trigger_rule):
raise AirflowException(
f"The trigger_rule must be one of {TriggerRule.all_triggers()},"
f"'{dag.dag_id if dag else ''}.{task_id}'; received '{trigger_rule}'."
)
self.trigger_rule: TriggerRule = TriggerRule(trigger_rule)
FailStopDagInvalidTriggerRule.check(dag=dag, trigger_rule=self.trigger_rule)
self.depends_on_past: bool = depends_on_past
self.ignore_first_depends_on_past: bool = ignore_first_depends_on_past
self.wait_for_past_depends_before_skipping: bool = wait_for_past_depends_before_skipping
self.wait_for_downstream: bool = wait_for_downstream
if wait_for_downstream:
self.depends_on_past = True
self.retry_delay = coerce_timedelta(retry_delay, key="retry_delay")
self.retry_exponential_backoff = retry_exponential_backoff
self.max_retry_delay = (
max_retry_delay
if max_retry_delay is None
else coerce_timedelta(max_retry_delay, key="max_retry_delay")
)
# At execution_time this becomes a normal dict
self.params: ParamsDict | dict = ParamsDict(params)
if priority_weight is not None and not isinstance(priority_weight, int):
raise AirflowException(
f"`priority_weight` for task '{self.task_id}' only accepts integers, "
f"received '{type(priority_weight)}'."
)
self.priority_weight = priority_weight
if not WeightRule.is_valid(weight_rule):
raise AirflowException(
f"The weight_rule must be one of "
f"{WeightRule.all_weight_rules},'{dag.dag_id if dag else ''}.{task_id}'; "
f"received '{weight_rule}'."
)
self.weight_rule = weight_rule
self.resources = coerce_resources(resources)
if task_concurrency and not max_active_tis_per_dag:
# TODO: Remove in Airflow 3.0
warnings.warn(
"The 'task_concurrency' parameter is deprecated. Please use 'max_active_tis_per_dag'.",
RemovedInAirflow3Warning,
stacklevel=2,
)
max_active_tis_per_dag = task_concurrency
self.max_active_tis_per_dag: int | None = max_active_tis_per_dag
self.max_active_tis_per_dagrun: int | None = max_active_tis_per_dagrun
self.do_xcom_push: bool = do_xcom_push
self.map_index_template: str | None = map_index_template
self.multiple_outputs: bool = multiple_outputs
self.doc_md = doc_md
self.doc_json = doc_json
self.doc_yaml = doc_yaml
self.doc_rst = doc_rst
self.doc = doc
self.upstream_task_ids: set[str] = set()
self.downstream_task_ids: set[str] = set()
if dag:
self.dag = dag
self._log_config_logger_name = "airflow.task.operators"
self._logger_name = logger_name
# Lineage
self.inlets: list = []
self.outlets: list = []
if inlets:
self.inlets = (
inlets
if isinstance(inlets, list)
else [
inlets,
]
)
if outlets:
self.outlets = (
outlets
if isinstance(outlets, list)
else [
outlets,
]
)
if isinstance(self.template_fields, str):
warnings.warn(
f"The `template_fields` value for {self.task_type} is a string "
"but should be a list or tuple of string. Wrapping it in a list for execution. "
f"Please update {self.task_type} accordingly.",
UserWarning,
stacklevel=2,
)
self.template_fields = [self.template_fields]
self._is_setup = False
self._is_teardown = False
if SetupTeardownContext.active:
SetupTeardownContext.update_context_map(self)
def __eq__(self, other):
if type(self) is type(other):
# Use getattr() instead of __dict__ as __dict__ doesn't return
# correct values for properties.
return all(getattr(self, c, None) == getattr(other, c, None) for c in self._comps)
return False