-
Notifications
You must be signed in to change notification settings - Fork 13.7k
/
test_local_task_job.py
1073 lines (916 loc) · 42.7 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
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.
#
import datetime
import os
import signal
import time
import uuid
from multiprocessing import Lock, Value
from typing import List, Union
from unittest import mock
from unittest.mock import patch
import psutil
import pytest
from airflow import settings
from airflow.exceptions import AirflowException, AirflowFailException, AirflowSkipException
from airflow.executors.sequential_executor import SequentialExecutor
from airflow.jobs.local_task_job import LocalTaskJob
from airflow.jobs.scheduler_job import SchedulerJob
from airflow.models.dagbag import DagBag
from airflow.models.taskinstance import TaskInstance
from airflow.operators.empty import EmptyOperator
from airflow.operators.python import BranchPythonOperator, 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.trigger_rule import TriggerRule
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.base_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 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
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 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
ti.task = op1
ti.refresh_from_task(op1)
job1.task_runner = StandardTaskRunner(job1)
job1.task_runner.process = mock.Mock()
with pytest.raises(AirflowException):
job1.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
job1.heartbeat_callback(session=None)
job1.task_runner.process.pid = 2
with pytest.raises(AirflowException):
job1.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
job1.heartbeat_callback()
@mock.patch('subprocess.check_call')
@mock.patch('airflow.jobs.local_task_job.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 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
ti.task = op1
ti.refresh_from_task(op1)
job1.task_runner = StandardTaskRunner(job1)
job1.task_runner.process = mock.Mock()
job1.task_runner.process.pid = 2
# 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'):
job1.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()
job1.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'):
job1.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
job1.heartbeat_callback()
@conf_vars({('core', 'default_impersonation'): 'testuser'})
@mock.patch('subprocess.check_call')
@mock.patch('airflow.jobs.local_task_job.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 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
ti.task = op1
ti.refresh_from_task(op1)
job1.task_runner = StandardTaskRunner(job1)
job1.task_runner.process = mock.Mock()
job1.task_runner.process.pid = 2
# 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'):
job1.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()
job1.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'):
job1.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
job1.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 = LocalTaskJob(task_instance=ti, executor=MockExecutor(do_update=False))
job.heartrate = 2
heartbeat_records = []
job.heartbeat_callback = lambda session: heartbeat_records.append(job.latest_heartbeat)
job._execute()
assert len(heartbeat_records) > 2
for i in range(1, len(heartbeat_records)):
time1 = heartbeat_records[i - 1]
time2 = heartbeat_records[i]
# Assert that difference small enough
delta = (time2 - time1).total_seconds()
assert abs(delta - job.heartrate) < 0.5
@patch('airflow.utils.process_utils.subprocess.check_call')
@patch.object(StandardTaskRunner, 'return_code')
def test_mark_success_no_kill(self, mock_return_code, _check_call, caplog, dag_maker):
"""
Test that ensures that mark_success in the UI doesn't cause
the task to fail, and that the task exits
"""
session = settings.Session()
def task_function(ti):
assert ti.state == State.RUNNING
# Simulate marking this successful in the UI
ti.state = State.SUCCESS
session.merge(ti)
session.commit()
# The below code will not run as heartbeat will detect change of state
time.sleep(10)
with dag_maker('test_mark_success'):
task = PythonOperator(task_id="task1", python_callable=task_function)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.refresh_from_task(task)
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True)
def dummy_return_code(*args, **kwargs):
return None if not job1.terminating else -9
# The return code when we mark success in the UI is None
mock_return_code.side_effect = dummy_return_code
with timeout(30):
job1.run()
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 = LocalTaskJob(task_instance=ti_run, executor=SequentialExecutor())
with patch.object(StandardTaskRunner, 'start', return_value=None) as mock_method:
job1.run()
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()
@pytest.mark.quarantined
@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 = LocalTaskJob(task_instance=ti_run, executor=SequentialExecutor())
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):
job1.run()
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, dag_maker):
"""
Test that ensures that mark_failure in the UI fails
the task, and executes on_failure_callback
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
failure_callback_called = Value('i', 0)
session = settings.Session()
def check_failure(context):
with failure_callback_called.get_lock():
failure_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_mark_failure'
assert context['exception'] == "task marked as failed externally"
def task_function(ti):
assert State.RUNNING == ti.state
ti.log.info("Marking TI as failed 'externally'")
ti.state = State.FAILED
session.merge(ti)
session.commit()
# This should not happen -- the state change should be noticed and the task should get killed
time.sleep(10)
assert False
with dag_maker("test_mark_failure", start_date=DEFAULT_DATE):
task = PythonOperator(
task_id='test_state_succeeded1',
python_callable=task_function,
on_failure_callback=check_failure,
)
dag_maker.create_dagrun()
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
with timeout(30):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
job1.run()
ti.refresh_from_db()
assert ti.state == State.FAILED
assert failure_callback_called.value == 1
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, dag_maker):
"""
Test that ensures that if a running task is externally skipped (due to a dagrun timeout)
It is logged in the task logs.
"""
session = settings.Session()
def task_function(ti):
assert State.RUNNING == ti.state
time.sleep(0.1)
ti.log.info("Marking TI as skipped externally")
ti.state = State.SKIPPED
session.merge(ti)
session.commit()
# This should not happen -- the state change should be noticed and the task should get killed
time.sleep(10)
assert False
with dag_maker(
"test_mark_failure", start_date=DEFAULT_DATE, dagrun_timeout=datetime.timedelta(microseconds=1)
):
task = PythonOperator(
task_id='skipped_externally',
python_callable=task_function,
)
dag_maker.create_dagrun()
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
with timeout(30):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
job1.run()
ti.refresh_from_db()
assert ti.state == State.SKIPPED
assert "DagRun timed out after " in caplog.text
@patch('airflow.utils.process_utils.subprocess.check_call')
@patch.object(StandardTaskRunner, 'return_code')
def test_failure_callback_only_called_once(self, mock_return_code, _check_call, dag_maker):
"""
Test that ensures that when a task exits with failure by itself,
failure callback is only called once
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
failure_callback_called = Value('i', 0)
callback_count_lock = Lock()
def failure_callback(context):
with callback_count_lock:
failure_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_failure_callback_race'
assert isinstance(context['exception'], AirflowFailException)
def task_function(ti):
raise AirflowFailException()
with dag_maker("test_failure_callback_race"):
task = PythonOperator(
task_id='test_exit_on_failure',
python_callable=task_function,
on_failure_callback=failure_callback,
)
dag_maker.create_dagrun()
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
# Simulate race condition where job1 heartbeat ran right after task
# state got set to failed by ti.handle_failure but before task process
# fully exits. See _execute loop in airflow/jobs/local_task_job.py.
# In this case, we have:
# * task_runner.return_code() is None
# * ti.state == State.Failed
#
# We also need to set return_code to a valid int after job1.terminating
# is set to True so _execute loop won't loop forever.
def dummy_return_code(*args, **kwargs):
return None if not job1.terminating else -9
mock_return_code.side_effect = dummy_return_code
with timeout(10):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callable above bigger
job1.run()
ti.refresh_from_db()
assert ti.state == State.FAILED # task exits with failure state
assert failure_callback_called.value == 1
@patch('airflow.utils.process_utils.subprocess.check_call')
@patch.object(StandardTaskRunner, 'return_code')
def test_mark_success_on_success_callback(self, mock_return_code, _check_call, caplog, dag_maker):
"""
Test that ensures that where a task is marked success in the UI
on_success_callback gets executed
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
success_callback_called = Value('i', 0)
session = settings.Session()
def success_callback(context):
with success_callback_called.get_lock():
success_callback_called.value = 1
assert context['dag_run'].dag_id == 'test_mark_success'
def task_function(ti):
assert ti.state == State.RUNNING
# mark it success in the UI
ti.state = State.SUCCESS
session.merge(ti)
session.commit()
# This should not happen -- the state change should be noticed and the task should get killed
time.sleep(10)
assert False
with dag_maker(dag_id='test_mark_success', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}):
task = PythonOperator(
task_id='test_state_succeeded1',
python_callable=task_function,
on_success_callback=success_callback,
)
dag_maker.create_dagrun()
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
def dummy_return_code(*args, **kwargs):
return None if not job1.terminating else -9
# The return code when we mark success in the UI is None
mock_return_code.side_effect = dummy_return_code
settings.engine.dispose()
with timeout(30):
job1.run() # This should run fast because of the return_code=None
ti.refresh_from_db()
assert success_callback_called.value == 1
assert "State of this instance has been externally set to success. "
"Terminating instance." in caplog.text
@patch('airflow.utils.process_utils.subprocess.check_call')
def test_task_sigkill_calls_on_failure_callback(self, _check_call, caplog, dag_maker):
"""
Test that ensures that when a task is killed with sigkill
on_failure_callback gets executed
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
failure_callback_called = Value('i', 0)
def failure_callback(context):
with failure_callback_called.get_lock():
failure_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_send_sigkill'
def task_function(ti):
assert ti.state == State.RUNNING
os.kill(os.getpid(), signal.SIGKILL)
with dag_maker(dag_id='test_send_sigkill'):
task = PythonOperator(
task_id='test_on_failure',
python_callable=task_function,
on_failure_callback=failure_callback,
)
dag_maker.create_dagrun()
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
settings.engine.dispose()
with timeout(10):
job1.run() # This should be fast because the signal is sent right away
ti.refresh_from_db()
assert failure_callback_called.value == 1
assert "Task exited with return code Negsignal.SIGKILL" in caplog.text
@pytest.mark.quarantined
def test_process_sigterm_calls_on_failure_callback(self, caplog, dag_maker):
"""
Test that ensures that when a task runner is killed with sigterm
on_failure_callback gets executed
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
failure_callback_called = Value('i', 0)
def failure_callback(context):
with failure_callback_called.get_lock():
failure_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_mark_failure'
def task_function(ti):
assert ti.state == State.RUNNING
os.kill(psutil.Process(os.getpid()).ppid(), signal.SIGTERM)
with dag_maker(dag_id='test_mark_failure', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}):
task = PythonOperator(
task_id='test_on_failure',
python_callable=task_function,
on_failure_callback=failure_callback,
)
dag_maker.create_dagrun()
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
settings.engine.dispose()
with timeout(10):
job1.run()
ti.refresh_from_db()
assert failure_callback_called.value == 1
assert "Received SIGTERM. Terminating subprocesses" in caplog.text
assert "Task exited with return code 143" in caplog.text
@pytest.mark.parametrize(
"conf, dependencies, init_state, first_run_state, second_run_state, error_message",
[
(
{('scheduler', 'schedule_after_task_execution'): 'True'},
{'A': 'B', 'B': 'C'},
{'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 -> C, with fast-follow ON when A runs, B should be QUEUED. Same for B and C.",
),
(
{('scheduler', 'schedule_after_task_execution'): 'False'},
{'A': 'B', 'B': 'C'},
{'A': State.QUEUED, 'B': State.NONE, 'C': State.NONE},
{'A': State.SUCCESS, 'B': State.NONE, 'C': State.NONE},
None,
"A -> B -> C, with fast-follow OFF, when A runs, B shouldn't be QUEUED.",
),
(
{('scheduler', 'schedule_after_task_execution'): 'True'},
{'A': 'B', 'C': 'B', 'D': 'C'},
{'A': State.QUEUED, 'B': State.NONE, 'C': State.NONE, 'D': State.NONE},
{'A': State.SUCCESS, 'B': State.NONE, 'C': State.NONE, 'D': State.NONE},
None,
"D -> C -> B & A -> B, when A runs but C isn't QUEUED yet, B shouldn't be QUEUED.",
),
(
{('scheduler', 'schedule_after_task_execution'): 'True'},
{'A': 'C', 'B': 'C'},
{'A': State.QUEUED, 'B': State.FAILED, 'C': State.NONE},
{'A': State.SUCCESS, 'B': State.FAILED, 'C': State.UPSTREAM_FAILED},
None,
"A -> C & B -> C, when A is QUEUED but B has FAILED, C is marked UPSTREAM_FAILED.",
),
],
)
def test_fast_follow(
self, conf, dependencies, init_state, first_run_state, second_run_state, error_message, dag_maker
):
with conf_vars(conf):
session = settings.Session()
python_callable = lambda: True
with dag_maker('test_dagrun_fast_follow') as dag:
task_a = PythonOperator(task_id='A', python_callable=python_callable)
task_b = PythonOperator(task_id='B', python_callable=python_callable)
task_c = PythonOperator(task_id='C', python_callable=python_callable)
if 'D' in init_state:
task_d = PythonOperator(task_id='D', python_callable=python_callable)
for upstream, downstream in dependencies.items():
dag.set_dependency(upstream, downstream)
scheduler_job = SchedulerJob(subdir=os.devnull)
scheduler_job.dagbag.bag_dag(dag, root_dag=dag)
dag_run = dag.create_dagrun(run_id='test_dagrun_fast_follow', state=State.RUNNING)
task_instance_a = TaskInstance(task_a, run_id=dag_run.run_id, state=init_state['A'])
task_instance_b = TaskInstance(task_b, run_id=dag_run.run_id, state=init_state['B'])
task_instance_c = TaskInstance(task_c, run_id=dag_run.run_id, state=init_state['C'])
if 'D' in init_state:
task_instance_d = TaskInstance(task_d, run_id=dag_run.run_id, state=init_state['D'])
session.merge(task_instance_d)
session.merge(task_instance_a)
session.merge(task_instance_b)
session.merge(task_instance_c)
session.flush()
job1 = LocalTaskJob(
task_instance=task_instance_a, ignore_ti_state=True, executor=SequentialExecutor()
)
job1.task_runner = StandardTaskRunner(job1)
job2 = LocalTaskJob(
task_instance=task_instance_b, ignore_ti_state=True, executor=SequentialExecutor()
)
job2.task_runner = StandardTaskRunner(job2)
settings.engine.dispose()
job1.run()
self.validate_ti_states(dag_run, first_run_state, error_message)
if second_run_state:
job2.run()
self.validate_ti_states(dag_run, second_run_state, error_message)
if scheduler_job.processor_agent:
scheduler_job.processor_agent.end()
@conf_vars({('scheduler', 'schedule_after_task_execution'): 'True'})
def test_mini_scheduler_works_with_wait_for_downstream(self, caplog, dag_maker):
session = settings.Session()
with dag_maker(default_args={'wait_for_downstream': True}, catchup=False) as dag:
task_a = PythonOperator(task_id='A', python_callable=lambda: True)
task_b = PythonOperator(task_id='B', python_callable=lambda: True)
task_c = PythonOperator(task_id='C', python_callable=lambda: True)
task_a >> task_b >> task_c
scheduler_job = SchedulerJob(subdir=os.devnull)
scheduler_job.dagbag.bag_dag(dag, root_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)
)
ti_a = TaskInstance(task_a, run_id=dr.run_id, state=State.SUCCESS)
ti_b = TaskInstance(task_b, run_id=dr.run_id, state=State.SUCCESS)
ti_c = TaskInstance(task_c, run_id=dr.run_id, state=State.RUNNING)
ti2_a = TaskInstance(task_a, run_id=dr2.run_id, state=State.NONE)
ti2_b = TaskInstance(task_b, run_id=dr2.run_id, state=State.NONE)
ti2_c = TaskInstance(task_c, run_id=dr2.run_id, state=State.NONE)
session.merge(ti_a)
session.merge(ti_b)
session.merge(ti_c)
session.merge(ti2_a)
session.merge(ti2_b)
session.merge(ti2_c)
session.flush()
job1 = LocalTaskJob(task_instance=ti2_a, ignore_ti_state=True, executor=SequentialExecutor())
job1.task_runner = StandardTaskRunner(job1)
t = time.time()
job1.run()
d = time.time() - t
ti2_a.refresh_from_db(session)
ti2_b.refresh_from_db(session)
assert ti2_a.state == State.SUCCESS
assert ti2_b.state == State.NONE
assert (
"0 downstream tasks scheduled from follow-on schedule" in caplog.text
), f"Failed after {d.total_seconds()}: {caplog.text}"
failed_deps = list(ti2_b.get_failed_dep_statuses(session=session))
assert len(failed_deps) == 1
assert failed_deps[0].dep_name == "Previous Dagrun State"
assert not failed_deps[0].passed
@pytest.mark.parametrize(
"exception, trigger_rule",
[
(AirflowFailException(), TriggerRule.ALL_DONE),
(AirflowFailException(), TriggerRule.ALL_FAILED),
(AirflowSkipException(), TriggerRule.ALL_DONE),
(AirflowSkipException(), TriggerRule.ALL_SKIPPED),
(AirflowSkipException(), TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS),
],
)
@conf_vars({('scheduler', 'schedule_after_task_execution'): 'True'})
def test_mini_scheduler_works_with_skipped_and_failed(
self, exception, trigger_rule, caplog, session, dag_maker
):
"""
In these cases D is running, at no decision can be made about C.
"""
def raise_():
raise exception
with dag_maker(catchup=False) as dag:
task_a = PythonOperator(task_id='A', python_callable=raise_)
task_b = PythonOperator(task_id='B', python_callable=lambda: True)
task_c = PythonOperator(task_id='C', python_callable=lambda: True, trigger_rule=trigger_rule)
task_d = PythonOperator(task_id='D', python_callable=lambda: True)
task_a >> task_b >> task_c
task_d >> task_c
dr = dag.create_dagrun(run_id='test_1', state=State.RUNNING, execution_date=DEFAULT_DATE)
ti_a = TaskInstance(task_a, run_id=dr.run_id, state=State.QUEUED)
ti_b = TaskInstance(task_b, run_id=dr.run_id, state=State.NONE)
ti_c = TaskInstance(task_c, run_id=dr.run_id, state=State.NONE)
ti_d = TaskInstance(task_d, run_id=dr.run_id, state=State.RUNNING)
session.merge(ti_a)
session.merge(ti_b)
session.merge(ti_c)
session.merge(ti_d)
session.flush()
job1 = LocalTaskJob(task_instance=ti_a, ignore_ti_state=True, executor=SequentialExecutor())
job1.task_runner = StandardTaskRunner(job1)
job1.run()
ti_b.refresh_from_db(session)
ti_c.refresh_from_db(session)
assert ti_b.state in (State.SKIPPED, State.UPSTREAM_FAILED)
assert ti_c.state == State.NONE
assert "0 downstream tasks scheduled from follow-on schedule" in caplog.text
failed_deps = list(ti_c.get_failed_dep_statuses(session=session))
assert len(failed_deps) == 1
assert failed_deps[0].dep_name == "Trigger Rule"
assert not failed_deps[0].passed
@pytest.mark.parametrize(
"trigger_rule",
[
TriggerRule.ONE_SUCCESS,
TriggerRule.ALL_SKIPPED,
TriggerRule.NONE_FAILED,
TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS,
],
)
@conf_vars({('scheduler', 'schedule_after_task_execution'): 'True'})
def test_mini_scheduler_works_with_branch_python_operator(self, trigger_rule, caplog, session, dag_maker):
"""
In these cases D is running, at no decision can be made about C.
"""
with dag_maker(catchup=False) as dag:
task_a = BranchPythonOperator(task_id='A', python_callable=lambda: [])
task_b = PythonOperator(task_id='B', python_callable=lambda: True)
task_c = PythonOperator(
task_id='C',
python_callable=lambda: True,
trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS,
)
task_d = PythonOperator(task_id='D', python_callable=lambda: True)
task_a >> task_b >> task_c
task_d >> task_c
dr = dag.create_dagrun(run_id='test_1', state=State.RUNNING, execution_date=DEFAULT_DATE)
ti_a = TaskInstance(task_a, run_id=dr.run_id, state=State.QUEUED)
ti_b = TaskInstance(task_b, run_id=dr.run_id, state=State.NONE)
ti_c = TaskInstance(task_c, run_id=dr.run_id, state=State.NONE)
ti_d = TaskInstance(task_d, run_id=dr.run_id, state=State.RUNNING)
session.merge(ti_a)
session.merge(ti_b)
session.merge(ti_c)
session.merge(ti_d)
session.flush()
job1 = LocalTaskJob(task_instance=ti_a, ignore_ti_state=True, executor=SequentialExecutor())
job1.task_runner = StandardTaskRunner(job1)
job1.run()
ti_b.refresh_from_db(session)
ti_c.refresh_from_db(session)
assert ti_b.state == State.SKIPPED
assert ti_c.state == State.NONE
assert "0 downstream tasks scheduled from follow-on schedule" in caplog.text
failed_deps = list(ti_c.get_failed_dep_statuses(session=session))
assert len(failed_deps) == 1
assert failed_deps[0].dep_name == "Trigger Rule"
assert not failed_deps[0].passed
@patch('airflow.utils.process_utils.subprocess.check_call')
def test_task_sigkill_works_with_retries(self, _check_call, caplog, dag_maker):
"""
Test that ensures that tasks are retried when they receive sigkill
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
retry_callback_called = Value('i', 0)
def retry_callback(context):
with retry_callback_called.get_lock():
retry_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_mark_failure_2'
def task_function(ti):
os.kill(os.getpid(), signal.SIGKILL)
with dag_maker(
dag_id='test_mark_failure_2', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}
):
task = PythonOperator(
task_id='test_on_failure',
python_callable=task_function,
retries=1,
on_retry_callback=retry_callback,
)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.refresh_from_task(task)
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
settings.engine.dispose()
with timeout(10):
job1.run()
assert retry_callback_called.value == 1
assert "Task exited with return code Negsignal.SIGKILL" in caplog.text
@pytest.mark.quarantined
def test_process_sigterm_works_with_retries(self, caplog, dag_maker):
"""
Test that ensures that task runner sets tasks to retry when they(task runner)
receive sigterm
"""
# use shared memory value so we can properly track value change even if
# it's been updated across processes.
retry_callback_called = Value('i', 0)
def retry_callback(context):
with retry_callback_called.get_lock():
retry_callback_called.value += 1
assert context['dag_run'].dag_id == 'test_mark_failure_2'
def task_function(ti):
while not ti.pid:
time.sleep(0.1)
os.kill(psutil.Process(os.getpid()).ppid(), signal.SIGTERM)