-
Notifications
You must be signed in to change notification settings - Fork 14.6k
/
Copy pathtaskinstance.py
3074 lines (2699 loc) · 124 KB
/
taskinstance.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.
from __future__ import annotations
import collections.abc
import contextlib
import hashlib
import logging
import math
import operator
import os
import signal
import warnings
from collections import defaultdict
from datetime import datetime, timedelta
from enum import Enum
from functools import partial
from pathlib import PurePath
from types import TracebackType
from typing import TYPE_CHECKING, Any, Callable, Collection, Generator, Iterable, Tuple
from urllib.parse import quote
import dill
import jinja2
import lazy_object_proxy
import pendulum
from jinja2 import TemplateAssertionError, UndefinedError
from sqlalchemy import (
Column,
DateTime,
Float,
ForeignKeyConstraint,
Index,
Integer,
PrimaryKeyConstraint,
String,
Text,
and_,
delete,
false,
func,
inspect,
or_,
text,
update,
)
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.mutable import MutableDict
from sqlalchemy.orm import reconstructor, relationship
from sqlalchemy.orm.attributes import NO_VALUE, set_committed_value
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.elements import BooleanClauseList
from sqlalchemy.sql.expression import ColumnOperators, case
from airflow import settings
from airflow.compat.functools import cache
from airflow.configuration import conf
from airflow.datasets import Dataset
from airflow.datasets.manager import dataset_manager
from airflow.exceptions import (
AirflowException,
AirflowFailException,
AirflowRescheduleException,
AirflowSensorTimeout,
AirflowSkipException,
AirflowTaskTimeout,
DagRunNotFound,
RemovedInAirflow3Warning,
TaskDeferralError,
TaskDeferred,
UnmappableXComLengthPushed,
UnmappableXComTypePushed,
XComForMappingNotPushed,
)
from airflow.listeners.listener import get_listener_manager
from airflow.models.base import Base, StringID
from airflow.models.dagbag import DagBag
from airflow.models.log import Log
from airflow.models.mappedoperator import MappedOperator
from airflow.models.param import process_params
from airflow.models.taskfail import TaskFail
from airflow.models.taskinstancekey import TaskInstanceKey
from airflow.models.taskmap import TaskMap
from airflow.models.taskreschedule import TaskReschedule
from airflow.models.xcom import LazyXComAccess, XCom
from airflow.plugins_manager import integrate_macros_plugins
from airflow.sentry import Sentry
from airflow.stats import Stats
from airflow.templates import SandboxedEnvironment
from airflow.ti_deps.dep_context import DepContext
from airflow.ti_deps.dependencies_deps import REQUEUEABLE_DEPS, RUNNING_DEPS
from airflow.timetables.base import DataInterval
from airflow.typing_compat import Literal, TypeGuard
from airflow.utils import timezone
from airflow.utils.context import ConnectionAccessor, Context, VariableAccessor, context_merge
from airflow.utils.email import send_email
from airflow.utils.helpers import prune_dict, render_template_to_string
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.utils.module_loading import qualname
from airflow.utils.net import get_hostname
from airflow.utils.operator_helpers import context_to_airflow_vars
from airflow.utils.platform import getuser
from airflow.utils.retries import run_with_db_retries
from airflow.utils.session import NEW_SESSION, create_session, provide_session
from airflow.utils.sqlalchemy import (
ExecutorConfigType,
ExtendedJSON,
UtcDateTime,
tuple_in_condition,
with_row_locks,
)
from airflow.utils.state import DagRunState, JobState, State, TaskInstanceState
from airflow.utils.task_group import MappedTaskGroup
from airflow.utils.timeout import timeout
from airflow.utils.xcom import XCOM_RETURN_KEY
TR = TaskReschedule
_CURRENT_CONTEXT: list[Context] = []
log = logging.getLogger(__name__)
if TYPE_CHECKING:
from airflow.models.abstractoperator import TaskStateChangeCallback
from airflow.models.baseoperator import BaseOperator
from airflow.models.dag import DAG, DagModel
from airflow.models.dagrun import DagRun
from airflow.models.dataset import DatasetEvent
from airflow.models.operator import Operator
from airflow.utils.task_group import TaskGroup
# This is a workaround because mypy doesn't work with hybrid_property
# TODO: remove this hack and move hybrid_property back to main import block
# See https://github.com/python/mypy/issues/4430
hybrid_property = property
else:
from sqlalchemy.ext.hybrid import hybrid_property
PAST_DEPENDS_MET = "past_depends_met"
class TaskReturnCode(Enum):
"""
Enum to signal manner of exit for task run command.
:meta private:
"""
DEFERRED = 100
"""When task exits with deferral to trigger."""
@contextlib.contextmanager
def set_current_context(context: Context) -> Generator[Context, None, None]:
"""
Sets the current execution context to the provided context object.
This method should be called once per Task execution, before calling operator.execute.
"""
_CURRENT_CONTEXT.append(context)
try:
yield context
finally:
expected_state = _CURRENT_CONTEXT.pop()
if expected_state != context:
log.warning(
"Current context is not equal to the state at context stack. Expected=%s, got=%s",
context,
expected_state,
)
def _stop_remaining_tasks(*, self, session: Session):
"""
Stop non-teardown tasks in dag.
:meta private:
"""
tis = self.dag_run.get_task_instances(session=session)
if TYPE_CHECKING:
assert isinstance(self.task.dag, DAG)
for ti in tis:
if ti.task_id == self.task_id or ti.state in (
TaskInstanceState.SUCCESS,
TaskInstanceState.FAILED,
):
continue
task = self.task.dag.task_dict[ti.task_id]
if not task.is_teardown:
if ti.state == TaskInstanceState.RUNNING:
log.info("Forcing task %s to fail due to dag's `fail_stop` setting", ti.task_id)
ti.error(session)
else:
log.info("Setting task %s to SKIPPED due to dag's `fail_stop` setting.", ti.task_id)
ti.set_state(state=TaskInstanceState.SKIPPED, session=session)
else:
log.info("Not skipping teardown task '%s'", ti.task_id)
def clear_task_instances(
tis: list[TaskInstance],
session: Session,
activate_dag_runs: None = None,
dag: DAG | None = None,
dag_run_state: DagRunState | Literal[False] = DagRunState.QUEUED,
) -> None:
"""
Clears a set of task instances, but makes sure the running ones get killed.
Also sets Dagrun's `state` to QUEUED and `start_date` to the time of execution.
But only for finished DRs (SUCCESS and FAILED).
Doesn't clear DR's `state` and `start_date`for running
DRs (QUEUED and RUNNING) because clearing the state for already
running DR is redundant and clearing `start_date` affects DR's duration.
:param tis: a list of task instances
:param session: current session
:param dag_run_state: state to set finished DagRuns to.
If set to False, DagRuns state will not be changed.
:param dag: DAG object
:param activate_dag_runs: Deprecated parameter, do not pass
"""
job_ids = []
# Keys: dag_id -> run_id -> map_indexes -> try_numbers -> task_id
task_id_by_key: dict[str, dict[str, dict[int, dict[int, set[str]]]]] = defaultdict(
lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(set)))
)
dag_bag = DagBag(read_dags_from_db=True)
for ti in tis:
if ti.state == TaskInstanceState.RUNNING:
if ti.job_id:
# If a task is cleared when running, set its state to RESTARTING so that
# the task is terminated and becomes eligible for retry.
ti.state = TaskInstanceState.RESTARTING
job_ids.append(ti.job_id)
else:
ti_dag = dag if dag and dag.dag_id == ti.dag_id else dag_bag.get_dag(ti.dag_id, session=session)
task_id = ti.task_id
if ti_dag and ti_dag.has_task(task_id):
task = ti_dag.get_task(task_id)
ti.refresh_from_task(task)
task_retries = task.retries
ti.max_tries = ti.try_number + task_retries - 1
else:
# Ignore errors when updating max_tries if the DAG or
# task are not found since database records could be
# outdated. We make max_tries the maximum value of its
# original max_tries or the last attempted try number.
ti.max_tries = max(ti.max_tries, ti.prev_attempted_tries)
ti.state = None
ti.external_executor_id = None
ti.clear_next_method_args()
session.merge(ti)
task_id_by_key[ti.dag_id][ti.run_id][ti.map_index][ti.try_number].add(ti.task_id)
if task_id_by_key:
# Clear all reschedules related to the ti to clear
# This is an optimization for the common case where all tis are for a small number
# of dag_id, run_id, try_number, and map_index. Use a nested dict of dag_id,
# run_id, try_number, map_index, and task_id to construct the where clause in a
# hierarchical manner. This speeds up the delete statement by more than 40x for
# large number of tis (50k+).
conditions = or_(
and_(
TR.dag_id == dag_id,
or_(
and_(
TR.run_id == run_id,
or_(
and_(
TR.map_index == map_index,
or_(
and_(TR.try_number == try_number, TR.task_id.in_(task_ids))
for try_number, task_ids in task_tries.items()
),
)
for map_index, task_tries in map_indexes.items()
),
)
for run_id, map_indexes in run_ids.items()
),
)
for dag_id, run_ids in task_id_by_key.items()
)
delete_qry = TR.__table__.delete().where(conditions)
session.execute(delete_qry)
if job_ids:
from airflow.jobs.job import Job
session.execute(update(Job).where(Job.id.in_(job_ids)).values(state=JobState.RESTARTING))
if activate_dag_runs is not None:
warnings.warn(
"`activate_dag_runs` parameter to clear_task_instances function is deprecated. "
"Please use `dag_run_state`",
RemovedInAirflow3Warning,
stacklevel=2,
)
if not activate_dag_runs:
dag_run_state = False
if dag_run_state is not False and tis:
from airflow.models.dagrun import DagRun # Avoid circular import
run_ids_by_dag_id = defaultdict(set)
for instance in tis:
run_ids_by_dag_id[instance.dag_id].add(instance.run_id)
drs = (
session.query(DagRun)
.filter(
or_(
and_(DagRun.dag_id == dag_id, DagRun.run_id.in_(run_ids))
for dag_id, run_ids in run_ids_by_dag_id.items()
)
)
.all()
)
dag_run_state = DagRunState(dag_run_state) # Validate the state value.
for dr in drs:
if dr.state in State.finished_dr_states:
dr.state = dag_run_state
dr.start_date = timezone.utcnow()
if dag_run_state == DagRunState.QUEUED:
dr.last_scheduling_decision = None
dr.start_date = None
session.flush()
def _is_mappable_value(value: Any) -> TypeGuard[Collection]:
"""Whether a value can be used for task mapping.
We only allow collections with guaranteed ordering, but exclude character
sequences since that's usually not what users would expect to be mappable.
"""
if not isinstance(value, (collections.abc.Sequence, dict)):
return False
if isinstance(value, (bytearray, bytes, str)):
return False
return True
def _creator_note(val):
"""Custom creator for the ``note`` association proxy."""
if isinstance(val, str):
return TaskInstanceNote(content=val)
elif isinstance(val, dict):
return TaskInstanceNote(**val)
else:
return TaskInstanceNote(*val)
class TaskInstance(Base, LoggingMixin):
"""
Task instances store the state of a task instance.
This table is the authority and single source of truth around what tasks
have run and the state they are in.
The SqlAlchemy model doesn't have a SqlAlchemy foreign key to the task or
dag model deliberately to have more control over transactions.
Database transactions on this table should insure double triggers and
any confusion around what task instances are or aren't ready to run
even while multiple schedulers may be firing task instances.
A value of -1 in map_index represents any of: a TI without mapped tasks;
a TI with mapped tasks that has yet to be expanded (state=pending);
a TI with mapped tasks that expanded to an empty list (state=skipped).
"""
__tablename__ = "task_instance"
task_id = Column(StringID(), primary_key=True, nullable=False)
dag_id = Column(StringID(), primary_key=True, nullable=False)
run_id = Column(StringID(), primary_key=True, nullable=False)
map_index = Column(Integer, primary_key=True, nullable=False, server_default=text("-1"))
start_date = Column(UtcDateTime)
end_date = Column(UtcDateTime)
duration = Column(Float)
state = Column(String(20))
_try_number = Column("try_number", Integer, default=0)
max_tries = Column(Integer, server_default=text("-1"))
hostname = Column(String(1000))
unixname = Column(String(1000))
job_id = Column(Integer)
pool = Column(String(256), nullable=False)
pool_slots = Column(Integer, default=1, nullable=False)
queue = Column(String(256))
priority_weight = Column(Integer)
operator = Column(String(1000))
custom_operator_name = Column(String(1000))
queued_dttm = Column(UtcDateTime)
queued_by_job_id = Column(Integer)
pid = Column(Integer)
executor_config = Column(ExecutorConfigType(pickler=dill))
updated_at = Column(UtcDateTime, default=timezone.utcnow, onupdate=timezone.utcnow)
external_executor_id = Column(StringID())
# The trigger to resume on if we are in state DEFERRED
trigger_id = Column(Integer)
# Optional timeout datetime for the trigger (past this, we'll fail)
trigger_timeout = Column(DateTime)
# The trigger_timeout should be TIMESTAMP(using UtcDateTime) but for ease of
# migration, we are keeping it as DateTime pending a change where expensive
# migration is inevitable.
# The method to call next, and any extra arguments to pass to it.
# Usually used when resuming from DEFERRED.
next_method = Column(String(1000))
next_kwargs = Column(MutableDict.as_mutable(ExtendedJSON))
# If adding new fields here then remember to add them to
# refresh_from_db() or they won't display in the UI correctly
__table_args__ = (
Index("ti_dag_state", dag_id, state),
Index("ti_dag_run", dag_id, run_id),
Index("ti_state", state),
Index("ti_state_lkp", dag_id, task_id, run_id, state),
# The below index has been added to improve performance on postgres setups with tens of millions of
# taskinstance rows. Aim is to improve the below query (it can be used to find the last successful
# execution date of a task instance):
# SELECT start_date FROM task_instance WHERE dag_id = 'xx' AND task_id = 'yy' AND state = 'success'
# ORDER BY start_date DESC NULLS LAST LIMIT 1;
# Existing "ti_state_lkp" is not enough for such query when this table has millions of rows, since
# rows have to be fetched in order to retrieve the start_date column. With this index, INDEX ONLY SCAN
# is performed and that query runs within milliseconds.
Index("ti_state_incl_start_date", dag_id, task_id, state, postgresql_include=["start_date"]),
Index("ti_pool", pool, state, priority_weight),
Index("ti_job_id", job_id),
Index("ti_trigger_id", trigger_id),
PrimaryKeyConstraint(
"dag_id", "task_id", "run_id", "map_index", name="task_instance_pkey", mssql_clustered=True
),
ForeignKeyConstraint(
[trigger_id],
["trigger.id"],
name="task_instance_trigger_id_fkey",
ondelete="CASCADE",
),
ForeignKeyConstraint(
[dag_id, run_id],
["dag_run.dag_id", "dag_run.run_id"],
name="task_instance_dag_run_fkey",
ondelete="CASCADE",
),
)
dag_model = relationship(
"DagModel",
primaryjoin="TaskInstance.dag_id == DagModel.dag_id",
foreign_keys=dag_id,
uselist=False,
innerjoin=True,
viewonly=True,
)
trigger = relationship("Trigger", uselist=False, back_populates="task_instance")
triggerer_job = association_proxy("trigger", "triggerer_job")
dag_run = relationship("DagRun", back_populates="task_instances", lazy="joined", innerjoin=True)
rendered_task_instance_fields = relationship("RenderedTaskInstanceFields", lazy="noload", uselist=False)
execution_date = association_proxy("dag_run", "execution_date")
task_instance_note = relationship(
"TaskInstanceNote",
back_populates="task_instance",
uselist=False,
cascade="all, delete, delete-orphan",
)
note = association_proxy("task_instance_note", "content", creator=_creator_note)
task: Operator # Not always set...
is_trigger_log_context: bool = False
"""Indicate to FileTaskHandler that logging context should be set up for trigger logging.
:meta private:
"""
def __init__(
self,
task: Operator,
execution_date: datetime | None = None,
run_id: str | None = None,
state: str | None = None,
map_index: int = -1,
):
super().__init__()
self.dag_id = task.dag_id
self.task_id = task.task_id
self.map_index = map_index
self.refresh_from_task(task)
# init_on_load will config the log
self.init_on_load()
if run_id is None and execution_date is not None:
from airflow.models.dagrun import DagRun # Avoid circular import
warnings.warn(
"Passing an execution_date to `TaskInstance()` is deprecated in favour of passing a run_id",
RemovedInAirflow3Warning,
# Stack level is 4 because SQLA adds some wrappers around the constructor
stacklevel=4,
)
# make sure we have a localized execution_date stored in UTC
if execution_date and not timezone.is_localized(execution_date):
self.log.warning(
"execution date %s has no timezone information. Using default from dag or system",
execution_date,
)
if self.task.has_dag():
if TYPE_CHECKING:
assert self.task.dag
execution_date = timezone.make_aware(execution_date, self.task.dag.timezone)
else:
execution_date = timezone.make_aware(execution_date)
execution_date = timezone.convert_to_utc(execution_date)
with create_session() as session:
run_id = (
session.query(DagRun.run_id)
.filter_by(dag_id=self.dag_id, execution_date=execution_date)
.scalar()
)
if run_id is None:
raise DagRunNotFound(
f"DagRun for {self.dag_id!r} with date {execution_date} not found"
) from None
self.run_id = run_id
self.try_number = 0
self.max_tries = self.task.retries
self.unixname = getuser()
if state:
self.state = state
self.hostname = ""
# Is this TaskInstance being currently running within `airflow tasks run --raw`.
# Not persisted to the database so only valid for the current process
self.raw = False
# can be changed when calling 'run'
self.test_mode = False
@property
def stats_tags(self) -> dict[str, str]:
return prune_dict({"dag_id": self.dag_id, "task_id": self.task_id})
@staticmethod
def insert_mapping(run_id: str, task: Operator, map_index: int) -> dict[str, Any]:
"""Insert mapping.
:meta private:
"""
return {
"dag_id": task.dag_id,
"task_id": task.task_id,
"run_id": run_id,
"_try_number": 0,
"hostname": "",
"unixname": getuser(),
"queue": task.queue,
"pool": task.pool,
"pool_slots": task.pool_slots,
"priority_weight": task.priority_weight_total,
"run_as_user": task.run_as_user,
"max_tries": task.retries,
"executor_config": task.executor_config,
"operator": task.task_type,
"custom_operator_name": getattr(task, "custom_operator_name", None),
"map_index": map_index,
}
@reconstructor
def init_on_load(self) -> None:
"""Initialize the attributes that aren't stored in the DB."""
# correctly config the ti log
self._log = logging.getLogger("airflow.task")
self.test_mode = False # can be changed when calling 'run'
@hybrid_property
def try_number(self):
"""
Return the try number that this task number will be when it is actually run.
If the TaskInstance is currently running, this will match the column in the
database, in all other cases this will be incremented.
"""
# This is designed so that task logs end up in the right file.
if self.state == TaskInstanceState.RUNNING:
return self._try_number
return self._try_number + 1
@try_number.setter
def try_number(self, value: int) -> None:
self._try_number = value
@property
def prev_attempted_tries(self) -> int:
"""
Calculate the number of previously attempted tries, defaulting to 0.
Expose this for the Task Tries and Gantt graph views.
Using `try_number` throws off the counts for non-running tasks.
Also useful in error logging contexts to get the try number for the last try that was attempted.
https://issues.apache.org/jira/browse/AIRFLOW-2143
"""
return self._try_number
@property
def next_try_number(self) -> int:
return self._try_number + 1
@property
def operator_name(self) -> str | None:
"""@property: use a more friendly display name for the operator, if set."""
return self.custom_operator_name or self.operator
def command_as_list(
self,
mark_success=False,
ignore_all_deps=False,
ignore_task_deps=False,
ignore_depends_on_past=False,
wait_for_past_depends_before_skipping=False,
ignore_ti_state=False,
local=False,
pickle_id: int | None = None,
raw=False,
job_id=None,
pool=None,
cfg_path=None,
) -> list[str]:
"""
Returns a command that can be executed anywhere where airflow is installed.
This command is part of the message sent to executors by the orchestrator.
"""
dag: DAG | DagModel
# Use the dag if we have it, else fallback to the ORM dag_model, which might not be loaded
if hasattr(self, "task") and hasattr(self.task, "dag") and self.task.dag is not None:
dag = self.task.dag
else:
dag = self.dag_model
should_pass_filepath = not pickle_id and dag
path: PurePath | None = None
if should_pass_filepath:
if dag.is_subdag:
if TYPE_CHECKING:
assert dag.parent_dag is not None
path = dag.parent_dag.relative_fileloc
else:
path = dag.relative_fileloc
if path:
if not path.is_absolute():
path = "DAGS_FOLDER" / path
return TaskInstance.generate_command(
self.dag_id,
self.task_id,
run_id=self.run_id,
mark_success=mark_success,
ignore_all_deps=ignore_all_deps,
ignore_task_deps=ignore_task_deps,
ignore_depends_on_past=ignore_depends_on_past,
wait_for_past_depends_before_skipping=wait_for_past_depends_before_skipping,
ignore_ti_state=ignore_ti_state,
local=local,
pickle_id=pickle_id,
file_path=path,
raw=raw,
job_id=job_id,
pool=pool,
cfg_path=cfg_path,
map_index=self.map_index,
)
@staticmethod
def generate_command(
dag_id: str,
task_id: str,
run_id: str,
mark_success: bool = False,
ignore_all_deps: bool = False,
ignore_depends_on_past: bool = False,
wait_for_past_depends_before_skipping: bool = False,
ignore_task_deps: bool = False,
ignore_ti_state: bool = False,
local: bool = False,
pickle_id: int | None = None,
file_path: PurePath | str | None = None,
raw: bool = False,
job_id: str | None = None,
pool: str | None = None,
cfg_path: str | None = None,
map_index: int = -1,
) -> list[str]:
"""
Generates the shell command required to execute this task instance.
:param dag_id: DAG ID
:param task_id: Task ID
:param run_id: The run_id of this task's DagRun
:param mark_success: Whether to mark the task as successful
:param ignore_all_deps: Ignore all ignorable dependencies.
Overrides the other ignore_* parameters.
:param ignore_depends_on_past: Ignore depends_on_past parameter of DAGs
(e.g. for Backfills)
:param wait_for_past_depends_before_skipping: Wait for past depends before marking the ti as skipped
:param ignore_task_deps: Ignore task-specific dependencies such as depends_on_past
and trigger rule
:param ignore_ti_state: Ignore the task instance's previous failure/success
:param local: Whether to run the task locally
:param pickle_id: If the DAG was serialized to the DB, the ID
associated with the pickled DAG
:param file_path: path to the file containing the DAG definition
:param raw: raw mode (needs more details)
:param job_id: job ID (needs more details)
:param pool: the Airflow pool that the task should run in
:param cfg_path: the Path to the configuration file
:return: shell command that can be used to run the task instance
"""
cmd = ["airflow", "tasks", "run", dag_id, task_id, run_id]
if mark_success:
cmd.extend(["--mark-success"])
if pickle_id:
cmd.extend(["--pickle", str(pickle_id)])
if job_id:
cmd.extend(["--job-id", str(job_id)])
if ignore_all_deps:
cmd.extend(["--ignore-all-dependencies"])
if ignore_task_deps:
cmd.extend(["--ignore-dependencies"])
if ignore_depends_on_past:
cmd.extend(["--depends-on-past", "ignore"])
elif wait_for_past_depends_before_skipping:
cmd.extend(["--depends-on-past", "wait"])
if ignore_ti_state:
cmd.extend(["--force"])
if local:
cmd.extend(["--local"])
if pool:
cmd.extend(["--pool", pool])
if raw:
cmd.extend(["--raw"])
if file_path:
cmd.extend(["--subdir", os.fspath(file_path)])
if cfg_path:
cmd.extend(["--cfg-path", cfg_path])
if map_index != -1:
cmd.extend(["--map-index", str(map_index)])
return cmd
@property
def log_url(self) -> str:
"""Log URL for TaskInstance."""
iso = quote(self.execution_date.isoformat())
base_url = conf.get_mandatory_value("webserver", "BASE_URL")
return (
f"{base_url}"
"/log"
f"?execution_date={iso}"
f"&task_id={self.task_id}"
f"&dag_id={self.dag_id}"
f"&map_index={self.map_index}"
)
@property
def mark_success_url(self) -> str:
"""URL to mark TI success."""
base_url = conf.get_mandatory_value("webserver", "BASE_URL")
return (
f"{base_url}"
"/confirm"
f"?task_id={self.task_id}"
f"&dag_id={self.dag_id}"
f"&dag_run_id={quote(self.run_id)}"
"&upstream=false"
"&downstream=false"
"&state=success"
)
@provide_session
def current_state(self, session: Session = NEW_SESSION) -> str:
"""
Get the very latest state from the database.
If a session is passed, we use and looking up the state becomes part of the session,
otherwise a new session is used.
sqlalchemy.inspect is used here to get the primary keys ensuring that if they change
it will not regress
:param session: SQLAlchemy ORM Session
"""
filters = (col == getattr(self, col.name) for col in inspect(TaskInstance).primary_key)
return session.query(TaskInstance.state).filter(*filters).scalar()
@provide_session
def error(self, session: Session = NEW_SESSION) -> None:
"""
Forces the task instance's state to FAILED in the database.
:param session: SQLAlchemy ORM Session
"""
self.log.error("Recording the task instance as FAILED")
self.state = TaskInstanceState.FAILED
session.merge(self)
session.commit()
@provide_session
def refresh_from_db(self, session: Session = NEW_SESSION, lock_for_update: bool = False) -> None:
"""
Refreshes the task instance from the database based on the primary key.
:param session: SQLAlchemy ORM Session
:param lock_for_update: if True, indicates that the database should
lock the TaskInstance (issuing a FOR UPDATE clause) until the
session is committed.
"""
self.log.debug("Refreshing TaskInstance %s from DB", self)
if self in session:
session.refresh(self, TaskInstance.__mapper__.column_attrs.keys())
qry = (
# To avoid joining any relationships, by default select all
# columns, not the object. This also means we get (effectively) a
# namedtuple back, not a TI object
session.query(*TaskInstance.__table__.columns).filter(
TaskInstance.dag_id == self.dag_id,
TaskInstance.task_id == self.task_id,
TaskInstance.run_id == self.run_id,
TaskInstance.map_index == self.map_index,
)
)
if lock_for_update:
for attempt in run_with_db_retries(logger=self.log):
with attempt:
ti: TaskInstance | None = qry.with_for_update().one_or_none()
else:
ti = qry.one_or_none()
if ti:
# Fields ordered per model definition
self.start_date = ti.start_date
self.end_date = ti.end_date
self.duration = ti.duration
self.state = ti.state
# Since we selected columns, not the object, this is the raw value
self.try_number = ti.try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.unixname = ti.unixname
self.job_id = ti.job_id
self.pool = ti.pool
self.pool_slots = ti.pool_slots or 1
self.queue = ti.queue
self.priority_weight = ti.priority_weight
self.operator = ti.operator
self.custom_operator_name = ti.custom_operator_name
self.queued_dttm = ti.queued_dttm
self.queued_by_job_id = ti.queued_by_job_id
self.pid = ti.pid
self.executor_config = ti.executor_config
self.external_executor_id = ti.external_executor_id
self.trigger_id = ti.trigger_id
self.next_method = ti.next_method
self.next_kwargs = ti.next_kwargs
else:
self.state = None
def refresh_from_task(self, task: Operator, pool_override: str | None = None) -> None:
"""
Copy common attributes from the given task.
:param task: The task object to copy from
:param pool_override: Use the pool_override instead of task's pool
"""
self.task = task
self.queue = task.queue
self.pool = pool_override or task.pool
self.pool_slots = task.pool_slots
self.priority_weight = task.priority_weight_total
self.run_as_user = task.run_as_user
# Do not set max_tries to task.retries here because max_tries is a cumulative
# value that needs to be stored in the db.
self.executor_config = task.executor_config
self.operator = task.task_type
self.custom_operator_name = getattr(task, "custom_operator_name", None)
@provide_session
def clear_xcom_data(self, session: Session = NEW_SESSION) -> None:
"""Clear all XCom data from the database for the task instance.
If the task is unmapped, all XComs matching this task ID in the same DAG
run are removed. If the task is mapped, only the one with matching map
index is removed.
:param session: SQLAlchemy ORM Session
"""
self.log.debug("Clearing XCom data")
if self.map_index < 0:
map_index: int | None = None
else:
map_index = self.map_index
XCom.clear(
dag_id=self.dag_id,
task_id=self.task_id,
run_id=self.run_id,
map_index=map_index,
session=session,
)
@property
def key(self) -> TaskInstanceKey:
"""Returns a tuple that identifies the task instance uniquely."""
return TaskInstanceKey(self.dag_id, self.task_id, self.run_id, self.try_number, self.map_index)
@provide_session
def set_state(self, state: str | None, session: Session = NEW_SESSION) -> bool:
"""
Set TaskInstance state.
:param state: State to set for the TI
:param session: SQLAlchemy ORM Session
:return: Was the state changed
"""
if self.state == state:
return False
current_time = timezone.utcnow()
self.log.debug("Setting task state for %s to %s", self, state)
self.state = state
self.start_date = self.start_date or current_time
if self.state in State.finished or self.state == TaskInstanceState.UP_FOR_RETRY:
self.end_date = self.end_date or current_time
self.duration = (self.end_date - self.start_date).total_seconds()
session.merge(self)
return True
@property
def is_premature(self) -> bool:
"""Returns whether a task is in UP_FOR_RETRY state and its retry interval has elapsed."""
# is the task still in the retry waiting period?
return self.state == TaskInstanceState.UP_FOR_RETRY and not self.ready_for_retry()
@provide_session
def are_dependents_done(self, session: Session = NEW_SESSION) -> bool:
"""
Checks whether the immediate dependents of this task instance have succeeded or have been skipped.
This is meant to be used by wait_for_downstream.
This is useful when you do not want to start processing the next
schedule of a task until the dependents are done. For instance,
if the task DROPs and recreates a table.
:param session: SQLAlchemy ORM Session
"""
task = self.task
if not task.downstream_task_ids:
return True
ti = session.query(func.count(TaskInstance.task_id)).filter(
TaskInstance.dag_id == self.dag_id,
TaskInstance.task_id.in_(task.downstream_task_ids),
TaskInstance.run_id == self.run_id,
TaskInstance.state.in_((TaskInstanceState.SKIPPED, TaskInstanceState.SUCCESS)),
)
count = ti[0][0]
return count == len(task.downstream_task_ids)
@provide_session
def get_previous_dagrun(
self,