-
Notifications
You must be signed in to change notification settings - Fork 135
/
bazelci.py
executable file
·4493 lines (3783 loc) · 161 KB
/
bazelci.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
#!/usr/bin/env python3
#
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed 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.
import argparse
import base64
import codecs
import collections
import concurrent.futures
import copy
import datetime
from glob import glob
import hashlib
import itertools
import json
import multiprocessing
import os
import os.path
import platform as platform_module
import random
import re
import requests
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.error
import urllib.request
import yaml
# Initialize the random number generator.
random.seed()
BUILDKITE_ORG = os.environ["BUILDKITE_ORGANIZATION_SLUG"]
THIS_IS_PRODUCTION = BUILDKITE_ORG == "bazel"
THIS_IS_TESTING = BUILDKITE_ORG == "bazel-testing"
THIS_IS_TRUSTED = BUILDKITE_ORG == "bazel-trusted"
THIS_IS_SPARTA = True
CLOUD_PROJECT = "bazel-public" if THIS_IS_TRUSTED else "bazel-untrusted"
GITHUB_BRANCH = {"bazel": "master", "bazel-trusted": "master", "bazel-testing": "testing"}[
BUILDKITE_ORG
]
SCRIPT_URL = "https://raw.githubusercontent.com/bazelbuild/continuous-integration/{}/buildkite/bazelci.py".format(
GITHUB_BRANCH
)
AGGREGATE_INCOMPATIBLE_TEST_RESULT_URL = "https://raw.githubusercontent.com/bazelbuild/continuous-integration/{}/buildkite/aggregate_incompatible_flags_test_result.py?{}".format(
GITHUB_BRANCH, int(time.time())
)
EMERGENCY_FILE_URL = "https://raw.githubusercontent.com/bazelbuild/continuous-integration/{}/buildkite/emergency.yml?{}".format(
GITHUB_BRANCH, int(time.time())
)
FLAKY_TESTS_BUCKET = {
"bazel-testing": "gs://bazel-testing-buildkite-stats/flaky-tests-bep/",
"bazel-trusted": "gs://bazel-buildkite-stats/flaky-tests-bep/",
"bazel": "gs://bazel-buildkite-stats/flaky-tests-bep/",
}[BUILDKITE_ORG]
KZIPS_BUCKET = {
"bazel-testing": "gs://bazel-kzips-testing/",
"bazel-trusted": "gs://bazel-kzips/",
"bazel": "gs://bazel-kzips/",
}[BUILDKITE_ORG]
# We don't collect logs in the trusted org
LOG_BUCKET = {
"bazel-testing": "https://storage.googleapis.com/bazel-testing-buildkite-artifacts",
"bazel-trusted": "",
"bazel": "https://storage.googleapis.com/bazel-untrusted-buildkite-artifacts",
}[BUILDKITE_ORG]
# Projects can opt out of receiving GitHub issues from --notify by adding `"do_not_notify": True` to their respective downstream entry.
DOWNSTREAM_PROJECTS_PRODUCTION = {
"Android Studio Plugin": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/android-studio.yml",
"pipeline_slug": "android-studio-plugin",
},
"Android Studio Plugin Google": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/android-studio.yml",
"pipeline_slug": "android-studio-plugin-google",
},
"Android Testing": {
"git_repository": "https://github.com/googlesamples/android-testing.git",
"file_config": "bazelci/buildkite-pipeline.yml",
"pipeline_slug": "android-testing",
"disabled_reason": "https://github.com/android/testing-samples/issues/417",
},
"Bazel": {
"git_repository": "https://github.com/bazelbuild/bazel.git",
"file_config": ".bazelci/postsubmit.yml",
"pipeline_slug": "bazel-bazel",
},
"Bazel Bench": {
"git_repository": "https://github.com/bazelbuild/bazel-bench.git",
"file_config": ".bazelci/postsubmit.yml",
"pipeline_slug": "bazel-bench",
},
"Bazel Examples": {
"git_repository": "https://github.com/bazelbuild/examples.git",
"pipeline_slug": "bazel-bazel-examples",
},
"Bazel Remote Cache": {
"git_repository": "https://github.com/buchgr/bazel-remote.git",
"pipeline_slug": "bazel-remote-cache",
},
"Bazel skylib": {
"git_repository": "https://github.com/bazelbuild/bazel-skylib.git",
"pipeline_slug": "bazel-skylib",
"owned_by_bazel": True,
},
"Bazel toolchains": {
"git_repository": "https://github.com/bazelbuild/bazel-toolchains.git",
"pipeline_slug": "bazel-toolchains",
},
"Bazelisk": {
"git_repository": "https://github.com/bazelbuild/bazelisk.git",
"file_config": ".bazelci/config.yml",
"pipeline_slug": "bazelisk",
},
"Buildfarm": {
"git_repository": "https://github.com/buildfarm/buildfarm.git",
"pipeline_slug": "buildfarm-farmer",
},
"Buildtools": {
"git_repository": "https://github.com/bazelbuild/buildtools.git",
"pipeline_slug": "buildtools",
},
"CLion Plugin": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/clion.yml",
"pipeline_slug": "clion-plugin",
},
"CLion Plugin Google": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/clion.yml",
"pipeline_slug": "clion-plugin-google",
},
"Cloud Robotics Core": {
"git_repository": "https://github.com/googlecloudrobotics/core.git",
"http_config": "https://raw.githubusercontent.com/bazelbuild/continuous-integration/master/pipelines/cloud-robotics.yml",
"pipeline_slug": "cloud-robotics-core",
},
"Flogger": {
"git_repository": "https://github.com/google/flogger.git",
"http_config": "https://raw.githubusercontent.com/bazelbuild/continuous-integration/master/pipelines/flogger.yml",
"pipeline_slug": "flogger",
},
"IntelliJ Plugin": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/intellij.yml",
"pipeline_slug": "intellij-plugin",
},
"IntelliJ Plugin Google": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/intellij.yml",
"pipeline_slug": "intellij-plugin-google",
},
"IntelliJ UE Plugin": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/intellij-ue.yml",
"pipeline_slug": "intellij-ue-plugin",
},
"IntelliJ UE Plugin Google": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/intellij-ue.yml",
"pipeline_slug": "intellij-ue-plugin-google",
},
"IntelliJ Plugin Aspect": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/aspect.yml",
"pipeline_slug": "intellij-plugin-aspect",
},
"IntelliJ Plugin Aspect Google": {
"git_repository": "https://github.com/bazelbuild/intellij.git",
"file_config": ".bazelci/aspect.yml",
"pipeline_slug": "intellij-plugin-aspect-google",
},
"Stardoc": {
"git_repository": "https://github.com/bazelbuild/stardoc.git",
"pipeline_slug": "stardoc",
"owned_by_bazel": True,
},
"TensorFlow": {
"git_repository": "https://github.com/tensorflow/tensorflow.git",
"http_config": "https://raw.githubusercontent.com/bazelbuild/continuous-integration/master/pipelines/tensorflow.yml",
"pipeline_slug": "tensorflow",
"disabled_reason": "https://github.com/tensorflow/tensorflow/issues/60508",
},
"rules_android": {
"git_repository": "https://github.com/bazelbuild/rules_android.git",
"pipeline_slug": "rules-android",
"owned_by_bazel": True,
},
"rules_android_ndk": {
"git_repository": "https://github.com/bazelbuild/rules_android_ndk.git",
"pipeline_slug": "rules-android-ndk",
"owned_by_bazel": True,
},
"rules_cc": {
"git_repository": "https://github.com/bazelbuild/rules_cc.git",
"pipeline_slug": "rules-cc",
"owned_by_bazel": True,
"disabled_reason": "https://github.com/bazelbuild/rules_cc/issues/190",
},
"rules_platform": {
"git_repository": "https://github.com/bazelbuild/rules_platform.git",
"pipeline_slug": "rules-platform",
"owned_by_bazel": True,
},
"rules_python": {
"git_repository": "https://github.com/bazelbuild/rules_python.git",
"pipeline_slug": "rules-python-python",
},
"rules_testing": {
"git_repository": "https://github.com/bazelbuild/rules_testing.git",
"pipeline_slug": "rules-testing",
"owned_by_bazel": True,
},
}
DOWNSTREAM_PROJECTS_TESTING = {
"Bazel": DOWNSTREAM_PROJECTS_PRODUCTION["Bazel"],
"Bazelisk": DOWNSTREAM_PROJECTS_PRODUCTION["Bazelisk"],
"rules_android": DOWNSTREAM_PROJECTS_PRODUCTION["rules_android"],
"rules_cc": DOWNSTREAM_PROJECTS_PRODUCTION["rules_cc"],
"rules_testing": DOWNSTREAM_PROJECTS_PRODUCTION["rules_testing"],
}
DOWNSTREAM_PROJECTS = {
"bazel-testing": DOWNSTREAM_PROJECTS_TESTING,
"bazel-trusted": {},
"bazel": DOWNSTREAM_PROJECTS_PRODUCTION,
}[BUILDKITE_ORG]
DOCKER_REGISTRY_PREFIX = {
"bazel-testing": "bazel-public/testing",
"bazel-trusted": "bazel-public",
"bazel": "bazel-public",
}[BUILDKITE_ORG]
# A map containing all supported platform names as keys, with the values being
# the platform name in a human readable format, and a the buildkite-agent's
# working directory.
PLATFORMS = {
"centos7": {
"name": "CentOS 7",
"emoji-name": ":centos: CentOS 7",
"publish_binary": ["ubuntu1404", "centos7", "linux"],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/centos7",
"python": "python3.6",
},
"centos7_java11": {
"name": "CentOS 7 (OpenJDK 11, gcc 4.8.5)",
"emoji-name": ":centos: CentOS 7 (OpenJDK 11, gcc 4.8.5)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/centos7-java11",
"python": "python3.6",
},
"centos7_java11_devtoolset10": {
"name": "CentOS 7 (OpenJDK 11, gcc 10.2.1)",
"emoji-name": ":centos: CentOS 7 (OpenJDK 11, gcc 10.2.1)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/centos7-java11-devtoolset10",
"python": "python3.6",
},
"debian10": {
"name": "Debian 10 Buster (OpenJDK 11, gcc 8.3.0)",
"emoji-name": ":debian: Debian 10 Buster (OpenJDK 11, gcc 8.3.0)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/debian10-java11",
"python": "python3.7",
},
"debian11": {
"name": "Debian 11 Bullseye (OpenJDK 17, gcc 10.2.1)",
"emoji-name": ":debian: Debian 11 Bullseye (OpenJDK 17, gcc 10.2.1)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/debian11-java17",
"python": "python3.9",
},
"ubuntu1604": {
"name": "Ubuntu 16.04 LTS (OpenJDK 8, gcc 5.4.0)",
"emoji-name": ":ubuntu: Ubuntu 16.04 LTS (OpenJDK 8, gcc 5.4.0)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu1604-java8",
"python": "python3.6",
},
"ubuntu1804": {
"name": "Ubuntu 18.04 LTS (OpenJDK 11, gcc 7.5.0)",
"emoji-name": ":ubuntu: Ubuntu 18.04 LTS (OpenJDK 11, gcc 7.5.0)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu1804-java11",
"python": "python3.6",
},
"ubuntu2004_java11": {
"name": "Ubuntu 20.04 LTS (OpenJDK 11, gcc 9.4.0)",
"emoji-name": ":ubuntu: Ubuntu 20.04 LTS (OpenJDK 11, gcc 9.4.0)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu2004-java11",
"python": "python3.8",
},
"ubuntu2004": {
"name": "Ubuntu 20.04 LTS",
"emoji-name": ":ubuntu: Ubuntu 20.04 LTS",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu2004",
"python": "python3.8",
},
"ubuntu2004_arm64": {
"name": "Ubuntu 20.04 LTS ARM64",
"emoji-name": ":ubuntu: Ubuntu 20.04 LTS ARM64",
"publish_binary": ["linux_arm64"],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu2004",
"python": "python3.8",
"queue": "arm64",
# TODO: Re-enable always-pull if we also publish docker containers for Linux ARM64
"always-pull": False,
},
"kythe_ubuntu2004": {
"name": "Kythe (Ubuntu 20.04 LTS)",
"emoji-name": "Kythe (:ubuntu: Ubuntu 20.04 LTS)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu2004-kythe",
"python": "python3.8",
},
"kythe_ubuntu2204": {
"name": "Kythe (Ubuntu 22.04 LTS)",
"emoji-name": "Kythe (:ubuntu: Ubuntu 22.04 LTS)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu2204-kythe",
"python": "python3",
},
"ubuntu2204_java17": {
"name": "Ubuntu 22.04 (OpenJDK 17, gcc 11.2.0)",
"emoji-name": ":ubuntu: Ubuntu 22.04 (OpenJDK 17, gcc 11.2.0)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu2204-java17",
"python": "python3",
},
"ubuntu2204": {
"name": "Ubuntu 22.04",
"emoji-name": ":ubuntu: Ubuntu 22.04 LTS",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu2204",
"python": "python3",
},
"ubuntu2404": {
"name": "Ubuntu 24.04",
"emoji-name": ":ubuntu: Ubuntu 24.04 LTS",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/ubuntu2404",
"python": "python3",
},
"fedora39": {
"name": "Fedora 39 (OpenJDK 17, gcc 13.1.1)",
"emoji-name": ":fedora: Fedora 39 (OpenJDK 17, gcc 13.1.1)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/fedora39-java17",
"python": "python3",
},
"fedora40": {
"name": "Fedora 40 (OpenJDK 21, gcc 14.1.1)",
"emoji-name": ":fedora: Fedora 40 (OpenJDK 21, gcc 14.1.1)",
"publish_binary": [],
"docker-image": f"gcr.io/{DOCKER_REGISTRY_PREFIX}/fedora40-java21",
"python": "python3",
},
"macos": {
"name": "macOS",
"emoji-name": ":darwin: macOS",
"publish_binary": ["macos"],
"queue": "macos",
"python": "python3",
},
"macos_arm64": {
"name": "macOS arm64",
"emoji-name": ":darwin: macOS arm64",
"publish_binary": ["macos_arm64"],
"queue": "macos_arm64",
"python": "python3",
},
"windows": {
"name": "Windows",
"emoji-name": ":windows: Windows",
"publish_binary": ["windows"],
"queue": "windows",
"python": "python.exe",
},
"windows_arm64": {
"name": "Windows ARM64",
"emoji-name": ":windows: Windows arm64",
"publish_binary": ["windows_arm64"],
# TODO(pcloudy): Switch to windows_arm64 queue when Windows ARM64 machines are available,
# current we just use x86_64 machines to do cross compile.
"queue": "windows",
"python": "python.exe",
},
}
# Generate rbe_ubuntu* platforms based on ubuntu* platforms.
for platform, platform_dict in PLATFORMS.copy().items():
if platform.startswith("ubuntu"):
rbe_platform_dict = copy.deepcopy(platform_dict)
rbe_platform_dict["name"] = "RBE {}".format(platform_dict["name"])
rbe_platform_dict["emoji-name"] = "RBE {}".format(platform_dict["emoji-name"])
rbe_platform_dict["publish_binary"] = []
PLATFORMS["rbe_{}".format(platform)] = rbe_platform_dict
BUILDIFIER_DOCKER_IMAGE = "gcr.io/bazel-public/buildifier"
# The platform used for various steps (e.g. stuff that formerly ran on the "pipeline" workers).
DEFAULT_PLATFORM = "ubuntu1804"
# In order to test that "the one Linux binary" that we build for our official releases actually
# works on all Linux distributions that we test on, we use the Linux binary built on our official
# release platform for all Linux downstream tests.
LINUX_BINARY_PLATFORM = "centos7"
XCODE_VERSION_REGEX = re.compile(r"^\d+\.\d+(\.\d+)?$")
XCODE_VERSION_OVERRIDES = {"10.2.1": "10.3", "11.2": "11.2.1", "11.3": "11.3.1"}
BUILD_LABEL_PATTERN = re.compile(r"^Build label: (\S+)$", re.MULTILINE)
SKIP_TASKS_ENV_VAR = "CI_SKIP_TASKS"
RUNNER_CMD = "bazelci.py runner"
# TODO: change to USE_BAZEL_DIFF once the feature has been tested in QA
USE_BAZEL_DIFF_ENV_VAR = "USE_BAZEL_DIFF"
BAZEL_DIFF_ANNOTATION_CTX = "'diff'"
# TODO(fweikert): Install bazel-diff on the Docker images and on the Mac machines
BAZEL_DIFF_URL = (
"https://github.com/Tinder/bazel-diff/releases/download/8.1.1/bazel-diff_deploy.jar"
)
AUTO_DIFFBASE_VALUES = frozenset(["1", "true", "auto"])
# Always run all test targets if any of the paths here are modified by the current commit.
# Values can be directory paths (with a trailing slash) or file paths.
DISABLE_BAZEL_DIFF_IF_MODIFIED = (".bazelci/", ".bazelversion", "MODULE.bazel", "repositories.bzl")
COMMIT_RE = re.compile(r"[0-9a-z]{40}")
CONFIG_FILE_EXTENSIONS = {".yml", ".yaml"}
KYTHE_DIR = "/usr/local/kythe"
INDEX_UPLOAD_POLICY_ALWAYS = "Always"
INDEX_UPLOAD_POLICY_IF_BUILD_SUCCESS = "IfBuildSuccess"
INDEX_UPLOAD_POLICY_NEVER = "Never"
ESCAPED_BACKSLASH = "%5C"
# The maximum number of tasks allowed in one pipeline yaml config file.
# This is to prevent accidentally creating too many tasks with the martix testing feature.
MAX_TASK_NUMBER = 80
_TEST_BEP_FILE = "test_bep.json"
_SHARD_RE = re.compile(r"(.+) \(shard (\d+)\)")
_SLOWEST_N_TARGETS = 20
class BuildkiteException(Exception):
"""
Raised whenever something goes wrong and we should exit with an error.
"""
pass
class BuildkiteInfraException(Exception):
"""
Raised whenever something goes wrong with the CI infra and we should immediately exit with an error.
"""
pass
class BinaryUploadRaceException(Exception):
"""
Raised when try_publish_binaries wasn't able to publish a set of binaries,
because the generation of the current file didn't match the expected value.
"""
pass
class BuildkiteClient(object):
_ENCRYPTED_BUILDKITE_UNTRUSTED_API_TOKEN = """
CiQA4DEB9ldzC+E39KomywtqXfaQ86hhulgeDsicds2BuvbCYzsSUAAqwcvXZPh9IMWlwWh94J2F
exosKKaWB0tSRJiPKnv2NPDfEqGul0ZwVjtWeASpugwxxKeLhFhPMcgHMPfndH6j2GEIY6nkKRbP
uwoRMCwe
""".strip()
_ENCRYPTED_BUILDKITE_TESTING_API_TOKEN = """
CiQAMTBkWjL1C+F5oon3+cC1vmum5+c1y5+96WQY44p0Lxd0PeASUQAy7iU0c6E3W5EOSFYfD5fA
MWy/SHaMno1NQSUa4xDOl5yc2kizrtxPPVkX4x9pLNuGUY/xwAn2n1DdiUdWZNWlY1bX2C4ex65e
P9w8kNhEbw==
""".strip()
_ENCRYPTED_BUILDKITE_TRUSTED_API_TOKEN = """
CiQAeiOS8AkJ92+STSUmqW/jlR9DKDZdX5PZIWn30PtyKXWE/74SVwC7bbymSHneleAcgXtVJsMu
2DEEVd/uEGIdiEJigmPAPTs4vtmX/7ZxTsMhJ+rxRYBGufw9LgT+G6Bjg0ETifavKWHGzw+NTgUa
gwD6RBL0qz1PFfg7Zw==
""".strip()
_BUILD_STATUS_URL_TEMPLATE = (
"https://api.buildkite.com/v2/organizations/{}/pipelines/{}/builds/{}"
)
_NEW_BUILD_URL_TEMPLATE = "https://api.buildkite.com/v2/organizations/{}/pipelines/{}/builds"
_RETRY_JOB_URL_TEMPLATE = (
"https://api.buildkite.com/v2/organizations/{}/pipelines/{}/builds/{}/jobs/{}/retry"
)
_PIPELINE_INFO_URL_TEMPLATE = "https://api.buildkite.com/v2/organizations/{}/pipelines/{}"
def __init__(self, org, pipeline):
self._org = org
self._pipeline = pipeline
self._token = self._get_buildkite_token()
def _get_buildkite_token(self):
return decrypt_token(
encrypted_token=(
self._ENCRYPTED_BUILDKITE_TRUSTED_API_TOKEN
if THIS_IS_TRUSTED
else self._ENCRYPTED_BUILDKITE_TESTING_API_TOKEN
if THIS_IS_TESTING
else self._ENCRYPTED_BUILDKITE_UNTRUSTED_API_TOKEN
),
kms_key=(
"buildkite-trusted-api-token"
if THIS_IS_TRUSTED
else "buildkite-testing-api-token"
if THIS_IS_TESTING
else "buildkite-untrusted-api-token"
),
project=("bazel-public" if THIS_IS_TRUSTED else "bazel-untrusted"),
)
def _open_url(self, url, params=[], retries=5):
params_str = "".join("&{}={}".format(k, v) for k, v in params)
full_url = "{}?access_token={}{}".format(url, self._token, params_str)
for attempt in range(retries):
try:
response = urllib.request.urlopen(full_url)
return response.read().decode("utf-8", "ignore")
except urllib.error.HTTPError as ex:
# Handle specific error codes
if ex.code == 429: # Too Many Requests
retry_after = ex.headers.get("RateLimit-Reset")
if retry_after:
wait_time = int(retry_after)
else:
wait_time = (2 ** attempt) # Exponential backoff if no RateLimit-Reset header
time.sleep(wait_time)
else:
raise BuildkiteException("Failed to open {}: {} - {}".format(url, ex.code, ex.reason))
raise BuildkiteException(f"Failed to open {url} after {retries} retries.")
def get_pipeline_info(self):
"""Get details for a pipeline given its organization slug
and pipeline slug.
See https://buildkite.com/docs/apis/rest-api/pipelines#get-a-pipeline
Returns
-------
dict
the metadata for the pipeline
"""
url = self._PIPELINE_INFO_URL_TEMPLATE.format(self._org, self._pipeline)
output = self._open_url(url)
return json.loads(output)
def get_build_info(self, build_number):
"""Get build info for a pipeline with a given build number
See https://buildkite.com/docs/apis/rest-api/builds#get-a-build
Parameters
----------
build_number : the build number
Returns
-------
dict
the metadata for the build
"""
url = self._BUILD_STATUS_URL_TEMPLATE.format(self._org, self._pipeline, build_number)
output = self._open_url(url)
return json.loads(output)
def get_build_info_list(self, params):
"""Get a list of build infos for this pipeline
See https://buildkite.com/docs/apis/rest-api/builds#list-builds-for-a-pipeline
Parameters
----------
params : the parameters to filter the result
Returns
-------
list of dict
the metadata for a list of builds
"""
url = self._BUILD_STATUS_URL_TEMPLATE.format(self._org, self._pipeline, "")
output = self._open_url(url, params)
return json.loads(output)
def get_build_log(self, job):
return self._open_url(job["raw_log_url"])
@staticmethod
def _check_response(response, expected_status_code):
if response.status_code != expected_status_code:
eprint("Exit code:", response.status_code)
eprint("Response:\n", response.text)
response.raise_for_status()
def trigger_new_build(self, commit, message=None, env={}):
"""Trigger a new build at a given commit and return the build metadata.
See https://buildkite.com/docs/apis/rest-api/builds#create-a-build
Parameters
----------
commit : the commit we want to build at
message : the message we should as the build titile
env : (optional) the environment variables to set
Returns
-------
dict
the metadata for the build
"""
pipeline_info = self.get_pipeline_info()
if not pipeline_info:
raise BuildkiteException(f"Cannot find pipeline info for pipeline {self._pipeline}.")
url = self._NEW_BUILD_URL_TEMPLATE.format(self._org, self._pipeline)
data = {
"commit": commit,
"branch": pipeline_info.get("default_branch") or "master",
"message": message if message else f"Trigger build at {commit}",
"env": env,
"ignore_pipeline_branch_filters": "true",
}
response = requests.post(url + "?access_token=" + self._token, json=data)
BuildkiteClient._check_response(response, requests.codes.created)
return json.loads(response.text)
def trigger_job_retry(self, build_number, job_id):
"""Trigger a job retry and return the job metadata.
See https://buildkite.com/docs/apis/rest-api/jobs#retry-a-job
Parameters
----------
build_number : the number of the build we want to retry
job_id : the id of the job we want to retry
Returns
-------
dict
the metadata for the job
"""
url = self._RETRY_JOB_URL_TEMPLATE.format(self._org, self._pipeline, build_number, job_id)
response = requests.put(url + "?access_token=" + self._token)
BuildkiteClient._check_response(response, requests.codes.ok)
return json.loads(response.text)
def wait_job_to_finish(self, build_number, job_id, interval_time=30, logger=None):
"""Wait a job to finish and return the job metadata
Parameters
----------
build_number : the number of the build we want to wait
job_id : the id of the job we want to wait
interval_time : (optional) the interval time to check the build status, default to 30s
logger : (optional) a logger to report progress
Returns
-------
dict
the latest metadata for the job
"""
t = 0
build_info = self.get_build_info(build_number)
while True:
for job in build_info["jobs"]:
if job["id"] == job_id:
state = job["state"]
if state != "scheduled" and state != "running" and state != "assigned":
return job
break
else:
raise BuildkiteException(
f"job id {job_id} doesn't exist in build " + build_info["web_url"]
)
url = build_info["web_url"]
if logger:
logger.log(f"Waiting for {url}, waited {t} seconds...")
time.sleep(interval_time)
t += interval_time
build_info = self.get_build_info(build_number)
def wait_build_to_finish(self, build_number, interval_time=30, logger=None):
"""Wait a build to finish and return the build metadata
Parameters
----------
build_number : the number of the build we want to wait
interval_time : (optional) the interval time to check the build status, default to 30s
logger : (optional) a logger to report progress
Returns
-------
dict
the latest metadata for the build
"""
t = 0
build_info = self.get_build_info(build_number)
while build_info["state"] == "scheduled" or build_info["state"] == "running":
url = build_info["web_url"]
if logger:
logger.log(f"Waiting for {url}, waited {t} seconds...")
time.sleep(interval_time)
t += interval_time
build_info = self.get_build_info(build_number)
return build_info
def decrypt_token(encrypted_token, kms_key, project="bazel-untrusted"):
try:
result = subprocess.run(
[
gcloud_command(),
"kms",
"decrypt",
"--project",
project,
"--location",
"global",
"--keyring",
"buildkite",
"--key",
kms_key,
"--ciphertext-file",
"-",
"--plaintext-file",
"-",
],
input=base64.b64decode(encrypted_token),
env=os.environ,
check=True,
stdout=subprocess.PIPE, # We cannot use capture_output since some workers run Python <3.7
stderr=subprocess.PIPE, # We cannot use capture_output since some workers run Python <3.7
)
return result.stdout.decode("utf-8").strip()
except subprocess.CalledProcessError as ex:
cause = ex.stderr.decode("utf-8")
raise BuildkiteException(f"Failed to decrypt token:\n{cause}")
def eprint(*args, **kwargs):
"""
Print to stderr and flush (just in case).
"""
print(*args, flush=True, file=sys.stderr, **kwargs)
def is_windows():
return os.name == "nt"
def is_mac():
return platform_module.system() == "Darwin"
def gsutil_command():
return "gsutil.cmd" if is_windows() else "gsutil"
def gcloud_command():
return "gcloud.cmd" if is_windows() else "gcloud"
def match_matrix_attr_pattern(s):
return re.match("^\${{\s*(\w+)\s*}}$", s)
def get_matrix_attributes(task):
"""Get unexpanded matrix attributes from the given task.
If a value of field matches "${{<name>}}", then <name> is a wanted matrix attribute.
eg. platform: ${{ platform }}
"""
attributes = []
for key, value in task.items():
if type(value) is str:
res = match_matrix_attr_pattern(value)
if res:
attributes.append(res.groups()[0])
return list(set(attributes))
def get_combinations(matrix, attributes):
"""Given a matrix and the wanted attributes, return all possible combinations.
eg.
With matrix = {'a': [1, 2], 'b': [1], 'c': [1]},
if attributes = ['a', 'b'], then returns [[('a', 1), ('b', 1)], [('a', 2), ('b', 1)]]
if attributes = ['b', 'c'], then returns [[('b', 1), ('c', 1)]]
if attributes = ['c'], then returns [[('c', 1)]]
"""
# Sort the attributes to make the output deterministic.
attributes.sort()
for attr in attributes:
if attr not in matrix:
raise BuildkiteException("${{ %s }} is not defined in `matrix` section." % attr)
pairs = [[(attr, value) for value in matrix[attr]] for attr in attributes]
return sorted(itertools.product(*pairs))
def get_expanded_task(task, combination):
"""Expand a task with the given combination of values of attributes."""
combination = dict(combination)
expanded_task = copy.deepcopy(task)
for key, value in task.items():
if type(value) is str:
res = match_matrix_attr_pattern(value)
if res:
attr = res.groups()[0]
expanded_task[key] = combination[attr]
return expanded_task
def fetch_configs(http_url, file_config, bazel_version=None):
"""
If specified fetches the build configuration from file_config or http_url, else tries to
read it from .bazelci/presubmit.yml.
Returns the json configuration as a python data structure.
"""
if file_config is not None and http_url is not None:
raise BuildkiteException("file_config and http_url cannot be set at the same time")
return load_config(http_url, file_config, bazel_version=bazel_version)
def expand_task_config(config):
# Expand tasks that uses attributes defined in the matrix section.
# The original task definition expands to multiple tasks for each possible combination.
tasks_to_expand = []
expanded_tasks = {}
matrix = config.pop("matrix", {})
for key, value in matrix.items():
if type(key) is not str or type(value) is not list:
raise BuildkiteException("Expect `matrix` is a map of str -> list")
for task in config["tasks"]:
attributes = get_matrix_attributes(config["tasks"][task])
if attributes:
tasks_to_expand.append(task)
count = 1
for combination in get_combinations(matrix, attributes):
expanded_task_name = "%s_config_%.2d" % (task, count)
count += 1
expanded_tasks[expanded_task_name] = get_expanded_task(
config["tasks"][task], combination
)
for task in tasks_to_expand:
config["tasks"].pop(task)
config["tasks"].update(expanded_tasks)
def maybe_overwrite_bazel_version(bazel_version, config):
if not bazel_version:
return
for task in config.get("tasks", {}):
config["tasks"][task]["old_bazel"] = config["tasks"][task].get("bazel")
config["tasks"][task]["bazel"] = bazel_version
matrix = config.get("matrix", {})
if "bazel" in matrix:
# This will only apply to "old_bazel" and avoid generating multiple tasks with the same config
matrix["bazel"] = [", ".join(matrix["bazel"])]
def load_config(http_url, file_config, allow_imports=True, bazel_version=None):
if http_url:
config = load_remote_yaml_file(http_url)
else:
file_config = file_config or ".bazelci/presubmit.yml"
with open(file_config, "r") as fd:
config = yaml.safe_load(fd)
# Legacy mode means that there is exactly one task per platform (e.g. ubuntu1604_nojdk),
# which means that we can get away with using the platform name as task ID.
# No other updates are needed since get_platform_for_task() falls back to using the
# task ID as platform if there is no explicit "platforms" field.
if "platforms" in config:
config["tasks"] = config.pop("platforms")
if "tasks" not in config:
config["tasks"] = {}
maybe_overwrite_bazel_version(bazel_version, config)
expand_task_config(config)
imports = config.pop("imports", None)
if imports:
if not allow_imports:
raise BuildkiteException("Nested imports are not allowed")
for i in imports:
imported_tasks = load_imported_tasks(i, http_url, file_config, bazel_version)
config["tasks"].update(imported_tasks)
if len(config["tasks"]) > MAX_TASK_NUMBER:
raise BuildkiteException(
"The number of tasks in one config file is limited to %s!" % MAX_TASK_NUMBER
)
return config
def load_remote_yaml_file(http_url):
with urllib.request.urlopen(http_url) as resp:
reader = codecs.getreader("utf-8")
return yaml.safe_load(reader(resp))
def load_imported_tasks(import_name, http_url, file_config, bazel_version):
if "/" in import_name:
raise BuildkiteException("Invalid import '%s'" % import_name)
old_path = http_url or file_config
new_path = "%s%s" % (old_path[: old_path.rfind("/") + 1], import_name)
if http_url:
http_url = new_path
else:
file_config = new_path
imported_config = load_config(http_url=http_url, file_config=file_config, allow_imports=False, bazel_version=bazel_version)
namespace = import_name.partition(".")[0]
tasks = {}
for task_name, task_config in imported_config["tasks"].items():
fix_imported_task_platform(task_name, task_config)
fix_imported_task_name(namespace, task_config)
fix_imported_task_working_directory(namespace, task_config)
tasks["%s_%s" % (namespace, task_name)] = task_config
return tasks
def fix_imported_task_platform(task_name, task_config):
if "platform" not in task_config:
task_config["platform"] = task_name
def fix_imported_task_name(namespace, task_config):
old_name = task_config.get("name")
task_config["name"] = "%s (%s)" % (namespace, old_name) if old_name else namespace
def fix_imported_task_working_directory(namespace, task_config):
old_dir = task_config.get("working_directory")
task_config["working_directory"] = os.path.join(namespace, old_dir) if old_dir else namespace
def print_collapsed_group(name):
eprint("\n\n--- {0}\n\n".format(name))