-
Notifications
You must be signed in to change notification settings - Fork 14.4k
/
test_job_runner.py
1667 lines (1442 loc) · 65.6 KB
/
test_job_runner.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 itertools
import logging
import multiprocessing
import os
import pathlib
import random
import socket
import sys
import textwrap
import threading
import time
from collections import deque
from datetime import datetime, timedelta
from logging.config import dictConfig
from unittest import mock
from unittest.mock import MagicMock, Mock, PropertyMock
import pytest
import time_machine
from sqlalchemy import func
from airflow.callbacks.callback_requests import CallbackRequest, DagCallbackRequest, SlaCallbackRequest
from airflow.config_templates.airflow_local_settings import DEFAULT_LOGGING_CONFIG
from airflow.configuration import conf
from airflow.dag_processing.manager import (
DagFileProcessorAgent,
DagFileProcessorManager,
DagFileStat,
DagParsingSignal,
DagParsingStat,
)
from airflow.dag_processing.processor import DagFileProcessorProcess
from airflow.jobs.dag_processor_job_runner import DagProcessorJobRunner
from airflow.jobs.job import Job
from airflow.models import DagBag, DagModel, DbCallbackRequest, errors
from airflow.models.dagcode import DagCode
from airflow.models.serialized_dag import SerializedDagModel
from airflow.utils import timezone
from airflow.utils.net import get_hostname
from airflow.utils.session import create_session
from tests.core.test_logging_config import SETTINGS_FILE_VALID, settings_context
from tests.models import TEST_DAGS_FOLDER
from tests.test_utils.config import conf_vars
from tests.test_utils.db import clear_db_callbacks, clear_db_dags, clear_db_runs, clear_db_serialized_dags
pytestmark = pytest.mark.db_test
logger = logging.getLogger(__name__)
TEST_DAG_FOLDER = pathlib.Path(__file__).parents[1].resolve() / "dags"
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
class FakeDagFileProcessorRunner(DagFileProcessorProcess):
# This fake processor will return the zombies it received in constructor
# as its processing result w/o actually parsing anything.
def __init__(self, file_path, pickle_dags, dag_ids, dag_directory, callbacks):
super().__init__(file_path, pickle_dags, dag_ids, dag_directory, callbacks)
# We need a "real" selectable handle for waitable_handle to work
readable, writable = multiprocessing.Pipe(duplex=False)
writable.send("abc")
writable.close()
self._waitable_handle = readable
self._result = 0, 0
def start(self):
pass
@property
def start_time(self):
return DEFAULT_DATE
@property
def pid(self):
return 1234
@property
def done(self):
return True
@property
def result(self):
return self._result
@staticmethod
def _create_process(file_path, callback_requests, dag_ids, dag_directory, pickle_dags):
return FakeDagFileProcessorRunner(
file_path,
pickle_dags,
dag_ids,
dag_directory,
callback_requests,
)
@property
def waitable_handle(self):
return self._waitable_handle
class TestDagProcessorJobRunner:
def setup_method(self):
dictConfig(DEFAULT_LOGGING_CONFIG)
clear_db_runs()
clear_db_serialized_dags()
clear_db_dags()
clear_db_callbacks()
def teardown_class(self):
clear_db_runs()
clear_db_serialized_dags()
clear_db_dags()
clear_db_callbacks()
def run_processor_manager_one_loop(self, manager, parent_pipe):
if not manager.processor._async_mode:
parent_pipe.send(DagParsingSignal.AGENT_RUN_ONCE)
results = []
while True:
manager.processor._run_parsing_loop()
while parent_pipe.poll(timeout=0.01):
obj = parent_pipe.recv()
if not isinstance(obj, DagParsingStat):
results.append(obj)
elif obj.done:
return results
raise RuntimeError("Shouldn't get here - nothing to read, but manager not finished!")
@conf_vars({("core", "load_examples"): "False"})
def test_remove_file_clears_import_error(self, tmp_path):
path_to_parse = tmp_path / "temp_dag.py"
# Generate original import error
path_to_parse.write_text("an invalid airflow DAG")
child_pipe, parent_pipe = multiprocessing.Pipe()
async_mode = "sqlite" not in conf.get("database", "sql_alchemy_conn")
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory=path_to_parse.parent,
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=child_pipe,
dag_ids=[],
pickle_dags=False,
async_mode=async_mode,
),
)
with create_session() as session:
self.run_processor_manager_one_loop(manager, parent_pipe)
import_errors = session.query(errors.ImportError).all()
assert len(import_errors) == 1
path_to_parse.unlink()
# Rerun the scheduler once the dag file has been removed
self.run_processor_manager_one_loop(manager, parent_pipe)
import_errors = session.query(errors.ImportError).all()
assert len(import_errors) == 0
session.rollback()
child_pipe.close()
parent_pipe.close()
@conf_vars({("core", "load_examples"): "False"})
def test_max_runs_when_no_files(self, tmp_path):
child_pipe, parent_pipe = multiprocessing.Pipe()
async_mode = "sqlite" not in conf.get("database", "sql_alchemy_conn")
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory=os.fspath(tmp_path),
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=child_pipe,
dag_ids=[],
pickle_dags=False,
async_mode=async_mode,
),
)
self.run_processor_manager_one_loop(manager, parent_pipe)
child_pipe.close()
parent_pipe.close()
@pytest.mark.backend("mysql", "postgres")
@mock.patch("airflow.dag_processing.processor.iter_airflow_imports")
def test_start_new_processes_with_same_filepath(self, _):
"""
Test that when a processor already exist with a filepath, a new processor won't be created
with that filepath. The filepath will just be removed from the list.
"""
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
file_1 = "file_1.py"
file_2 = "file_2.py"
file_3 = "file_3.py"
manager.processor._file_path_queue = deque([file_1, file_2, file_3])
# Mock that only one processor exists. This processor runs with 'file_1'
manager.processor._processors[file_1] = MagicMock()
# Start New Processes
manager.processor.start_new_processes()
# Because of the config: '[scheduler] parsing_processes = 2'
# verify that only one extra process is created
# and since a processor with 'file_1' already exists,
# even though it is first in '_file_path_queue'
# a new processor is created with 'file_2' and not 'file_1'.
assert file_1 in manager.processor._processors.keys()
assert file_2 in manager.processor._processors.keys()
assert deque([file_3]) == manager.processor._file_path_queue
def test_set_file_paths_when_processor_file_path_not_in_new_file_paths(self):
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
mock_processor = MagicMock()
mock_processor.stop.side_effect = AttributeError("DagFileProcessor object has no attribute stop")
mock_processor.terminate.side_effect = None
manager.processor._processors["missing_file.txt"] = mock_processor
manager.processor._file_stats["missing_file.txt"] = DagFileStat(0, 0, None, None, 0)
manager.processor.set_file_paths(["abc.txt"])
assert manager.processor._processors == {}
assert "missing_file.txt" not in manager.processor._file_stats
def test_set_file_paths_when_processor_file_path_is_in_new_file_paths(self):
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
mock_processor = MagicMock()
mock_processor.stop.side_effect = AttributeError("DagFileProcessor object has no attribute stop")
mock_processor.terminate.side_effect = None
manager.processor._processors["abc.txt"] = mock_processor
manager.processor.set_file_paths(["abc.txt"])
assert manager.processor._processors == {"abc.txt": mock_processor}
@conf_vars({("scheduler", "file_parsing_sort_mode"): "alphabetical"})
@mock.patch("zipfile.is_zipfile", return_value=True)
@mock.patch("airflow.utils.file.might_contain_dag", return_value=True)
@mock.patch("airflow.utils.file.find_path_from_directory", return_value=True)
@mock.patch("airflow.utils.file.os.path.isfile", return_value=True)
def test_file_paths_in_queue_sorted_alphabetically(
self, mock_isfile, mock_find_path, mock_might_contain_dag, mock_zipfile
):
"""Test dag files are sorted alphabetically"""
dag_files = ["file_3.py", "file_2.py", "file_4.py", "file_1.py"]
mock_find_path.return_value = dag_files
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
manager.processor.set_file_paths(dag_files)
assert manager.processor._file_path_queue == deque()
manager.processor.prepare_file_path_queue()
assert manager.processor._file_path_queue == deque(
["file_1.py", "file_2.py", "file_3.py", "file_4.py"]
)
@conf_vars({("scheduler", "file_parsing_sort_mode"): "random_seeded_by_host"})
@mock.patch("zipfile.is_zipfile", return_value=True)
@mock.patch("airflow.utils.file.might_contain_dag", return_value=True)
@mock.patch("airflow.utils.file.find_path_from_directory", return_value=True)
@mock.patch("airflow.utils.file.os.path.isfile", return_value=True)
def test_file_paths_in_queue_sorted_random_seeded_by_host(
self, mock_isfile, mock_find_path, mock_might_contain_dag, mock_zipfile
):
"""Test files are randomly sorted and seeded by host name"""
dag_files = ["file_3.py", "file_2.py", "file_4.py", "file_1.py"]
mock_find_path.return_value = dag_files
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
manager.processor.set_file_paths(dag_files)
assert manager.processor._file_path_queue == deque()
manager.processor.prepare_file_path_queue()
expected_order = deque(dag_files)
random.Random(get_hostname()).shuffle(expected_order)
assert manager.processor._file_path_queue == expected_order
# Verify running it again produces same order
manager.processor._file_paths = []
manager.processor.prepare_file_path_queue()
assert manager.processor._file_path_queue == expected_order
@pytest.fixture
def change_platform_timezone(self, monkeypatch):
monkeypatch.setenv("TZ", "Europe/Paris")
# propagate new timezone to C routines
# this is only needed for Unix. On Windows, exporting the TZ env variable
# is enough (see https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-s-localtime32-s-localtime64-s?view=msvc-170#remarks)
tzset = getattr(time, "tzset", None)
if tzset is not None:
tzset()
yield
# reset timezone to platform's default
monkeypatch.delenv("TZ")
if tzset is not None:
tzset()
@conf_vars({("scheduler", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("zipfile.is_zipfile", return_value=True)
@mock.patch("airflow.utils.file.might_contain_dag", return_value=True)
@mock.patch("airflow.utils.file.find_path_from_directory", return_value=True)
@mock.patch("airflow.utils.file.os.path.isfile", return_value=True)
@mock.patch("airflow.utils.file.os.path.getmtime")
def test_file_paths_in_queue_sorted_by_modified_time(
self,
mock_getmtime,
mock_isfile,
mock_find_path,
mock_might_contain_dag,
mock_zipfile,
change_platform_timezone,
):
"""Test files are sorted by modified time"""
paths_with_mtime = {"file_3.py": 3.0, "file_2.py": 2.0, "file_4.py": 5.0, "file_1.py": 4.0}
dag_files = list(paths_with_mtime.keys())
mock_getmtime.side_effect = list(paths_with_mtime.values())
mock_find_path.return_value = dag_files
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
manager.processor.set_file_paths(dag_files)
assert manager.processor._file_path_queue == deque()
manager.processor.prepare_file_path_queue()
assert manager.processor._file_path_queue == deque(
["file_4.py", "file_1.py", "file_3.py", "file_2.py"]
)
@conf_vars({("scheduler", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("zipfile.is_zipfile", return_value=True)
@mock.patch("airflow.utils.file.might_contain_dag", return_value=True)
@mock.patch("airflow.utils.file.find_path_from_directory", return_value=True)
@mock.patch("airflow.utils.file.os.path.isfile", return_value=True)
@mock.patch("airflow.utils.file.os.path.getmtime")
def test_file_paths_in_queue_excludes_missing_file(
self,
mock_getmtime,
mock_isfile,
mock_find_path,
mock_might_contain_dag,
mock_zipfile,
change_platform_timezone,
):
"""Check that a file is not enqueued for processing if it has been deleted"""
dag_files = ["file_3.py", "file_2.py", "file_4.py"]
mock_getmtime.side_effect = [1.0, 2.0, FileNotFoundError()]
mock_find_path.return_value = dag_files
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
manager.processor.set_file_paths(dag_files)
manager.processor.prepare_file_path_queue()
assert manager.processor._file_path_queue == deque(["file_2.py", "file_3.py"])
@conf_vars({("scheduler", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("zipfile.is_zipfile", return_value=True)
@mock.patch("airflow.utils.file.might_contain_dag", return_value=True)
@mock.patch("airflow.utils.file.find_path_from_directory", return_value=True)
@mock.patch("airflow.utils.file.os.path.isfile", return_value=True)
@mock.patch("airflow.utils.file.os.path.getmtime")
def test_add_new_file_to_parsing_queue(
self,
mock_getmtime,
mock_isfile,
mock_find_path,
mock_might_contain_dag,
mock_zipfile,
change_platform_timezone,
):
"""Check that new file is added to parsing queue"""
dag_files = ["file_1.py", "file_2.py", "file_3.py"]
mock_getmtime.side_effect = [1.0, 2.0, 3.0]
mock_find_path.return_value = dag_files
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
manager.processor.set_file_paths(dag_files)
manager.processor.prepare_file_path_queue()
assert manager.processor._file_path_queue == deque(["file_3.py", "file_2.py", "file_1.py"])
manager.processor.set_file_paths([*dag_files, "file_4.py"])
manager.processor.add_new_file_path_to_queue()
assert manager.processor._file_path_queue == deque(
["file_4.py", "file_3.py", "file_2.py", "file_1.py"]
)
@conf_vars({("scheduler", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("airflow.settings.TIMEZONE", timezone.utc)
@mock.patch("zipfile.is_zipfile", return_value=True)
@mock.patch("airflow.utils.file.might_contain_dag", return_value=True)
@mock.patch("airflow.utils.file.find_path_from_directory", return_value=True)
@mock.patch("airflow.utils.file.os.path.isfile", return_value=True)
@mock.patch("airflow.utils.file.os.path.getmtime")
def test_recently_modified_file_is_parsed_with_mtime_mode(
self,
mock_getmtime,
mock_isfile,
mock_find_path,
mock_might_contain_dag,
mock_zipfile,
change_platform_timezone,
):
"""
Test recently updated files are processed even if min_file_process_interval is not reached
"""
freezed_base_time = timezone.datetime(2020, 1, 5, 0, 0, 0)
initial_file_1_mtime = (freezed_base_time - timedelta(minutes=5)).timestamp()
dag_files = ["file_1.py"]
mock_getmtime.side_effect = [initial_file_1_mtime]
mock_find_path.return_value = dag_files
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=3,
processor_timeout=timedelta(days=365),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
# let's say the DAG was just parsed 10 seconds before the Freezed time
last_finish_time = freezed_base_time - timedelta(seconds=10)
manager.processor._file_stats = {
"file_1.py": DagFileStat(1, 0, last_finish_time, timedelta(seconds=1.0), 1),
}
with time_machine.travel(freezed_base_time):
manager.processor.set_file_paths(dag_files)
assert manager.processor._file_path_queue == deque()
# File Path Queue will be empty as the "modified time" < "last finish time"
manager.processor.prepare_file_path_queue()
assert manager.processor._file_path_queue == deque()
# Simulate the DAG modification by using modified_time which is greater
# than the last_parse_time but still less than now - min_file_process_interval
file_1_new_mtime = freezed_base_time - timedelta(seconds=5)
file_1_new_mtime_ts = file_1_new_mtime.timestamp()
with time_machine.travel(freezed_base_time):
manager.processor.set_file_paths(dag_files)
assert manager.processor._file_path_queue == deque()
# File Path Queue will be empty as the "modified time" < "last finish time"
mock_getmtime.side_effect = [file_1_new_mtime_ts]
manager.processor.prepare_file_path_queue()
# Check that file is added to the queue even though file was just recently passed
assert manager.processor._file_path_queue == deque(["file_1.py"])
assert last_finish_time < file_1_new_mtime
assert (
manager.processor._file_process_interval
> (freezed_base_time - manager.processor.get_last_finish_time("file_1.py")).total_seconds()
)
def test_scan_stale_dags(self):
"""
Ensure that DAGs are marked inactive when the file is parsed but the
DagModel.last_parsed_time is not updated.
"""
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(minutes=10),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
test_dag_path = str(TEST_DAG_FOLDER / "test_example_bash_operator.py")
dagbag = DagBag(test_dag_path, read_dags_from_db=False, include_examples=False)
with create_session() as session:
# Add stale DAG to the DB
dag = dagbag.get_dag("test_example_bash_operator")
dag.last_parsed_time = timezone.utcnow()
dag.sync_to_db()
SerializedDagModel.write_dag(dag)
# Add DAG to the file_parsing_stats
stat = DagFileStat(
num_dags=1,
import_errors=0,
last_finish_time=timezone.utcnow() + timedelta(hours=1),
last_duration=1,
run_count=1,
)
manager.processor._file_paths = [test_dag_path]
manager.processor._file_stats[test_dag_path] = stat
active_dag_count = (
session.query(func.count(DagModel.dag_id))
.filter(DagModel.is_active, DagModel.fileloc == test_dag_path)
.scalar()
)
assert active_dag_count == 1
serialized_dag_count = (
session.query(func.count(SerializedDagModel.dag_id))
.filter(SerializedDagModel.fileloc == test_dag_path)
.scalar()
)
assert serialized_dag_count == 1
manager.processor._scan_stale_dags()
active_dag_count = (
session.query(func.count(DagModel.dag_id))
.filter(DagModel.is_active, DagModel.fileloc == test_dag_path)
.scalar()
)
assert active_dag_count == 0
serialized_dag_count = (
session.query(func.count(SerializedDagModel.dag_id))
.filter(SerializedDagModel.fileloc == test_dag_path)
.scalar()
)
assert serialized_dag_count == 0
@conf_vars(
{
("core", "load_examples"): "False",
("scheduler", "standalone_dag_processor"): "True",
("scheduler", "stale_dag_threshold"): "50",
}
)
def test_scan_stale_dags_standalone_mode(self):
"""
Ensure only dags from current dag_directory are updated
"""
dag_directory = "directory"
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory=dag_directory,
max_runs=1,
processor_timeout=timedelta(minutes=10),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
test_dag_path = str(TEST_DAG_FOLDER / "test_example_bash_operator.py")
dagbag = DagBag(test_dag_path, read_dags_from_db=False)
other_test_dag_path = str(TEST_DAG_FOLDER / "test_scheduler_dags.py")
other_dagbag = DagBag(other_test_dag_path, read_dags_from_db=False)
with create_session() as session:
# Add stale DAG to the DB
dag = dagbag.get_dag("test_example_bash_operator")
dag.last_parsed_time = timezone.utcnow()
dag.sync_to_db(processor_subdir=dag_directory)
# Add stale DAG to the DB
other_dag = other_dagbag.get_dag("test_start_date_scheduling")
other_dag.last_parsed_time = timezone.utcnow()
other_dag.sync_to_db(processor_subdir="other")
# Add DAG to the file_parsing_stats
stat = DagFileStat(
num_dags=1,
import_errors=0,
last_finish_time=timezone.utcnow() + timedelta(hours=1),
last_duration=1,
run_count=1,
)
manager.processor._file_paths = [test_dag_path]
manager.processor._file_stats[test_dag_path] = stat
active_dag_count = session.query(func.count(DagModel.dag_id)).filter(DagModel.is_active).scalar()
assert active_dag_count == 2
manager.processor._scan_stale_dags()
active_dag_count = session.query(func.count(DagModel.dag_id)).filter(DagModel.is_active).scalar()
assert active_dag_count == 1
@mock.patch(
"airflow.dag_processing.processor.DagFileProcessorProcess.waitable_handle", new_callable=PropertyMock
)
@mock.patch("airflow.dag_processing.processor.DagFileProcessorProcess.pid", new_callable=PropertyMock)
@mock.patch("airflow.dag_processing.processor.DagFileProcessorProcess.kill")
def test_kill_timed_out_processors_kill(self, mock_kill, mock_pid, mock_waitable_handle):
mock_pid.return_value = 1234
mock_waitable_handle.return_value = 3
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory="directory",
max_runs=1,
processor_timeout=timedelta(seconds=5),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
processor = DagFileProcessorProcess(
file_path="abc.txt",
pickle_dags=False,
dag_ids=[],
dag_directory=TEST_DAG_FOLDER,
callback_requests=[],
)
processor._start_time = timezone.make_aware(datetime.min)
manager.processor._processors = {"abc.txt": processor}
manager.processor.waitables[3] = processor
initial_waitables = len(manager.processor.waitables)
manager.processor._kill_timed_out_processors()
mock_kill.assert_called_once_with()
assert len(manager.processor._processors) == 0
assert len(manager.processor.waitables) == initial_waitables - 1
@mock.patch("airflow.dag_processing.processor.DagFileProcessorProcess.pid", new_callable=PropertyMock)
@mock.patch("airflow.dag_processing.processor.DagFileProcessorProcess")
def test_kill_timed_out_processors_no_kill(self, mock_dag_file_processor, mock_pid):
mock_pid.return_value = 1234
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory=TEST_DAG_FOLDER,
max_runs=1,
processor_timeout=timedelta(seconds=5),
signal_conn=MagicMock(),
dag_ids=[],
pickle_dags=False,
async_mode=True,
),
)
processor = DagFileProcessorProcess(
file_path="abc.txt",
pickle_dags=False,
dag_ids=[],
dag_directory=str(TEST_DAG_FOLDER),
callback_requests=[],
)
processor._start_time = timezone.make_aware(datetime.max)
manager.processor._processors = {"abc.txt": processor}
manager.processor._kill_timed_out_processors()
mock_dag_file_processor.kill.assert_not_called()
@conf_vars({("core", "load_examples"): "False"})
@pytest.mark.execution_timeout(10)
def test_dag_with_system_exit(self):
"""
Test to check that a DAG with a system.exit() doesn't break the scheduler.
"""
dag_id = "exit_test_dag"
dag_directory = TEST_DAG_FOLDER.parent / "dags_with_system_exit"
# Delete the one valid DAG/SerializedDAG, and check that it gets re-created
clear_db_dags()
clear_db_serialized_dags()
child_pipe, parent_pipe = multiprocessing.Pipe()
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory=dag_directory,
dag_ids=[],
max_runs=1,
processor_timeout=timedelta(seconds=5),
signal_conn=child_pipe,
pickle_dags=False,
async_mode=True,
),
)
manager.processor._run_parsing_loop()
result = None
while parent_pipe.poll(timeout=None):
result = parent_pipe.recv()
if isinstance(result, DagParsingStat) and result.done:
break
# Three files in folder should be processed
assert sum(stat.run_count for stat in manager.processor._file_stats.values()) == 3
with create_session() as session:
assert session.get(DagModel, dag_id) is not None
@conf_vars({("core", "load_examples"): "False"})
def test_import_error_with_dag_directory(self, tmp_path):
TEMP_DAG_FILENAME = "temp_dag.py"
processor_dir_1 = tmp_path / "processor_1"
processor_dir_1.mkdir()
filename_1 = os.path.join(processor_dir_1, TEMP_DAG_FILENAME)
with open(filename_1, "w") as f:
f.write("an invalid airflow DAG")
processor_dir_2 = tmp_path / "processor_2"
processor_dir_2.mkdir()
filename_1 = os.path.join(processor_dir_2, TEMP_DAG_FILENAME)
with open(filename_1, "w") as f:
f.write("an invalid airflow DAG")
with create_session() as session:
child_pipe, parent_pipe = multiprocessing.Pipe()
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory=processor_dir_1,
dag_ids=[],
max_runs=1,
signal_conn=child_pipe,
processor_timeout=timedelta(seconds=5),
pickle_dags=False,
async_mode=False,
),
)
self.run_processor_manager_one_loop(manager, parent_pipe)
import_errors = session.query(errors.ImportError).order_by("id").all()
assert len(import_errors) == 1
assert import_errors[0].processor_subdir == str(processor_dir_1)
child_pipe, parent_pipe = multiprocessing.Pipe()
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory=processor_dir_2,
dag_ids=[],
max_runs=1,
signal_conn=child_pipe,
processor_timeout=timedelta(seconds=5),
pickle_dags=False,
async_mode=True,
),
)
self.run_processor_manager_one_loop(manager, parent_pipe)
import_errors = session.query(errors.ImportError).order_by("id").all()
assert len(import_errors) == 2
assert import_errors[0].processor_subdir == str(processor_dir_1)
assert import_errors[1].processor_subdir == str(processor_dir_2)
session.rollback()
@conf_vars({("core", "load_examples"): "False"})
@pytest.mark.backend("mysql", "postgres")
@pytest.mark.execution_timeout(30)
@mock.patch("airflow.dag_processing.manager.DagFileProcessorProcess")
def test_pipe_full_deadlock(self, mock_processor):
dag_filepath = TEST_DAG_FOLDER / "test_scheduler_dags.py"
child_pipe, parent_pipe = multiprocessing.Pipe()
# Shrink the buffers to exacerbate the problem!
for fd in (parent_pipe.fileno(),):
sock = socket.socket(fileno=fd)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024)
sock.detach()
exit_event = threading.Event()
# To test this behaviour we need something that continually fills the
# parent pipe's buffer (and keeps it full).
def keep_pipe_full(pipe, exit_event):
for n in itertools.count(1):
if exit_event.is_set():
break
req = CallbackRequest(str(dag_filepath))
logger.info("Sending CallbackRequests %d", n)
try:
pipe.send(req)
except TypeError:
# This is actually the error you get when the parent pipe
# is closed! Nicely handled, eh?
break
except OSError:
break
logger.debug(" Sent %d CallbackRequests", n)
thread = threading.Thread(target=keep_pipe_full, args=(parent_pipe, exit_event))
fake_processors = []
def fake_processor_(*args, **kwargs):
nonlocal fake_processors
processor = FakeDagFileProcessorRunner._create_process(*args, **kwargs)
fake_processors.append(processor)
return processor
mock_processor.side_effect = fake_processor_
manager = DagFileProcessorManager(
dag_directory=dag_filepath,
dag_ids=[],
# A reasonable large number to ensure that we trigger the deadlock
max_runs=100,
processor_timeout=timedelta(seconds=5),
signal_conn=child_pipe,
pickle_dags=False,
async_mode=True,
)
try:
thread.start()
# If this completes without hanging, then the test is good!
manager._run_parsing_loop()
exit_event.set()
finally:
logger.info("Closing pipes")
parent_pipe.close()
child_pipe.close()
logger.info("Closed pipes")
logger.info("Joining thread")
thread.join(timeout=1.0)
logger.info("Joined thread")
@conf_vars({("core", "load_examples"): "False"})
@mock.patch("airflow.dag_processing.manager.Stats.timing")
def test_send_file_processing_statsd_timing(self, statsd_timing_mock, tmp_path):
path_to_parse = tmp_path / "temp_dag.py"
dag_code = textwrap.dedent(
"""
from airflow import DAG
dag = DAG(dag_id='temp_dag', schedule='0 0 * * *')
"""
)
path_to_parse.write_text(dag_code)
child_pipe, parent_pipe = multiprocessing.Pipe()
async_mode = "sqlite" not in conf.get("database", "sql_alchemy_conn")
manager = DagProcessorJobRunner(
job=Job(),
processor=DagFileProcessorManager(
dag_directory=path_to_parse.parent,
max_runs=1,
processor_timeout=timedelta(days=365),
signal_conn=child_pipe,
dag_ids=[],
pickle_dags=False,
async_mode=async_mode,
),
)
self.run_processor_manager_one_loop(manager, parent_pipe)
last_runtime = manager.processor.get_last_runtime(manager.processor.file_paths[0])
child_pipe.close()
parent_pipe.close()
statsd_timing_mock.assert_has_calls(
[
mock.call("dag_processing.last_duration.temp_dag", timedelta(seconds=last_runtime)),
mock.call(
"dag_processing.last_duration",
timedelta(seconds=last_runtime),
tags={"file_name": "temp_dag"},
),
],
any_order=True,
)
def test_refresh_dags_dir_doesnt_delete_zipped_dags(self, tmp_path):
"""Test DagProcessorJobRunner._refresh_dag_dir method"""