-
Notifications
You must be signed in to change notification settings - Fork 17.6k
Expand file tree
/
Copy pathtest_manager.py
More file actions
2745 lines (2328 loc) · 114 KB
/
Copy pathtest_manager.py
File metadata and controls
2745 lines (2328 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import copy
import json
import logging
import os
import random
import re
import shutil
import signal
import textwrap
import time
import zipfile
from collections import defaultdict, deque
from datetime import datetime, timedelta
from pathlib import Path
from socket import socket, socketpair
from unittest import mock
from unittest.mock import MagicMock
import msgspec
import pytest
import time_machine
from sqlalchemy import func, select
from uuid6 import uuid7
from airflow._shared.timezones import timezone
from airflow.callbacks.callback_requests import DagCallbackRequest
from airflow.dag_processing.bundles.base import BaseDagBundle
from airflow.dag_processing.bundles.manager import DagBundlesManager
from airflow.dag_processing.dagbag import DagBag
from airflow.dag_processing.manager import (
BundleState,
DagFileInfo,
DagFileProcessorManager,
DagFileStat,
)
from airflow.dag_processing.processor import DagFileParsingResult, DagFileProcessorProcess
from airflow.models import DagModel, DbCallbackRequest
from airflow.models.asset import TaskOutletAssetReference
from airflow.models.dag_version import DagVersion
from airflow.models.dagbundle import DagBundleModel
from airflow.models.dagcode import DagCode
from airflow.models.serialized_dag import SerializedDagModel
from airflow.models.team import Team
from airflow.utils.net import get_hostname
from airflow.utils.session import create_session
from tests_common.test_utils.compat import ParseImportError
from tests_common.test_utils.config import conf_vars
from tests_common.test_utils.dag import sync_dag_to_db
from tests_common.test_utils.db import (
clear_db_assets,
clear_db_callbacks,
clear_db_dag_bundles,
clear_db_dags,
clear_db_import_errors,
clear_db_runs,
clear_db_serialized_dags,
clear_db_teams,
)
from unit.models import TEST_DAGS_FOLDER
pytestmark = pytest.mark.db_test
logger = logging.getLogger(__name__)
TEST_DAG_FOLDER = Path(__file__).parents[1].resolve() / "dags"
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
def _get_file_infos(files: list[str | Path]) -> list[DagFileInfo]:
return [DagFileInfo(bundle_name="testing", bundle_path=TEST_DAGS_FOLDER, rel_path=Path(f)) for f in files]
def _get_versioned_file_info(file: str | Path, bundle_version: str = "v1") -> DagFileInfo:
return DagFileInfo(
bundle_name="testing",
bundle_path=TEST_DAGS_FOLDER,
rel_path=Path(file),
bundle_version=bundle_version,
)
def mock_get_mtime(file: Path):
f = str(file)
m = re.match(pattern=r".*ss=(.+?)\.\w+", string=f)
if not m:
raise ValueError(f"unexpected: {file}")
match = m.group(1)
if match == "<class 'FileNotFoundError'>":
raise FileNotFoundError()
try:
return int(match)
except Exception:
raise ValueError(f"could not convert value {match} to int")
def encode_mtime_in_filename(val):
from pathlib import PurePath
out = []
for fname, mtime in val:
f = PurePath(PurePath(fname).name)
addition = f"ss={str(mtime)}"
out.append(f"{f.stem}-{addition}{f.suffix}")
return out
def _create_zip_bundle_with_valid_and_broken_dags(zip_path: Path) -> None:
with zipfile.ZipFile(zip_path, "w") as zf:
zf.writestr(
"valid_dag.py",
textwrap.dedent(
"""
from datetime import datetime
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.sdk import DAG
with DAG(
dag_id="zip_valid_dag",
start_date=datetime(2024, 1, 1),
schedule=None,
catchup=False,
):
EmptyOperator(task_id="task")
"""
),
)
zf.writestr(
"broken_dag.py",
textwrap.dedent(
"""
from airflow.sdk import DAG
raise RuntimeError("broken zip dag")
"""
),
)
class TestDagFileProcessorManager:
@pytest.fixture(autouse=True)
def _disable_examples(self):
with conf_vars({("core", "load_examples"): "False"}):
yield
def setup_method(self):
clear_db_teams()
clear_db_assets()
clear_db_runs()
clear_db_serialized_dags()
clear_db_dags()
clear_db_callbacks()
clear_db_import_errors()
clear_db_dag_bundles()
def teardown_class(self):
clear_db_teams()
clear_db_assets()
clear_db_runs()
clear_db_serialized_dags()
clear_db_dags()
clear_db_callbacks()
clear_db_import_errors()
clear_db_dag_bundles()
def mock_processor(self, start_time: float | None = None) -> tuple[DagFileProcessorProcess, socket]:
proc = MagicMock()
logger_filehandle = MagicMock()
proc.create_time.return_value = time.time()
proc.wait.return_value = 0
read_end, write_end = socketpair()
ret = DagFileProcessorProcess(
process_log=MagicMock(),
id=uuid7(),
pid=1234,
process=proc,
stdin=write_end,
logger_filehandle=logger_filehandle,
client=MagicMock(),
bundle_name="testing",
dag_file_rel_path="test_dag.py",
)
if start_time:
ret.start_time = start_time
ret._open_sockets.clear()
return ret, read_end
@pytest.fixture
def clear_parse_import_errors(self):
clear_db_import_errors()
@pytest.mark.usefixtures("clear_parse_import_errors")
@conf_vars({("core", "load_examples"): "False"})
def test_remove_file_clears_import_error(self, tmp_path, configure_testing_dag_bundle):
path_to_parse = tmp_path / "temp_dag.py"
# Generate original import error
path_to_parse.write_text("an invalid airflow DAG")
with configure_testing_dag_bundle(path_to_parse):
manager = DagFileProcessorManager(
max_runs=1,
processor_timeout=365 * 86_400,
)
manager.run()
with create_session() as session:
import_errors = session.scalars(select(ParseImportError)).all()
assert len(import_errors) == 1
path_to_parse.unlink()
# Rerun the parser once the dag file has been removed
manager.run()
with create_session() as session:
import_errors = session.scalars(select(ParseImportError)).all()
assert len(import_errors) == 0
session.rollback()
@pytest.mark.usefixtures("clear_parse_import_errors")
def test_clear_orphaned_import_errors_keeps_zip_inner_file_errors(self, session, tmp_path):
zip_path = tmp_path / "test_zip.zip"
_create_zip_bundle_with_valid_and_broken_dags(zip_path)
session.add(
ParseImportError(
filename="test_zip.zip/broken_dag.py",
bundle_name="testing",
timestamp=timezone.utcnow(),
stacktrace="zip import error",
)
)
session.flush()
manager = DagFileProcessorManager(max_runs=1)
manager.clear_orphaned_import_errors(
bundle_name="testing",
observed_filelocs=manager._get_observed_filelocs(
{
DagFileInfo(
bundle_name="testing",
rel_path=Path("test_zip.zip"),
bundle_path=tmp_path,
)
}
),
session=session,
)
session.flush()
import_errors = session.scalars(select(ParseImportError)).all()
assert len(import_errors) == 1
assert import_errors[0].filename == "test_zip.zip/broken_dag.py"
def test_get_observed_filelocs_expands_zip_inner_paths(self, tmp_path):
zip_path = tmp_path / "test_zip.zip"
_create_zip_bundle_with_valid_and_broken_dags(zip_path)
manager = DagFileProcessorManager(max_runs=1)
observed_filelocs = manager._get_observed_filelocs(
{
DagFileInfo(
bundle_name="testing",
rel_path=Path("test_zip.zip"),
bundle_path=tmp_path,
)
}
)
assert observed_filelocs == {
"test_zip.zip/valid_dag.py",
"test_zip.zip/broken_dag.py",
}
@pytest.mark.usefixtures("clear_parse_import_errors")
def test_refresh_dag_bundles_keeps_zip_inner_file_errors(self, session, tmp_path, configure_dag_bundles):
bundle_path = tmp_path / "bundleone"
bundle_path.mkdir()
zip_path = bundle_path / "test_zip.zip"
_create_zip_bundle_with_valid_and_broken_dags(zip_path)
session.add(
ParseImportError(
filename="test_zip.zip/broken_dag.py",
bundle_name="bundleone",
timestamp=timezone.utcnow(),
stacktrace="zip import error",
)
)
session.flush()
with configure_dag_bundles({"bundleone": bundle_path}):
DagBundlesManager().sync_bundles_to_db()
manager = DagFileProcessorManager(max_runs=1)
manager._dag_bundles = list(DagBundlesManager().get_all_dag_bundles())
manager._refresh_dag_bundles({})
import_errors = session.scalars(select(ParseImportError)).all()
assert len(import_errors) == 1
assert import_errors[0].filename == "test_zip.zip/broken_dag.py"
def test_refresh_dag_bundles_calls_legacy_deactivate_deleted_dags_override(
self, tmp_path, configure_dag_bundles
):
bundle_path = tmp_path / "bundleone"
bundle_path.mkdir()
dag_path = bundle_path / "test_dag.py"
dag_path.write_text("from airflow.sdk import DAG\n")
class BackwardCompatibleManager(DagFileProcessorManager):
seen_bundle_name: str | None = None
seen_present: set[DagFileInfo] | None = None
def deactivate_deleted_dags(self, bundle_name: str, present: set[DagFileInfo]) -> None:
self.seen_bundle_name = bundle_name
self.seen_present = present
with configure_dag_bundles({"bundleone": bundle_path}):
DagBundlesManager().sync_bundles_to_db()
manager = BackwardCompatibleManager(max_runs=1)
manager._dag_bundles = list(DagBundlesManager().get_all_dag_bundles())
manager._refresh_dag_bundles({})
assert manager.seen_bundle_name == "bundleone"
assert manager.seen_present == {
DagFileInfo(
bundle_name="bundleone",
rel_path=Path("test_dag.py"),
bundle_path=bundle_path,
)
}
@conf_vars({("core", "load_examples"): "False"})
def test_max_runs_when_no_files(self, tmp_path):
with conf_vars({("core", "dags_folder"): str(tmp_path)}):
manager = DagFileProcessorManager(max_runs=1)
manager.run()
# TODO: AIP-66 no asserts?
def test_start_new_processes_with_same_filepath(self, configure_testing_dag_bundle):
"""
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.
"""
with configure_testing_dag_bundle("/tmp"):
manager = DagFileProcessorManager(max_runs=1)
manager._dag_bundles = list(DagBundlesManager().get_all_dag_bundles())
file_1 = DagFileInfo(bundle_name="testing", rel_path=Path("file_1.py"), bundle_path=TEST_DAGS_FOLDER)
file_2 = DagFileInfo(bundle_name="testing", rel_path=Path("file_2.py"), bundle_path=TEST_DAGS_FOLDER)
file_3 = DagFileInfo(bundle_name="testing", rel_path=Path("file_3.py"), bundle_path=TEST_DAGS_FOLDER)
manager._file_queue = deque([file_1, file_2, file_3])
# Mock that only one processor exists. This processor runs with 'file_1'
manager._processors[file_1] = MagicMock()
# Start New Processes
with mock.patch.object(DagFileProcessorManager, "_create_process"):
manager._start_new_processes()
# Because of the config: '[dag_processor] 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._processors.keys()
assert file_2 in manager._processors.keys()
assert deque([file_3]) == manager._file_queue
def test_handle_removed_files_when_processor_file_path_not_in_new_file_paths(self):
"""Ensure processors and file stats are removed when the file path is not in the new file paths"""
manager = DagFileProcessorManager(max_runs=1)
bundle_name = "testing"
file = DagFileInfo(
bundle_name=bundle_name, rel_path=Path("missing_file.txt"), bundle_path=TEST_DAGS_FOLDER
)
manager._processors[file] = MagicMock()
manager._file_stats[file] = DagFileStat()
manager.handle_removed_files({bundle_name: set()})
assert manager._processors == {}
assert file not in manager._file_stats
def test_handle_removed_files_when_processor_file_path_is_present(self):
"""handle_removed_files should not purge files that are still present."""
manager = DagFileProcessorManager(max_runs=1)
bundle_name = "testing"
file = DagFileInfo(bundle_name=bundle_name, rel_path=Path("abc.txt"), bundle_path=TEST_DAGS_FOLDER)
mock_processor = MagicMock()
manager._processors[file] = mock_processor
manager.handle_removed_files(known_files={bundle_name: {file}})
assert manager._processors == {file: mock_processor}
def test_handle_removed_files_uses_public_extension_points(self):
manager = DagFileProcessorManager(max_runs=1)
bundle_name = "testing"
file = DagFileInfo(bundle_name=bundle_name, rel_path=Path("abc.txt"), bundle_path=TEST_DAGS_FOLDER)
with (
mock.patch.object(manager, "purge_removed_files_from_queue") as purge_queue,
mock.patch.object(manager, "terminate_orphan_processes") as terminate_processors,
mock.patch.object(manager, "remove_orphaned_file_stats") as remove_stats,
):
manager.handle_removed_files(known_files={bundle_name: {file}})
purge_queue.assert_called_once_with(present={file})
terminate_processors.assert_called_once_with(present={file})
remove_stats.assert_called_once_with(present={file})
def test_purge_removed_files_keeps_versioned_callback_file_when_unversioned_file_is_present(self):
manager = DagFileProcessorManager(max_runs=1)
versioned_file = _get_versioned_file_info("callbacks.py")
present_file = _get_file_infos(["callbacks.py"])[0]
manager._file_queue = deque([versioned_file])
manager.purge_removed_files_from_queue(present={present_file})
assert manager._file_queue == deque([versioned_file])
def test_purge_removed_files_drops_versioned_callback_file_when_truly_absent(self):
manager = DagFileProcessorManager(max_runs=1)
versioned_file = _get_versioned_file_info("callbacks.py")
manager._file_queue = deque([versioned_file])
manager.purge_removed_files_from_queue(present=set())
assert manager._file_queue == deque()
def test_terminate_orphan_processes_keeps_versioned_callback_processor_when_unversioned_file_is_present(
self,
):
manager = DagFileProcessorManager(max_runs=1)
versioned_file = _get_versioned_file_info("callbacks.py")
present_file = _get_file_infos(["callbacks.py"])[0]
processor = MagicMock()
manager._processors[versioned_file] = processor
manager.terminate_orphan_processes(present={present_file})
assert manager._processors == {versioned_file: processor}
processor.kill.assert_not_called()
def test_terminate_orphan_processes_kills_processor_when_file_is_truly_absent(self):
manager = DagFileProcessorManager(max_runs=1)
versioned_file = _get_versioned_file_info("callbacks.py")
processor = MagicMock()
manager._processors[versioned_file] = processor
manager.terminate_orphan_processes(present=set())
assert manager._processors == {}
processor.kill.assert_called_once_with(signal.SIGKILL)
def test_remove_orphaned_file_stats_keeps_versioned_callback_stats_when_unversioned_file_is_present(self):
manager = DagFileProcessorManager(max_runs=1)
versioned_file = _get_versioned_file_info("callbacks.py")
present_file = _get_file_infos(["callbacks.py"])[0]
manager._file_stats[versioned_file] = DagFileStat()
manager.remove_orphaned_file_stats(present={present_file})
assert manager._file_stats == {versioned_file: DagFileStat()}
def test_remove_orphaned_file_stats_drops_versioned_callback_stats_when_truly_absent(self):
manager = DagFileProcessorManager(max_runs=1)
versioned_file = _get_versioned_file_info("callbacks.py")
manager._file_stats[versioned_file] = DagFileStat()
manager.remove_orphaned_file_stats(present=set())
assert manager._file_stats == {}
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "alphabetical"})
def test_files_in_queue_sorted_alphabetically(self):
"""Test dag files are sorted alphabetically"""
file_names = ["file_3.py", "file_2.py", "file_4.py", "file_1.py"]
dag_files = _get_file_infos(file_names)
ordered_dag_files = _get_file_infos(sorted(file_names))
manager = DagFileProcessorManager(max_runs=1)
known_files = {"some-bundle": set(dag_files)}
assert manager._file_queue == deque()
manager.prepare_file_queue(known_files=known_files)
assert manager._file_queue == deque(ordered_dag_files)
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "random_seeded_by_host"})
def test_files_sorted_random_seeded_by_host(self):
"""Test files are randomly sorted and seeded by host name"""
f_infos = _get_file_infos(["file_3.py", "file_2.py", "file_4.py", "file_1.py"])
known_files = {"anything": f_infos}
manager = DagFileProcessorManager(max_runs=1)
assert manager._file_queue == deque()
manager.prepare_file_queue(known_files=known_files) # using list over test for reproducibility
random.Random(get_hostname()).shuffle(f_infos)
expected = deque(f_infos)
assert manager._file_queue == expected
# Verify running it again produces same order
manager._files = []
manager.prepare_file_queue(known_files=known_files)
assert manager._file_queue == expected
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("airflow.utils.file.os.path.getmtime", new=mock_get_mtime)
def test_files_sorted_by_modified_time(self):
"""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),
]
filenames = encode_mtime_in_filename(paths_with_mtime)
dag_files = _get_file_infos(filenames)
manager = DagFileProcessorManager(max_runs=1)
assert manager._file_queue == deque()
manager.prepare_file_queue(known_files={"any": set(dag_files)})
ordered_files = _get_file_infos(
[
"file_4-ss=5.0.py",
"file_1-ss=4.0.py",
"file_3-ss=3.0.py",
"file_2-ss=2.0.py",
]
)
assert manager._file_queue == deque(ordered_files)
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("airflow.utils.file.os.path.getmtime", new=mock_get_mtime)
def test_queued_files_exclude_missing_file(self):
"""Check that a file is not enqueued for processing if it has been deleted"""
file_and_mtime = [("file_3.py", 2.0), ("file_2.py", 3.0), ("file_4.py", FileNotFoundError)]
filenames = encode_mtime_in_filename(file_and_mtime)
file_infos = _get_file_infos(filenames)
manager = DagFileProcessorManager(max_runs=1)
manager.prepare_file_queue(known_files={"any": set(file_infos)})
ordered_files = _get_file_infos(["file_2-ss=3.0.py", "file_3-ss=2.0.py"])
assert manager._file_queue == deque(ordered_files)
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("airflow.utils.file.os.path.getmtime", new=mock_get_mtime)
def test_add_new_file_to_parsing_queue(self):
"""Check that new file is added to parsing queue"""
dag_files = _get_file_infos(["file_1-ss=2.0.py", "file_2-ss=3.0.py", "file_3-ss=4.0.py"])
from random import Random
Random("file_2.py").random()
manager = DagFileProcessorManager(max_runs=1)
manager.prepare_file_queue(known_files={"any": set(dag_files)})
assert set(manager._file_queue) == set(dag_files)
manager.prepare_file_queue(
known_files={"any": set((*dag_files, *_get_file_infos(["file_4-ss=1.0.py"])))}
)
# manager._add_new_files_to_queue()
ordered_files = _get_file_infos(
[
"file_3-ss=4.0.py",
"file_2-ss=3.0.py",
"file_1-ss=2.0.py",
"file_4-ss=1.0.py",
]
)
assert manager._file_queue == deque(ordered_files)
def test_add_new_files_to_queue_behavior(self):
"""
Check that _add_new_files_to_queue:
1. Adds new files to the front of the queue.
2. Skips files that are currently being processed.
3. Skips files that have already been processed (in _file_stats).
4. Does not re-add files already in the queue.
"""
manager = DagFileProcessorManager(max_runs=1)
file_1 = DagFileInfo(bundle_name="testing", rel_path=Path("file_1.py"), bundle_path=TEST_DAGS_FOLDER)
file_2 = DagFileInfo(bundle_name="testing", rel_path=Path("file_2.py"), bundle_path=TEST_DAGS_FOLDER)
file_3 = DagFileInfo(bundle_name="testing", rel_path=Path("file_3.py"), bundle_path=TEST_DAGS_FOLDER)
file_4 = DagFileInfo(bundle_name="testing", rel_path=Path("file_4.py"), bundle_path=TEST_DAGS_FOLDER)
# Setup:
# file_1 is already in the queue
manager._file_queue = deque([file_1])
# file_3 is currently being processed
manager._processors[file_3] = MagicMock()
# file_4 has already been processed
manager._file_stats[file_4] = DagFileStat(num_dags=1)
# known_files contains all four
known_files = {"testing": {file_1, file_2, file_3, file_4}}
manager._add_new_files_to_queue(known_files)
# file_4 should be ignored (in file_stats)
# file_3 should be ignored (processing)
# file_2 should be at the front (new)
# file_1 should remain (already in queue)
assert list(manager._file_queue) == [file_2, file_1]
def test_add_new_files_to_queue_skips_versioned_files_already_represented(self):
manager = DagFileProcessorManager(max_runs=1)
queued_versioned_file = _get_versioned_file_info("file_1.py")
processed_versioned_file = _get_versioned_file_info("file_3.py")
parsed_versioned_file = _get_versioned_file_info("file_4.py")
new_file = _get_file_infos(["file_2.py"])[0]
manager._file_queue = deque([queued_versioned_file])
manager._processors[processed_versioned_file] = MagicMock()
manager._file_stats[parsed_versioned_file] = DagFileStat(num_dags=1)
known_files = {
"testing": {
_get_file_infos(["file_1.py"])[0],
new_file,
_get_file_infos(["file_3.py"])[0],
_get_file_infos(["file_4.py"])[0],
}
}
manager._add_new_files_to_queue(known_files)
assert list(manager._file_queue) == [new_file, queued_versioned_file]
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("airflow.utils.file.os.path.getmtime", new=mock_get_mtime)
def test_resort_file_queue_by_mtime(self):
"""
Check that existing files in the queue are re-sorted by mtime when calling _resort_file_queue,
if sort mode is modified_time.
"""
# Prepare some files with mtimes
files_with_mtime = [
("file_1.py", 100.0),
("file_2.py", 200.0),
]
filenames = encode_mtime_in_filename(files_with_mtime)
dag_files = _get_file_infos(filenames)
# dag_files[0] -> file_1 (mtime 100)
# dag_files[1] -> file_2 (mtime 200)
manager = DagFileProcessorManager(max_runs=1)
# Populate queue with unsorted files
# Queue: [file_1 (100), file_2 (200)]
manager._file_queue = deque([dag_files[0], dag_files[1]])
manager._resort_file_queue()
# Verify resort happened: [file_2 (200), file_1 (100)]
assert list(manager._file_queue) == [dag_files[1], dag_files[0]]
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "alphabetical"})
def test_resort_file_queue_does_nothing_when_alphabetical(self):
"""
Check that _resort_file_queue does NOT change the order if sort mode is alphabetical.
"""
file_a = DagFileInfo(bundle_name="testing", rel_path=Path("a.py"), bundle_path=TEST_DAGS_FOLDER)
file_b = DagFileInfo(bundle_name="testing", rel_path=Path("b.py"), bundle_path=TEST_DAGS_FOLDER)
manager = DagFileProcessorManager(max_runs=1)
# Populate queue in non-alphabetical order
manager._file_queue = deque([file_b, file_a])
manager._resort_file_queue()
# Order should remain unchanged
assert list(manager._file_queue) == [file_b, file_a]
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("airflow.utils.file.os.path.getmtime", new=mock_get_mtime)
def test_resort_file_queue_keeps_callbacks_at_front(self):
"""
Check that files with pending callbacks stay at the front of the queue
regardless of their modification time, and preserve their relative order.
"""
files_with_mtime = [
("callback_1.py", 50.0), # has callback, oldest mtime
("callback_2.py", 300.0), # has callback, newest mtime
("regular_1.py", 100.0), # no callback
("regular_2.py", 200.0), # no callback
]
filenames = encode_mtime_in_filename(files_with_mtime)
dag_files = _get_file_infos(filenames)
# dag_files[0] -> callback_1 (mtime 50)
# dag_files[1] -> callback_2 (mtime 300)
# dag_files[2] -> regular_1 (mtime 100)
# dag_files[3] -> regular_2 (mtime 200)
manager = DagFileProcessorManager(max_runs=1)
# Queue order: callback_1, callback_2, regular_1, regular_2
manager._file_queue = deque([dag_files[0], dag_files[1], dag_files[2], dag_files[3]])
# Both callback files have pending callbacks
manager._callback_to_execute[dag_files[0]] = [MagicMock()]
manager._callback_to_execute[dag_files[1]] = [MagicMock()]
manager._resort_file_queue()
# Callback files should stay at front in original order (callback_1, callback_2)
# despite callback_1 having the oldest mtime and callback_2 having the newest
# Regular files should be sorted by mtime (newest first): regular_2 (200), regular_1 (100)
assert list(manager._file_queue) == [dag_files[0], dag_files[1], dag_files[3], dag_files[2]]
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("airflow.utils.file.os.path.getmtime")
def test_recently_modified_file_is_parsed_with_mtime_mode(self, mock_getmtime):
"""
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_file = DagFileInfo(
bundle_name="testing", rel_path=Path("file_1.py"), bundle_path=TEST_DAGS_FOLDER
)
known_files = {"does-not-matter": {dag_file}}
mock_getmtime.side_effect = [initial_file_1_mtime]
manager = DagFileProcessorManager(max_runs=3)
# let's say the DAG was just parsed 10 seconds before the Freezed time
last_finish_time = freezed_base_time - timedelta(seconds=10)
manager._file_stats = {
dag_file: DagFileStat(1, 0, last_finish_time, 1.0, 1, 1),
}
with time_machine.travel(freezed_base_time):
assert manager._file_queue == deque()
# File Path Queue will be empty as the "modified time" < "last finish time"
manager.prepare_file_queue(known_files=known_files)
assert manager._file_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):
assert manager._file_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.prepare_file_queue(known_files=known_files)
# Check that file is added to the queue even though file was just recently passed
assert manager._file_queue == deque([dag_file])
assert last_finish_time < file_1_new_mtime
assert (
manager._file_process_interval
> (freezed_base_time - manager._file_stats[dag_file].last_finish_time).total_seconds()
)
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "alphabetical"})
def test_prepare_file_queue_skips_file_when_versioned_processor_is_in_progress(self):
manager = DagFileProcessorManager(max_runs=1)
versioned_file = _get_versioned_file_info("file_1.py")
known_file = _get_file_infos(["file_1.py"])[0]
manager._processors[versioned_file] = MagicMock()
manager.prepare_file_queue(known_files={"testing": {known_file}})
assert manager._file_queue == deque()
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "alphabetical"})
def test_prepare_file_queue_skips_file_when_versioned_stat_is_at_run_limit(self):
manager = DagFileProcessorManager(max_runs=1)
versioned_file = _get_versioned_file_info("file_1.py")
known_file = _get_file_infos(["file_1.py"])[0]
manager._file_stats[versioned_file] = DagFileStat(run_count=1)
manager.prepare_file_queue(known_files={"testing": {known_file}})
assert manager._file_queue == deque()
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "alphabetical"})
def test_prepare_file_queue_skips_recently_processed_file_with_versioned_stats(self):
manager = DagFileProcessorManager(max_runs=3)
versioned_file = _get_versioned_file_info("file_1.py")
known_file = _get_file_infos(["file_1.py"])[0]
manager._file_stats[versioned_file] = DagFileStat(
last_finish_time=timezone.utcnow() - timedelta(seconds=10),
run_count=1,
)
manager.prepare_file_queue(known_files={"testing": {known_file}})
assert manager._file_queue == deque()
@conf_vars({("dag_processor", "file_parsing_sort_mode"): "modified_time"})
@mock.patch("airflow.utils.file.os.path.getmtime")
def test_recently_modified_file_uses_versioned_stats_without_creating_duplicate_entries(
self, mock_getmtime
):
freezed_base_time = timezone.datetime(2020, 1, 5, 0, 0, 0)
versioned_file = _get_versioned_file_info("file_1.py")
known_file = _get_file_infos(["file_1.py"])[0]
known_files = {"testing": {known_file}}
last_finish_time = freezed_base_time - timedelta(seconds=10)
manager = DagFileProcessorManager(max_runs=3)
manager._file_stats = {
versioned_file: DagFileStat(1, 0, last_finish_time, 1.0, 1, 1),
}
with time_machine.travel(freezed_base_time):
mock_getmtime.side_effect = [(freezed_base_time - timedelta(seconds=5)).timestamp()]
manager.prepare_file_queue(known_files=known_files)
assert manager._file_queue == deque([known_file])
assert known_file not in manager._file_stats
assert versioned_file in manager._file_stats
def test_file_paths_in_queue_sorted_by_priority(self):
from airflow.models.dagbag import DagPriorityParsingRequest
parsing_request = DagPriorityParsingRequest(relative_fileloc="file_1.py", bundle_name="dags-folder")
with create_session() as session:
session.add(parsing_request)
session.commit()
file1 = DagFileInfo(
bundle_name="dags-folder", rel_path=Path("file_1.py"), bundle_path=TEST_DAGS_FOLDER
)
file2 = DagFileInfo(
bundle_name="dags-folder", rel_path=Path("file_2.py"), bundle_path=TEST_DAGS_FOLDER
)
manager = DagFileProcessorManager(max_runs=1)
manager._dag_bundles = list(DagBundlesManager().get_all_dag_bundles())
manager._file_queue = deque([file2, file1])
manager._queue_requested_files_for_parsing()
assert manager._file_queue == deque([file1, file2])
assert manager._force_refresh_bundles == {"dags-folder"}
with create_session() as session2:
parsing_request_after = session2.get(DagPriorityParsingRequest, parsing_request.id)
assert parsing_request_after is None
def test_parsing_requests_only_bundles_being_parsed(self, testing_dag_bundle):
"""Ensure the manager only handles parsing requests for bundles being parsed in this manager"""
from airflow.models.dagbag import DagPriorityParsingRequest
with create_session() as session:
session.add(DagPriorityParsingRequest(relative_fileloc="file_1.py", bundle_name="dags-folder"))
session.add(DagPriorityParsingRequest(relative_fileloc="file_x.py", bundle_name="testing"))
session.commit()
file1 = DagFileInfo(
bundle_name="dags-folder", rel_path=Path("file_1.py"), bundle_path=TEST_DAGS_FOLDER
)
manager = DagFileProcessorManager(max_runs=1)
manager._dag_bundles = list(DagBundlesManager().get_all_dag_bundles())
manager._queue_requested_files_for_parsing()
assert manager._file_queue == deque([file1])
with create_session() as session2:
parsing_request_after = session2.scalars(select(DagPriorityParsingRequest)).all()
assert len(parsing_request_after) == 1
assert parsing_request_after[0].relative_fileloc == "file_x.py"
def test_queue_requested_files_for_parsing_uses_public_claim_hook(self):
file1 = DagFileInfo(
bundle_name="dags-folder", rel_path=Path("file_1.py"), bundle_path=TEST_DAGS_FOLDER
)
file2 = DagFileInfo(
bundle_name="dags-folder", rel_path=Path("file_2.py"), bundle_path=TEST_DAGS_FOLDER
)
class ApiBackedManager(DagFileProcessorManager):
def claim_priority_files(self) -> list[DagFileInfo]:
return [file1]
manager = ApiBackedManager(max_runs=1)
manager._file_queue = deque([file2])
manager._queue_requested_files_for_parsing()
assert manager._file_queue == deque([file1, file2])
assert manager._force_refresh_bundles == {"dags-folder"}
def test_request_bundle_refresh_marks_bundles_for_refresh(self):
"""`request_bundle_refresh` adds the bundles to the force-refresh set."""
manager = DagFileProcessorManager(max_runs=1)
assert manager._force_refresh_bundles == set()
manager.request_bundle_refresh(["bundleone", "bundletwo"])
manager.request_bundle_refresh(["bundleone"]) # idempotent
assert manager._force_refresh_bundles == {"bundleone", "bundletwo"}
def test_request_bundle_refresh_accepts_single_bundle_name(self):
"""`request_bundle_refresh` treats a string as one bundle name, not an iterable."""
manager = DagFileProcessorManager(max_runs=1)
manager.request_bundle_refresh("bundleone")
assert manager._force_refresh_bundles == {"bundleone"}
@pytest.mark.usefixtures("testing_dag_bundle")
def test_scan_stale_dags(self, session):
"""
Ensure that DAGs are marked inactive when the file is parsed but the
DagModel.last_parsed_time is not updated.
"""
manager = DagFileProcessorManager(
max_runs=1,
processor_timeout=10 * 60,
)
bundle = MagicMock()
bundle.name = "testing"
manager._dag_bundles = [bundle]
test_dag_path = DagFileInfo(
bundle_name="testing",
rel_path=Path("test_example_bash_operator.py"),
bundle_path=TEST_DAGS_FOLDER,
)
dagbag = DagBag(
test_dag_path.absolute_path,
include_examples=False,
bundle_path=test_dag_path.bundle_path,
)
# Add stale DAG to the DB
dag = dagbag.get_dag("test_example_bash_operator")
sync_dag_to_db(dag, session=session)
# 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,
last_num_of_db_queries=1,
)
manager._files = [test_dag_path]
manager._file_stats[test_dag_path] = stat
active_dag_count = session.scalar(
select(func.count(DagModel.dag_id)).where(
~DagModel.is_stale,
DagModel.relative_fileloc == str(test_dag_path.rel_path),
DagModel.bundle_name == test_dag_path.bundle_name,
)
)
assert active_dag_count == 1
manager._scan_stale_dags()
active_dag_count = session.scalar(
select(func.count(DagModel.dag_id)).where(
~DagModel.is_stale,
DagModel.relative_fileloc == str(test_dag_path.rel_path),
DagModel.bundle_name == test_dag_path.bundle_name,
)
)
assert active_dag_count == 0
serialized_dag_count = session.scalar(
select(func.count(SerializedDagModel.dag_id)).where(SerializedDagModel.dag_id == dag.dag_id)
)
# Deactivating the DagModel should not delete the SerializedDagModel
# SerializedDagModel gives history about Dags