Repository navigation
Expand file tree
/
Copy pathtask_runner.py
More file actions
2002 lines (1697 loc) · 78.7 KB
/
Copy pathtask_runner.py
File metadata and controls
2002 lines (1697 loc) · 78.7 KB
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.
"""The entrypoint for the actual task execution process."""
from __future__ import annotations
import contextvars
import functools
import os
import sys
import time
from collections.abc import Callable, Iterable, Iterator, Mapping
from contextlib import ExitStack, contextmanager, suppress
from datetime import datetime, timedelta, timezone
from itertools import product
from pathlib import Path
from typing import TYPE_CHECKING, Annotated, Any, Literal
from urllib.parse import quote
import attrs
import lazy_object_proxy
import structlog
from opentelemetry import trace
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from pydantic import AwareDatetime, ConfigDict, Field, JsonValue, TypeAdapter
from structlog.contextvars import bind_contextvars
from airflow.dag_processing.bundles.base import BaseDagBundle, BundleVersionLock
from airflow.dag_processing.bundles.manager import DagBundlesManager
from airflow.sdk._shared.observability.metrics.stats import Stats
from airflow.sdk._shared.template_rendering import truncate_rendered_value
from airflow.sdk.api.client import get_hostname, getuser
from airflow.sdk.api.datamodels._generated import (
AssetProfile,
DagRun,
PreviousTIResponse,
TaskInstance,
TaskInstanceState,
TIRunContext,
)
from airflow.sdk.bases.operator import BaseOperator, ExecutorSafeguard
from airflow.sdk.bases.xcom import BaseXCom
from airflow.sdk.configuration import conf
from airflow.sdk.definitions._internal.dag_parsing_context import _airflow_parsing_context_manager
from airflow.sdk.definitions._internal.types import NOTSET, ArgNotSet, is_arg_set
from airflow.sdk.definitions.asset import Asset, AssetAlias, AssetNameRef, AssetUniqueKey, AssetUriRef
from airflow.sdk.definitions.mappedoperator import MappedOperator
from airflow.sdk.definitions.param import process_params
from airflow.sdk.exceptions import (
AirflowException,
AirflowInactiveAssetInInletOrOutletException,
AirflowRescheduleException,
AirflowRuntimeError,
AirflowTaskTimeout,
ErrorType,
TaskDeferred,
)
from airflow.sdk.execution_time.callback_runner import create_executable_runner
from airflow.sdk.execution_time.comms import (
AssetEventDagRunReferenceResult,
CommsDecoder,
DagResult,
DagRunStateResult,
DeferTask,
DRCount,
ErrorResponse,
GetDag,
GetDagRunState,
GetDRCount,
GetPreviousDagRun,
GetPreviousTI,
GetTaskBreadcrumbs,
GetTaskRescheduleStartDate,
GetTaskStates,
GetTICount,
InactiveAssetsResult,
PreviousDagRunResult,
PreviousTIResult,
RescheduleTask,
ResendLoggingFD,
RetryTask,
SentFDs,
SetRenderedFields,
SetRenderedMapIndex,
SkipDownstreamTasks,
StartupDetails,
SucceedTask,
TaskBreadcrumbsResult,
TaskRescheduleStartDate,
TaskState,
TaskStatesResult,
TICount,
ToSupervisor,
ToTask,
TriggerDagRun,
ValidateInletsAndOutlets,
)
from airflow.sdk.execution_time.context import (
ConnectionAccessor,
InletEventsAccessors,
MacrosAccessor,
OutletEventAccessors,
TriggeringAssetEventsAccessor,
VariableAccessor,
context_get_outlet_events,
context_to_airflow_vars,
get_previous_dagrun_success,
set_current_context,
)
from airflow.sdk.execution_time.sentry import Sentry
from airflow.sdk.execution_time.xcom import XCom
from airflow.sdk.listener import get_listener_manager
from airflow.sdk.observability.metrics import stats_utils
from airflow.sdk.timezone import coerce_datetime
if TYPE_CHECKING:
import jinja2
from pendulum.datetime import DateTime
from structlog.typing import FilteringBoundLogger as Logger
from airflow.sdk.definitions._internal.abstractoperator import AbstractOperator
from airflow.sdk.definitions.context import Context
from airflow.sdk.exceptions import DagRunTriggerException
from airflow.sdk.types import OutletEventAccessorsProtocol
log = structlog.get_logger("task")
tracer = trace.get_tracer(__name__)
@contextmanager
def _make_task_span(msg: StartupDetails):
parent_context = (
TraceContextTextMapPropagator().extract(msg.ti.context_carrier) if msg.ti.context_carrier else None
)
ti = msg.ti
span_name = f"worker.{ti.task_id}"
if ti.map_index is not None and ti.map_index >= 0:
span_name += f"[{ti.map_index}]"
with tracer.start_as_current_span(span_name, context=parent_context) as span:
span.set_attributes(
{
"airflow.dag_id": ti.dag_id,
"airflow.task_id": ti.task_id,
"airflow.dag_run.run_id": ti.run_id,
"airflow.task_instance.try_number": ti.try_number,
"airflow.task_instance.map_index": ti.map_index if ti.map_index is not None else -1,
}
)
yield span
class TaskRunnerMarker:
"""Marker for listener hooks, to properly detect from which component they are called."""
# TODO: Move this entire class into a separate file:
# `airflow/sdk/execution_time/task_instance.py`
# or `airflow/sdk/execution_time/runtime_ti.py`
class RuntimeTaskInstance(TaskInstance):
model_config = ConfigDict(arbitrary_types_allowed=True)
task: BaseOperator
bundle_instance: BaseDagBundle
_cached_template_context: Context | None = None
"""The Task Instance context. This is used to cache get_template_context."""
_terminal_state_send_failed: bool = False
"""True when the supervisor IPC send for a non-success terminal state raised; signals main() to sys.exit(1) after finalize() so the supervisor doesn't misclassify the run as SUCCESS via exit code 0."""
_ti_context_from_server: Annotated[TIRunContext | None, Field(repr=False)] = None
"""The Task Instance context from the API server, if any."""
max_tries: int = 0
"""The maximum number of retries for the task."""
start_date: AwareDatetime
"""Start date of the task instance."""
end_date: AwareDatetime | None = None
state: TaskInstanceState | None = None
is_mapped: bool | None = None
"""True if the original task was mapped."""
rendered_map_index: str | None = None
sentry_integration: str = ""
def __rich_repr__(self):
yield "id", self.id
yield "task_id", self.task_id
yield "dag_id", self.dag_id
yield "run_id", self.run_id
yield "max_tries", self.max_tries
yield "task", type(self.task)
yield "start_date", self.start_date
__rich_repr__.angular = True # type: ignore[attr-defined]
def get_template_context(self) -> Context:
# TODO: Move this to `airflow.sdk.execution_time.context`
# once we port the entire context logic from airflow/utils/context.py ?
from airflow.sdk.plugins_manager import integrate_macros_plugins
integrate_macros_plugins()
dag_run_conf: dict[str, Any] | None = None
if from_server := self._ti_context_from_server:
dag_run_conf = from_server.dag_run.conf or dag_run_conf
validated_params = process_params(self.task.dag, self.task, dag_run_conf, suppress_exception=False)
# Cache the context object, which ensures that all calls to get_template_context
# are operating on the same context object.
self._cached_template_context: Context = self._cached_template_context or {
# From the Task Execution interface
"dag": self.task.dag,
"inlets": self.task.inlets,
"map_index_template": self.task.map_index_template,
"outlets": self.task.outlets,
"run_id": self.run_id,
"task": self.task,
"task_instance": self,
"ti": self,
"outlet_events": OutletEventAccessors(),
"inlet_events": InletEventsAccessors(self.task.inlets),
"macros": MacrosAccessor(),
"params": validated_params,
# TODO: Make this go through Public API longer term.
# "test_mode": task_instance.test_mode,
"var": {
"json": VariableAccessor(deserialize_json=True),
"value": VariableAccessor(deserialize_json=False),
},
"conn": ConnectionAccessor(),
}
if from_server:
dag_run = from_server.dag_run
context_from_server: Context = {
# TODO: Assess if we need to pass these through timezone.coerce_datetime
"dag_run": dag_run, # type: ignore[typeddict-item] # Removable after #46522
"triggering_asset_events": TriggeringAssetEventsAccessor.build(
AssetEventDagRunReferenceResult.from_asset_event_dag_run_reference(event)
for event in dag_run.consumed_asset_events
),
"task_instance_key_str": f"{self.task.dag_id}__{self.task.task_id}__{dag_run.run_id}",
"task_reschedule_count": from_server.task_reschedule_count or 0,
"prev_start_date_success": lazy_object_proxy.Proxy(
lambda: coerce_datetime(get_previous_dagrun_success(self.id).start_date)
),
"prev_end_date_success": lazy_object_proxy.Proxy(
lambda: coerce_datetime(get_previous_dagrun_success(self.id).end_date)
),
}
self._cached_template_context.update(context_from_server)
if logical_date := coerce_datetime(dag_run.logical_date):
if TYPE_CHECKING:
assert isinstance(logical_date, DateTime)
ds = logical_date.strftime("%Y-%m-%d")
ds_nodash = ds.replace("-", "")
ts = logical_date.isoformat()
ts_nodash = logical_date.strftime("%Y%m%dT%H%M%S")
ts_nodash_with_tz = ts.replace("-", "").replace(":", "")
# logical_date and data_interval either coexist or be None together
self._cached_template_context.update(
{
# keys that depend on logical_date
"logical_date": logical_date,
"ds": ds,
"ds_nodash": ds_nodash,
"task_instance_key_str": f"{self.task.dag_id}__{self.task.task_id}__{ds_nodash}",
"ts": ts,
"ts_nodash": ts_nodash,
"ts_nodash_with_tz": ts_nodash_with_tz,
# keys that depend on data_interval
"data_interval_end": coerce_datetime(dag_run.data_interval_end),
"data_interval_start": coerce_datetime(dag_run.data_interval_start),
"prev_data_interval_start_success": lazy_object_proxy.Proxy(
lambda: coerce_datetime(get_previous_dagrun_success(self.id).data_interval_start)
),
"prev_data_interval_end_success": lazy_object_proxy.Proxy(
lambda: coerce_datetime(get_previous_dagrun_success(self.id).data_interval_end)
),
}
)
# Backward compatibility: old servers may still send upstream_map_indexes
upstream_map_indexes = getattr(from_server, "upstream_map_indexes", None)
if upstream_map_indexes is not None:
setattr(self, "_upstream_map_indexes", upstream_map_indexes)
return self._cached_template_context
def render_templates(
self, context: Context | None = None, jinja_env: jinja2.Environment | None = None
) -> BaseOperator:
"""
Render templates in the operator fields.
If the task was originally mapped, this may replace ``self.task`` with
the unmapped, fully rendered BaseOperator. The original ``self.task``
before replacement is returned.
"""
if not context:
context = self.get_template_context()
original_task = self.task
if TYPE_CHECKING:
assert context
ti = context["ti"]
if TYPE_CHECKING:
assert original_task
assert self.task
assert ti.task
# If self.task is mapped, this call replaces self.task to point to the
# unmapped BaseOperator created by this function! This is because the
# MappedOperator is useless for template rendering, and we need to be
# able to access the unmapped task instead.
self.task.render_template_fields(context, jinja_env)
self.is_mapped = original_task.is_mapped
return original_task
def xcom_pull(
self,
task_ids: str | Iterable[str] | None = None,
dag_id: str | None = None,
key: str = BaseXCom.XCOM_RETURN_KEY,
include_prior_dates: bool = False,
*,
map_indexes: int | Iterable[int] | None | ArgNotSet = NOTSET,
default: Any = None,
run_id: str | None = None,
) -> Any:
"""
Pull XComs either from the API server (BaseXCom) or from the custom XCOM backend if configured.
The pull can be filtered optionally by certain criterion.
:param key: A key for the XCom. If provided, only XComs with matching
keys will be returned. The default key is ``'return_value'``, also
available as constant ``XCOM_RETURN_KEY``. This key is automatically
given to XComs returned by tasks (as opposed to being pushed
manually).
:param task_ids: Only XComs from tasks with matching ids will be
pulled. If *None* (default), the task_id of the calling task is used.
:param dag_id: If provided, only pulls XComs from this Dag. If *None*
(default), the Dag of the calling task is used.
:param map_indexes: If provided, only pull XComs with matching indexes.
If *None* (default), this is inferred from the task(s) being pulled
(see below for details).
:param include_prior_dates: If False, only XComs from the current
logical_date are returned. If *True*, XComs from previous dates
are returned as well.
:param run_id: If provided, only pulls XComs from a DagRun w/a matching run_id.
If *None* (default), the run_id of the calling task is used.
When pulling one single task (``task_id`` is *None* or a str) without
specifying ``map_indexes``, the return value is a single XCom entry
(map_indexes is set to map_index of the calling task instance).
When pulling task is mapped the specified ``map_index`` is used, so by default
pulling on mapped task will result in no matching XComs if the task instance
of the method call is not mapped. Otherwise, the map_index of the calling task
instance is used. Setting ``map_indexes`` to *None* will pull XCom as it would
from a non mapped task.
In either case, ``default`` (*None* if not specified) is returned if no
matching XComs are found.
When pulling multiple tasks (i.e. either ``task_id`` or ``map_index`` is
a non-str iterable), a list of matching XComs is returned. Elements in
the list is ordered by item ordering in ``task_id`` and ``map_index``.
"""
if dag_id is None:
dag_id = self.dag_id
if run_id is None:
run_id = self.run_id
single_task_requested = isinstance(task_ids, (str, type(None)))
single_map_index_requested = isinstance(map_indexes, (int, type(None)))
if task_ids is None:
# default to the current task if not provided
task_ids = [self.task_id]
elif isinstance(task_ids, str):
task_ids = [task_ids]
# If map_indexes is not specified, pull xcoms from all map indexes for each task
if not is_arg_set(map_indexes):
xcoms: list[Any] = []
for t_id in task_ids:
values = XCom.get_all(
run_id=run_id,
key=key,
task_id=t_id,
dag_id=dag_id,
include_prior_dates=include_prior_dates,
)
if values is None:
xcoms.append(None)
else:
xcoms.extend(values)
# For single task pulling from unmapped task, return single value
if single_task_requested and len(xcoms) == 1:
return xcoms[0]
return xcoms
# Original logic when map_indexes is explicitly specified
map_indexes_iterable: Iterable[int | None] = []
if isinstance(map_indexes, int) or map_indexes is None:
map_indexes_iterable = [map_indexes]
elif isinstance(map_indexes, Iterable):
map_indexes_iterable = map_indexes
else:
raise TypeError(
f"Invalid type for map_indexes: expected int, iterable of ints, or None, got {type(map_indexes)}"
)
xcoms = []
for t_id, m_idx in product(task_ids, map_indexes_iterable):
value = XCom.get_one(
run_id=run_id,
key=key,
task_id=t_id,
dag_id=dag_id,
map_index=m_idx,
include_prior_dates=include_prior_dates,
)
if value is None:
xcoms.append(default)
else:
xcoms.append(value)
if single_task_requested and single_map_index_requested:
return xcoms[0]
return xcoms
def xcom_push(self, key: str, value: Any):
"""
Make an XCom available for tasks to pull.
:param key: Key to store the value under.
:param value: Value to store. Only be JSON-serializable values may be used.
"""
_xcom_push(self, key, value)
def get_relevant_upstream_map_indexes(
self, upstream: BaseOperator, ti_count: int | None, session: Any
) -> int | range | None:
"""
Compute the relevant upstream map indexes for XCom resolution.
:param upstream: The upstream operator
:param ti_count: The total count of task instances for this task's expansion
:param session: Not used (kept for API compatibility)
:return: None (use entire value), int (single index), or range (subset of indexes)
"""
from airflow.sdk.execution_time.task_mapping import get_relevant_map_indexes, get_ti_count_for_task
map_index = self.map_index
if map_index is None or map_index < 0:
return None
# If ti_count not provided, we need to query it
if ti_count is None:
ti_count = get_ti_count_for_task(self.task_id, self.dag_id, self.run_id)
if not ti_count:
return None
return get_relevant_map_indexes(
task=self.task,
run_id=self.run_id,
map_index=map_index,
ti_count=ti_count,
relative=upstream,
dag_id=self.dag_id,
)
def get_first_reschedule_date(self, context: Context) -> AwareDatetime | None:
"""Get the first reschedule date for the task instance if found, none otherwise."""
if context.get("task_reschedule_count", 0) == 0:
# If the task has not been rescheduled, there is no need to ask the supervisor
return None
max_tries: int = self.max_tries
retries: int = self.task.retries or 0
first_try_number = max_tries - retries + 1
log.debug("Requesting first reschedule date from supervisor")
response = SUPERVISOR_COMMS.send(
msg=GetTaskRescheduleStartDate(ti_id=self.id, try_number=first_try_number)
)
if TYPE_CHECKING:
assert isinstance(response, TaskRescheduleStartDate)
return response.start_date
def get_previous_dagrun(self, state: str | None = None) -> DagRun | None:
"""Return the previous Dag run before the given logical date, optionally filtered by state."""
context = self.get_template_context()
dag_run = context.get("dag_run")
log.debug("Getting previous Dag run", dag_run=dag_run)
if dag_run is None:
return None
if dag_run.logical_date is None:
return None
response = SUPERVISOR_COMMS.send(
msg=GetPreviousDagRun(dag_id=self.dag_id, logical_date=dag_run.logical_date, state=state)
)
if TYPE_CHECKING:
assert isinstance(response, PreviousDagRunResult)
return response.dag_run
def get_previous_ti(
self,
state: TaskInstanceState | None = None,
logical_date: AwareDatetime | None = None,
map_index: int = -1,
) -> PreviousTIResponse | None:
"""
Return the previous task instance matching the given criteria.
:param state: Filter by TaskInstance state
:param logical_date: Filter by logical date (returns TI before this date)
:param map_index: Filter by map_index (defaults to -1 for non-mapped tasks)
:return: Previous task instance or None if not found
"""
context = self.get_template_context()
dag_run = context.get("dag_run")
log.debug("Getting previous task instance", task_id=self.task_id, state=state)
# Use current dag run's logical_date if not provided
effective_logical_date = logical_date
if effective_logical_date is None and dag_run and dag_run.logical_date:
effective_logical_date = dag_run.logical_date
response = SUPERVISOR_COMMS.send(
msg=GetPreviousTI(
dag_id=self.dag_id,
task_id=self.task_id,
logical_date=effective_logical_date,
map_index=map_index,
state=state,
)
)
if TYPE_CHECKING:
assert isinstance(response, PreviousTIResult)
return response.task_instance
@staticmethod
def get_ti_count(
dag_id: str,
map_index: int | None = None,
task_ids: list[str] | None = None,
task_group_id: str | None = None,
logical_dates: list[datetime] | None = None,
run_ids: list[str] | None = None,
states: list[str] | None = None,
) -> int:
"""Return the number of task instances matching the given criteria."""
response = SUPERVISOR_COMMS.send(
GetTICount(
dag_id=dag_id,
map_index=map_index,
task_ids=task_ids,
task_group_id=task_group_id,
logical_dates=logical_dates,
run_ids=run_ids,
states=states,
),
)
if TYPE_CHECKING:
assert isinstance(response, TICount)
return response.count
@staticmethod
def get_task_states(
dag_id: str,
map_index: int | None = None,
task_ids: list[str] | None = None,
task_group_id: str | None = None,
logical_dates: list[datetime] | None = None,
run_ids: list[str] | None = None,
) -> dict[str, Any]:
"""Return the task states matching the given criteria."""
response = SUPERVISOR_COMMS.send(
GetTaskStates(
dag_id=dag_id,
map_index=map_index,
task_ids=task_ids,
task_group_id=task_group_id,
logical_dates=logical_dates,
run_ids=run_ids,
),
)
if TYPE_CHECKING:
assert isinstance(response, TaskStatesResult)
return response.task_states
@staticmethod
def get_task_breadcrumbs(dag_id: str, run_id: str) -> Iterable[dict[str, Any]]:
"""Return task breadcrumbs for the given dag run."""
response = SUPERVISOR_COMMS.send(GetTaskBreadcrumbs(dag_id=dag_id, run_id=run_id))
if TYPE_CHECKING:
assert isinstance(response, TaskBreadcrumbsResult)
return response.breadcrumbs
@staticmethod
def get_dr_count(
dag_id: str,
logical_dates: list[datetime] | None = None,
run_ids: list[str] | None = None,
states: list[str] | None = None,
) -> int:
"""Return the number of Dag runs matching the given criteria."""
response = SUPERVISOR_COMMS.send(
GetDRCount(
dag_id=dag_id,
logical_dates=logical_dates,
run_ids=run_ids,
states=states,
),
)
if TYPE_CHECKING:
assert isinstance(response, DRCount)
return response.count
@staticmethod
def get_dagrun_state(dag_id: str, run_id: str) -> str:
"""Return the state of the Dag run with the given Run ID."""
response = SUPERVISOR_COMMS.send(msg=GetDagRunState(dag_id=dag_id, run_id=run_id))
if TYPE_CHECKING:
assert isinstance(response, DagRunStateResult)
return response.state
@staticmethod
def get_dag(dag_id: str) -> DagResult:
"""Return the DAG with the given dag_id."""
response = SUPERVISOR_COMMS.send(msg=GetDag(dag_id=dag_id))
if TYPE_CHECKING:
assert isinstance(response, DagResult)
return response
@property
def log_url(self) -> str:
run_id = quote(self.run_id)
base_url = conf.get("api", "base_url", fallback="http://localhost:8080/")
map_index_value = self.map_index
map_index = (
f"/mapped/{map_index_value}" if map_index_value is not None and map_index_value >= 0 else ""
)
try_number_value = self.try_number
try_number = (
f"?try_number={try_number_value}" if try_number_value is not None and try_number_value > 0 else ""
)
_log_uri = f"{base_url.rstrip('/')}/dags/{self.dag_id}/runs/{run_id}/tasks/{self.task_id}{map_index}{try_number}"
return _log_uri
@property
def mark_success_url(self) -> str:
"""URL to mark TI success."""
return self.log_url
def _xcom_push(ti: RuntimeTaskInstance, key: str, value: Any, mapped_length: int | None = None) -> None:
"""Push a XCom through XCom.set, which pushes to XCom Backend if configured."""
# Private function, as we don't want to expose the ability to manually set `mapped_length` to SDK
# consumers
XCom.set(
key=key,
value=value,
dag_id=ti.dag_id,
task_id=ti.task_id,
run_id=ti.run_id,
map_index=ti.map_index,
_mapped_length=mapped_length,
)
def _xcom_push_to_db(ti: RuntimeTaskInstance, key: str, value: Any) -> None:
"""Push a XCom directly to metadata DB, bypassing custom xcom_backend."""
XCom._set_xcom_in_db(
key=key,
value=value,
dag_id=ti.dag_id,
task_id=ti.task_id,
run_id=ti.run_id,
map_index=ti.map_index,
)
def _maybe_reschedule_startup_failure(
*,
ti_context: TIRunContext,
log: Logger,
) -> None:
"""
Attempt to reschedule the task when a startup failure occurs.
This does not count as a retry. If the reschedule limit is exceeded, this function
returns and the caller should fail the task.
"""
missing_dag_retries = conf.getint("workers", "missing_dag_retries", fallback=3)
missing_dag_retry_delay = conf.getint("workers", "missing_dag_retry_delay", fallback=60)
reschedule_count = int(getattr(ti_context, "task_reschedule_count", 0) or 0)
if missing_dag_retries > 0 and reschedule_count < missing_dag_retries:
raise AirflowRescheduleException(
reschedule_date=datetime.now(tz=timezone.utc) + timedelta(seconds=missing_dag_retry_delay)
)
log.error(
"Startup reschedule limit exceeded",
reschedule_count=reschedule_count,
max_reschedules=missing_dag_retries,
)
def parse(what: StartupDetails, log: Logger) -> RuntimeTaskInstance:
# TODO: Task-SDK:
# Using BundleDagBag here is about 98% wrong, but it'll do for now
from airflow.dag_processing.dagbag import BundleDagBag
bundle_info = what.bundle_info
bundle_instance = DagBundlesManager().get_bundle(
name=bundle_info.name,
version=bundle_info.version,
)
bundle_instance.initialize()
_verify_bundle_access(bundle_instance, log)
dag_absolute_path = os.fspath(Path(bundle_instance.path, what.dag_rel_path))
bag = BundleDagBag(
dag_folder=dag_absolute_path,
safe_mode=False,
load_op_links=False,
bundle_path=bundle_instance.path,
bundle_name=bundle_info.name,
)
if TYPE_CHECKING:
assert what.ti.dag_id
try:
dag = bag.dags[what.ti.dag_id]
except KeyError:
log.error(
"Dag not found during start up", dag_id=what.ti.dag_id, bundle=bundle_info, path=what.dag_rel_path
)
_maybe_reschedule_startup_failure(ti_context=what.ti_context, log=log)
sys.exit(1)
# install_loader()
try:
task = dag.task_dict[what.ti.task_id]
except KeyError:
log.error(
"Task not found in Dag during start up",
dag_id=dag.dag_id,
task_id=what.ti.task_id,
bundle=bundle_info,
path=what.dag_rel_path,
)
_maybe_reschedule_startup_failure(ti_context=what.ti_context, log=log)
sys.exit(1)
if not isinstance(task, (BaseOperator, MappedOperator)):
raise TypeError(
f"task is of the wrong type, got {type(task)}, wanted {BaseOperator} or {MappedOperator}"
)
return RuntimeTaskInstance.model_construct(
**what.ti.model_dump(exclude_unset=True),
task=task,
bundle_instance=bundle_instance,
_ti_context_from_server=what.ti_context,
max_tries=what.ti_context.max_tries,
start_date=what.start_date,
state=TaskInstanceState.RUNNING,
sentry_integration=what.sentry_integration,
)
# This global variable will be used by Connection/Variable/XCom classes, or other parts of the task's execution,
# to send requests back to the supervisor process.
#
# Why it needs to be a global:
# - Many parts of Airflow's codebase (e.g., connections, variables, and XComs) may rely on making dynamic requests
# to the parent process during task execution.
# - These calls occur in various locations and cannot easily pass the `CommsDecoder` instance through the
# deeply nested execution stack.
# - By defining `SUPERVISOR_COMMS` as a global, it ensures that this communication mechanism is readily
# accessible wherever needed during task execution without modifying every layer of the call stack.
SUPERVISOR_COMMS: CommsDecoder[ToTask, ToSupervisor]
# State machine!
# 1. Start up (receive details from supervisor)
# 2. Execution (run task code, possibly send requests)
# 3. Shutdown and report status
def _verify_bundle_access(bundle_instance: BaseDagBundle, log: Logger) -> None:
"""
Verify bundle is accessible by the current user.
This is called after user impersonation (if any) to ensure the bundle
is actually accessible. Uses os.access() which works with any permission
scheme (standard Unix permissions, ACLs, SELinux, etc.).
:param bundle_instance: The bundle instance to check
:param log: Logger instance
:raises AirflowException: if bundle is not accessible
"""
from getpass import getuser
from airflow.sdk.exceptions import AirflowException
bundle_path = bundle_instance.path
if not bundle_path.exists():
# Already handled by initialize() with a warning
return
# Check read permission (and execute for directories to list contents)
access_mode = os.R_OK
if bundle_path.is_dir():
access_mode |= os.X_OK
if not os.access(bundle_path, access_mode):
raise AirflowException(
f"Bundle '{bundle_instance.name}' path '{bundle_path}' is not accessible "
f"by user '{getuser()}'. When using run_as_user, ensure bundle directories "
f"are readable by the impersonated user. "
f"See: https://airflow.apache.org/docs/apache-airflow/stable/administration-and-deployment/dag-bundles.html"
)
def get_startup_details() -> StartupDetails:
# The parent sends us a StartupDetails message un-prompted. After this, every single message is only sent
# in response to us sending a request.
if os.environ.get("_AIRFLOW__REEXECUTED_PROCESS") == "1" and (
msgjson := os.environ.get("_AIRFLOW__STARTUP_MSG")
):
# Clear any Kerberos replace cache if there is one, so new process can't reuse it.
os.environ.pop("KRB5CCNAME", None)
# entrypoint of re-exec process
msg: StartupDetails = TypeAdapter(StartupDetails).validate_json(msgjson)
reinit_supervisor_comms()
# We delay this message until _after_ we've got the logging re-configured, otherwise it will show up
# on stdout
log.debug("Using serialized startup message from environment", msg=msg)
else:
# normal entry point
msg = SUPERVISOR_COMMS._get_response() # type: ignore[assignment]
if not isinstance(msg, StartupDetails):
raise RuntimeError(f"Unhandled startup message {type(msg)} {msg}")
return msg
def startup(msg: StartupDetails) -> tuple[RuntimeTaskInstance, Context, Logger]:
# setproctitle causes issue on Mac OS: https://github.com/benoitc/gunicorn/issues/3021
os_type = sys.platform
if os_type == "darwin":
log.debug("Mac OS detected, skipping setproctitle")
else:
from setproctitle import setproctitle
setproctitle(f"airflow worker -- {msg.ti.id}")
# Bind TI identifiers so every subsequent log line from this worker process
# carries ti_id, enabling single-grep lifecycle reconstruction across components.
bind_contextvars(
ti_id=str(msg.ti.id),
dag_id=msg.ti.dag_id,
task_id=msg.ti.task_id,
run_id=msg.ti.run_id,
try_number=msg.ti.try_number,
map_index=msg.ti.map_index,
)
try:
get_listener_manager().hook.on_starting(component=TaskRunnerMarker())
except Exception:
log.exception("error calling listener")
with _airflow_parsing_context_manager(dag_id=msg.ti.dag_id, task_id=msg.ti.task_id):
ti = parse(msg, log)
log.debug("Dag file parsed", file=msg.dag_rel_path)
run_as_user = getattr(ti.task, "run_as_user", None) or conf.get(
"core", "default_impersonation", fallback=None
)
if os.environ.get("_AIRFLOW__REEXECUTED_PROCESS") != "1" and run_as_user and run_as_user != getuser():
# enters here for re-exec process
os.environ["_AIRFLOW__REEXECUTED_PROCESS"] = "1"
# store startup message in environment for re-exec process
os.environ["_AIRFLOW__STARTUP_MSG"] = msg.model_dump_json()
os.set_inheritable(SUPERVISOR_COMMS.socket.fileno(), True)
# Import main directly from the module instead of re-executing the file.
# This ensures that when other parts modules import
# airflow.sdk.execution_time.task_runner, they get the same module instance
# with the properly initialized SUPERVISOR_COMMS global variable.
# If we re-executed the module with `python -m`, it would load as __main__ and future
# imports would get a fresh copy without the initialized globals.
rexec_python_code = "from airflow.sdk.execution_time.task_runner import main; main()"
cmd = ["sudo", "-E", "-H", "-u", run_as_user, sys.executable, "-c", rexec_python_code]
log.info(
"Running command",
command=cmd,
)
os.execvp("sudo", cmd)
# ideally, we should never reach here, but if we do, we should return None, None, None
return None, None, None
return ti, ti.get_template_context(), log
def _serialize_template_field(
template_field: Any, name: str
) -> str | dict | list | int | float | bool | None:
"""
Return a serializable representation of the templated field.
The walk has two responsibilities:
1. **Make the template_field JSON-encodable** — every container is rebuilt
with primitive leaves (str/int/float/bool/None), tuples and sets are
flattened to lists, and unsupported objects fall through to ``str()``
so ``json.dumps`` never raises on the result.
2. **Keep the output deterministic across parses** — callables are replaced
with their qualified name (never the default ``<function ... at 0x...>``
repr), dicts are key-sorted, and (frozen)sets are sorted by element so
the same input always produces the same string.
Uses the SDK secrets masker to redact secrets in the serialized output.
"""
import inspect
from airflow.sdk._shared.module_loading import qualname
from airflow.sdk._shared.secrets_masker import redact
def normalize_dict_key(key) -> str:
"""Normalize a dict key to a serialized string type."""
# Serialized template_field keys must all be strings, not a mix of types, so that
# downstream json.dumps(..., sort_keys=True) does not raise on mixed-type keys.
return str(serialize_object(key))