forked from apache/airflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_local_task_job.py
975 lines (840 loc) · 38.3 KB
/
test_local_task_job.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
#
# 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 datetime
import logging
import multiprocessing as mp
import os
import re
import signal
import threading
import time
import uuid
import warnings
from unittest import mock
from unittest.mock import patch
import psutil
import pytest
from airflow import DAG, settings
from airflow.exceptions import AirflowException
from airflow.executors.sequential_executor import SequentialExecutor
from airflow.jobs.job import Job, run_job
from airflow.jobs.local_task_job_runner import SIGSEGV_MESSAGE, LocalTaskJobRunner
from airflow.jobs.scheduler_job_runner import SchedulerJobRunner
from airflow.models.dagbag import DagBag
from airflow.models.serialized_dag import SerializedDagModel
from airflow.models.taskinstance import TaskInstance
from airflow.operators.empty import EmptyOperator
from airflow.operators.python import PythonOperator
from airflow.task.task_runner.standard_task_runner import StandardTaskRunner
from airflow.utils import timezone
from airflow.utils.net import get_hostname
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.timeout import timeout
from airflow.utils.types import DagRunType
from tests.test_utils import db
from tests.test_utils.asserts import assert_queries_count
from tests.test_utils.config import conf_vars
from tests.test_utils.mock_executor import MockExecutor
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
TEST_DAG_FOLDER = os.environ["AIRFLOW__CORE__DAGS_FOLDER"]
@pytest.fixture
def clear_db():
db.clear_db_dags()
db.clear_db_jobs()
db.clear_db_runs()
db.clear_db_task_fail()
yield
@pytest.fixture(scope="class")
def clear_db_class():
yield
db.clear_db_dags()
db.clear_db_jobs()
db.clear_db_runs()
db.clear_db_task_fail()
@pytest.fixture(scope="module")
def dagbag():
return DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
@pytest.mark.usefixtures("clear_db_class", "clear_db")
class TestLocalTaskJob:
@pytest.fixture(autouse=True)
def set_instance_attrs(self, dagbag):
self.dagbag = dagbag
with patch("airflow.jobs.job.sleep") as self.mock_base_job_sleep:
yield
def validate_ti_states(self, dag_run, ti_state_mapping, error_message):
for task_id, expected_state in ti_state_mapping.items():
task_instance = dag_run.get_task_instance(task_id=task_id)
task_instance.refresh_from_db()
assert task_instance.state == expected_state, error_message
def test_localtaskjob_essential_attr(self, dag_maker):
"""
Check whether essential attributes
of LocalTaskJob can be assigned with
proper values without intervention
"""
with dag_maker("test_localtaskjob_essential_attr"):
op1 = EmptyOperator(task_id="op1")
dr = dag_maker.create_dagrun()
ti = dr.get_task_instance(task_id=op1.task_id)
job1 = Job(dag_id=ti.dag_id, executor=SequentialExecutor())
LocalTaskJobRunner(job=job1, task_instance=ti, ignore_ti_state=True)
essential_attr = ["dag_id", "job_type", "start_date", "hostname"]
check_result_1 = [hasattr(job1, attr) for attr in essential_attr]
assert all(check_result_1)
check_result_2 = [getattr(job1, attr) is not None for attr in essential_attr]
assert all(check_result_2)
def test_localtaskjob_heartbeat(self, dag_maker):
session = settings.Session()
with dag_maker("test_localtaskjob_heartbeat"):
op1 = EmptyOperator(task_id="op1")
dr = dag_maker.create_dagrun()
ti = dr.get_task_instance(task_id=op1.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = "blablabla"
session.commit()
job1 = Job(dag_id=ti.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti, ignore_ti_state=True)
ti.task = op1
ti.refresh_from_task(op1)
job1.task_runner = StandardTaskRunner(job_runner)
job1.task_runner.process = mock.Mock()
job_runner.task_runner = job1.task_runner
with pytest.raises(AirflowException):
job_runner.heartbeat_callback()
job1.task_runner.process.pid = 1
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.merge(ti)
session.commit()
assert ti.pid != os.getpid()
assert not ti.run_as_user
assert not job1.task_runner.run_as_user
job_runner.heartbeat_callback(session=None)
job1.task_runner.process.pid = 2
with pytest.raises(AirflowException):
job_runner.heartbeat_callback()
# Now, set the ti.pid to None and test that no error
# is raised.
ti.pid = None
session.merge(ti)
session.commit()
assert ti.pid != job1.task_runner.process.pid
assert not ti.run_as_user
assert not job1.task_runner.run_as_user
job_runner.heartbeat_callback()
@mock.patch("subprocess.check_call")
@mock.patch("airflow.jobs.local_task_job_runner.psutil")
def test_localtaskjob_heartbeat_with_run_as_user(self, psutil_mock, _, dag_maker):
session = settings.Session()
with dag_maker("test_localtaskjob_heartbeat"):
op1 = EmptyOperator(task_id="op1", run_as_user="myuser")
dr = dag_maker.create_dagrun()
ti = dr.get_task_instance(task_id=op1.task_id, session=session)
ti.state = State.RUNNING
ti.pid = 2
ti.hostname = get_hostname()
session.commit()
job1 = Job(dag_id=ti.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti, ignore_ti_state=True)
ti.task = op1
ti.refresh_from_task(op1)
job1.task_runner = StandardTaskRunner(job_runner)
job1.task_runner.process = mock.Mock()
job1.task_runner.process.pid = 2
job_runner.task_runner = job1.task_runner
# Here, ti.pid is 2, the parent process of ti.pid is a mock(different).
# And task_runner process is 2. Should fail
with pytest.raises(AirflowException, match="PID of job runner does not match"):
job_runner.heartbeat_callback()
job1.task_runner.process.pid = 1
# We make the parent process of ti.pid to equal the task_runner process id
psutil_mock.Process.return_value.ppid.return_value = 1
ti.state = State.RUNNING
ti.pid = 2
# The task_runner process id is 1, same as the parent process of ti.pid
# as seen above
assert ti.run_as_user
session.merge(ti)
session.commit()
job_runner.heartbeat_callback(session=None)
# Here the task_runner process id is changed to 2
# while parent process of ti.pid is kept at 1, which is different
job1.task_runner.process.pid = 2
with pytest.raises(AirflowException, match="PID of job runner does not match"):
job_runner.heartbeat_callback()
# Here we set the ti.pid to None and test that no error is
# raised
ti.pid = None
session.merge(ti)
session.commit()
assert ti.run_as_user
assert job1.task_runner.run_as_user == ti.run_as_user
assert ti.pid != job1.task_runner.process.pid
job_runner.heartbeat_callback()
@conf_vars({("core", "default_impersonation"): "testuser"})
@mock.patch("subprocess.check_call")
@mock.patch("airflow.jobs.local_task_job_runner.psutil")
def test_localtaskjob_heartbeat_with_default_impersonation(self, psutil_mock, _, dag_maker):
session = settings.Session()
with dag_maker("test_localtaskjob_heartbeat"):
op1 = EmptyOperator(task_id="op1")
dr = dag_maker.create_dagrun()
ti = dr.get_task_instance(task_id=op1.task_id, session=session)
ti.state = State.RUNNING
ti.pid = 2
ti.hostname = get_hostname()
session.commit()
job1 = Job(dag_id=ti.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job1, task_instance=ti, ignore_ti_state=True)
ti.task = op1
ti.refresh_from_task(op1)
job1.task_runner = StandardTaskRunner(job_runner)
job1.task_runner.process = mock.Mock()
job1.task_runner.process.pid = 2
job_runner.task_runner = job1.task_runner
# Here, ti.pid is 2, the parent process of ti.pid is a mock(different).
# And task_runner process is 2. Should fail
with pytest.raises(AirflowException, match="PID of job runner does not match"):
job_runner.heartbeat_callback()
job1.task_runner.process.pid = 1
# We make the parent process of ti.pid to equal the task_runner process id
psutil_mock.Process.return_value.ppid.return_value = 1
ti.state = State.RUNNING
ti.pid = 2
# The task_runner process id is 1, same as the parent process of ti.pid
# as seen above
assert job1.task_runner.run_as_user == "testuser"
session.merge(ti)
session.commit()
job_runner.heartbeat_callback(session=None)
# Here the task_runner process id is changed to 2
# while parent process of ti.pid is kept at 1, which is different
job1.task_runner.process.pid = 2
with pytest.raises(AirflowException, match="PID of job runner does not match"):
job_runner.heartbeat_callback()
# Now, set the ti.pid to None and test that no error
# is raised.
ti.pid = None
session.merge(ti)
session.commit()
assert job1.task_runner.run_as_user == "testuser"
assert ti.run_as_user is None
assert ti.pid != job1.task_runner.process.pid
job_runner.heartbeat_callback()
def test_heartbeat_failed_fast(self):
"""
Test that task heartbeat will sleep when it fails fast
"""
self.mock_base_job_sleep.side_effect = time.sleep
dag_id = "test_heartbeat_failed_fast"
task_id = "test_heartbeat_failed_fast_op"
with create_session() as session:
dag_id = "test_heartbeat_failed_fast"
task_id = "test_heartbeat_failed_fast_op"
dag = self.dagbag.get_dag(dag_id)
task = dag.get_task(task_id)
dr = dag.create_dagrun(
run_id="test_heartbeat_failed_fast_run",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = dr.task_instances[0]
ti.refresh_from_task(task)
ti.state = State.QUEUED
ti.hostname = get_hostname()
ti.pid = 1
session.commit()
job = Job(dag_id=ti.dag_id, executor=MockExecutor(do_update=False))
job_runner = LocalTaskJobRunner(job=job, task_instance=ti)
job.heartrate = 2
heartbeat_records = []
job_runner.heartbeat_callback = lambda session: heartbeat_records.append(job.latest_heartbeat)
run_job(job=job, execute_callable=job_runner._execute)
assert len(heartbeat_records) > 2
for time1, time2 in zip(heartbeat_records, heartbeat_records[1:]):
# Assert that difference small enough
delta = (time2 - time1).total_seconds()
assert abs(delta - job.heartrate) < 0.8
def test_mark_success_no_kill(self, caplog, get_test_dag, session):
"""
Test that ensures that mark_success in the UI doesn't cause
the task to fail, and that the task exits
"""
dag = get_test_dag("test_mark_state")
dr = dag.create_dagrun(
state=State.RUNNING,
execution_date=DEFAULT_DATE,
run_type=DagRunType.SCHEDULED,
session=session,
)
task = dag.get_task(task_id="test_mark_success_no_kill")
ti = dr.get_task_instance(task.task_id)
ti.refresh_from_task(task)
job1 = Job(dag_id=ti.dag_id)
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti, ignore_ti_state=True)
with timeout(30):
run_job(job=job1, execute_callable=job_runner._execute)
ti.refresh_from_db()
assert State.SUCCESS == ti.state
assert (
"State of this instance has been externally set to success. Terminating instance." in caplog.text
)
def test_localtaskjob_double_trigger(self):
dag = self.dagbag.dags.get("test_localtaskjob_double_trigger")
task = dag.get_task("test_localtaskjob_double_trigger_task")
session = settings.Session()
dag.clear()
dr = dag.create_dagrun(
run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session,
)
ti = dr.get_task_instance(task_id=task.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.merge(ti)
session.commit()
ti_run = TaskInstance(task=task, run_id=dr.run_id)
ti_run.refresh_from_db()
job1 = Job(dag_id=ti_run.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti_run)
with patch.object(StandardTaskRunner, "start", return_value=None) as mock_method:
run_job(job=job1, execute_callable=job_runner._execute)
mock_method.assert_not_called()
ti = dr.get_task_instance(task_id=task.task_id, session=session)
assert ti.pid == 1
assert ti.state == State.RUNNING
session.close()
@patch.object(StandardTaskRunner, "return_code")
@mock.patch("airflow.jobs.scheduler_job_runner.Stats.incr", autospec=True)
def test_local_task_return_code_metric(self, mock_stats_incr, mock_return_code, create_dummy_dag):
_, task = create_dummy_dag("test_localtaskjob_code")
ti_run = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti_run.refresh_from_db()
job1 = Job(dag_id=ti_run.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti_run)
job1.id = 95
mock_return_code.side_effect = [None, -9, None]
with timeout(10):
run_job(job=job1, execute_callable=job_runner._execute)
mock_stats_incr.assert_has_calls(
[
mock.call("local_task_job.task_exit.95.test_localtaskjob_code.op1.-9"),
mock.call(
"local_task_job.task_exit",
tags={
"job_id": 95,
"dag_id": "test_localtaskjob_code",
"task_id": "op1",
"return_code": -9,
},
),
]
)
@patch.object(StandardTaskRunner, "return_code")
def test_localtaskjob_maintain_heart_rate(self, mock_return_code, caplog, create_dummy_dag):
_, task = create_dummy_dag("test_localtaskjob_double_trigger")
ti_run = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti_run.refresh_from_db()
job1 = Job(dag_id=ti_run.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti_run)
time_start = time.time()
# this should make sure we only heartbeat once and exit at the second
# loop in _execute(). While the heartbeat exits at second loop, return_code
# is also called by task_runner.terminate method for proper clean up,
# hence the extra value after 0.
mock_return_code.side_effect = [None, 0, None]
with timeout(10):
run_job(job=job1, execute_callable=job_runner._execute)
assert mock_return_code.call_count == 3
time_end = time.time()
assert self.mock_base_job_sleep.call_count == 1
assert job1.state == State.SUCCESS
# Consider we have patched sleep call, it should not be sleeping to
# keep up with the heart rate in other unpatched places
#
# We already make sure patched sleep call is only called once
assert time_end - time_start < job1.heartrate
assert "Task exited with return code 0" in caplog.text
def test_mark_failure_on_failure_callback(self, caplog, get_test_dag):
"""
Test that ensures that mark_failure in the UI fails
the task, and executes on_failure_callback
"""
dag = get_test_dag("test_mark_state")
with create_session() as session:
dr = dag.create_dagrun(
state=State.RUNNING,
execution_date=DEFAULT_DATE,
run_type=DagRunType.SCHEDULED,
session=session,
)
task = dag.get_task(task_id="test_mark_failure_externally")
ti = dr.get_task_instance(task.task_id)
ti.refresh_from_task(task)
job1 = Job(dag_id=ti.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti, ignore_ti_state=True)
with timeout(30):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
run_job(job=job1, execute_callable=job_runner._execute)
ti.refresh_from_db()
assert ti.state == State.FAILED
assert (
"State of this instance has been externally set to failed. Terminating instance."
) in caplog.text
def test_dagrun_timeout_logged_in_task_logs(self, caplog, get_test_dag):
"""
Test that ensures that if a running task is externally skipped (due to a dagrun timeout)
It is logged in the task logs.
"""
dag = get_test_dag("test_mark_state")
dag.dagrun_timeout = datetime.timedelta(microseconds=1)
with create_session() as session:
dr = dag.create_dagrun(
state=State.RUNNING,
start_date=DEFAULT_DATE,
execution_date=DEFAULT_DATE,
run_type=DagRunType.SCHEDULED,
session=session,
)
task = dag.get_task(task_id="test_mark_skipped_externally")
ti = dr.get_task_instance(task.task_id)
ti.refresh_from_task(task)
job1 = Job(dag_id=ti.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti, ignore_ti_state=True)
with timeout(30):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
run_job(job=job1, execute_callable=job_runner._execute)
ti.refresh_from_db()
assert ti.state == State.SKIPPED
assert "DagRun timed out after " in caplog.text
def test_failure_callback_called_by_airflow_run_raw_process(self, monkeypatch, tmp_path, get_test_dag):
"""
Ensure failure callback of a task is run by the airflow run --raw process
"""
callback_file = tmp_path.joinpath("callback.txt")
callback_file.touch()
monkeypatch.setenv("AIRFLOW_CALLBACK_FILE", str(callback_file))
dag = get_test_dag("test_on_failure_callback")
with create_session() as session:
dag.create_dagrun(
state=State.RUNNING,
execution_date=DEFAULT_DATE,
run_type=DagRunType.SCHEDULED,
session=session,
)
task = dag.get_task(task_id="test_on_failure_callback_task")
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = Job(executor=SequentialExecutor(), dag_id=ti.dag_id)
job_runner = LocalTaskJobRunner(job1, task_instance=ti, ignore_ti_state=True)
run_job(job=job1, execute_callable=job_runner._execute)
ti.refresh_from_db()
assert ti.state == State.FAILED # task exits with failure state
with open(callback_file) as f:
lines = f.readlines()
assert len(lines) == 1 # invoke once
assert lines[0].startswith(ti.key.primary)
m = re.match(r"^.+pid: (\d+)$", lines[0])
assert m, "pid expected in output."
assert os.getpid() != int(m.group(1))
def test_mark_success_on_success_callback(self, caplog, get_test_dag):
"""
Test that ensures that where a task is marked success in the UI
on_success_callback gets executed
"""
dag = get_test_dag("test_mark_state")
with create_session() as session:
dr = dag.create_dagrun(
state=State.RUNNING,
execution_date=DEFAULT_DATE,
run_type=DagRunType.SCHEDULED,
session=session,
)
task = dag.get_task(task_id="test_mark_success_no_kill")
ti = dr.get_task_instance(task.task_id)
ti.refresh_from_task(task)
job = Job(executor=SequentialExecutor(), dag_id=ti.dag_id)
job_runner = LocalTaskJobRunner(job=job, task_instance=ti, ignore_ti_state=True)
with timeout(30):
# This should run fast because of the return_code=None
run_job(job=job, execute_callable=job_runner._execute)
ti.refresh_from_db()
assert (
"State of this instance has been externally set to success. Terminating instance." in caplog.text
)
@pytest.mark.parametrize("signal_type", [signal.SIGTERM, signal.SIGKILL])
def test_process_os_signal_calls_on_failure_callback(
self, monkeypatch, tmp_path, get_test_dag, signal_type
):
"""
Test that ensures that when a task is killed with sigkill or sigterm
on_failure_callback does not get executed by LocalTaskJob.
Callbacks should not be executed by LocalTaskJob. If the task killed via sigkill,
it will be reaped as zombie, then the callback is executed
"""
callback_file = tmp_path.joinpath("callback.txt")
# callback_file will be created by the task: bash_sleep
monkeypatch.setenv("AIRFLOW_CALLBACK_FILE", str(callback_file))
dag = get_test_dag("test_on_failure_callback")
with create_session() as session:
dag.create_dagrun(
state=State.RUNNING,
execution_date=DEFAULT_DATE,
run_type=DagRunType.SCHEDULED,
session=session,
)
task = dag.get_task(task_id="bash_sleep")
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
signal_sent_status = {"sent": False}
def get_ti_current_pid(ti) -> str:
with create_session() as session:
pid = (
session.query(TaskInstance.pid)
.filter(
TaskInstance.dag_id == ti.dag_id,
TaskInstance.task_id == ti.task_id,
TaskInstance.run_id == ti.run_id,
)
.one_or_none()
)
return pid[0]
def send_signal(ti, signal_sent, sig):
while True:
task_pid = get_ti_current_pid(
ti
) # get pid from the db, which is the pid of airflow run --raw
if (
task_pid and ti.current_state() == State.RUNNING and os.path.isfile(callback_file)
): # ensure task is running before sending sig
signal_sent["sent"] = True
os.kill(task_pid, sig)
break
time.sleep(1)
thread = threading.Thread(
name="signaler",
target=send_signal,
args=(ti, signal_sent_status, signal_type),
)
thread.daemon = True
thread.start()
job1 = Job(dag_id=ti.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti, ignore_ti_state=True)
run_job(job=job1, execute_callable=job_runner._execute)
ti.refresh_from_db()
assert signal_sent_status["sent"]
if signal_type == signal.SIGTERM:
assert ti.state == State.FAILED
with open(callback_file) as f:
lines = f.readlines()
assert len(lines) == 1
assert lines[0].startswith(ti.key.primary)
m = re.match(r"^.+pid: (\d+)$", lines[0])
assert m, "pid expected in output."
pid = int(m.group(1))
assert os.getpid() != pid # ensures callback is NOT run by LocalTaskJob
assert ti.pid == pid # ensures callback is run by airflow run --raw (TaskInstance#_run_raw_task)
elif signal_type == signal.SIGKILL:
assert (
ti.state == State.RUNNING
) # task exits with running state, will be reaped as zombie by scheduler
with open(callback_file) as f:
lines = f.readlines()
assert len(lines) == 0
@pytest.mark.parametrize(
"conf, init_state, first_run_state, second_run_state, task_ids_to_run, error_message",
[
(
{("scheduler", "schedule_after_task_execution"): "True"},
{"A": State.QUEUED, "B": State.NONE, "C": State.NONE},
{"A": State.SUCCESS, "B": State.SCHEDULED, "C": State.NONE},
{"A": State.SUCCESS, "B": State.SUCCESS, "C": State.SCHEDULED},
["A", "B"],
"A -> B -> C, with fast-follow ON when A runs, B should be QUEUED. Same for B and C.",
),
(
{("scheduler", "schedule_after_task_execution"): "False"},
{"A": State.QUEUED, "B": State.NONE, "C": State.NONE},
{"A": State.SUCCESS, "B": State.NONE, "C": State.NONE},
None,
["A", "B"],
"A -> B -> C, with fast-follow OFF, when A runs, B shouldn't be QUEUED.",
),
(
{("scheduler", "schedule_after_task_execution"): "True"},
{"D": State.QUEUED, "E": State.NONE, "F": State.NONE, "G": State.NONE},
{"D": State.SUCCESS, "E": State.NONE, "F": State.NONE, "G": State.NONE},
None,
["D", "E"],
"G -> F -> E & D -> E, when D runs but F isn't QUEUED yet, E shouldn't be QUEUED.",
),
(
{("scheduler", "schedule_after_task_execution"): "True"},
{"H": State.QUEUED, "I": State.FAILED, "J": State.NONE},
{"H": State.SUCCESS, "I": State.FAILED, "J": State.UPSTREAM_FAILED},
None,
["H", "I"],
"H -> J & I -> J, when H is QUEUED but I has FAILED, J is marked UPSTREAM_FAILED.",
),
],
)
def test_fast_follow(
self,
conf,
init_state,
first_run_state,
second_run_state,
task_ids_to_run,
error_message,
get_test_dag,
):
with conf_vars(conf):
dag = get_test_dag(
"test_dagrun_fast_follow",
)
scheduler_job = Job()
scheduler_job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
scheduler_job_runner.dagbag.bag_dag(dag, root_dag=dag)
dag_run = dag.create_dagrun(run_id="test_dagrun_fast_follow", state=State.RUNNING)
ti_by_task_id = {}
with create_session() as session:
for task_id in init_state:
ti = TaskInstance(dag.get_task(task_id), run_id=dag_run.run_id, state=init_state[task_id])
session.merge(ti)
ti_by_task_id[task_id] = ti
ti = TaskInstance(task=dag.get_task(task_ids_to_run[0]), execution_date=dag_run.execution_date)
ti.refresh_from_db()
job1 = Job(executor=SequentialExecutor(), dag_id=ti.dag_id)
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti, ignore_ti_state=True)
job1.task_runner = StandardTaskRunner(job_runner)
run_job(job=job1, execute_callable=job_runner._execute)
self.validate_ti_states(dag_run, first_run_state, error_message)
if second_run_state:
ti = TaskInstance(
task=dag.get_task(task_ids_to_run[1]), execution_date=dag_run.execution_date
)
ti.refresh_from_db()
job2 = Job(dag_id=ti.dag_id, executor=SequentialExecutor())
job_runner = LocalTaskJobRunner(job=job2, task_instance=ti, ignore_ti_state=True)
job2.task_runner = StandardTaskRunner(job_runner)
run_job(job2, execute_callable=job_runner._execute)
self.validate_ti_states(dag_run, second_run_state, error_message)
if scheduler_job_runner.processor_agent:
scheduler_job_runner.processor_agent.end()
@conf_vars({("scheduler", "schedule_after_task_execution"): "True"})
def test_mini_scheduler_works_with_wait_for_upstream(self, caplog, get_test_dag):
dag = get_test_dag("test_dagrun_fast_follow")
dag.catchup = False
SerializedDagModel.write_dag(dag)
dr = dag.create_dagrun(run_id="test_1", state=State.RUNNING, execution_date=DEFAULT_DATE)
dr2 = dag.create_dagrun(
run_id="test_2", state=State.RUNNING, execution_date=DEFAULT_DATE + datetime.timedelta(hours=1)
)
task_k = dag.get_task("K")
task_l = dag.get_task("L")
with create_session() as session:
ti_k = TaskInstance(task_k, run_id=dr.run_id, state=State.SUCCESS)
ti_b = TaskInstance(task_l, run_id=dr.run_id, state=State.SUCCESS)
ti2_k = TaskInstance(task_k, run_id=dr2.run_id, state=State.NONE)
ti2_l = TaskInstance(task_l, run_id=dr2.run_id, state=State.NONE)
session.merge(ti_k)
session.merge(ti_b)
session.merge(ti2_k)
session.merge(ti2_l)
job1 = Job(
executor=SequentialExecutor(),
dag_id=ti2_k.dag_id,
)
job_runner = LocalTaskJobRunner(job=job1, task_instance=ti2_k, ignore_ti_state=True)
job1.task_runner = StandardTaskRunner(job_runner)
run_job(job=job1, execute_callable=job_runner._execute)
ti2_k.refresh_from_db()
ti2_l.refresh_from_db()
assert ti2_k.state == State.SUCCESS
assert ti2_l.state == State.NONE
failed_deps = list(ti2_l.get_failed_dep_statuses())
assert len(failed_deps) == 1
assert failed_deps[0].dep_name == "Previous Dagrun State"
assert not failed_deps[0].passed
def test_process_sigsegv_error_message(self, caplog, dag_maker):
"""Test that shows error if process failed with segmentation fault."""
caplog.set_level(logging.CRITICAL, logger="local_task_job.py")
def task_function(ti):
# pytest enable faulthandler by default unless `-p no:faulthandler` is given.
# It can not be disabled on the test level out of the box and
# that mean debug traceback would show in pytest output.
# For avoid this we disable it within the task which run in separate process.
import faulthandler
if faulthandler.is_enabled():
faulthandler.disable()
while not ti.pid:
time.sleep(0.1)
os.kill(psutil.Process(os.getpid()).ppid(), signal.SIGSEGV)
with dag_maker(dag_id="test_segmentation_fault"):
task = PythonOperator(
task_id="test_sigsegv",
python_callable=task_function,
)
dag_run = dag_maker.create_dagrun()
ti = TaskInstance(task=task, run_id=dag_run.run_id)
ti.refresh_from_db()
job = Job(executor=SequentialExecutor(), dag_id=ti.dag_id)
job_runner = LocalTaskJobRunner(job=job, task_instance=ti, ignore_ti_state=True)
settings.engine.dispose()
with timeout(10):
with pytest.raises(AirflowException, match=r"Segmentation Fault detected"):
run_job(job=job, execute_callable=job_runner._execute)
assert SIGSEGV_MESSAGE in caplog.messages
@pytest.fixture()
def clean_db_helper():
yield
db.clear_db_jobs()
db.clear_db_runs()
@pytest.mark.usefixtures("clean_db_helper")
@mock.patch("airflow.task.task_runner.get_task_runner")
def test_number_of_queries_single_loop(mock_get_task_runner, dag_maker):
codes: list[int | None] = 9 * [None] + [0]
mock_get_task_runner.return_value.return_code.side_effects = [[0], codes]
unique_prefix = str(uuid.uuid4())
with dag_maker(dag_id=f"{unique_prefix}_test_number_of_queries"):
task = EmptyOperator(task_id="test_state_succeeded1")
dr = dag_maker.create_dagrun(run_id=unique_prefix, state=State.NONE)
ti = dr.task_instances[0]
ti.refresh_from_task(task)
job = Job(dag_id=ti.dag_id, executor=MockExecutor())
job_runner = LocalTaskJobRunner(job=job, task_instance=ti)
with assert_queries_count(18):
run_job(job=job, execute_callable=job_runner._execute)
class TestSigtermOnRunner:
"""Test receive SIGTERM on Task Runner."""
@pytest.mark.parametrize(
"daemon", [pytest.param(True, id="daemon"), pytest.param(False, id="non-daemon")]
)
@pytest.mark.parametrize(
"mp_method, wait_timeout",
[
pytest.param(
"fork",
10,
marks=pytest.mark.skipif(not hasattr(os, "fork"), reason="Forking not available"),
id="fork",
),
pytest.param("spawn", 30, id="spawn"),
],
)
def test_process_sigterm_works_with_retries(
self, mp_method, wait_timeout, daemon, clear_db, request, capfd
):
"""Test that ensures that task runner sets tasks to retry when task runner receive SIGTERM."""
mp_context = mp.get_context(mp_method)
# Use shared memory value, so we can properly track value change
# even if it's been updated across processes.
retry_callback_called = mp_context.Value("i", 0)
task_started = mp_context.Value("i", 0)
dag_id = f"test_task_runner_sigterm_{mp_method}_{'' if daemon else 'non_'}daemon"
task_id = "test_on_retry_callback"
execution_date = DEFAULT_DATE
run_id = f"test-{execution_date.date().isoformat()}"
# Run LocalTaskJob in separate process
proc = mp_context.Process(
target=self._sigterm_local_task_runner,
args=(dag_id, task_id, run_id, execution_date, task_started, retry_callback_called),
name="LocalTaskJob-TestProcess",
daemon=daemon,
)
proc.start()
try:
with timeout(wait_timeout, "Timeout during waiting start LocalTaskJob"):
while task_started.value == 0:
time.sleep(0.2)
os.kill(proc.pid, signal.SIGTERM)
with timeout(wait_timeout, "Timeout during waiting callback"):
while retry_callback_called.value == 0:
time.sleep(0.2)
finally:
proc.kill()
assert retry_callback_called.value == 1
# Internally callback finished before TaskInstance commit changes in DB (as of Jan 2022).
# So we can't easily check TaskInstance.state without any race conditions drawbacks,
# and fact that process with LocalTaskJob could be already killed.
# We could add state validation (`UP_FOR_RETRY`) if callback mechanism changed.
pytest_capture = request.config.option.capture
if pytest_capture == "no":
# Since we run `LocalTaskJob` in the separate process we can grab ut easily by `caplog`.
# However, we could grab it from stdout/stderr but only if `-s` flag set, see:
# https://github.com/pytest-dev/pytest/issues/5997
captured = capfd.readouterr()
for msg in [
"Received SIGTERM. Terminating subprocesses",
"Task exited with return code 143",
]:
assert msg in captured.out or msg in captured.err
else:
warnings.warn(
f"Skip test logs in stdout/stderr when capture enabled: {pytest_capture}, "
f"please pass `-s` option.",
UserWarning,
)
@staticmethod
def _sigterm_local_task_runner(
dag_id,
task_id,
run_id,
execution_date,
is_started,
callback_value,
):
"""Helper function which create infinity task and run it by LocalTaskJob."""
settings.engine.pool.dispose()
settings.engine.dispose()
def retry_callback(context):
assert context["dag_run"].dag_id == dag_id
with callback_value.get_lock():
callback_value.value += 1
def task_function():
with is_started.get_lock():
is_started.value = 1
while True:
time.sleep(0.25)
with DAG(dag_id=dag_id, schedule=None, start_date=execution_date) as dag:
task = PythonOperator(
task_id=task_id,
python_callable=task_function,
retries=1,
on_retry_callback=retry_callback,
)
dag.create_dagrun(state=State.RUNNING, run_id=run_id, execution_date=execution_date)
ti = TaskInstance(task=task, execution_date=execution_date)
ti.refresh_from_db()
job = Job(executor=SequentialExecutor(), dag_id=ti.dag_id)
job_runner = LocalTaskJobRunner(job=job, task_instance=ti, ignore_ti_state=True)
run_job(job=job, execute_callable=job_runner._execute)