-
Notifications
You must be signed in to change notification settings - Fork 14.4k
/
test_scheduler_job.py
5376 lines (4456 loc) · 212 KB
/
test_scheduler_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.
from __future__ import annotations
import contextlib
import datetime
import logging
import os
from collections import deque
from datetime import timedelta
from typing import Generator
from unittest import mock
from unittest.mock import MagicMock, patch
import psutil
import pytest
import time_machine
from sqlalchemy import func
import airflow.example_dags
from airflow import settings
from airflow.callbacks.callback_requests import DagCallbackRequest, SlaCallbackRequest, TaskCallbackRequest
from airflow.callbacks.database_callback_sink import DatabaseCallbackSink
from airflow.callbacks.pipe_callback_sink import PipeCallbackSink
from airflow.dag_processing.manager import DagFileProcessorAgent
from airflow.datasets import Dataset
from airflow.exceptions import AirflowException
from airflow.executors.base_executor import BaseExecutor
from airflow.executors.executor_constants import MOCK_EXECUTOR
from airflow.executors.executor_loader import ExecutorLoader
from airflow.jobs.backfill_job_runner import BackfillJobRunner
from airflow.jobs.job import Job, run_job
from airflow.jobs.local_task_job_runner import LocalTaskJobRunner
from airflow.jobs.scheduler_job_runner import SchedulerJobRunner
from airflow.models.dag import DAG, DagModel
from airflow.models.dagbag import DagBag
from airflow.models.dagrun import DagRun
from airflow.models.dataset import DatasetDagRunQueue, DatasetEvent, DatasetModel
from airflow.models.db_callback_request import DbCallbackRequest
from airflow.models.pool import Pool
from airflow.models.serialized_dag import SerializedDagModel
from airflow.models.taskinstance import SimpleTaskInstance, TaskInstance, TaskInstanceKey
from airflow.operators.bash import BashOperator
from airflow.operators.empty import EmptyOperator
from airflow.serialization.serialized_objects import SerializedDAG
from airflow.utils import timezone
from airflow.utils.file import list_py_file_paths
from airflow.utils.session import create_session, provide_session
from airflow.utils.state import DagRunState, JobState, State, TaskInstanceState
from airflow.utils.types import DagRunType
from tests.listeners import dag_listener
from tests.listeners.test_listeners import get_listener_manager
from tests.models import TEST_DAGS_FOLDER
from tests.test_utils.asserts import assert_queries_count
from tests.test_utils.config import conf_vars, env_vars
from tests.test_utils.db import (
clear_db_dags,
clear_db_datasets,
clear_db_import_errors,
clear_db_jobs,
clear_db_pools,
clear_db_runs,
clear_db_serialized_dags,
clear_db_sla_miss,
set_default_pool_slots,
)
from tests.test_utils.mock_executor import MockExecutor
from tests.test_utils.mock_operators import CustomOperator
from tests.utils.test_timezone import UTC
pytestmark = pytest.mark.db_test
ROOT_FOLDER = os.path.realpath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir)
)
PERF_DAGS_FOLDER = os.path.join(ROOT_FOLDER, "tests", "test_utils", "perf", "dags")
ELASTIC_DAG_FILE = os.path.join(PERF_DAGS_FOLDER, "elastic_dag.py")
TEST_DAG_FOLDER = os.environ["AIRFLOW__CORE__DAGS_FOLDER"]
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
TRY_NUMBER = 1
@pytest.fixture(scope="class")
def disable_load_example():
with conf_vars({("core", "load_examples"): "false"}):
with env_vars({"AIRFLOW__CORE__LOAD_EXAMPLES": "false"}):
yield
@pytest.fixture(scope="module")
def dagbag():
# Ensure the DAGs we are looking at from the DB are up-to-date
non_serialized_dagbag = DagBag(read_dags_from_db=False, include_examples=False)
non_serialized_dagbag.sync_to_db()
return DagBag(read_dags_from_db=True)
@pytest.fixture
def load_examples():
with conf_vars({("core", "load_examples"): "True"}):
yield
# Patch the MockExecutor into the dict of known executors in the Loader
@patch.dict(
ExecutorLoader.executors, {MOCK_EXECUTOR: f"{MockExecutor.__module__}.{MockExecutor.__qualname__}"}
)
@pytest.mark.usefixtures("disable_load_example")
@pytest.mark.need_serialized_dag
class TestSchedulerJob:
@staticmethod
def clean_db():
clear_db_runs()
clear_db_pools()
clear_db_dags()
clear_db_sla_miss()
clear_db_import_errors()
clear_db_jobs()
clear_db_datasets()
# DO NOT try to run clear_db_serialized_dags() here - this will break the tests
# The tests expect DAGs to be fully loaded here via setUpClass method below
@pytest.fixture(autouse=True)
def per_test(self) -> Generator:
self.clean_db()
self.job_runner = None
yield
if self.job_runner and self.job_runner.processor_agent:
self.job_runner.processor_agent.end()
self.job_runner = None
self.clean_db()
@pytest.fixture(autouse=True)
def set_instance_attrs(self, dagbag) -> Generator:
self.dagbag: DagBag = dagbag
# Speed up some tests by not running the tasks, just look at what we
# enqueue!
self.null_exec: MockExecutor | None = MockExecutor()
# Since we don't want to store the code for the DAG defined in this file
with patch("airflow.dag_processing.manager.SerializedDagModel.remove_deleted_dags"), patch(
"airflow.models.dag.DagCode.bulk_sync_to_db"
):
yield
self.null_exec = None
del self.dagbag
@pytest.mark.parametrize(
"configs",
[
{("scheduler", "standalone_dag_processor"): "False"},
{("scheduler", "standalone_dag_processor"): "True"},
],
)
def test_is_alive(self, configs):
with conf_vars(configs):
scheduler_job = Job(heartrate=10, state=State.RUNNING)
self.job_runner = SchedulerJobRunner(scheduler_job)
assert scheduler_job.is_alive()
scheduler_job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=20)
assert scheduler_job.is_alive()
scheduler_job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=31)
assert not scheduler_job.is_alive()
# test because .seconds was used before instead of total_seconds
# internal repr of datetime is (days, seconds)
scheduler_job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(days=1)
assert not scheduler_job.is_alive()
scheduler_job.state = State.SUCCESS
scheduler_job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=10)
assert (
not scheduler_job.is_alive()
), "Completed jobs even with recent heartbeat should not be alive"
def run_single_scheduler_loop_with_no_dags(self, dags_folder):
"""
Utility function that runs a single scheduler loop without actually
changing/scheduling any dags. This is useful to simulate the other side effects of
running a scheduler loop, e.g. to see what parse errors there are in the
dags_folder.
:param dags_folder: the directory to traverse
"""
scheduler_job = Job(
executor=self.null_exec,
num_times_parse_dags=1,
subdir=os.path.join(dags_folder),
)
self.job_runner = SchedulerJobRunner(scheduler_job)
scheduler_job.heartrate = 0
run_job(scheduler_job, execute_callable=self.job_runner._execute)
def test_no_orphan_process_will_be_left(self, tmp_path):
current_process = psutil.Process()
old_children = current_process.children(recursive=True)
scheduler_job = Job(
executor=MockExecutor(do_update=False),
)
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.fspath(tmp_path), num_runs=1)
run_job(scheduler_job, execute_callable=self.job_runner._execute)
# Remove potential noise created by previous tests.
current_children = set(current_process.children(recursive=True)) - set(old_children)
assert not current_children
@mock.patch("airflow.jobs.scheduler_job_runner.TaskCallbackRequest")
@mock.patch("airflow.jobs.scheduler_job_runner.Stats.incr")
def test_process_executor_events(self, mock_stats_incr, mock_task_callback, dag_maker):
dag_id = "test_process_executor_events"
task_id_1 = "dummy_task"
session = settings.Session()
with dag_maker(dag_id=dag_id, fileloc="/test_path1/"):
task1 = EmptyOperator(task_id=task_id_1)
ti1 = dag_maker.create_dagrun().get_task_instance(task1.task_id)
mock_stats_incr.reset_mock()
executor = MockExecutor(do_update=False)
task_callback = mock.MagicMock()
mock_task_callback.return_value = task_callback
scheduler_job = Job(executor=executor)
self.job_runner = SchedulerJobRunner(scheduler_job)
self.job_runner.processor_agent = mock.MagicMock()
ti1.state = State.QUEUED
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key] = State.FAILED, None
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db(session=session)
assert ti1.state == State.FAILED
scheduler_job.executor.callback_sink.send.assert_not_called()
self.job_runner.processor_agent.reset_mock()
# ti in success state
ti1.state = State.SUCCESS
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key] = State.SUCCESS, None
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db(session=session)
assert ti1.state == State.SUCCESS
scheduler_job.executor.callback_sink.send.assert_not_called()
mock_stats_incr.assert_has_calls(
[
mock.call(
"scheduler.tasks.killed_externally",
tags={"dag_id": dag_id, "task_id": ti1.task_id},
),
mock.call("operator_failures_EmptyOperator", tags={"dag_id": dag_id, "task_id": ti1.task_id}),
mock.call("ti_failures", tags={"dag_id": dag_id, "task_id": ti1.task_id}),
],
any_order=True,
)
@mock.patch("airflow.jobs.scheduler_job_runner.TaskCallbackRequest")
@mock.patch("airflow.jobs.scheduler_job_runner.Stats.incr")
def test_process_executor_events_with_no_callback(self, mock_stats_incr, mock_task_callback, dag_maker):
dag_id = "test_process_executor_events_with_no_callback"
task_id = "test_task"
run_id = "test_run"
mock_stats_incr.reset_mock()
executor = MockExecutor(do_update=False)
task_callback = mock.MagicMock()
mock_task_callback.return_value = task_callback
scheduler_job = Job(executor=executor)
self.job_runner = SchedulerJobRunner(scheduler_job)
self.job_runner.processor_agent = mock.MagicMock()
session = settings.Session()
with dag_maker(dag_id=dag_id, fileloc="/test_path1/"):
task1 = EmptyOperator(task_id=task_id, retries=1)
ti1 = dag_maker.create_dagrun(
run_id=run_id, execution_date=DEFAULT_DATE + timedelta(hours=1)
).get_task_instance(task1.task_id)
mock_stats_incr.reset_mock()
executor = MockExecutor(do_update=False)
task_callback = mock.MagicMock()
mock_task_callback.return_value = task_callback
scheduler_job = Job(executor=executor)
self.job_runner = SchedulerJobRunner(scheduler_job)
self.job_runner.processor_agent = mock.MagicMock()
ti1.state = State.QUEUED
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key] = State.FAILED, None
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db(session=session)
assert ti1.state == State.UP_FOR_RETRY
scheduler_job.executor.callback_sink.send.assert_not_called()
# ti in success state
ti1.state = State.SUCCESS
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key] = State.SUCCESS, None
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db(session=session)
assert ti1.state == State.SUCCESS
scheduler_job.executor.callback_sink.send.assert_not_called()
mock_stats_incr.assert_has_calls(
[
mock.call(
"scheduler.tasks.killed_externally",
tags={"dag_id": dag_id, "task_id": task_id},
),
mock.call("operator_failures_EmptyOperator", tags={"dag_id": dag_id, "task_id": task_id}),
mock.call("ti_failures", tags={"dag_id": dag_id, "task_id": task_id}),
],
any_order=True,
)
@mock.patch("airflow.jobs.scheduler_job_runner.TaskCallbackRequest")
@mock.patch("airflow.jobs.scheduler_job_runner.Stats.incr")
def test_process_executor_events_with_callback(self, mock_stats_incr, mock_task_callback, dag_maker):
dag_id = "test_process_executor_events_with_callback"
task_id_1 = "dummy_task"
with dag_maker(dag_id=dag_id, fileloc="/test_path1/") as dag:
task1 = EmptyOperator(task_id=task_id_1, on_failure_callback=lambda x: print("hi"))
ti1 = dag_maker.create_dagrun().get_task_instance(task1.task_id)
mock_stats_incr.reset_mock()
executor = MockExecutor(do_update=False)
task_callback = mock.MagicMock()
mock_task_callback.return_value = task_callback
scheduler_job = Job(executor=executor)
self.job_runner = SchedulerJobRunner(scheduler_job)
self.job_runner.processor_agent = mock.MagicMock()
session = settings.Session()
ti1.state = State.QUEUED
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key] = State.FAILED, None
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db()
# The state will remain in queued here and
# will be set to failed in dag parsing process
assert ti1.state == State.QUEUED
mock_task_callback.assert_called_once_with(
full_filepath=dag.fileloc,
simple_task_instance=mock.ANY,
processor_subdir=None,
msg="Executor reports task instance "
"<TaskInstance: test_process_executor_events_with_callback.dummy_task test [queued]> "
"finished (failed) although the task says it's queued. (Info: None) "
"Was the task killed externally?",
)
scheduler_job.executor.callback_sink.send.assert_called_once_with(task_callback)
scheduler_job.executor.callback_sink.reset_mock()
mock_stats_incr.assert_called_once_with(
"scheduler.tasks.killed_externally",
tags={
"dag_id": "test_process_executor_events_with_callback",
"task_id": "dummy_task",
},
)
@mock.patch("airflow.jobs.scheduler_job_runner.TaskCallbackRequest")
@mock.patch("airflow.jobs.scheduler_job_runner.Stats.incr")
def test_process_executor_event_missing_dag(self, mock_stats_incr, mock_task_callback, dag_maker, caplog):
dag_id = "test_process_executor_events_with_callback"
task_id_1 = "dummy_task"
with dag_maker(dag_id=dag_id, fileloc="/test_path1/"):
task1 = EmptyOperator(task_id=task_id_1, on_failure_callback=lambda x: print("hi"))
ti1 = dag_maker.create_dagrun().get_task_instance(task1.task_id)
mock_stats_incr.reset_mock()
executor = MockExecutor(do_update=False)
task_callback = mock.MagicMock()
mock_task_callback.return_value = task_callback
scheduler_job = Job(executor=executor)
self.job_runner = SchedulerJobRunner(scheduler_job)
self.job_runner.dagbag = mock.MagicMock()
self.job_runner.dagbag.get_dag.side_effect = Exception("failed")
self.job_runner.processor_agent = mock.MagicMock()
session = settings.Session()
ti1.state = State.QUEUED
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key] = State.FAILED, None
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db()
assert ti1.state == State.FAILED
@mock.patch("airflow.jobs.scheduler_job_runner.TaskCallbackRequest")
@mock.patch("airflow.jobs.scheduler_job_runner.Stats.incr")
def test_process_executor_events_ti_requeued(self, mock_stats_incr, mock_task_callback, dag_maker):
dag_id = "test_process_executor_events_ti_requeued"
task_id_1 = "dummy_task"
session = settings.Session()
with dag_maker(dag_id=dag_id, fileloc="/test_path1/"):
task1 = EmptyOperator(task_id=task_id_1)
ti1 = dag_maker.create_dagrun().get_task_instance(task1.task_id)
mock_stats_incr.reset_mock()
executor = MockExecutor(do_update=False)
task_callback = mock.MagicMock()
mock_task_callback.return_value = task_callback
scheduler_job = Job(executor=executor)
self.job_runner = SchedulerJobRunner(scheduler_job)
self.id = 1
self.job_runner.processor_agent = mock.MagicMock()
# ti is queued with another try number - do not fail it
ti1.state = State.QUEUED
ti1.queued_by_job_id = 1
ti1.try_number = 2
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key.with_try_number(1)] = State.SUCCESS, None
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db(session=session)
assert ti1.state == State.QUEUED
scheduler_job.executor.callback_sink.send.assert_not_called()
# ti is queued by another scheduler - do not fail it
ti1.state = State.QUEUED
ti1.queued_by_job_id = 2
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key] = State.SUCCESS, None
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db(session=session)
assert ti1.state == State.QUEUED
scheduler_job.executor.callback_sink.send.assert_not_called()
# ti is queued by this scheduler but it is handed back to the executor - do not fail it
ti1.state = State.QUEUED
ti1.queued_by_job_id = 1
session.merge(ti1)
session.commit()
executor.event_buffer[ti1.key] = State.SUCCESS, None
executor.has_task = mock.MagicMock(return_value=True)
self.job_runner._process_executor_events(session=session)
ti1.refresh_from_db(session=session)
assert ti1.state == State.QUEUED
scheduler_job.executor.callback_sink.send.assert_not_called()
mock_stats_incr.assert_not_called()
def test_execute_task_instances_is_paused_wont_execute(self, session, dag_maker):
dag_id = "SchedulerJobTest.test_execute_task_instances_is_paused_wont_execute"
task_id_1 = "dummy_task"
with dag_maker(dag_id=dag_id, session=session) as dag:
EmptyOperator(task_id=task_id_1)
assert isinstance(dag, SerializedDAG)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
dr1 = dag_maker.create_dagrun(run_type=DagRunType.BACKFILL_JOB)
(ti1,) = dr1.task_instances
ti1.state = State.SCHEDULED
self.job_runner._critical_section_enqueue_task_instances(session)
session.flush()
ti1.refresh_from_db(session=session)
assert State.SCHEDULED == ti1.state
session.rollback()
def test_execute_task_instances_backfill_tasks_wont_execute(self, dag_maker):
"""
Tests that backfill tasks won't get executed.
"""
dag_id = "SchedulerJobTest.test_execute_task_instances_backfill_tasks_wont_execute"
task_id_1 = "dummy_task"
with dag_maker(dag_id=dag_id):
task1 = EmptyOperator(task_id=task_id_1)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
session = settings.Session()
dr1 = dag_maker.create_dagrun(run_type=DagRunType.BACKFILL_JOB)
ti1 = TaskInstance(task1, run_id=dr1.run_id)
ti1.refresh_from_db()
ti1.state = State.SCHEDULED
session.merge(ti1)
session.flush()
assert dr1.is_backfill
self.job_runner._critical_section_enqueue_task_instances(session)
session.flush()
ti1.refresh_from_db()
assert State.SCHEDULED == ti1.state
session.rollback()
@conf_vars({("scheduler", "standalone_dag_processor"): "False"})
def test_setup_callback_sink_not_standalone_dag_processor(self):
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull, num_runs=1)
self.job_runner._execute()
assert isinstance(scheduler_job.executor.callback_sink, PipeCallbackSink)
@conf_vars({("scheduler", "standalone_dag_processor"): "True"})
def test_setup_callback_sink_standalone_dag_processor(self):
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull, num_runs=1)
self.job_runner._execute()
assert isinstance(scheduler_job.executor.callback_sink, DatabaseCallbackSink)
def test_find_executable_task_instances_backfill(self, dag_maker):
dag_id = "SchedulerJobTest.test_find_executable_task_instances_backfill"
task_id_1 = "dummy"
with dag_maker(dag_id=dag_id, max_active_tasks=16):
task1 = EmptyOperator(task_id=task_id_1)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
session = settings.Session()
dr1 = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
dr2 = dag_maker.create_dagrun_after(dr1, run_type=DagRunType.BACKFILL_JOB, state=State.RUNNING)
ti_backfill = dr2.get_task_instance(task1.task_id)
ti_with_dagrun = dr1.get_task_instance(task1.task_id)
# ti_with_paused
ti_backfill.state = State.SCHEDULED
ti_with_dagrun.state = State.SCHEDULED
session.merge(dr2)
session.merge(ti_backfill)
session.merge(ti_with_dagrun)
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
assert 1 == len(res)
res_keys = (x.key for x in res)
assert ti_with_dagrun.key in res_keys
session.rollback()
def test_find_executable_task_instances_pool(self, dag_maker):
dag_id = "SchedulerJobTest.test_find_executable_task_instances_pool"
task_id_1 = "dummy"
task_id_2 = "dummydummy"
session = settings.Session()
with dag_maker(dag_id=dag_id, max_active_tasks=16, session=session):
EmptyOperator(task_id=task_id_1, pool="a", priority_weight=2)
EmptyOperator(task_id=task_id_2, pool="b", priority_weight=1)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
dr1 = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
dr2 = dag_maker.create_dagrun_after(dr1, run_type=DagRunType.SCHEDULED)
tis = [
dr1.get_task_instance(task_id_1, session=session),
dr1.get_task_instance(task_id_2, session=session),
dr2.get_task_instance(task_id_1, session=session),
dr2.get_task_instance(task_id_2, session=session),
]
tis.sort(key=lambda ti: ti.key)
for ti in tis:
ti.state = State.SCHEDULED
session.merge(ti)
pool = Pool(pool="a", slots=1, description="haha", include_deferred=False)
pool2 = Pool(pool="b", slots=100, description="haha", include_deferred=False)
session.add(pool)
session.add(pool2)
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
session.flush()
assert 3 == len(res)
res_keys = []
for ti in res:
res_keys.append(ti.key)
assert tis[0].key in res_keys
assert tis[2].key in res_keys
assert tis[3].key in res_keys
session.rollback()
@pytest.mark.parametrize(
"state, total_executed_ti",
[
(DagRunState.SUCCESS, 0),
(DagRunState.FAILED, 0),
(DagRunState.RUNNING, 2),
(DagRunState.QUEUED, 0),
],
)
def test_find_executable_task_instances_only_running_dagruns(
self, state, total_executed_ti, dag_maker, session
):
"""Test that only task instances of 'running' dagruns are executed"""
dag_id = "SchedulerJobTest.test_find_executable_task_instances_only_running_dagruns"
task_id_1 = "dummy"
task_id_2 = "dummydummy"
with dag_maker(dag_id=dag_id, session=session):
EmptyOperator(task_id=task_id_1)
EmptyOperator(task_id=task_id_2)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
dr = dag_maker.create_dagrun(state=state)
tis = dr.task_instances
for ti in tis:
ti.state = State.SCHEDULED
session.merge(ti)
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
session.flush()
assert total_executed_ti == len(res)
def test_find_executable_task_instances_order_execution_date(self, dag_maker):
"""
Test that task instances follow execution_date order priority. If two dagruns with
different execution dates are scheduled, tasks with earliest dagrun execution date will first
be executed
"""
dag_id_1 = "SchedulerJobTest.test_find_executable_task_instances_order_execution_date-a"
dag_id_2 = "SchedulerJobTest.test_find_executable_task_instances_order_execution_date-b"
task_id = "task-a"
session = settings.Session()
with dag_maker(dag_id=dag_id_1, max_active_tasks=16, session=session):
EmptyOperator(task_id=task_id)
dr1 = dag_maker.create_dagrun(execution_date=DEFAULT_DATE + timedelta(hours=1))
with dag_maker(dag_id=dag_id_2, max_active_tasks=16, session=session):
EmptyOperator(task_id=task_id)
dr2 = dag_maker.create_dagrun()
dr1 = session.merge(dr1, load=False)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
tis = dr1.task_instances + dr2.task_instances
for ti in tis:
ti.state = State.SCHEDULED
session.merge(ti)
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=1, session=session)
session.flush()
assert [ti.key for ti in res] == [tis[1].key]
session.rollback()
def test_find_executable_task_instances_order_priority(self, dag_maker):
dag_id_1 = "SchedulerJobTest.test_find_executable_task_instances_order_priority-a"
dag_id_2 = "SchedulerJobTest.test_find_executable_task_instances_order_priority-b"
task_id = "task-a"
session = settings.Session()
with dag_maker(dag_id=dag_id_1, max_active_tasks=16, session=session):
EmptyOperator(task_id=task_id, priority_weight=1)
dr1 = dag_maker.create_dagrun()
with dag_maker(dag_id=dag_id_2, max_active_tasks=16, session=session):
EmptyOperator(task_id=task_id, priority_weight=4)
dr2 = dag_maker.create_dagrun()
dr1 = session.merge(dr1, load=False)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
tis = dr1.task_instances + dr2.task_instances
for ti in tis:
ti.state = State.SCHEDULED
session.merge(ti)
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=1, session=session)
session.flush()
assert [ti.key for ti in res] == [tis[1].key]
session.rollback()
def test_find_executable_task_instances_order_priority_with_pools(self, dag_maker):
"""
The scheduler job should pick tasks with higher priority for execution
even if different pools are involved.
"""
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
session = settings.Session()
dag_id = "SchedulerJobTest.test_find_executable_task_instances_order_priority_with_pools"
session.add(Pool(pool="pool1", slots=32, include_deferred=False))
session.add(Pool(pool="pool2", slots=32, include_deferred=False))
with dag_maker(dag_id=dag_id, max_active_tasks=2):
op1 = EmptyOperator(task_id="dummy1", priority_weight=1, pool="pool1")
op2 = EmptyOperator(task_id="dummy2", priority_weight=2, pool="pool2")
op3 = EmptyOperator(task_id="dummy3", priority_weight=3, pool="pool1")
dag_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
ti1 = dag_run.get_task_instance(op1.task_id, session)
ti2 = dag_run.get_task_instance(op2.task_id, session)
ti3 = dag_run.get_task_instance(op3.task_id, session)
ti1.state = State.SCHEDULED
ti2.state = State.SCHEDULED
ti3.state = State.SCHEDULED
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
assert 2 == len(res)
assert ti3.key == res[0].key
assert ti2.key == res[1].key
session.rollback()
def test_find_executable_task_instances_order_execution_date_and_priority(self, dag_maker):
dag_id_1 = "SchedulerJobTest.test_find_executable_task_instances_order_execution_date_and_priority-a"
dag_id_2 = "SchedulerJobTest.test_find_executable_task_instances_order_execution_date_and_priority-b"
task_id = "task-a"
session = settings.Session()
with dag_maker(dag_id=dag_id_1, max_active_tasks=16, session=session):
EmptyOperator(task_id=task_id, priority_weight=1)
dr1 = dag_maker.create_dagrun()
with dag_maker(dag_id=dag_id_2, max_active_tasks=16, session=session):
EmptyOperator(task_id=task_id, priority_weight=4)
dr2 = dag_maker.create_dagrun(execution_date=DEFAULT_DATE + timedelta(hours=1))
dr1 = session.merge(dr1, load=False)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
tis = dr1.task_instances + dr2.task_instances
for ti in tis:
ti.state = State.SCHEDULED
session.merge(ti)
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=1, session=session)
session.flush()
assert [ti.key for ti in res] == [tis[1].key]
session.rollback()
def test_find_executable_task_instances_in_default_pool(self, dag_maker):
set_default_pool_slots(1)
dag_id = "SchedulerJobTest.test_find_executable_task_instances_in_default_pool"
with dag_maker(dag_id=dag_id):
op1 = EmptyOperator(task_id="dummy1")
op2 = EmptyOperator(task_id="dummy2")
scheduler_job = Job(executor=MockExecutor())
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull, num_runs=1)
session = settings.Session()
dr1 = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
dr2 = dag_maker.create_dagrun_after(dr1, run_type=DagRunType.SCHEDULED, state=State.RUNNING)
ti1 = dr1.get_task_instance(op1.task_id, session)
ti2 = dr2.get_task_instance(op2.task_id, session)
ti1.state = State.SCHEDULED
ti2.state = State.SCHEDULED
session.flush()
# Two tasks w/o pool up for execution and our default pool size is 1
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
assert 1 == len(res)
ti2.state = State.RUNNING
session.flush()
# One task w/o pool up for execution and one task running
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
assert 0 == len(res)
session.rollback()
session.close()
def test_queued_task_instances_fails_with_missing_dag(self, dag_maker, session):
"""Check that task instances of missing DAGs are failed"""
dag_id = "SchedulerJobTest.test_find_executable_task_instances_not_in_dagbag"
task_id_1 = "dummy"
task_id_2 = "dummydummy"
with dag_maker(dag_id=dag_id, session=session, default_args={"max_active_tis_per_dag": 1}):
EmptyOperator(task_id=task_id_1)
EmptyOperator(task_id=task_id_2)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
self.job_runner.dagbag = mock.MagicMock()
self.job_runner.dagbag.get_dag.return_value = None
dr = dag_maker.create_dagrun(state=DagRunState.RUNNING)
tis = dr.task_instances
for ti in tis:
ti.state = State.SCHEDULED
session.merge(ti)
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
session.flush()
assert 0 == len(res)
tis = dr.get_task_instances(session=session)
assert len(tis) == 2
assert all(ti.state == State.FAILED for ti in tis)
def test_nonexistent_pool(self, dag_maker):
dag_id = "SchedulerJobTest.test_nonexistent_pool"
with dag_maker(dag_id=dag_id, max_active_tasks=16):
EmptyOperator(task_id="dummy_wrong_pool", pool="this_pool_doesnt_exist")
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
session = settings.Session()
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.state = State.SCHEDULED
session.merge(ti)
session.commit()
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
session.flush()
assert 0 == len(res)
session.rollback()
def test_infinite_pool(self, dag_maker):
dag_id = "SchedulerJobTest.test_infinite_pool"
with dag_maker(dag_id=dag_id, concurrency=16):
EmptyOperator(task_id="dummy", pool="infinite_pool")
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
session = settings.Session()
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.state = State.SCHEDULED
session.merge(ti)
infinite_pool = Pool(
pool="infinite_pool",
slots=-1,
description="infinite pool",
include_deferred=False,
)
session.add(infinite_pool)
session.commit()
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
session.flush()
assert 1 == len(res)
session.rollback()
def test_not_enough_pool_slots(self, caplog, dag_maker):
dag_id = "SchedulerJobTest.test_test_not_enough_pool_slots"
with dag_maker(dag_id=dag_id, concurrency=16):
EmptyOperator(task_id="cannot_run", pool="some_pool", pool_slots=4)
EmptyOperator(task_id="can_run", pool="some_pool", pool_slots=1)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
session = settings.Session()
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.state = State.SCHEDULED
session.merge(ti)
ti = dr.task_instances[1]
ti.state = State.SCHEDULED
session.merge(ti)
some_pool = Pool(pool="some_pool", slots=2, description="my pool", include_deferred=False)
session.add(some_pool)
session.commit()
with caplog.at_level(logging.WARNING):
self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
assert (
"Not executing <TaskInstance: "
"SchedulerJobTest.test_test_not_enough_pool_slots.cannot_run test [scheduled]>. "
"Requested pool slots (4) are greater than total pool slots: '2' for pool: some_pool"
in caplog.text
)
assert (
session.query(TaskInstance)
.filter(TaskInstance.dag_id == dag_id, TaskInstance.state == State.SCHEDULED)
.count()
== 1
)
assert (
session.query(TaskInstance)
.filter(TaskInstance.dag_id == dag_id, TaskInstance.state == State.QUEUED)
.count()
== 1
)
session.flush()
session.rollback()
def test_find_executable_task_instances_none(self, dag_maker):
dag_id = "SchedulerJobTest.test_find_executable_task_instances_none"
task_id_1 = "dummy"
with dag_maker(dag_id=dag_id, max_active_tasks=16):
EmptyOperator(task_id=task_id_1)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
session = settings.Session()
assert 0 == len(self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session))
session.rollback()
def test_tis_for_queued_dagruns_are_not_run(self, dag_maker):
"""
This tests that tis from queued dagruns are not queued
"""
dag_id = "test_tis_for_queued_dagruns_are_not_run"
task_id_1 = "dummy"
with dag_maker(dag_id):
task1 = EmptyOperator(task_id=task_id_1)
dr1 = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, state=State.QUEUED)
dr2 = dag_maker.create_dagrun_after(dr1, run_type=DagRunType.SCHEDULED)
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)
session = settings.Session()
ti1 = TaskInstance(task1, run_id=dr1.run_id)
ti2 = TaskInstance(task1, run_id=dr2.run_id)
ti1.state = State.SCHEDULED
ti2.state = State.SCHEDULED
session.merge(ti1)
session.merge(ti2)
session.flush()
res = self.job_runner._executable_task_instances_to_queued(max_tis=32, session=session)
assert 1 == len(res)
assert ti2.key == res[0].key
ti1.refresh_from_db()
ti2.refresh_from_db()
assert ti1.state == State.SCHEDULED
assert ti2.state == State.QUEUED
def test_find_executable_task_instances_concurrency(self, dag_maker):
dag_id = "SchedulerJobTest.test_find_executable_task_instances_concurrency"
session = settings.Session()
with dag_maker(dag_id=dag_id, max_active_tasks=2, session=session):
EmptyOperator(task_id="dummy")
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job, subdir=os.devnull)