-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
test_kubernetes_executor.py
1384 lines (1215 loc) · 59.3 KB
/
test_kubernetes_executor.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 pathlib
import random
import re
import string
import sys
from datetime import datetime, timedelta
from unittest import mock
import pytest
import yaml
from kubernetes.client import models as k8s
from kubernetes.client.rest import ApiException
from urllib3 import HTTPResponse
from airflow import AirflowException
from airflow.exceptions import PodReconciliationError
from airflow.models.taskinstancekey import TaskInstanceKey
from airflow.operators.bash import BashOperator
from airflow.operators.empty import EmptyOperator
from airflow.utils import timezone
from airflow.utils.state import State, TaskInstanceState
from tests.test_utils.config import conf_vars
try:
from airflow.executors.kubernetes_executor import KubernetesExecutor
from airflow.executors.kubernetes_executor_types import POD_EXECUTOR_DONE_KEY
from airflow.executors.kubernetes_executor_utils import (
AirflowKubernetesScheduler,
KubernetesJobWatcher,
ResourceVersion,
create_pod_id,
get_base_pod_from_template,
)
from airflow.kubernetes import pod_generator
from airflow.kubernetes.kubernetes_helper_functions import (
annotations_for_logging_task_metadata,
annotations_to_key,
get_logs_task_metadata,
)
from airflow.kubernetes.pod_generator import PodGenerator
except ImportError:
AirflowKubernetesScheduler = None # type: ignore
class TestAirflowKubernetesScheduler:
@staticmethod
def _gen_random_string(seed, str_len):
char_list = []
for char_seed in range(str_len):
random.seed(str(seed) * char_seed)
char_list.append(random.choice(string.printable))
return "".join(char_list)
def _cases(self):
cases = [
("my_dag_id", "my-task-id"),
("my.dag.id", "my.task.id"),
("MYDAGID", "MYTASKID"),
("my_dag_id", "my_task_id"),
("mydagid" * 200, "my_task_id" * 200),
("my_dág_id", "my_tásk_id"),
("Компьютер", "niedołężność"),
("影師嗎", "中華民國;$"),
]
cases.extend(
[(self._gen_random_string(seed, 200), self._gen_random_string(seed, 200)) for seed in range(100)]
)
return cases
@staticmethod
def _is_valid_pod_id(name):
regex = r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$"
return len(name) <= 253 and all(ch.lower() == ch for ch in name) and re.match(regex, name)
@staticmethod
def _is_safe_label_value(value):
regex = r"^[^a-z0-9A-Z]*|[^a-zA-Z0-9_\-\.]|[^a-z0-9A-Z]*$"
return len(value) <= 63 and re.match(regex, value)
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
def test_create_pod_id(self):
for dag_id, task_id in self._cases():
pod_name = PodGenerator.make_unique_pod_id(create_pod_id(dag_id, task_id))
assert self._is_valid_pod_id(pod_name)
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
@mock.patch("airflow.kubernetes.pod_generator.PodGenerator")
@mock.patch("airflow.executors.kubernetes_executor.KubeConfig")
def test_get_base_pod_from_template(self, mock_kubeconfig, mock_generator):
# Provide non-existent file path,
# so None will be passed to deserialize_model_dict().
pod_template_file_path = "/bar/biz"
get_base_pod_from_template(pod_template_file_path, None)
assert "deserialize_model_dict" == mock_generator.mock_calls[0][0]
assert mock_generator.mock_calls[0][1][0] is None
mock_kubeconfig.pod_template_file = "/foo/bar"
get_base_pod_from_template(None, mock_kubeconfig)
assert "deserialize_model_dict" == mock_generator.mock_calls[1][0]
assert mock_generator.mock_calls[1][1][0] is None
# Provide existent file path,
# so loaded YAML file content should be used to call deserialize_model_dict(), rather than None.
path = sys.path[0] + "/tests/kubernetes/pod.yaml"
with open(path) as stream:
expected_pod_dict = yaml.safe_load(stream)
pod_template_file_path = path
get_base_pod_from_template(pod_template_file_path, None)
assert "deserialize_model_dict" == mock_generator.mock_calls[2][0]
assert mock_generator.mock_calls[2][1][0] == expected_pod_dict
mock_kubeconfig.pod_template_file = path
get_base_pod_from_template(None, mock_kubeconfig)
assert "deserialize_model_dict" == mock_generator.mock_calls[3][0]
assert mock_generator.mock_calls[3][1][0] == expected_pod_dict
def test_make_safe_label_value(self):
for dag_id, task_id in self._cases():
safe_dag_id = pod_generator.make_safe_label_value(dag_id)
assert self._is_safe_label_value(safe_dag_id)
safe_task_id = pod_generator.make_safe_label_value(task_id)
assert self._is_safe_label_value(safe_task_id)
dag_id = "my_dag_id"
assert dag_id == pod_generator.make_safe_label_value(dag_id)
dag_id = "my_dag_id_" + "a" * 64
assert "my_dag_id_" + "a" * 43 + "-0ce114c45" == pod_generator.make_safe_label_value(dag_id)
def test_execution_date_serialize_deserialize(self):
datetime_obj = datetime.now()
serialized_datetime = pod_generator.datetime_to_label_safe_datestring(datetime_obj)
new_datetime_obj = pod_generator.label_safe_datestring_to_datetime(serialized_datetime)
assert datetime_obj == new_datetime_obj
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.client")
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
def test_delete_pod_successfully(self, mock_watcher, mock_client, mock_kube_client):
pod_name = "my-pod-1"
namespace = "my-namespace-1"
mock_delete_namespace = mock.MagicMock()
mock_kube_client.return_value.delete_namespaced_pod = mock_delete_namespace
kube_executor = KubernetesExecutor()
kube_executor.job_id = 1
kube_executor.start()
try:
kube_executor.kube_scheduler.delete_pod(pod_name, namespace)
mock_delete_namespace.assert_called_with(pod_name, namespace, body=mock_client.V1DeleteOptions())
finally:
kube_executor.end()
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.client")
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
def test_delete_pod_raises_404(self, mock_watcher, mock_client, mock_kube_client):
pod_name = "my-pod-1"
namespace = "my-namespace-2"
mock_delete_namespace = mock.MagicMock()
mock_kube_client.return_value.delete_namespaced_pod = mock_delete_namespace
# ApiException is raised because status is not 404
mock_kube_client.return_value.delete_namespaced_pod.side_effect = ApiException(status=400)
kube_executor = KubernetesExecutor()
kube_executor.job_id = 1
kube_executor.start()
with pytest.raises(ApiException):
kube_executor.kube_scheduler.delete_pod(pod_name, namespace)
mock_delete_namespace.assert_called_with(pod_name, namespace, body=mock_client.V1DeleteOptions())
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.client")
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
def test_delete_pod_404_not_raised(self, mock_watcher, mock_client, mock_kube_client):
pod_name = "my-pod-1"
namespace = "my-namespace-3"
mock_delete_namespace = mock.MagicMock()
mock_kube_client.return_value.delete_namespaced_pod = mock_delete_namespace
# ApiException not raised because the status is 404
mock_kube_client.return_value.delete_namespaced_pod.side_effect = ApiException(status=404)
kube_executor = KubernetesExecutor()
kube_executor.job_id = 1
kube_executor.start()
try:
kube_executor.kube_scheduler.delete_pod(pod_name, namespace)
mock_delete_namespace.assert_called_with(pod_name, namespace, body=mock_client.V1DeleteOptions())
finally:
kube_executor.end()
class TestKubernetesExecutor:
"""
Tests if an ApiException from the Kube Client will cause the task to
be rescheduled.
"""
def setup_method(self) -> None:
self.kubernetes_executor = KubernetesExecutor()
self.kubernetes_executor.job_id = 5
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
@pytest.mark.parametrize(
"status, should_requeue",
[
pytest.param(403, True, id="403 Forbidden"),
pytest.param(12345, True, id="12345 fake-unhandled-reason"),
pytest.param(422, False, id="422 Unprocessable Entity"),
pytest.param(400, False, id="400 BadRequest"),
],
)
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_run_next_exception_requeue(
self, mock_get_kube_client, mock_kubernetes_job_watcher, status, should_requeue
):
"""
When pod scheduling fails with either reason 'Forbidden', or any reason not yet
handled in the relevant try-except block, the task should stay in the ``task_queue``
and be attempted on a subsequent executor sync. When reason is 'Unprocessable Entity'
or 'BadRequest', the task should be failed without being re-queued.
Note on error scenarios:
- 403 Forbidden will be returned when your request exceeds namespace quota.
- 422 Unprocessable Entity is returned when your parameters are valid but unsupported
e.g. limits lower than requests.
- 400 BadRequest is returned when your parameters are invalid e.g. asking for cpu=100ABC123.
"""
path = sys.path[0] + "/tests/kubernetes/pod_generator_base_with_secrets.yaml"
response = HTTPResponse(body='{"message": "any message"}', status=status)
# A mock kube_client that throws errors when making a pod
mock_kube_client = mock.patch("kubernetes.client.CoreV1Api", autospec=True)
mock_kube_client.create_namespaced_pod = mock.MagicMock(side_effect=ApiException(http_resp=response))
mock_get_kube_client.return_value = mock_kube_client
mock_api_client = mock.MagicMock()
mock_api_client.sanitize_for_serialization.return_value = {}
mock_kube_client.api_client = mock_api_client
config = {
("kubernetes", "pod_template_file"): path,
}
with conf_vars(config):
kubernetes_executor = self.kubernetes_executor
kubernetes_executor.start()
try:
# Execute a task while the Api Throws errors
try_number = 1
task_instance_key = TaskInstanceKey("dag", "task", "run_id", try_number)
kubernetes_executor.execute_async(
key=task_instance_key,
queue=None,
command=["airflow", "tasks", "run", "true", "some_parameter"],
)
kubernetes_executor.sync()
assert mock_kube_client.create_namespaced_pod.call_count == 1
if should_requeue:
assert not kubernetes_executor.task_queue.empty()
# Disable the ApiException
mock_kube_client.create_namespaced_pod.side_effect = None
# Execute the task without errors should empty the queue
mock_kube_client.create_namespaced_pod.reset_mock()
kubernetes_executor.sync()
assert mock_kube_client.create_namespaced_pod.called
assert kubernetes_executor.task_queue.empty()
else:
assert kubernetes_executor.task_queue.empty()
assert kubernetes_executor.event_buffer[task_instance_key][0] == State.FAILED
finally:
kubernetes_executor.end()
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
@mock.patch("airflow.settings.pod_mutation_hook")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_run_next_pmh_error(self, mock_get_kube_client, mock_pmh):
"""
Exception during Pod Mutation Hook execution should be handled gracefully.
"""
exception_in_pmh = Exception("Purposely generate error for test")
mock_pmh.side_effect = exception_in_pmh
mock_kube_client = mock.patch("kubernetes.client.CoreV1Api", autospec=True)
mock_kube_client.create_namespaced_pod = mock.MagicMock()
mock_get_kube_client.return_value = mock_kube_client
kubernetes_executor = self.kubernetes_executor
kubernetes_executor.start()
try:
try_number = 1
task_instance_key = TaskInstanceKey("dag", "task", "run_id", try_number)
kubernetes_executor.execute_async(
key=task_instance_key,
queue=None,
command=["airflow", "tasks", "run", "true", "some_parameter"],
)
kubernetes_executor.sync()
# The pod_mutation_hook should have been called once.
assert mock_pmh.call_count == 1
# There should be no pod creation request sent
assert mock_kube_client.create_namespaced_pod.call_count == 0
# The task is not re-queued and there is the failed record in event_buffer
assert kubernetes_executor.task_queue.empty()
assert kubernetes_executor.event_buffer[task_instance_key][0] == State.FAILED
assert kubernetes_executor.event_buffer[task_instance_key][1].__cause__ == exception_in_pmh
finally:
kubernetes_executor.end()
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_run_next_pod_reconciliation_error(self, mock_get_kube_client, mock_kubernetes_job_watcher):
"""
When construct_pod raises PodReconciliationError, we should fail the task.
"""
path = sys.path[0] + "/tests/kubernetes/pod_generator_base_with_secrets.yaml"
mock_kube_client = mock.patch("kubernetes.client.CoreV1Api", autospec=True)
fail_msg = "test message"
mock_kube_client.create_namespaced_pod = mock.MagicMock(side_effect=PodReconciliationError(fail_msg))
mock_get_kube_client.return_value = mock_kube_client
mock_api_client = mock.MagicMock()
mock_api_client.sanitize_for_serialization.return_value = {}
mock_kube_client.api_client = mock_api_client
config = {("kubernetes", "pod_template_file"): path}
with conf_vars(config):
kubernetes_executor = self.kubernetes_executor
kubernetes_executor.start()
try:
# Execute a task while the Api Throws errors
try_number = 1
task_instance_key = TaskInstanceKey("dag", "task", "run_id", try_number)
kubernetes_executor.execute_async(
key=task_instance_key,
queue=None,
command=["airflow", "tasks", "run", "true", "some_parameter"],
)
kubernetes_executor.sync()
assert kubernetes_executor.task_queue.empty()
assert kubernetes_executor.event_buffer[task_instance_key][0] == State.FAILED
assert kubernetes_executor.event_buffer[task_instance_key][1].args[0] == fail_msg
finally:
kubernetes_executor.end()
@mock.patch("airflow.executors.kubernetes_executor.KubeConfig")
@mock.patch("airflow.executors.kubernetes_executor.KubernetesExecutor.sync")
@mock.patch("airflow.executors.base_executor.BaseExecutor.trigger_tasks")
@mock.patch("airflow.executors.base_executor.Stats.gauge")
def test_gauge_executor_metrics(self, mock_stats_gauge, mock_trigger_tasks, mock_sync, mock_kube_config):
executor = self.kubernetes_executor
executor.heartbeat()
calls = [
mock.call(
"executor.open_slots", value=mock.ANY, tags={"status": "open", "name": "KubernetesExecutor"}
),
mock.call(
"executor.queued_tasks",
value=mock.ANY,
tags={"status": "queued", "name": "KubernetesExecutor"},
),
mock.call(
"executor.running_tasks",
value=mock.ANY,
tags={"status": "running", "name": "KubernetesExecutor"},
),
]
mock_stats_gauge.assert_has_calls(calls)
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_invalid_executor_config(self, mock_get_kube_client, mock_kubernetes_job_watcher):
executor = self.kubernetes_executor
executor.start()
try:
assert executor.event_buffer == {}
executor.execute_async(
key=("dag", "task", datetime.utcnow(), 1),
queue=None,
command=["airflow", "tasks", "run", "true", "some_parameter"],
executor_config=k8s.V1Pod(
spec=k8s.V1PodSpec(
containers=[k8s.V1Container(name="base", image="myimage", image_pull_policy="Always")]
)
),
)
assert list(executor.event_buffer.values())[0][1] == "Invalid executor_config passed"
finally:
executor.end()
@pytest.mark.execution_timeout(10)
@pytest.mark.skipif(
AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed"
)
@mock.patch("airflow.executors.kubernetes_executor_utils.AirflowKubernetesScheduler.run_pod_async")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_pod_template_file_override_in_executor_config(self, mock_get_kube_client, mock_run_pod_async):
current_folder = pathlib.Path(__file__).parent.resolve()
template_file = str(
(current_folder / "kubernetes_executor_template_files" / "basic_template.yaml").resolve()
)
mock_kube_client = mock.patch("kubernetes.client.CoreV1Api", autospec=True)
mock_get_kube_client.return_value = mock_kube_client
with conf_vars({("kubernetes", "pod_template_file"): ""}):
executor = self.kubernetes_executor
executor.start()
try:
assert executor.event_buffer == {}
assert executor.task_queue.empty()
executor.execute_async(
key=TaskInstanceKey("dag", "task", "run_id", 1),
queue=None,
command=["airflow", "tasks", "run", "true", "some_parameter"],
executor_config={
"pod_template_file": template_file,
"pod_override": k8s.V1Pod(
metadata=k8s.V1ObjectMeta(labels={"release": "stable"}),
spec=k8s.V1PodSpec(
containers=[k8s.V1Container(name="base", image="airflow:3.6")],
),
),
},
)
assert not executor.task_queue.empty()
task = executor.task_queue.get_nowait()
_, _, expected_executor_config, expected_pod_template_file = task
executor.task_queue.task_done()
# Test that the correct values have been put to queue
assert expected_executor_config.metadata.labels == {"release": "stable"}
assert expected_pod_template_file == template_file
self.kubernetes_executor.kube_scheduler.run_next(task)
mock_run_pod_async.assert_called_once_with(
k8s.V1Pod(
api_version="v1",
kind="Pod",
metadata=k8s.V1ObjectMeta(
name=mock.ANY,
namespace="default",
annotations={
"dag_id": "dag",
"run_id": "run_id",
"task_id": "task",
"try_number": "1",
},
labels={
"airflow-worker": "5",
"airflow_version": mock.ANY,
"dag_id": "dag",
"run_id": "run_id",
"kubernetes_executor": "True",
"mylabel": "foo",
"release": "stable",
"task_id": "task",
"try_number": "1",
},
),
spec=k8s.V1PodSpec(
containers=[
k8s.V1Container(
name="base",
image="airflow:3.6",
args=["airflow", "tasks", "run", "true", "some_parameter"],
env=[k8s.V1EnvVar(name="AIRFLOW_IS_K8S_EXECUTOR_POD", value="True")],
)
],
image_pull_secrets=[k8s.V1LocalObjectReference(name="airflow-registry")],
scheduler_name="default-scheduler",
security_context=k8s.V1PodSecurityContext(fs_group=50000, run_as_user=50000),
),
)
)
finally:
executor.end()
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_change_state_running(self, mock_get_kube_client, mock_kubernetes_job_watcher):
executor = self.kubernetes_executor
executor.start()
try:
key = ("dag_id", "task_id", "run_id", "try_number1")
executor.running = {key}
executor._change_state(key, State.RUNNING, "pod_name", "default")
assert executor.event_buffer[key][0] == State.RUNNING
assert executor.running == {key}
finally:
executor.end()
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.AirflowKubernetesScheduler.delete_pod")
def test_change_state_success(self, mock_delete_pod, mock_get_kube_client, mock_kubernetes_job_watcher):
executor = self.kubernetes_executor
executor.start()
try:
key = ("dag_id", "task_id", "run_id", "try_number2")
executor.running = {key}
executor._change_state(key, State.SUCCESS, "pod_name", "default")
assert executor.event_buffer[key][0] == State.SUCCESS
assert executor.running == set()
mock_delete_pod.assert_called_once_with(pod_name="pod_name", namespace="default")
finally:
executor.end()
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.AirflowKubernetesScheduler")
def test_change_state_failed_no_deletion(
self, mock_kubescheduler, mock_get_kube_client, mock_kubernetes_job_watcher
):
mock_delete_pod = mock_kubescheduler.return_value.delete_pod
mock_patch_pod = mock_kubescheduler.return_value.patch_pod_executor_done
executor = self.kubernetes_executor
executor.kube_config.delete_worker_pods = False
executor.kube_config.delete_worker_pods_on_failure = False
executor.start()
try:
key = ("dag_id", "task_id", "run_id", "try_number3")
executor.running = {key}
executor._change_state(key, State.FAILED, "pod_id", "test-namespace")
assert executor.event_buffer[key][0] == State.FAILED
assert executor.running == set()
mock_delete_pod.assert_not_called()
mock_patch_pod.assert_called_once_with(pod_name="pod_id", namespace="test-namespace")
finally:
executor.end()
@pytest.mark.parametrize(
"ti_state", [TaskInstanceState.SUCCESS, TaskInstanceState.FAILED, TaskInstanceState.DEFERRED]
)
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.AirflowKubernetesScheduler.delete_pod")
def test_change_state_none(
self,
mock_delete_pod,
mock_get_kube_client,
mock_kubernetes_job_watcher,
ti_state,
create_task_instance,
):
"""Ensure that when change_state gets state=None, it looks up the TI state from the db"""
executor = self.kubernetes_executor
executor.start()
try:
ti = create_task_instance(state=ti_state)
key = ti.key
executor.running = {key}
executor._change_state(key, None, "pod_name", "default")
assert executor.event_buffer[key][0] == ti_state
assert executor.running == set()
mock_delete_pod.assert_called_once_with(pod_name="pod_name", namespace="default")
finally:
executor.end()
@pytest.mark.parametrize(
"multi_namespace_mode_namespace_list, watchers_keys",
[
pytest.param(["A", "B", "C"], ["A", "B", "C"]),
pytest.param(None, ["ALL_NAMESPACES"]),
],
)
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_watchers_under_multi_namespace_mode(
self, mock_get_kube_client, multi_namespace_mode_namespace_list, watchers_keys
):
executor = self.kubernetes_executor
executor.kube_config.multi_namespace_mode = True
executor.kube_config.multi_namespace_mode_namespace_list = multi_namespace_mode_namespace_list
executor.start()
try:
assert list(executor.kube_scheduler.kube_watchers.keys()) == watchers_keys
assert all(
isinstance(v, KubernetesJobWatcher) for v in executor.kube_scheduler.kube_watchers.values()
)
finally:
executor.end()
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.AirflowKubernetesScheduler")
def test_change_state_skip_pod_deletion(
self, mock_kubescheduler, mock_get_kube_client, mock_kubernetes_job_watcher
):
mock_delete_pod = mock_kubescheduler.return_value.delete_pod
mock_patch_pod = mock_kubescheduler.return_value.patch_pod_executor_done
executor = self.kubernetes_executor
executor.kube_config.delete_worker_pods = False
executor.kube_config.delete_worker_pods_on_failure = False
executor.start()
try:
key = ("dag_id", "task_id", "run_id", "try_number2")
executor.running = {key}
executor._change_state(key, State.SUCCESS, "pod_name", "test-namespace")
assert executor.event_buffer[key][0] == State.SUCCESS
assert executor.running == set()
mock_delete_pod.assert_not_called()
mock_patch_pod.assert_called_once_with(pod_name="pod_name", namespace="test-namespace")
finally:
executor.end()
@mock.patch("airflow.executors.kubernetes_executor_utils.KubernetesJobWatcher")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.AirflowKubernetesScheduler")
def test_change_state_failed_pod_deletion(
self, mock_kubescheduler, mock_get_kube_client, mock_kubernetes_job_watcher
):
mock_delete_pod = mock_kubescheduler.return_value.delete_pod
mock_patch_pod = mock_kubescheduler.return_value.patch_pod_executor_done
executor = self.kubernetes_executor
executor.kube_config.delete_worker_pods_on_failure = True
executor.start()
try:
key = ("dag_id", "task_id", "run_id", "try_number2")
executor.running = {key}
executor._change_state(key, State.FAILED, "pod_name", "test-namespace")
assert executor.event_buffer[key][0] == State.FAILED
assert executor.running == set()
mock_delete_pod.assert_called_once_with(pod_name="pod_name", namespace="test-namespace")
mock_patch_pod.assert_not_called()
finally:
executor.end()
@mock.patch("airflow.executors.kubernetes_executor.KubernetesExecutor.adopt_launched_task")
@mock.patch("airflow.executors.kubernetes_executor.KubernetesExecutor._adopt_completed_pods")
def test_try_adopt_task_instances(self, mock_adopt_completed_pods, mock_adopt_launched_task):
executor = self.kubernetes_executor
executor.scheduler_job_id = "10"
ti_key = annotations_to_key(
{
"dag_id": "dag",
"run_id": "run_id",
"task_id": "task",
"try_number": "1",
}
)
mock_ti = mock.MagicMock(queued_by_job_id="1", external_executor_id="1", key=ti_key)
pod = k8s.V1Pod(metadata=k8s.V1ObjectMeta(name="foo"))
mock_kube_client = mock.MagicMock()
mock_kube_client.list_namespaced_pod.return_value.items = [pod]
executor.kube_client = mock_kube_client
# First adoption
reset_tis = executor.try_adopt_task_instances([mock_ti])
mock_kube_client.list_namespaced_pod.assert_called_once_with(
namespace="default",
field_selector="status.phase!=Succeeded",
label_selector="kubernetes_executor=True,airflow-worker=1,airflow_executor_done!=True",
)
mock_adopt_launched_task.assert_called_once_with(mock_kube_client, pod, {ti_key: mock_ti})
mock_adopt_completed_pods.assert_called_once()
assert reset_tis == [mock_ti] # assume failure adopting when checking return
# Second adoption (queued_by_job_id and external_executor_id no longer match)
mock_kube_client.reset_mock()
mock_adopt_launched_task.reset_mock()
mock_adopt_completed_pods.reset_mock()
mock_ti.queued_by_job_id = "10" # scheduler_job would have updated this after the first adoption
executor.scheduler_job_id = "20"
# assume success adopting, `adopt_launched_task` pops `ti_key` from `tis_to_flush_by_key`
mock_adopt_launched_task.side_effect = (
lambda client, pod, tis_to_flush_by_key: tis_to_flush_by_key.pop(ti_key)
)
reset_tis = executor.try_adopt_task_instances([mock_ti])
mock_kube_client.list_namespaced_pod.assert_called_once_with(
namespace="default",
field_selector="status.phase!=Succeeded",
label_selector="kubernetes_executor=True,airflow-worker=10,airflow_executor_done!=True",
)
mock_adopt_launched_task.assert_called_once() # Won't check args this time around as they get mutated
mock_adopt_completed_pods.assert_called_once()
assert reset_tis == [] # This time our return is empty - no TIs to reset
@mock.patch("airflow.executors.kubernetes_executor.KubernetesExecutor._adopt_completed_pods")
def test_try_adopt_task_instances_multiple_scheduler_ids(self, mock_adopt_completed_pods):
"""We try to find pods only once per scheduler id"""
executor = self.kubernetes_executor
mock_kube_client = mock.MagicMock()
executor.kube_client = mock_kube_client
mock_tis = [
mock.MagicMock(queued_by_job_id="10", external_executor_id="1", dag_id="dag", task_id="task"),
mock.MagicMock(queued_by_job_id="40", external_executor_id="1", dag_id="dag", task_id="task2"),
mock.MagicMock(queued_by_job_id="40", external_executor_id="1", dag_id="dag", task_id="task3"),
]
executor.try_adopt_task_instances(mock_tis)
assert mock_kube_client.list_namespaced_pod.call_count == 2
mock_kube_client.list_namespaced_pod.assert_has_calls(
[
mock.call(
namespace="default",
field_selector="status.phase!=Succeeded",
label_selector="kubernetes_executor=True,airflow-worker=10,airflow_executor_done!=True",
),
mock.call(
namespace="default",
field_selector="status.phase!=Succeeded",
label_selector="kubernetes_executor=True,airflow-worker=40,airflow_executor_done!=True",
),
],
any_order=True,
)
@mock.patch("airflow.executors.kubernetes_executor.KubernetesExecutor.adopt_launched_task")
@mock.patch("airflow.executors.kubernetes_executor.KubernetesExecutor._adopt_completed_pods")
def test_try_adopt_task_instances_no_matching_pods(
self, mock_adopt_completed_pods, mock_adopt_launched_task
):
executor = self.kubernetes_executor
mock_ti = mock.MagicMock(queued_by_job_id="1", external_executor_id="1", dag_id="dag", task_id="task")
mock_kube_client = mock.MagicMock()
mock_kube_client.list_namespaced_pod.return_value.items = []
executor.kube_client = mock_kube_client
tis_to_flush = executor.try_adopt_task_instances([mock_ti])
assert tis_to_flush == [mock_ti]
mock_adopt_launched_task.assert_not_called()
mock_adopt_completed_pods.assert_called_once()
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_adopt_launched_task(self, mock_kube_client):
executor = self.kubernetes_executor
executor.scheduler_job_id = "modified"
annotations = {
"dag_id": "dag",
"run_id": "run_id",
"task_id": "task",
"try_number": "1",
}
ti_key = annotations_to_key(annotations)
pod = k8s.V1Pod(
metadata=k8s.V1ObjectMeta(name="foo", labels={"airflow-worker": "bar"}, annotations=annotations)
)
tis_to_flush_by_key = {ti_key: {}}
executor.adopt_launched_task(mock_kube_client, pod=pod, tis_to_flush_by_key=tis_to_flush_by_key)
mock_kube_client.patch_namespaced_pod.assert_called_once_with(
body={"metadata": {"labels": {"airflow-worker": "modified"}}},
name="foo",
namespace=None,
)
assert tis_to_flush_by_key == {}
assert executor.running == {ti_key}
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_adopt_launched_task_api_exception(self, mock_kube_client):
"""We shouldn't think we are running the task if aren't able to patch the pod"""
executor = self.kubernetes_executor
executor.scheduler_job_id = "modified"
annotations = {
"dag_id": "dag",
"run_id": "run_id",
"task_id": "task",
"try_number": "1",
}
ti_key = annotations_to_key(annotations)
pod = k8s.V1Pod(metadata=k8s.V1ObjectMeta(name="foo", annotations=annotations))
tis_to_flush_by_key = {ti_key: {}}
mock_kube_client.patch_namespaced_pod.side_effect = ApiException(status=400)
executor.adopt_launched_task(mock_kube_client, pod=pod, tis_to_flush_by_key=tis_to_flush_by_key)
mock_kube_client.patch_namespaced_pod.assert_called_once_with(
body={"metadata": {"labels": {"airflow-worker": "modified"}}},
name="foo",
namespace=None,
)
assert tis_to_flush_by_key == {ti_key: {}}
assert executor.running == set()
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_adopt_completed_pods(self, mock_kube_client):
"""We should adopt all completed pods from other schedulers"""
executor = self.kubernetes_executor
executor.scheduler_job_id = "modified"
executor.kube_client = mock_kube_client
executor.kube_config.kube_namespace = "somens"
pod_names = ["one", "two"]
def get_annotations(pod_name):
return {
"dag_id": "dag",
"run_id": "run_id",
"task_id": pod_name,
"try_number": "1",
}
mock_kube_client.list_namespaced_pod.return_value.items = [
k8s.V1Pod(
metadata=k8s.V1ObjectMeta(
name=pod_name,
labels={"airflow-worker": pod_name},
annotations=get_annotations(pod_name),
namespace="somens",
)
)
for pod_name in pod_names
]
expected_running_ti_keys = {annotations_to_key(get_annotations(pod_name)) for pod_name in pod_names}
executor._adopt_completed_pods(mock_kube_client)
mock_kube_client.list_namespaced_pod.assert_called_once_with(
namespace="somens",
field_selector="status.phase=Succeeded",
label_selector="kubernetes_executor=True,airflow-worker!=modified,airflow_executor_done!=True",
)
assert len(pod_names) == mock_kube_client.patch_namespaced_pod.call_count
mock_kube_client.patch_namespaced_pod.assert_has_calls(
[
mock.call(
body={"metadata": {"labels": {"airflow-worker": "modified"}}},
name=pod_name,
namespace="somens",
)
for pod_name in pod_names
],
any_order=True,
)
assert executor.running == expected_running_ti_keys
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_not_adopt_unassigned_task(self, mock_kube_client):
"""
We should not adopt any tasks that were not assigned by the scheduler.
This ensures that there is no contention over pod management.
"""
executor = self.kubernetes_executor
executor.scheduler_job_id = "modified"
tis_to_flush_by_key = {"foobar": {}}
pod = k8s.V1Pod(
metadata=k8s.V1ObjectMeta(
name="foo",
labels={"airflow-worker": "bar"},
annotations={
"dag_id": "dag",
"run_id": "run_id",
"task_id": "task",
"try_number": "1",
},
)
)
executor.adopt_launched_task(mock_kube_client, pod=pod, tis_to_flush_by_key=tis_to_flush_by_key)
assert not mock_kube_client.patch_namespaced_pod.called
assert tis_to_flush_by_key == {"foobar": {}}
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
@mock.patch("airflow.executors.kubernetes_executor_utils.AirflowKubernetesScheduler.delete_pod")
def test_cleanup_stuck_queued_tasks(self, mock_delete_pod, mock_kube_client, dag_maker, session):
"""Delete any pods associated with a task stuck in queued."""
executor = KubernetesExecutor()
executor.start()
executor.scheduler_job_id = "123"
with dag_maker(dag_id="test_cleanup_stuck_queued_tasks"):
op = BashOperator(task_id="bash", bash_command=["echo 0", "echo 1"])
dag_run = dag_maker.create_dagrun()
ti = dag_run.get_task_instance(op.task_id, session)
ti.retries = 1
ti.state = State.QUEUED
ti.queued_dttm = timezone.utcnow() - timedelta(minutes=30)
ti.refresh_from_db()
tis = [ti]
executor.cleanup_stuck_queued_tasks(tis)
mock_delete_pod.assert_called_once()
assert executor.running == set()
executor.end()
@pytest.mark.parametrize(
"raw_multi_namespace_mode, raw_value_namespace_list, expected_value_in_kube_config",
[
pytest.param("true", "A,B,C", ["A", "B", "C"]),
pytest.param("true", "", None),
pytest.param("false", "A,B,C", None),
pytest.param("false", "", None),
],
)
def test_kube_config_get_namespace_list(
self, raw_multi_namespace_mode, raw_value_namespace_list, expected_value_in_kube_config
):
config = {
("kubernetes", "multi_namespace_mode"): raw_multi_namespace_mode,
("kubernetes", "multi_namespace_mode_namespace_list"): raw_value_namespace_list,
}
with conf_vars(config):
executor = KubernetesExecutor()
assert executor.kube_config.multi_namespace_mode_namespace_list == expected_value_in_kube_config
def test_clear_not_launched_queued_tasks_not_launched(self, dag_maker, create_dummy_dag, session):
"""If a pod isn't found for a TI, reset the state to scheduled"""
mock_kube_client = mock.MagicMock()
mock_kube_client.list_namespaced_pod.return_value = k8s.V1PodList(items=[])
create_dummy_dag(dag_id="test_clear", task_id="task1", with_dagrun_type=None)
dag_run = dag_maker.create_dagrun()
ti = dag_run.task_instances[0]
ti.state = State.QUEUED
ti.queued_by_job_id = 1
session.flush()
executor = self.kubernetes_executor
executor.job_id = 1
executor.kube_client = mock_kube_client
executor.clear_not_launched_queued_tasks(session=session)
ti.refresh_from_db()
assert ti.state == State.SCHEDULED
assert mock_kube_client.list_namespaced_pod.call_count == 2
mock_kube_client.list_namespaced_pod.assert_any_call(
namespace="default", label_selector="dag_id=test_clear,task_id=task1,airflow-worker=1,run_id=test"
)
# also check that we fall back to execution_date if we didn't find the pod with run_id
execution_date_label = pod_generator.datetime_to_label_safe_datestring(ti.execution_date)
mock_kube_client.list_namespaced_pod.assert_called_with(
namespace="default",
label_selector=(
f"dag_id=test_clear,task_id=task1,airflow-worker=1,execution_date={execution_date_label}"
),
)
@pytest.mark.parametrize(
"task_queue, kubernetes_queue",
[
pytest.param("default", None),
pytest.param("kubernetes", None),
pytest.param("kubernetes", "kubernetes"),
],
)
def test_clear_not_launched_queued_tasks_launched(
self, dag_maker, create_dummy_dag, session, task_queue, kubernetes_queue
):
"""Leave the state alone if a pod already exists"""
mock_kube_client = mock.MagicMock()
mock_kube_client.list_namespaced_pod.return_value = k8s.V1PodList(items=["something"])
create_dummy_dag(dag_id="test_clear", task_id="task1", with_dagrun_type=None)
dag_run = dag_maker.create_dagrun()
ti = dag_run.task_instances[0]