-
Notifications
You must be signed in to change notification settings - Fork 14.4k
/
test_pod.py
1784 lines (1603 loc) · 66.5 KB
/
test_pod.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 re
from contextlib import contextmanager, nullcontext
from unittest import mock
from unittest.mock import MagicMock, patch
import pendulum
import pytest
from kubernetes.client import ApiClient, V1PodSecurityContext, V1PodStatus, models as k8s
from pytest import param
from urllib3 import HTTPResponse
from urllib3.packages.six import BytesIO
from airflow.exceptions import AirflowException, AirflowSkipException, TaskDeferred
from airflow.models import DAG, DagModel, DagRun, TaskInstance
from airflow.models.xcom import XCom
from airflow.providers.cncf.kubernetes.operators.pod import KubernetesPodOperator, _optionally_suppress
from airflow.providers.cncf.kubernetes.secret import Secret
from airflow.providers.cncf.kubernetes.triggers.pod import KubernetesPodTrigger
from airflow.providers.cncf.kubernetes.utils.pod_manager import PodPhase
from airflow.providers.cncf.kubernetes.utils.xcom_sidecar import PodDefaults
from airflow.utils import timezone
from airflow.utils.session import create_session
from airflow.utils.types import DagRunType
from tests.test_utils import db
DEFAULT_DATE = timezone.datetime(2016, 1, 1, 1, 0, 0)
KPO_MODULE = "airflow.providers.cncf.kubernetes.operators.pod"
POD_MANAGER_CLASS = "airflow.providers.cncf.kubernetes.utils.pod_manager.PodManager"
POD_MANAGER_MODULE = "airflow.providers.cncf.kubernetes.utils.pod_manager"
HOOK_CLASS = "airflow.providers.cncf.kubernetes.operators.pod.KubernetesHook"
KUB_OP_PATH = "airflow.providers.cncf.kubernetes.operators.pod.KubernetesPodOperator.{}"
TEST_TASK_ID = "kubernetes_task_async"
TEST_NAMESPACE = "default"
TEST_IMAGE = "ubuntu:16.04"
TEST_CMDS = ["bash", "-cx"]
TEST_ARGS = ["echo", "10", "echo pwd"]
TEST_LABELS = {"foo": "bar"}
TEST_NAME = "test-pod"
TEST_SUCCESS_MESSAGE = "All containers inside pod have started successfully."
@contextmanager
def temp_override_attr(obj, attr, val):
orig = getattr(obj, attr)
setattr(obj, attr, val)
yield
setattr(obj, attr, orig)
@pytest.fixture(scope="function", autouse=True)
def clear_db():
db.clear_db_dags()
db.clear_db_runs()
yield
def create_context(task, persist_to_db=False, map_index=None):
if task.has_dag():
dag = task.dag
else:
dag = DAG(dag_id="dag", start_date=pendulum.now())
dag.add_task(task)
dag_run = DagRun(
run_id=DagRun.generate_run_id(DagRunType.MANUAL, DEFAULT_DATE),
run_type=DagRunType.MANUAL,
dag_id=dag.dag_id,
)
task_instance = TaskInstance(task=task, run_id=dag_run.run_id)
task_instance.dag_run = dag_run
if map_index is not None:
task_instance.map_index = map_index
if persist_to_db:
with create_session() as session:
session.add(DagModel(dag_id=dag.dag_id))
session.add(dag_run)
session.add(task_instance)
session.commit()
return {
"dag": dag,
"ts": DEFAULT_DATE.isoformat(),
"task": task,
"ti": task_instance,
"task_instance": task_instance,
"run_id": "test",
}
@pytest.mark.execution_timeout(300)
class TestKubernetesPodOperator:
@pytest.fixture(autouse=True)
def setup_tests(self, dag_maker):
self.create_pod_patch = patch(f"{POD_MANAGER_CLASS}.create_pod")
self.await_pod_patch = patch(f"{POD_MANAGER_CLASS}.await_pod_start")
self.await_pod_completion_patch = patch(f"{POD_MANAGER_CLASS}.await_pod_completion")
self._default_client_patch = patch(f"{HOOK_CLASS}._get_default_client")
self.create_mock = self.create_pod_patch.start()
self.await_start_mock = self.await_pod_patch.start()
self.await_pod_mock = self.await_pod_completion_patch.start()
self._default_client_mock = self._default_client_patch.start()
self.dag_maker = dag_maker
yield
patch.stopall()
def test_templates(self, create_task_instance_of_operator):
dag_id = "TestKubernetesPodOperator"
ti = create_task_instance_of_operator(
KubernetesPodOperator,
dag_id=dag_id,
task_id="task-id",
namespace="{{ dag.dag_id }}",
container_resources=k8s.V1ResourceRequirements(
requests={"memory": "{{ dag.dag_id }}", "cpu": "{{ dag.dag_id }}"},
limits={"memory": "{{ dag.dag_id }}", "cpu": "{{ dag.dag_id }}"},
),
pod_template_file="{{ dag.dag_id }}",
config_file="{{ dag.dag_id }}",
labels="{{ dag.dag_id }}",
env_vars=["{{ dag.dag_id }}"],
arguments="{{ dag.dag_id }}",
cmds="{{ dag.dag_id }}",
image="{{ dag.dag_id }}",
)
rendered = ti.render_templates()
assert dag_id == rendered.container_resources.limits["memory"]
assert dag_id == rendered.container_resources.limits["cpu"]
assert dag_id == rendered.container_resources.requests["memory"]
assert dag_id == rendered.container_resources.requests["cpu"]
assert dag_id == ti.task.image
assert dag_id == ti.task.cmds
assert dag_id == ti.task.namespace
assert dag_id == ti.task.config_file
assert dag_id == ti.task.labels
assert dag_id == ti.task.pod_template_file
assert dag_id == ti.task.arguments
assert dag_id == ti.task.env_vars[0]
def run_pod(self, operator: KubernetesPodOperator, map_index: int = -1) -> k8s.V1Pod:
with self.dag_maker(dag_id="dag") as dag:
operator.dag = dag
dr = self.dag_maker.create_dagrun(run_id="test")
(ti,) = dr.task_instances
ti.map_index = map_index
self.dag_run = dr
context = ti.get_template_context(session=self.dag_maker.session)
self.dag_maker.session.commit() # So 'execute' can read dr and ti.
remote_pod_mock = MagicMock()
remote_pod_mock.status.phase = "Succeeded"
self.await_pod_mock.return_value = remote_pod_mock
operator.execute(context=context)
return self.await_start_mock.call_args.kwargs["pod"]
def sanitize_for_serialization(self, obj):
return ApiClient().sanitize_for_serialization(obj)
@patch(HOOK_CLASS)
def test_config_path(self, hook_mock):
file_path = "/tmp/fake_file"
k = KubernetesPodOperator(
namespace="default",
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
do_xcom_push=False,
config_file=file_path,
)
remote_pod_mock = MagicMock()
remote_pod_mock.status.phase = "Succeeded"
self.await_pod_mock.return_value = remote_pod_mock
self.run_pod(k)
hook_mock.assert_called_once_with(
cluster_context=None,
conn_id="kubernetes_default",
config_file=file_path,
in_cluster=None,
)
@pytest.mark.parametrize(
"input",
[
param([k8s.V1EnvVar(name="{{ bar }}", value="{{ foo }}")], id="current"),
param({"{{ bar }}": "{{ foo }}"}, id="backcompat"),
],
)
def test_env_vars(self, input):
k = KubernetesPodOperator(
env_vars=input,
task_id="task",
)
k.render_template_fields(context={"foo": "footemplated", "bar": "bartemplated"})
assert k.env_vars[0].value == "footemplated"
assert k.env_vars[0].name == "bartemplated"
def test_security_context(self):
security_context = V1PodSecurityContext(run_as_user=1245)
k = KubernetesPodOperator(
security_context=security_context,
task_id="task",
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.security_context == security_context
def test_container_security_context(self):
container_security_context = {"allowPrivilegeEscalation": False}
k = KubernetesPodOperator(
container_security_context=container_security_context,
task_id="task",
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[0].security_context == container_security_context
def test_envs_from_configmaps(self):
env_from = [k8s.V1EnvFromSource(config_map_ref=k8s.V1ConfigMapEnvSource(name="test-config-map"))]
k = KubernetesPodOperator(
task_id="task",
env_from=env_from,
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[0].env_from == env_from
def test_envs_from_configmaps_backcompat(self):
# todo: formally deprecate / remove this?
k = KubernetesPodOperator(
task_id="task",
configmaps=["test-config-map"],
)
expected = [k8s.V1EnvFromSource(config_map_ref=k8s.V1ConfigMapEnvSource(name="test-config-map"))]
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[0].env_from == expected
def test_envs_from_secrets(self):
secret_ref = "secret_name"
secrets = [Secret("env", None, secret_ref)]
k = KubernetesPodOperator(
secrets=secrets,
task_id="test",
)
pod = k.build_pod_request_obj()
assert pod.spec.containers[0].env_from == [
k8s.V1EnvFromSource(secret_ref=k8s.V1SecretEnvSource(name=secret_ref))
]
@pytest.mark.parametrize(("in_cluster",), ([True], [False]))
@patch(HOOK_CLASS)
def test_labels(self, hook_mock, in_cluster):
hook_mock.return_value.is_in_cluster = in_cluster
k = KubernetesPodOperator(
namespace="default",
image="ubuntu:16.04",
cmds=["bash", "-cx"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=in_cluster,
do_xcom_push=False,
)
pod = self.run_pod(k)
assert pod.metadata.labels == {
"foo": "bar",
"dag_id": "dag",
"kubernetes_pod_operator": "True",
"task_id": "task",
"try_number": "1",
"airflow_version": mock.ANY,
"run_id": "test",
"airflow_kpo_in_cluster": str(in_cluster),
}
def test_labels_mapped(self):
k = KubernetesPodOperator(
name="test",
task_id="task",
)
pod = k.build_pod_request_obj(create_context(k, map_index=10))
assert pod.metadata.labels == {
"dag_id": "dag",
"kubernetes_pod_operator": "True",
"task_id": "task",
"try_number": "1",
"airflow_version": mock.ANY,
"run_id": "test",
"map_index": "10",
"airflow_kpo_in_cluster": str(k.hook.is_in_cluster),
}
def test_find_custom_pod_labels(self):
k = KubernetesPodOperator(
labels={"foo": "bar", "hello": "airflow"},
name="test",
task_id="task",
)
context = create_context(k)
label_selector = k._build_find_pod_label_selector(context)
assert "foo=bar" in label_selector and "hello=airflow" in label_selector
@patch(HOOK_CLASS, new=MagicMock)
def test_find_pod_labels(self):
k = KubernetesPodOperator(
namespace="default",
image="ubuntu:16.04",
cmds=["bash", "-cx"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
)
self.run_pod(k)
_, kwargs = k.client.list_namespaced_pod.call_args
assert kwargs["label_selector"] == (
"dag_id=dag,foo=bar,kubernetes_pod_operator=True,run_id=test,task_id=task,"
"already_checked!=True,!airflow-worker"
)
@patch(HOOK_CLASS, new=MagicMock)
def test_pod_dns_options(self):
dns_config = k8s.V1PodDNSConfig(
nameservers=["192.0.2.1", "192.0.2.3"],
searches=["ns1.svc.cluster-domain.example", "my.dns.search.suffix"],
options=[
k8s.V1PodDNSConfigOption(
name="ndots",
value="2",
)
],
)
hostname = "busybox-2"
subdomain = "busybox-subdomain"
k = KubernetesPodOperator(
namespace="default",
image="ubuntu:16.04",
cmds=["bash", "-cx"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
dns_config=dns_config,
hostname=hostname,
subdomain=subdomain,
)
self.run_pod(k)
pod_spec = k.pod.spec
assert pod_spec.dns_config == dns_config
assert pod_spec.subdomain == subdomain
assert pod_spec.hostname == hostname
@pytest.mark.parametrize(
"val",
[
param([k8s.V1LocalObjectReference("fakeSecret")], id="current"),
param("fakeSecret", id="backcompat"),
],
)
def test_image_pull_secrets_correctly_set(self, val):
k = KubernetesPodOperator(
task_id="task",
image_pull_secrets=val,
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.image_pull_secrets == [k8s.V1LocalObjectReference(name="fakeSecret")]
def test_omitted_name(self):
k = KubernetesPodOperator(task_id="this-task-name")
pod = k.build_pod_request_obj(create_context(k))
assert re.match("this-task-name-[a-z0-9]+", pod.metadata.name) is not None
@pytest.mark.parametrize("use_template", [True, False])
@pytest.mark.parametrize("use_pod_spec", [True, False])
@patch("pathlib.Path")
@patch(f"{KPO_MODULE}.KubernetesPodOperator.find_pod")
@patch.dict(
"os.environ", AIRFLOW_CONN_MY_CONN='{"extra": {"extra__kubernetes__namespace": "extra-namespace"}}'
)
def test_omitted_namespace_with_conn(
self, mock_find, mock_path, pod_template_file, use_template, pod_spec, use_pod_spec
):
"""
Namespace precedence is as follows:
- KPO
- airflow connection
- infer from k8s when in a cluster
- 'default' namespace as a fallback
Here we check when KPO omitted but we do have a conn where namespace defined.
In this case, the namespace should be as defined in connection.
"""
k = KubernetesPodOperator(
task_id="task",
kubernetes_conn_id="my_conn",
**(dict(pod_template_file=pod_template_file) if use_template else {}),
**(dict(full_pod_spec=pod_spec) if use_pod_spec else {}),
)
context = create_context(k)
pod = k.build_pod_request_obj(context)
mock_path.assert_not_called()
if use_pod_spec:
expected_namespace = "podspecnamespace"
elif use_template:
expected_namespace = "templatenamespace"
else:
expected_namespace = "extra-namespace"
assert pod.metadata.namespace == expected_namespace
mock_find.return_value = pod
k.get_or_create_pod(
pod_request_obj=pod,
context=context,
)
mock_find.assert_called_once_with(expected_namespace, context=context)
@patch("pathlib.Path")
@patch(f"{KPO_MODULE}.KubernetesPodOperator.find_pod")
@patch.dict("os.environ", AIRFLOW_CONN_MY_CONN='{"extra": {}}')
def test_omitted_namespace_with_conn_no_value(self, mock_find, mock_path):
"""
Namespace precedence is as follows:
- KPO
- airflow connection
- infer from k8s when in a cluster
- 'default' namespace as a fallback
Here we check when KPO omitted but we do have a conn where namespace defined.
In this case, we should continue down the change.
Here we mock not in k8s and therefore get 'default'.
"""
k = KubernetesPodOperator(
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
task_id="task",
name="hello",
kubernetes_conn_id="my_conn",
)
mock_path.return_value.exists.return_value = False
context = create_context(k)
pod = k.build_pod_request_obj(context)
mock_path.assert_called()
assert pod.metadata.namespace == "default"
mock_find.return_value = pod
k.get_or_create_pod(
pod_request_obj=pod,
context=context,
)
mock_find.assert_called_once_with("default", context=context)
@patch("pathlib.Path")
@patch(f"{KPO_MODULE}.KubernetesPodOperator.find_pod")
def test_omitted_namespace_no_conn(self, mock_find, mock_path):
"""
Namespace precedence is as follows:
- KPO
- airflow connection
- infer from k8s when in a cluster
- 'default' namespace as a fallback
Here we check when KPO omitted and no airflow connection, but we are in k8s.
In this case, we should use the value from k8s.
"""
mock_path.return_value.exists.return_value = True
mock_path.return_value.read_text.return_value = "abc"
k = KubernetesPodOperator(
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
task_id="task",
name="hello",
)
context = create_context(k)
pod = k.build_pod_request_obj(context)
mock_path.assert_called_once_with("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
assert pod.metadata.namespace == "abc"
mock_find.return_value = pod
k.get_or_create_pod(
pod_request_obj=pod,
context=context,
)
mock_find.assert_called_once_with("abc", context=context)
@patch("pathlib.Path")
@patch(f"{KPO_MODULE}.KubernetesPodOperator.find_pod")
def test_omitted_namespace_no_conn_not_in_k8s(self, mock_find, mock_path):
"""
Namespace precedence is as follows:
- KPO
- airflow connection
- infer from k8s when in a cluster
- 'default' namespace as a fallback
Here we check when KPO omitted and no airflow connection and not in a k8s pod.
In this case we should end up with the 'default' namespace.
"""
mock_path.return_value.exists.return_value = False
k = KubernetesPodOperator(
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
task_id="task",
name="hello",
)
context = create_context(k)
pod = k.build_pod_request_obj(context)
mock_path.assert_called_once_with("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
assert pod.metadata.namespace == "default"
mock_find.return_value = pod
k.get_or_create_pod(
pod_request_obj=pod,
context=context,
)
mock_find.assert_called_once_with("default", context=context)
def test_xcom_sidecar_container_image_custom(self):
image = "private.repo/alpine:3.13"
with temp_override_attr(PodDefaults.SIDECAR_CONTAINER, "image", image):
k = KubernetesPodOperator(
name="test",
task_id="task",
do_xcom_push=True,
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[1].image == image
def test_xcom_sidecar_container_image_default(self):
k = KubernetesPodOperator(
name="test",
task_id="task",
do_xcom_push=True,
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[1].image == "alpine"
def test_xcom_sidecar_container_resources_default(self):
k = KubernetesPodOperator(
name="test",
task_id="task",
do_xcom_push=True,
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[1].resources == k8s.V1ResourceRequirements(
requests={
"cpu": "1m",
"memory": "10Mi",
},
)
def test_xcom_sidecar_container_resources_custom(self):
resources = {
"requests": {"cpu": "1m", "memory": "10Mi"},
"limits": {"cpu": "10m", "memory": "50Mi"},
}
with temp_override_attr(PodDefaults.SIDECAR_CONTAINER, "resources", resources):
k = KubernetesPodOperator(
name="test",
task_id="task",
do_xcom_push=True,
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[1].resources == resources
def test_image_pull_policy_correctly_set(self):
k = KubernetesPodOperator(
task_id="task",
image_pull_policy="Always",
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[0].image_pull_policy == "Always"
def test_termination_message_policy_correctly_set(self):
k = KubernetesPodOperator(
task_id="task",
termination_message_policy="FallbackToLogsOnError",
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[0].termination_message_policy == "FallbackToLogsOnError"
def test_termination_message_policy_default_value_correctly_set(self):
k = KubernetesPodOperator(
task_id="task",
)
pod = k.build_pod_request_obj(create_context(k))
assert pod.spec.containers[0].termination_message_policy == "File"
@pytest.mark.parametrize(
"task_kwargs, should_be_deleted",
[
({}, True), # default values
({"is_delete_operator_pod": True}, True), # check b/c of is_delete_operator_pod
({"is_delete_operator_pod": False}, False), # check b/c of is_delete_operator_pod
({"on_finish_action": "delete_pod"}, True),
({"on_finish_action": "delete_succeeded_pod"}, False),
({"on_finish_action": "keep_pod"}, False),
],
)
@patch(f"{POD_MANAGER_CLASS}.delete_pod")
@patch(f"{KPO_MODULE}.KubernetesPodOperator.find_pod")
def test_pod_delete_after_await_container_error(
self, find_pod_mock, delete_pod_mock, task_kwargs, should_be_deleted
):
"""
When KPO fails unexpectedly during await_container, we should still try to delete the pod,
and the pod we try to delete should be the one returned from find_pod earlier.
"""
cont_status = MagicMock()
cont_status.name = "base"
cont_status.state.terminated.message = "my-failure"
find_pod_mock.return_value.status.container_statuses = [cont_status]
k = KubernetesPodOperator(task_id="task", **task_kwargs)
self.await_pod_mock.side_effect = AirflowException("fake failure")
with pytest.raises(AirflowException, match="my-failure"):
context = create_context(k)
context["ti"].xcom_push = MagicMock()
k.execute(context=context)
if should_be_deleted:
delete_pod_mock.assert_called_with(find_pod_mock.return_value)
else:
delete_pod_mock.assert_not_called()
@pytest.mark.parametrize("should_fail", [True, False])
@patch(f"{POD_MANAGER_CLASS}.delete_pod")
@patch(f"{POD_MANAGER_CLASS}.await_pod_completion")
def test_pod_delete_not_called_when_creation_fails(self, await_pod_mock, delete_pod_mock, should_fail):
"""
When pod creation fails, we never get a read of the remote pod. In this case we don't attempt
to delete the pod.
"""
k = KubernetesPodOperator(
task_id="task",
on_finish_action="delete_pod",
)
if should_fail:
self.create_mock.side_effect = AirflowException("fake failure")
else:
await_pod_mock.return_value.status.phase = "Succeeded"
cm = pytest.raises(AirflowException) if should_fail else nullcontext()
with cm:
self.run_pod(k)
if should_fail:
delete_pod_mock.assert_not_called()
else:
delete_pod_mock.assert_called()
@pytest.mark.parametrize("randomize", [True, False])
def test_provided_pod_name(self, randomize):
name_base = "test"
k = KubernetesPodOperator(
name=name_base,
random_name_suffix=randomize,
task_id="task",
)
context = create_context(k)
pod = k.build_pod_request_obj(context)
if randomize:
assert pod.metadata.name.startswith(name_base)
assert pod.metadata.name != name_base
else:
assert pod.metadata.name == name_base
@pytest.fixture
def pod_spec(self):
return k8s.V1Pod(
metadata=k8s.V1ObjectMeta(name="hello", labels={"foo": "bar"}, namespace="podspecnamespace"),
spec=k8s.V1PodSpec(
containers=[
k8s.V1Container(
name="base",
image="ubuntu:16.04",
command=["something"],
)
]
),
)
@pytest.mark.parametrize(("randomize_name",), ([True], [False]))
def test_full_pod_spec(self, randomize_name, pod_spec):
pod_spec_name_base = pod_spec.metadata.name
k = KubernetesPodOperator(
task_id="task",
random_name_suffix=randomize_name,
full_pod_spec=pod_spec,
)
context = create_context(k)
pod = k.build_pod_request_obj(context)
if randomize_name:
assert pod.metadata.name.startswith(pod_spec_name_base)
assert pod.metadata.name != pod_spec_name_base
else:
assert pod.metadata.name == pod_spec_name_base
assert pod.metadata.namespace == pod_spec.metadata.namespace
assert pod.spec.containers[0].image == pod_spec.spec.containers[0].image
assert pod.spec.containers[0].command == pod_spec.spec.containers[0].command
# Check labels are added from pod_template_file and
# the pod identifying labels including Airflow version
assert pod.metadata.labels == {
"foo": "bar",
"dag_id": "dag",
"kubernetes_pod_operator": "True",
"task_id": "task",
"try_number": "1",
"airflow_version": mock.ANY,
"airflow_kpo_in_cluster": str(k.hook.is_in_cluster),
"run_id": "test",
}
@pytest.mark.parametrize(("randomize_name",), ([True], [False]))
def test_full_pod_spec_kwargs(self, randomize_name, pod_spec):
# kwargs take precedence, however
image = "some.custom.image:andtag"
name_base = "world"
k = KubernetesPodOperator(
task_id="task",
random_name_suffix=randomize_name,
full_pod_spec=pod_spec,
name=name_base,
image=image,
labels={"hello": "world"},
)
pod = k.build_pod_request_obj(create_context(k))
# make sure the kwargs takes precedence (and that name is randomized when expected)
if randomize_name:
assert pod.metadata.name.startswith(name_base)
assert pod.metadata.name != name_base
else:
assert pod.metadata.name == name_base
assert pod.spec.containers[0].image == image
# Check labels are added from pod_template_file, the operator itself and
# the pod identifying labels including Airflow version
assert pod.metadata.labels == {
"foo": "bar",
"hello": "world",
"dag_id": "dag",
"kubernetes_pod_operator": "True",
"task_id": "task",
"try_number": "1",
"airflow_version": mock.ANY,
"airflow_kpo_in_cluster": str(k.hook.is_in_cluster),
"run_id": "test",
}
@pytest.fixture
def pod_template_file(self, tmp_path):
pod_template_yaml = b"""
apiVersion: v1
kind: Pod
metadata:
name: hello
namespace: templatenamespace
labels:
foo: bar
spec:
serviceAccountName: foo
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/role
operator: In
values:
- foo
- bar
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
preference:
matchExpressions:
- key: kubernetes.io/role
operator: In
values:
- foo
- bar
containers:
- name: base
image: ubuntu:16.04
imagePullPolicy: Always
command:
- something
"""
tpl_file = tmp_path / "template.yaml"
tpl_file.write_bytes(pod_template_yaml)
yield tpl_file
@pytest.mark.parametrize(("randomize_name",), ([True], [False]))
def test_pod_template_file(self, randomize_name, pod_template_file):
k = KubernetesPodOperator(
task_id="task",
random_name_suffix=randomize_name,
pod_template_file=pod_template_file,
)
pod = k.build_pod_request_obj(create_context(k))
if randomize_name:
assert pod.metadata.name.startswith("hello")
assert pod.metadata.name != "hello"
else:
assert pod.metadata.name == "hello"
# Check labels are added from pod_template_file and
# the pod identifying labels including Airflow version
assert pod.metadata.labels == {
"foo": "bar",
"dag_id": "dag",
"kubernetes_pod_operator": "True",
"task_id": "task",
"try_number": "1",
"airflow_version": mock.ANY,
"airflow_kpo_in_cluster": str(k.hook.is_in_cluster),
"run_id": "test",
}
assert pod.metadata.namespace == "templatenamespace"
assert pod.spec.containers[0].image == "ubuntu:16.04"
assert pod.spec.containers[0].image_pull_policy == "Always"
assert pod.spec.containers[0].command == ["something"]
assert pod.spec.service_account_name == "foo"
affinity = {
"node_affinity": {
"preferred_during_scheduling_ignored_during_execution": [
{
"preference": {
"match_expressions": [
{"key": "kubernetes.io/role", "operator": "In", "values": ["foo", "bar"]}
],
"match_fields": None,
},
"weight": 1,
}
],
"required_during_scheduling_ignored_during_execution": {
"node_selector_terms": [
{
"match_expressions": [
{"key": "kubernetes.io/role", "operator": "In", "values": ["foo", "bar"]}
],
"match_fields": None,
}
]
},
},
"pod_affinity": None,
"pod_anti_affinity": None,
}
assert pod.spec.affinity.to_dict() == affinity
@pytest.mark.parametrize(("randomize_name",), ([True], [False]))
def test_pod_template_file_kwargs_override(self, randomize_name, pod_template_file):
# kwargs take precedence, however
image = "some.custom.image:andtag"
name_base = "world"
k = KubernetesPodOperator(
task_id="task",
pod_template_file=pod_template_file,
name=name_base,
random_name_suffix=randomize_name,
image=image,
labels={"hello": "world"},
)
pod = k.build_pod_request_obj(create_context(k))
# make sure the kwargs takes precedence (and that name is randomized when expected)
if randomize_name:
assert pod.metadata.name.startswith(name_base)
assert pod.metadata.name != name_base
else:
assert pod.metadata.name == name_base
assert pod.spec.containers[0].image == image
# Check labels are added from pod_template_file, the operator itself and
# the pod identifying labels including Airflow version
assert pod.metadata.labels == {
"foo": "bar",
"hello": "world",
"dag_id": "dag",
"kubernetes_pod_operator": "True",
"task_id": "task",
"try_number": "1",
"airflow_version": mock.ANY,
"airflow_kpo_in_cluster": str(k.hook.is_in_cluster),
"run_id": "test",
}
@patch(f"{POD_MANAGER_CLASS}.fetch_container_logs")
@patch(f"{POD_MANAGER_CLASS}.await_container_completion", new=MagicMock)
def test_no_handle_failure_on_success(self, fetch_container_mock):
name_base = "test"
k = KubernetesPodOperator(name=name_base, task_id="task")
fetch_container_mock.return_value = None
remote_pod_mock = MagicMock()
remote_pod_mock.status.phase = "Succeeded"
self.await_pod_mock.return_value = remote_pod_mock
# assert does not raise
self.run_pod(k)
def test_create_with_affinity(self):
affinity = {
"nodeAffinity": {
"preferredDuringSchedulingIgnoredDuringExecution": [
{
"weight": 1,
"preference": {
"matchExpressions": [{"key": "disktype", "operator": "In", "values": ["ssd"]}]
},
}
]
}
}
k = KubernetesPodOperator(
task_id="task",
affinity=affinity,
)
pod = k.build_pod_request_obj(create_context(k))
sanitized_pod = self.sanitize_for_serialization(pod)
assert isinstance(pod.spec.affinity, k8s.V1Affinity)
assert sanitized_pod["spec"]["affinity"] == affinity
k8s_api_affinity = k8s.V1Affinity(
node_affinity=k8s.V1NodeAffinity(
preferred_during_scheduling_ignored_during_execution=[
k8s.V1PreferredSchedulingTerm(
weight=1,
preference=k8s.V1NodeSelectorTerm(
match_expressions=[
k8s.V1NodeSelectorRequirement(key="disktype", operator="In", values=["ssd"])
]
),
)
]
),
)
k = KubernetesPodOperator(
task_id="task",
affinity=k8s_api_affinity,
)
pod = k.build_pod_request_obj(create_context(k))
sanitized_pod = self.sanitize_for_serialization(pod)
assert isinstance(pod.spec.affinity, k8s.V1Affinity)
assert sanitized_pod["spec"]["affinity"] == affinity
def test_tolerations(self):
k8s_api_tolerations = [k8s.V1Toleration(key="key", operator="Equal", value="value")]
tolerations = [{"key": "key", "operator": "Equal", "value": "value"}]
k = KubernetesPodOperator(
task_id="task",
tolerations=tolerations,
)
pod = k.build_pod_request_obj(create_context(k))
sanitized_pod = self.sanitize_for_serialization(pod)
assert isinstance(pod.spec.tolerations[0], k8s.V1Toleration)
assert sanitized_pod["spec"]["tolerations"] == tolerations
k = KubernetesPodOperator(