-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
kubernetes_commands.py
1794 lines (1712 loc) · 65.3 KB
/
kubernetes_commands.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 multiprocessing as mp
import os
import re
import shutil
import sys
import tempfile
from copy import deepcopy
from pathlib import Path
from shlex import quote
import click
from airflow_breeze.commands.common_options import (
option_answer,
option_debug_resources,
option_dry_run,
option_include_success_outputs,
option_parallelism,
option_python,
option_python_versions,
option_run_in_parallel,
option_skip_cleanup,
option_use_uv,
option_verbose,
)
from airflow_breeze.commands.production_image_commands import run_build_production_image
from airflow_breeze.global_constants import ALLOWED_EXECUTORS, ALLOWED_KUBERNETES_VERSIONS
from airflow_breeze.params.build_prod_params import BuildProdParams
from airflow_breeze.utils.ci_group import ci_group
from airflow_breeze.utils.click_utils import BreezeGroup
from airflow_breeze.utils.console import Output, get_console
from airflow_breeze.utils.custom_param_types import CacheableChoice, CacheableDefault
from airflow_breeze.utils.kubernetes_utils import (
CHART_PATH,
K8S_CLUSTERS_PATH,
SCRIPTS_CI_KUBERNETES_PATH,
KubernetesPythonVersion,
create_virtualenv,
get_config_folder,
get_k8s_env,
get_kind_cluster_config_path,
get_kind_cluster_name,
get_kubeconfig_file,
get_kubectl_cluster_name,
get_kubernetes_python_combos,
make_sure_kubernetes_tools_are_installed,
print_cluster_urls,
run_command_with_k8s_env,
set_random_cluster_ports,
)
from airflow_breeze.utils.parallel import (
DockerBuildxProgressMatcher,
GenericRegexpProgressMatcher,
check_async_run_results,
run_with_pool,
)
from airflow_breeze.utils.recording import generating_command_images
from airflow_breeze.utils.run_utils import RunCommandResult, check_if_image_exists, run_command
PARALLEL_PYTEST_ARGS = [
"--verbosity=0",
"--strict-markers",
"--durations=100",
"--maxfail=50",
"--color=yes",
# timeouts in seconds for individual tests
"--timeouts-order",
"moi",
"--setup-timeout=300",
"--execution-timeout=300",
"--teardown-timeout=300",
# Only display summary for non-expected case
# f - failed
# E - error
# X - xpassed (passed even if expected to fail)
# The following cases are not displayed:
# s - skipped
# x - xfailed (expected to fail and failed)
# p - passed
# P - passed with output
"-rfEX",
]
@click.group(cls=BreezeGroup, name="k8s", help="Tools that developers use to run Kubernetes tests")
def kubernetes_group():
pass
option_copy_local_sources = click.option(
"--copy-local-sources/--no-copy-local-sources",
help="Copy local sources to the image.",
default=True,
show_default=True,
envvar="COPY_LOCAL_SOURCES",
)
option_executor = click.option(
"--executor",
help="Executor to use for a kubernetes cluster.",
type=CacheableChoice(ALLOWED_EXECUTORS),
show_default=True,
default=CacheableDefault(ALLOWED_EXECUTORS[0]),
envvar="EXECUTOR",
)
option_force_recreate_cluster = click.option(
"--force-recreate-cluster",
help="Force recreation of the cluster even if it is already created.",
is_flag=True,
envvar="FORCE_RECREATE_CLUSTER",
)
option_force_venv_setup = click.option(
"--force-venv-setup",
help="Force recreation of the virtualenv.",
is_flag=True,
envvar="FORCE_VENV_SETUP",
)
option_image_tag = click.option(
"-t",
"--image-tag",
help="Image tag used to build K8S image from.",
default="latest",
show_default=True,
envvar="IMAGE_TAG",
)
option_kubernetes_version = click.option(
"--kubernetes-version",
help="Kubernetes version used to create the KinD cluster of.",
type=CacheableChoice(ALLOWED_KUBERNETES_VERSIONS),
show_default=True,
default=CacheableDefault(ALLOWED_KUBERNETES_VERSIONS[0]),
envvar="KUBERNETES_VERSION",
)
option_kubernetes_versions = click.option(
"--kubernetes-versions",
help="Kubernetes versions used to run in parallel (space separated).",
type=str,
show_default=True,
default=" ".join(ALLOWED_KUBERNETES_VERSIONS),
envvar="KUBERNETES_VERSIONS",
)
option_multi_namespace_mode = click.option(
"--multi-namespace-mode",
help="Use multi namespace mode.",
is_flag=True,
envvar="MULTI_NAMESPACE_MODE",
)
option_rebuild_base_image = click.option(
"--rebuild-base-image",
help="Rebuilds base Airflow image before building K8S image.",
is_flag=True,
envvar="REBUILD_BASE_IMAGE",
)
option_upgrade = click.option(
"--upgrade",
help="Upgrade Helm Chart rather than installing it.",
is_flag=True,
envvar="UPGRADE",
)
option_use_docker = click.option(
"--use-docker",
help="Use Docker to start k8s executor (otherwise k9s from PATH is used and only"
" run with docker if not found on PATH).",
is_flag=True,
envvar="USE_DOCKER",
)
option_use_standard_naming = click.option(
"--use-standard-naming",
help="Use standard naming.",
is_flag=True,
envvar="USE_STANDARD_NAMING",
)
option_wait_time_in_seconds = click.option(
"--wait-time-in-seconds",
help="Wait for Airflow webserver for specified number of seconds.",
type=click.IntRange(0),
default=120,
envvar="WAIT_TIME_IN_SECONDS",
)
option_wait_time_in_seconds_0_default = click.option(
"--wait-time-in-seconds",
help="Wait for Airflow webserver for specified number of seconds.",
type=click.IntRange(0),
default=0,
envvar="WAIT_TIME_IN_SECONDS",
)
option_parallelism_cluster = click.option(
"--parallelism",
help="Maximum number of processes to use while running the operation in parallel for cluster operations.",
type=click.IntRange(1, max(1, (mp.cpu_count() + 1) // 3) if not generating_command_images() else 4),
default=max(1, (mp.cpu_count() + 1) // 3) if not generating_command_images() else 2,
envvar="PARALLELISM",
show_default=True,
)
option_all = click.option("--all", help="Apply it to all created clusters", is_flag=True, envvar="ALL")
K8S_CLUSTER_CREATE_PROGRESS_REGEXP = r".*airflow-python-[0-9.]+-v[0-9.].*|.*Connecting to localhost.*"
K8S_UPLOAD_PROGRESS_REGEXP = r".*airflow-python-[0-9.]+-v[0-9.].*"
K8S_CONFIGURE_CLUSTER_PROGRESS_REGEXP = r".*airflow-python-[0-9.]+-v[0-9.].*"
K8S_DEPLOY_PROGRESS_REGEXP = r".*airflow-python-[0-9.]+-v[0-9.].*"
K8S_TEST_PROGRESS_REGEXP = r".*airflow-python-[0-9.]+-v[0-9.].*|^kubernetes_tests/.*"
PREVIOUS_LINE_K8S_TEST_REGEXP = r"^kubernetes_tests/.*"
COMPLETE_TEST_REGEXP = (
r"\s*#(\d*) |"
r".*airflow-python-[0-9.]+-v[0-9.].*|"
r".*Connecting to localhost.*|"
r"^kubernetes_tests/.*|"
r".*Error during running tests.*|"
r".*Successfully run tests.*"
)
@kubernetes_group.command(name="setup-env", help="Setup shared Kubernetes virtual environment and tools.")
@option_force_venv_setup
@option_verbose
@option_dry_run
def setup_env(force_venv_setup: bool):
result = create_virtualenv(force_venv_setup=force_venv_setup)
if result.returncode != 0:
sys.exit(1)
make_sure_kubernetes_tools_are_installed()
get_console().print("\n[warning]NEXT STEP:[/][info] You might now create your cluster by:\n")
get_console().print("\nbreeze k8s create-cluster\n")
def _create_cluster(
python: str,
kubernetes_version: str,
output: Output | None,
num_tries: int,
force_recreate_cluster: bool,
) -> tuple[int, str]:
while True:
if force_recreate_cluster:
_delete_cluster(python=python, kubernetes_version=kubernetes_version, output=output)
kubeconfig_file = get_kubeconfig_file(python=python, kubernetes_version=kubernetes_version)
cluster_name = get_kind_cluster_name(python=python, kubernetes_version=kubernetes_version)
kubeconfig_file.parent.mkdir(parents=True, exist_ok=True)
kubeconfig_file.touch(mode=0o700)
get_console(output=output).print(f"[info]Creating KinD cluster {cluster_name}!")
set_random_cluster_ports(python=python, kubernetes_version=kubernetes_version, output=output)
result = run_command_with_k8s_env(
[
"kind",
"create",
"cluster",
"--name",
cluster_name,
"--config",
str(get_kind_cluster_config_path(python=python, kubernetes_version=kubernetes_version)),
"--image",
f"kindest/node:{kubernetes_version}",
],
python=python,
kubernetes_version=kubernetes_version,
output=output,
text=True,
check=False,
)
if result.returncode == 0:
print_cluster_urls(python=python, kubernetes_version=kubernetes_version, output=output)
get_console(output=output).print(f"[success]KinD cluster {cluster_name} created!\n")
get_console(output=output).print(
"\n[warning]NEXT STEP:[/][info] You might now configure your cluster by:\n"
)
get_console(output=output).print("\nbreeze k8s configure-cluster\n")
return result.returncode, f"K8S cluster {cluster_name}."
num_tries -= 1
if num_tries == 0:
return result.returncode, f"K8S cluster {cluster_name}."
else:
get_console(output=output).print(
f"[warning]Failed to create KinD cluster {cluster_name}. "
f"Retrying! There are {num_tries} tries left.\n"
)
_delete_cluster(python=python, kubernetes_version=kubernetes_version, output=output)
@kubernetes_group.command(
name="create-cluster",
help="Create a KinD Cluster for Python and Kubernetes version specified "
"(optionally create all clusters in parallel).",
)
@option_force_recreate_cluster
@option_python
@option_kubernetes_version
@option_run_in_parallel
@option_parallelism_cluster
@option_skip_cleanup
@option_debug_resources
@option_include_success_outputs
@option_kubernetes_versions
@option_python_versions
@option_verbose
@option_dry_run
def create_cluster(
force_recreate_cluster: bool,
python: str,
kubernetes_version: str,
run_in_parallel: bool,
skip_cleanup: bool,
debug_resources: bool,
include_success_outputs: bool,
parallelism: int,
kubernetes_versions: str,
python_versions: str,
):
result = create_virtualenv(force_venv_setup=False)
if result.returncode != 0:
sys.exit(result.returncode)
make_sure_kubernetes_tools_are_installed()
if run_in_parallel:
python_version_array: list[str] = python_versions.split(" ")
kubernetes_version_array: list[str] = kubernetes_versions.split(" ")
combo_titles, short_combo_titles, combos = get_kubernetes_python_combos(
kubernetes_version_array, python_version_array
)
with ci_group(f"Creating clusters {short_combo_titles}"):
with run_with_pool(
parallelism=parallelism,
all_params=combo_titles,
debug_resources=debug_resources,
progress_matcher=GenericRegexpProgressMatcher(
regexp=K8S_CLUSTER_CREATE_PROGRESS_REGEXP, lines_to_search=15
),
) as (pool, outputs):
results = [
pool.apply_async(
_create_cluster,
kwds={
"python": combo.python_version,
"kubernetes_version": combo.kubernetes_version,
"force_recreate_cluster": False,
"num_tries": 3, # when creating cluster in parallel, sometimes we need to retry
"output": outputs[index],
},
)
for index, combo in enumerate(combos)
]
check_async_run_results(
results=results,
success="All clusters created.",
outputs=outputs,
skip_cleanup=skip_cleanup,
include_success_outputs=include_success_outputs,
)
else:
return_code, _ = _create_cluster(
python=python,
kubernetes_version=kubernetes_version,
output=None,
force_recreate_cluster=force_recreate_cluster,
num_tries=1,
)
if return_code != 0:
sys.exit(return_code)
def _delete_cluster(python: str, kubernetes_version: str, output: Output | None):
cluster_name = get_kind_cluster_name(python=python, kubernetes_version=kubernetes_version)
get_console(output=output).print(f"[info]Deleting KinD cluster {cluster_name}!")
folder = get_config_folder(python=python, kubernetes_version=kubernetes_version)
run_command_with_k8s_env(
[
"kind",
"delete",
"cluster",
"--name",
cluster_name,
],
python=python,
kubernetes_version=kubernetes_version,
output=output,
text=True,
check=False,
)
if not folder.exists():
get_console(output=output).print(
f"[warning]KinD cluster {cluster_name} was not created before but "
f"running delete in case it was created manually !\n"
)
shutil.rmtree(folder, ignore_errors=True)
get_console(output=output).print(f"[success]KinD cluster {cluster_name} deleted!\n")
def _delete_all_clusters():
clusters = list(K8S_CLUSTERS_PATH.iterdir())
if clusters:
get_console().print("\n[info]Deleting clusters")
for cluster_name in clusters:
resolved_path = cluster_name.resolve()
python, kubernetes_version = _get_python_kubernetes_version_from_name(resolved_path.name)
if python and kubernetes_version:
_delete_cluster(
python=python,
kubernetes_version=kubernetes_version,
output=None,
)
else:
get_console().print(
f"[warning]The cluster {resolved_path.name} does not match expected name. "
f"Just removing the {resolved_path}!\n"
)
if resolved_path.is_dir():
shutil.rmtree(cluster_name.resolve(), ignore_errors=True)
else:
resolved_path.unlink()
else:
get_console().print("\n[warning]No clusters.\n")
@kubernetes_group.command(
name="delete-cluster", help="Delete the current KinD Cluster (optionally all clusters)."
)
@option_python
@option_kubernetes_version
@option_all
@option_verbose
@option_dry_run
def delete_cluster(python: str, kubernetes_version: str, all: bool):
result = create_virtualenv(force_venv_setup=False)
if result.returncode != 0:
sys.exit(result.returncode)
make_sure_kubernetes_tools_are_installed()
if all:
_delete_all_clusters()
else:
_delete_cluster(python=python, kubernetes_version=kubernetes_version, output=None)
def _get_python_kubernetes_version_from_name(cluster_name: str) -> tuple[str | None, str | None]:
matcher = re.compile(r"airflow-python-(\d+\.\d+)-(v\d+.\d+.\d+)")
cluster_match = matcher.search(cluster_name)
if cluster_match:
python = cluster_match.group(1)
kubernetes_version = cluster_match.group(2)
return python, kubernetes_version
else:
return None, None
LIST_CONSOLE_WIDTH = 120
def _status(python: str, kubernetes_version: str, wait_time_in_seconds: int) -> bool:
cluster_name = get_kind_cluster_name(python=python, kubernetes_version=kubernetes_version)
kubectl_cluster_name = get_kubectl_cluster_name(python=python, kubernetes_version=kubernetes_version)
if not get_kind_cluster_config_path(python=python, kubernetes_version=kubernetes_version).exists():
get_console().print(f"\n[warning]Cluster: {cluster_name} has not been created yet\n")
get_console().print(
"[info]Run: "
f"`breeze k8s create-cluster --python {python} --kubernetes-version {kubernetes_version}`"
"to create it.\n"
)
return False
get_console().print("[info]" + "=" * LIST_CONSOLE_WIDTH)
get_console().print(f"[info]Cluster: {cluster_name}\n")
kubeconfig_file = get_kubeconfig_file(python=python, kubernetes_version=kubernetes_version)
get_console().print(f" * KUBECONFIG={kubeconfig_file}")
kind_config_file = get_kind_cluster_config_path(python=python, kubernetes_version=kubernetes_version)
get_console().print(f" * KINDCONFIG={kind_config_file}")
get_console().print(f"\n[info]Cluster info: {cluster_name}\n")
result = run_command_with_k8s_env(
["kubectl", "cluster-info", "--cluster", kubectl_cluster_name],
python=python,
kubernetes_version=kubernetes_version,
check=False,
)
if result.returncode != 0:
return False
get_console().print(f"\n[info]Storage class for {cluster_name}\n")
result = run_command_with_k8s_env(
["kubectl", "get", "storageclass", "--cluster", kubectl_cluster_name],
python=python,
kubernetes_version=kubernetes_version,
check=False,
)
if result.returncode != 0:
return False
get_console().print(f"\n[info]Running pods for {cluster_name}\n")
result = run_command_with_k8s_env(
["kubectl", "get", "-n", "kube-system", "pods", "--cluster", kubectl_cluster_name],
python=python,
kubernetes_version=kubernetes_version,
check=False,
)
if result.returncode != 0:
return False
print_cluster_urls(python, kubernetes_version, wait_time_in_seconds=wait_time_in_seconds, output=None)
get_console().print(f"\n[success]Cluster healthy: {cluster_name}\n")
return True
@kubernetes_group.command(
name="status",
help="Check status of the current cluster and airflow deployed to it (optionally all clusters).",
)
@option_python
@option_kubernetes_version
@option_wait_time_in_seconds_0_default
@option_all
@option_verbose
@option_dry_run
def status(kubernetes_version: str, python: str, wait_time_in_seconds: int, all: bool):
result = create_virtualenv(force_venv_setup=False)
if result.returncode != 0:
sys.exit(result.returncode)
make_sure_kubernetes_tools_are_installed()
if all:
clusters = list(K8S_CLUSTERS_PATH.iterdir())
if clusters:
failed = False
get_console().print("[info]\nCluster status:\n")
for cluster_name in clusters:
name = cluster_name.name
found_python, found_kubernetes_version = _get_python_kubernetes_version_from_name(name)
if not found_python or not found_kubernetes_version:
get_console().print(f"[warning]\nCould not get cluster from {name}. Skipping.\n")
elif not _status(
python=found_python,
kubernetes_version=found_kubernetes_version,
wait_time_in_seconds=wait_time_in_seconds,
):
failed = True
if failed:
get_console().print("\n[error]Some clusters are not healthy!\n")
sys.exit(1)
else:
get_console().print("\n[warning]No clusters.\n")
sys.exit(1)
else:
if not _status(
python=python,
kubernetes_version=kubernetes_version,
wait_time_in_seconds=wait_time_in_seconds,
):
get_console().print("\n[error]The cluster is not healthy!\n")
sys.exit(1)
def check_if_base_image_exists(params: BuildProdParams) -> bool:
return check_if_image_exists(image=params.airflow_image_name_with_tag)
def _rebuild_k8s_image(
python: str,
image_tag: str,
rebuild_base_image: bool,
copy_local_sources: bool,
use_uv: bool,
output: Output | None,
) -> tuple[int, str]:
params = BuildProdParams(python=python, image_tag=image_tag, use_uv=use_uv)
if rebuild_base_image:
run_build_production_image(
prod_image_params=params,
param_description=f"Python: {params.python}, Platform: {params.platform}",
output=output,
)
else:
if not check_if_base_image_exists(params):
get_console(output=output).print(
f"[error]The base PROD image {params.airflow_image_name_with_tag} does not exist locally.\n"
)
if image_tag == "latest":
get_console(output=output).print(
"[warning]Please add `--rebuild-base-image` flag or rebuild it manually with:\n"
)
get_console(output=output).print(f"breeze prod-image build --python {python}\n")
else:
get_console(output=output).print("[warning]Please pull the image:\n")
get_console(output=output).print(
f"breeze prod-image pull --python {python} --image-tag {image_tag}\n"
)
sys.exit(1)
get_console(output=output).print(
f"[info]Building the K8S image for Python {python} using "
f"airflow base image: {params.airflow_image_name_with_tag}\n"
)
if copy_local_sources:
extra_copy_command = "COPY --chown=airflow:0 . /opt/airflow/"
else:
extra_copy_command = ""
docker_image_for_kubernetes_tests = f"""
FROM {params.airflow_image_name_with_tag}
USER airflow
{extra_copy_command}
COPY --chown=airflow:0 airflow/example_dags/ /opt/airflow/dags/
COPY --chown=airflow:0 airflow/providers/cncf/kubernetes/kubernetes_executor_templates/ /opt/airflow/pod_templates/
ENV GUNICORN_CMD_ARGS='--preload' AIRFLOW__WEBSERVER__WORKER_REFRESH_INTERVAL=0
"""
image = f"{params.airflow_image_kubernetes}:latest"
docker_build_result = run_command(
["docker", "build", "--tag", image, ".", "-f", "-"],
input=docker_image_for_kubernetes_tests,
text=True,
check=False,
output=output,
)
if docker_build_result.returncode != 0:
get_console(output=output).print("[error]Error when building the kubernetes image.")
return docker_build_result.returncode, f"K8S image for Python {python}"
def _upload_k8s_image(python: str, kubernetes_version: str, output: Output | None) -> tuple[int, str]:
params = BuildProdParams(python=python)
cluster_name = get_kind_cluster_name(python=python, kubernetes_version=kubernetes_version)
get_console(output=output).print(
f"[info]Uploading Airflow image {params.airflow_image_kubernetes} to cluster {cluster_name}"
)
kind_load_result = run_command_with_k8s_env(
["kind", "load", "docker-image", "--name", cluster_name, params.airflow_image_kubernetes],
python=python,
output=output,
kubernetes_version=kubernetes_version,
check=False,
)
if kind_load_result.returncode != 0:
get_console(output=output).print(
f"[error]Error when uploading {params.airflow_image_kubernetes} image to "
f"KinD cluster {cluster_name}."
)
return kind_load_result.returncode, f"Uploaded K8S image to {cluster_name}"
@kubernetes_group.command(
name="build-k8s-image",
help="Build k8s-ready airflow image (optionally all images in parallel).",
)
@option_answer
@option_copy_local_sources
@option_debug_resources
@option_dry_run
@option_image_tag
@option_include_success_outputs
@option_parallelism
@option_python
@option_python_versions
@option_rebuild_base_image
@option_run_in_parallel
@option_skip_cleanup
@option_use_uv
@option_verbose
def build_k8s_image(
copy_local_sources: bool,
debug_resources: bool,
image_tag: str,
include_success_outputs: bool,
parallelism: int,
python: str,
python_versions: str,
rebuild_base_image: bool,
run_in_parallel: bool,
skip_cleanup: bool,
use_uv: bool,
):
result = create_virtualenv(force_venv_setup=False)
if result.returncode != 0:
sys.exit(result.returncode)
make_sure_kubernetes_tools_are_installed()
if run_in_parallel:
python_version_array: list[str] = python_versions.split(" ")
with ci_group(f"Building K8s images for {python_versions}"):
with run_with_pool(
parallelism=parallelism,
all_params=[f"Image {python}" for python in python_version_array],
debug_resources=debug_resources,
progress_matcher=DockerBuildxProgressMatcher(),
) as (pool, outputs):
results = [
pool.apply_async(
_rebuild_k8s_image,
kwds={
"python": _python,
"image_tag": image_tag,
"rebuild_base_image": rebuild_base_image,
"copy local sources": copy_local_sources,
"use_uv": use_uv,
"output": outputs[index],
},
)
for index, _python in enumerate(python_version_array)
]
check_async_run_results(
results=results,
success="All K8S images built correctly.",
outputs=outputs,
skip_cleanup=skip_cleanup,
include_success_outputs=include_success_outputs,
)
else:
return_code, _ = _rebuild_k8s_image(
python=python,
image_tag=image_tag,
rebuild_base_image=rebuild_base_image,
copy_local_sources=copy_local_sources,
use_uv=use_uv,
output=None,
)
if return_code == 0:
get_console().print("\n[warning]NEXT STEP:[/][info] You might now upload your k8s image by:\n")
get_console().print("\nbreeze k8s upload-k8s-image\n")
sys.exit(return_code)
@kubernetes_group.command(
name="upload-k8s-image",
help="Upload k8s-ready airflow image to the KinD cluster (optionally to all clusters in parallel)",
)
@option_python
@option_kubernetes_version
@option_run_in_parallel
@option_parallelism
@option_skip_cleanup
@option_debug_resources
@option_include_success_outputs
@option_python_versions
@option_kubernetes_versions
@option_verbose
@option_dry_run
def upload_k8s_image(
python: str,
kubernetes_version: str,
run_in_parallel: bool,
parallelism: int,
skip_cleanup: bool,
debug_resources: bool,
include_success_outputs: bool,
python_versions: str,
kubernetes_versions: str,
):
result = create_virtualenv(force_venv_setup=False)
if result.returncode != 0:
sys.exit(result.returncode)
make_sure_kubernetes_tools_are_installed()
if run_in_parallel:
python_version_array: list[str] = python_versions.split(" ")
kubernetes_version_array: list[str] = kubernetes_versions.split(" ")
combo_titles, short_combo_titles, combos = get_kubernetes_python_combos(
kubernetes_version_array, python_version_array
)
with ci_group(f"Uploading K8s images for {short_combo_titles}"):
with run_with_pool(
parallelism=parallelism,
all_params=combo_titles,
debug_resources=debug_resources,
progress_matcher=GenericRegexpProgressMatcher(
regexp=K8S_UPLOAD_PROGRESS_REGEXP, lines_to_search=2
),
) as (pool, outputs):
results = [
pool.apply_async(
_upload_k8s_image,
kwds={
"python": combo.python_version,
"kubernetes_version": combo.kubernetes_version,
"output": outputs[index],
},
)
for index, combo in enumerate(combos)
]
check_async_run_results(
results=results,
success="All K8S images uploaded correctly.",
outputs=outputs,
skip_cleanup=skip_cleanup,
include_success_outputs=include_success_outputs,
)
else:
return_code, _ = _upload_k8s_image(
python=python,
kubernetes_version=kubernetes_version,
output=None,
)
if return_code == 0:
get_console().print("\n[warning]NEXT STEP:[/][info] You might now deploy airflow by:\n")
get_console().print("\nbreeze k8s deploy-airflow\n")
sys.exit(return_code)
HELM_DEFAULT_NAMESPACE = "default"
HELM_AIRFLOW_NAMESPACE = "airflow"
TEST_NAMESPACE = "test-namespace"
def _recreate_namespaces(
python: str,
kubernetes_version: str,
output: Output | None,
) -> RunCommandResult:
cluster_name = get_kubectl_cluster_name(python=python, kubernetes_version=kubernetes_version)
get_console(output=output).print(f"[info]Deleting K8S namespaces for {cluster_name}")
run_command_with_k8s_env(
["kubectl", "delete", "namespace", HELM_AIRFLOW_NAMESPACE],
python=python,
kubernetes_version=kubernetes_version,
output=output,
check=False,
)
run_command_with_k8s_env(
["kubectl", "delete", "namespace", TEST_NAMESPACE],
python=python,
kubernetes_version=kubernetes_version,
output=output,
check=False,
)
get_console(output=output).print("[info]Creating namespaces")
result = run_command_with_k8s_env(
["kubectl", "create", "namespace", HELM_AIRFLOW_NAMESPACE],
python=python,
kubernetes_version=kubernetes_version,
output=output,
check=False,
)
if result.returncode != 0:
return result
result = run_command_with_k8s_env(
["kubectl", "create", "namespace", TEST_NAMESPACE],
python=python,
kubernetes_version=kubernetes_version,
output=output,
check=False,
)
if result.returncode == 0:
get_console(output=output).print(f"[success]Created K8S namespaces for cluster {cluster_name}\n")
return result
def _deploy_test_resources(python: str, kubernetes_version: str, output: Output | None) -> RunCommandResult:
cluster_name = get_kubectl_cluster_name(python=python, kubernetes_version=kubernetes_version)
get_console(output=output).print(f"[info]Deploying test resources for cluster {cluster_name}")
result = run_command_with_k8s_env(
[
"kubectl",
"apply",
"-f",
str(SCRIPTS_CI_KUBERNETES_PATH / "volumes.yaml"),
"--namespace",
HELM_DEFAULT_NAMESPACE,
],
python=python,
kubernetes_version=kubernetes_version,
output=output,
check=False,
)
if result.returncode != 0:
return result
result = run_command_with_k8s_env(
[
"kubectl",
"apply",
"-f",
str(SCRIPTS_CI_KUBERNETES_PATH / "nodeport.yaml"),
"--namespace",
HELM_AIRFLOW_NAMESPACE,
],
python=python,
kubernetes_version=kubernetes_version,
output=output,
check=False,
)
if result.returncode == 0:
get_console(output=output).print(f"[success]Deployed test resources for cluster {cluster_name}")
return result
def _configure_k8s_cluster(python: str, kubernetes_version: str, output: Output | None) -> tuple[int, str]:
cluster_name = get_kind_cluster_name(python=python, kubernetes_version=kubernetes_version)
get_console(output=output).print(f"[info]Configuring {cluster_name} to be ready for Airflow deployment")
result = _recreate_namespaces(
python=python,
kubernetes_version=kubernetes_version,
output=output,
)
if result.returncode == 0:
result = _deploy_test_resources(
python=python,
kubernetes_version=kubernetes_version,
output=output,
)
return result.returncode, f"Configure {cluster_name}"
@kubernetes_group.command(
name="configure-cluster",
help="Configures cluster for airflow deployment - creates namespaces and test resources "
"(optionally for all clusters in parallel).",
)
@option_python
@option_kubernetes_version
@option_run_in_parallel
@option_parallelism_cluster
@option_skip_cleanup
@option_debug_resources
@option_include_success_outputs
@option_python_versions
@option_kubernetes_versions
@option_verbose
@option_dry_run
def configure_cluster(
python: str,
kubernetes_version: str,
run_in_parallel: bool,
parallelism: int,
skip_cleanup: bool,
debug_resources: bool,
include_success_outputs: bool,
python_versions: str,
kubernetes_versions: str,
):
result = create_virtualenv(force_venv_setup=False)
if result.returncode != 0:
sys.exit(result.returncode)
make_sure_kubernetes_tools_are_installed()
if run_in_parallel:
python_version_array: list[str] = python_versions.split(" ")
kubernetes_version_array: list[str] = kubernetes_versions.split(" ")
combo_titles, short_combo_titles, combos = get_kubernetes_python_combos(
kubernetes_version_array, python_version_array
)
with ci_group(f"Setting up clusters for {short_combo_titles}"):
with run_with_pool(
parallelism=parallelism,
all_params=combo_titles,
debug_resources=debug_resources,
progress_matcher=GenericRegexpProgressMatcher(
regexp=K8S_CONFIGURE_CLUSTER_PROGRESS_REGEXP, lines_to_search=10
),
) as (pool, outputs):
results = [
pool.apply_async(
_configure_k8s_cluster,
kwds={
"python": combo.python_version,
"kubernetes_version": combo.kubernetes_version,
"output": outputs[index],
},
)
for index, combo in enumerate(combos)
]
check_async_run_results(
results=results,
success="All clusters configured correctly.",
outputs=outputs,
skip_cleanup=skip_cleanup,
include_success_outputs=include_success_outputs,
)
else:
return_code, _ = _configure_k8s_cluster(
python=python,
kubernetes_version=kubernetes_version,
output=None,
)
if return_code == 0:
get_console().print("\n[warning]NEXT STEP:[/][info] You might now build your k8s image by:\n")
get_console().print("\nbreeze k8s build-k8s-image\n")
sys.exit(return_code)
def _deploy_helm_chart(
python: str,
upgrade: bool,
kubernetes_version: str,
output: Output | None,
executor: str,
use_standard_naming: bool,
extra_options: tuple[str, ...] | None = None,
multi_namespace_mode: bool = False,
) -> RunCommandResult:
cluster_name = get_kubectl_cluster_name(python=python, kubernetes_version=kubernetes_version)
action = "Deploying" if not upgrade else "Upgrading"
get_console(output=output).print(f"[info]{action} {cluster_name} with airflow Helm Chart.")
with tempfile.TemporaryDirectory(prefix="chart_") as tmp_dir:
tmp_chart_path = Path(tmp_dir).resolve() / "chart"
shutil.copytree(CHART_PATH, os.fspath(tmp_chart_path), ignore_dangling_symlinks=True)
get_console(output=output).print(f"[info]Copied chart sources to {tmp_chart_path}")
kubectl_context = get_kubectl_cluster_name(python=python, kubernetes_version=kubernetes_version)