-
Notifications
You must be signed in to change notification settings - Fork 14k
/
build.gradle
3843 lines (3242 loc) · 117 KB
/
build.gradle
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.
import org.ajoberstar.grgit.Grgit
import org.gradle.api.JavaVersion
import java.nio.charset.StandardCharsets
buildscript {
repositories {
mavenCentral()
}
apply from: "$rootDir/gradle/dependencies.gradle"
dependencies {
// For Apache Rat plugin to ignore non-Git files
classpath "org.ajoberstar.grgit:grgit-core:$versions.grgit"
}
}
plugins {
id 'com.github.ben-manes.versions' version '0.48.0'
id 'idea'
id 'jacoco'
id 'java-library'
id 'org.owasp.dependencycheck' version '8.2.1'
id 'org.nosphere.apache.rat' version "0.8.1"
id "io.swagger.core.v3.swagger-gradle-plugin" version "${swaggerVersion}"
id "com.github.spotbugs" version '6.0.25' apply false
id 'org.scoverage' version '8.0.3' apply false
id 'io.github.goooler.shadow' version '8.1.3' apply false
id 'com.diffplug.spotless' version "6.25.0"
}
ext {
gradleVersion = versions.gradle
minJavaVersion = 11
buildVersionFileName = "kafka-version.properties"
defaultMaxHeapSize = "2g"
defaultJvmArgs = ["-Xss4m", "-XX:+UseParallelGC"]
// "JEP 403: Strongly Encapsulate JDK Internals" causes some tests to fail when they try
// to access internals (often via mocking libraries). We use `--add-opens` as a workaround
// for now and we'll fix it properly (where possible) via KAFKA-13275.
if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_16))
defaultJvmArgs.addAll(
"--add-opens=java.base/java.io=ALL-UNNAMED",
"--add-opens=java.base/java.lang=ALL-UNNAMED",
"--add-opens=java.base/java.nio=ALL-UNNAMED",
"--add-opens=java.base/java.nio.file=ALL-UNNAMED",
"--add-opens=java.base/java.util=ALL-UNNAMED",
"--add-opens=java.base/java.util.concurrent=ALL-UNNAMED",
"--add-opens=java.base/java.util.regex=ALL-UNNAMED",
"--add-opens=java.base/java.util.stream=ALL-UNNAMED",
"--add-opens=java.base/java.text=ALL-UNNAMED",
"--add-opens=java.base/java.time=ALL-UNNAMED",
"--add-opens=java.security.jgss/sun.security.krb5=ALL-UNNAMED"
)
maxTestForks = project.hasProperty('maxParallelForks') ? maxParallelForks.toInteger() : Runtime.runtime.availableProcessors()
maxScalacThreads = project.hasProperty('maxScalacThreads') ? maxScalacThreads.toInteger() :
Math.min(Runtime.runtime.availableProcessors(), 8)
userIgnoreFailures = project.hasProperty('ignoreFailures') ? ignoreFailures.toBoolean() : false
userMaxTestRetries = project.hasProperty('maxTestRetries') ? maxTestRetries.toInteger() : 0
userMaxTestRetryFailures = project.hasProperty('maxTestRetryFailures') ? maxTestRetryFailures.toInteger() : 0
userMaxQuarantineTestRetries = project.hasProperty('maxQuarantineTestRetries') ? maxQuarantineTestRetries.toInteger() : 0
userMaxQuarantineTestRetryFailures = project.hasProperty('maxQuarantineTestRetryFailures') ? maxQuarantineTestRetryFailures.toInteger() : 0
skipSigning = project.hasProperty('skipSigning') && skipSigning.toBoolean()
shouldSign = !skipSigning && !version.endsWith("SNAPSHOT")
mavenUrl = project.hasProperty('mavenUrl') ? project.mavenUrl : ''
mavenUsername = project.hasProperty('mavenUsername') ? project.mavenUsername : ''
mavenPassword = project.hasProperty('mavenPassword') ? project.mavenPassword : ''
userShowStandardStreams = project.hasProperty("showStandardStreams") ? showStandardStreams : null
userTestLoggingEvents = project.hasProperty("testLoggingEvents") ? Arrays.asList(testLoggingEvents.split(",")) : null
userEnableTestCoverage = project.hasProperty("enableTestCoverage") ? enableTestCoverage : false
userKeepAliveModeString = project.hasProperty("keepAliveMode") ? keepAliveMode : "daemon"
userKeepAliveMode = KeepAliveMode.values().find(m -> m.name().toLowerCase().equals(userKeepAliveModeString))
if (userKeepAliveMode == null) {
def keepAliveValues = KeepAliveMode.values().collect(m -> m.name.toLowerCase())
throw new GradleException("Unexpected value for keepAliveMode property. Expected one of $keepAliveValues, but received: $userKeepAliveModeString")
}
// See README.md for details on this option and the reasoning for the default
userScalaOptimizerMode = project.hasProperty("scalaOptimizerMode") ? scalaOptimizerMode : "inline-kafka"
def scalaOptimizerValues = ["none", "method", "inline-kafka", "inline-scala"]
if (!scalaOptimizerValues.contains(userScalaOptimizerMode))
throw new GradleException("Unexpected value for scalaOptimizerMode property. Expected one of $scalaOptimizerValues, but received: $userScalaOptimizerMode")
generatedDocsDir = new File("${project.rootDir}/docs/generated")
repo = file("$rootDir/.git").isDirectory() ? Grgit.open(currentDir: project.getRootDir()) : null
commitId = determineCommitId()
configureJavaCompiler = { name, options ->
// -parameters generates arguments with parameter names in TestInfo#getDisplayName.
// ref: https://github.com/junit-team/junit5/blob/4c0dddad1b96d4a20e92a2cd583954643ac56ac0/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTest.java#L161-L164
if (name == "compileTestJava" || name == "compileTestScala") {
options.compilerArgs << "-parameters"
options.compilerArgs += ["--release", String.valueOf(minJavaVersion)]
} else if (name == "compileJava" || name == "compileScala") {
options.compilerArgs << "-Xlint:all"
if (!project.path.startsWith(":connect") && !project.path.startsWith(":storage"))
options.compilerArgs << "-Xlint:-rawtypes"
options.compilerArgs << "-encoding" << "UTF-8"
options.compilerArgs << "-Xlint:-rawtypes"
options.compilerArgs << "-Xlint:-serial"
options.compilerArgs << "-Xlint:-try"
options.compilerArgs << "-Werror"
options.compilerArgs += ["--release", String.valueOf(minJavaVersion)]
}
}
runtimeTestLibs = [
libs.slf4jReload4j,
libs.junitPlatformLanucher,
project(":test-common:test-common-runtime")
]
}
allprojects {
repositories {
mavenCentral()
}
dependencyUpdates {
revision="release"
resolutionStrategy {
componentSelection { rules ->
rules.all { ComponentSelection selection ->
boolean rejected = ['snap', 'alpha', 'beta', 'rc', 'cr', 'm'].any { qualifier ->
selection.candidate.version ==~ /(?i).*[.-]${qualifier}[.\d-]*/
}
if (rejected) {
selection.reject('Release candidate')
}
}
}
}
}
configurations.all {
// zinc is the Scala incremental compiler, it has a configuration for its own dependencies
// that are unrelated to the project dependencies, we should not change them
if (name != "zinc") {
resolutionStrategy {
force(
// be explicit about the javassist dependency version instead of relying on the transitive version
libs.javassist,
// ensure we have a single version in the classpath despite transitive dependencies
libs.scalaLibrary,
libs.scalaReflect,
libs.jacksonAnnotations,
// be explicit about the Netty dependency version instead of relying on the version set by
// ZooKeeper (potentially older and containing CVEs)
libs.nettyHandler,
libs.nettyTransportNativeEpoll,
// be explicit about the reload4j version instead of relying on the transitive versions
libs.reload4j
)
}
}
}
task printAllDependencies(type: DependencyReportTask) {}
tasks.withType(Javadoc) {
options.charSet = 'UTF-8'
options.docEncoding = 'UTF-8'
options.encoding = 'UTF-8'
options.memberLevel = JavadocMemberLevel.PUBLIC // Document only public members/API
// Turn off doclint for now, see https://blog.joda.org/2014/02/turning-off-doclint-in-jdk-8-javadoc.html for rationale
options.addStringOption('Xdoclint:none', '-quiet')
// Javadoc warnings should fail the build in JDK 15+ https://bugs.openjdk.org/browse/JDK-8200363
options.addBooleanOption('Werror', JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_15))
options.links "https://docs.oracle.com/en/java/javase/${JavaVersion.current().majorVersion}/docs/api/"
}
clean {
delete "${projectDir}/src/generated"
delete "${projectDir}/src/generated-test"
}
}
def determineCommitId() {
def takeFromHash = 16
if (project.hasProperty('commitId')) {
commitId.take(takeFromHash)
} else if (repo != null) {
repo.head().id.take(takeFromHash)
} else {
"unknown"
}
}
/**
* For a given Project, compute a nice dash separated directory name
* to store the JUnit XML files in. E.g., Project ":connect:api" -> "connect-api"
*/
static def projectToJUnitXmlPath(project) {
var p = project
var projectNames = []
while (p != null) {
projectNames.push(p.name)
p = p.parent
if (p.name == "kafka") {
break;
}
}
return projectNames.join("/")
}
apply from: file('wrapper.gradle')
if (repo != null) {
rat {
dependsOn subprojects.collect {
it.tasks.matching {
it.name == "processMessages" || it.name == "processTestMessages"
}
}
verbose.set(true)
reportDir.set(project.file('build/rat'))
stylesheet.set(file('gradle/resources/rat-output-to-html.xsl'))
// Exclude everything under the directory that git should be ignoring via .gitignore or that isn't checked in. These
// restrict us only to files that are checked in or are staged.
excludes = new ArrayList<String>(repo.clean(ignore: false, directories: true, dryRun: true))
// And some of the files that we have checked in should also be excluded from this check
excludes.addAll([
'**/.git/**',
'**/build/**',
'CONTRIBUTING.md',
'PULL_REQUEST_TEMPLATE.md',
'gradlew',
'gradlew.bat',
'gradle/wrapper/gradle-wrapper.properties',
'trogdor/README.md',
'**/README.md',
'**/id_rsa',
'**/id_rsa.pub',
'checkstyle/suppressions.xml',
'streams/quickstart/java/src/test/resources/projects/basic/goal.txt',
'streams/streams-scala/logs/*',
'licenses/*',
'**/generated/**',
'clients/src/test/resources/serializedData/*',
'docker/test/fixtures/secrets/*',
'docker/examples/fixtures/secrets/*',
'docker/docker_official_images/.gitkeep'
])
}
} else {
rat.enabled = false
}
println("Starting build with version $version (commit id ${commitId == null ? "null" : commitId.take(8)}) using Gradle $gradleVersion, Java ${JavaVersion.current()} and Scala ${versions.scala}")
println("Build properties: ignoreFailures=$userIgnoreFailures, maxParallelForks=$maxTestForks, maxScalacThreads=$maxScalacThreads, maxTestRetries=$userMaxTestRetries")
subprojects {
// enable running :dependencies task recursively on all subprojects
// eg: ./gradlew allDeps
task allDeps(type: DependencyReportTask) {}
// enable running :dependencyInsight task recursively on all subprojects
// eg: ./gradlew allDepInsight --configuration runtime --dependency com.fasterxml.jackson.core:jackson-databind
task allDepInsight(type: DependencyInsightReportTask) {showingAllVariants = false} doLast {}
apply plugin: 'java-library'
apply plugin: 'checkstyle'
apply plugin: "com.github.spotbugs"
// We use the shadow plugin for the jmh-benchmarks module and the `-all` jar can get pretty large, so
// don't publish it
def shouldPublish = !project.name.equals('jmh-benchmarks')
def shouldPublishWithShadow = (['clients'].contains(project.name))
if (shouldPublish) {
apply plugin: 'maven-publish'
apply plugin: 'signing'
// Add aliases for the task names used by the maven plugin for backwards compatibility
// The maven plugin was replaced by the maven-publish plugin in Gradle 7.0
tasks.register('install').configure { dependsOn(publishToMavenLocal) }
tasks.register('uploadArchives').configure { dependsOn(publish) }
}
// apply the eclipse plugin only to subprojects that hold code. 'connect' is just a folder.
if (!project.name.equals('connect')) {
apply plugin: 'eclipse'
fineTuneEclipseClasspathFile(eclipse, project)
}
java {
consistentResolution {
// resolve the compileClasspath and then "inject" the result of resolution as strict constraints into the runtimeClasspath
useCompileClasspathVersions()
}
}
tasks.withType(JavaCompile) {
configureJavaCompiler(name, options)
}
if (shouldPublish) {
publishing {
repositories {
// To test locally, invoke gradlew with `-PmavenUrl=file:///some/local/path`
maven {
url = mavenUrl
credentials {
username = mavenUsername
password = mavenPassword
}
}
}
publications {
mavenJava(MavenPublication) {
if (!shouldPublishWithShadow) {
from components.java
} else {
apply plugin: 'io.github.goooler.shadow'
project.shadow.component(mavenJava)
// Fix for avoiding inclusion of runtime dependencies marked as 'shadow' in MANIFEST Class-Path.
// https://github.com/johnrengelman/shadow/issues/324
afterEvaluate {
pom.withXml { xml ->
if (xml.asNode().get('dependencies') == null) {
xml.asNode().appendNode('dependencies')
}
def dependenciesNode = xml.asNode().get('dependencies').get(0)
project.configurations.shadowed.allDependencies.each {
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', it.group)
dependencyNode.appendNode('artifactId', it.name)
dependencyNode.appendNode('version', it.version)
dependencyNode.appendNode('scope', 'runtime')
}
}
}
}
afterEvaluate {
["srcJar", "javadocJar", "scaladocJar", "testJar", "testSrcJar"].forEach { taskName ->
def task = tasks.findByName(taskName)
if (task != null)
artifact task
}
artifactId = base.archivesName.get()
pom {
name = 'Apache Kafka'
url = 'https://kafka.apache.org'
licenses {
license {
name = 'The Apache License, Version 2.0'
url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution = 'repo'
}
}
}
}
}
}
}
if (shouldSign) {
signing {
sign publishing.publications.mavenJava
}
}
}
def testLoggingEvents = ["passed", "skipped", "failed"]
def testShowStandardStreams = false
def testExceptionFormat = 'full'
// Gradle built-in logging only supports sending test output to stdout, which generates a lot
// of noise, especially for passing tests. We really only want output for failed tests. This
// hooks into the output and logs it (so we don't have to buffer it all in memory) and only
// saves the output for failing tests. Directory and filenames are such that you can, e.g.,
// create a Jenkins rule to collect failed test output.
def logTestStdout = {
def testId = { TestDescriptor descriptor ->
"${descriptor.className}.${descriptor.name}".toString()
}
def logFiles = new HashMap<String, File>()
def logStreams = new HashMap<String, FileOutputStream>()
beforeTest { TestDescriptor td ->
def tid = testId(td)
// truncate the file name if it's too long
def logFile = new File(
"${projectDir}/build/reports/testOutput/${tid.substring(0, Math.min(tid.size(),240))}.test.stdout"
)
logFile.parentFile.mkdirs()
logFiles.put(tid, logFile)
logStreams.put(tid, new FileOutputStream(logFile))
}
onOutput { TestDescriptor td, TestOutputEvent toe ->
def tid = testId(td)
// Some output can happen outside the context of a specific test (e.g. at the class level)
// and beforeTest/afterTest seems to not be invoked for these cases (and similarly, there's
// a TestDescriptor hierarchy that includes the thread executing the test, Gradle tasks,
// etc). We see some of these in practice and it seems like something buggy in the Gradle
// test runner since we see it *before* any tests and it is frequently not related to any
// code in the test (best guess is that it is tail output from last test). We won't have
// an output file for these, so simply ignore them. If they become critical for debugging,
// they can be seen with showStandardStreams.
if (td.name == td.className || td.className == null) {
// silently ignore output unrelated to specific test methods
return
} else if (logStreams.get(tid) == null) {
println "WARNING: unexpectedly got output for a test [${tid}]" +
" that we didn't previously see in the beforeTest hook." +
" Message for debugging: [" + toe.message + "]."
return
}
try {
logStreams.get(tid).write(toe.message.getBytes(StandardCharsets.UTF_8))
} catch (Exception e) {
println "ERROR: Failed to write output for test ${tid}"
e.printStackTrace()
}
}
afterTest { TestDescriptor td, TestResult tr ->
def tid = testId(td)
try {
logStreams.get(tid).close()
if (tr.resultType != TestResult.ResultType.FAILURE) {
logFiles.get(tid).delete()
} else {
def file = logFiles.get(tid)
println "${tid} failed, log available in ${file}"
}
} catch (Exception e) {
println "ERROR: Failed to close stdout file for ${tid}"
e.printStackTrace()
} finally {
logFiles.remove(tid)
logStreams.remove(tid)
}
}
}
// The suites are for running sets of tests in IDEs.
// Gradle will run each test class, so we exclude the suites to avoid redundantly running the tests twice.
def testsToExclude = ['**/*Suite.class']
test {
ext {
isGithubActions = System.getenv('GITHUB_ACTIONS') != null
hadFailure = false // Used to track if any tests failed, see afterSuite below
}
maxParallelForks = maxTestForks
ignoreFailures = userIgnoreFailures || ext.isGithubActions
maxHeapSize = defaultMaxHeapSize
jvmArgs = defaultJvmArgs
// KAFKA-17433 Used by deflake.yml github action to repeat individual tests
systemProperty("kafka.cluster.test.repeat", project.findProperty("kafka.cluster.test.repeat"))
systemProperty("kafka.test.catalog.file", project.findProperty("kafka.test.catalog.file"))
systemProperty("kafka.test.run.quarantined", "false")
testLogging {
events = userTestLoggingEvents ?: testLoggingEvents
showStandardStreams = userShowStandardStreams ?: testShowStandardStreams
exceptionFormat = testExceptionFormat
displayGranularity = 0
}
logTestStdout.rehydrate(delegate, owner, this)()
exclude testsToExclude
useJUnitPlatform {
includeEngines 'junit-jupiter'
excludeTags 'flaky'
}
develocity {
testRetry {
maxRetries = userMaxTestRetries
maxFailures = userMaxTestRetryFailures
}
}
// As we process results, check if there were any test failures.
afterSuite { desc, result ->
if (result.resultType == TestResult.ResultType.FAILURE) {
ext.hadFailure = true
}
}
// This closure will copy JUnit XML files out of the sub-project's build directory and into
// a top-level build/junit-xml directory. This is necessary to avoid reporting on tests which
// were not run, but instead were restored via FROM-CACHE. See KAFKA-17479 for more details.
doLast {
if (ext.isGithubActions) {
def moduleDirPath = projectToJUnitXmlPath(project)
def dest = rootProject.layout.buildDirectory.dir("junit-xml/${moduleDirPath}/test").get().asFile
println "Copy JUnit XML for ${project.name} to $dest"
ant.copy(todir: "$dest") {
ant.fileset(dir: "${test.reports.junitXml.entryPoint}")
}
// If there were any test failures, we want to fail the task to prevent the failures
// from being cached.
if (ext.hadFailure) {
throw new GradleException("Failing this task since '${project.name}:${name}' had test failures.")
}
}
}
}
task quarantinedTest(type: Test, dependsOn: compileJava) {
ext {
isGithubActions = System.getenv('GITHUB_ACTIONS') != null
}
// Disable caching and up-to-date for this task. We always want quarantined tests
// to run and never want to cache their results. Since we do this, we can avoid
// explicitly failing the build like we do in "test" with ext.hadFailure.
outputs.upToDateWhen { false }
outputs.cacheIf { false }
maxParallelForks = maxTestForks
ignoreFailures = userIgnoreFailures
maxHeapSize = defaultMaxHeapSize
jvmArgs = defaultJvmArgs
// KAFKA-17433 Used by deflake.yml github action to repeat individual tests
systemProperty("kafka.cluster.test.repeat", project.findProperty("kafka.cluster.test.repeat"))
systemProperty("kafka.test.catalog.file", project.findProperty("kafka.test.catalog.file"))
systemProperty("kafka.test.run.quarantined", "true")
testLogging {
events = userTestLoggingEvents ?: testLoggingEvents
showStandardStreams = userShowStandardStreams ?: testShowStandardStreams
exceptionFormat = testExceptionFormat
displayGranularity = 0
}
logTestStdout.rehydrate(delegate, owner, this)()
useJUnitPlatform {
includeEngines 'junit-jupiter'
}
develocity {
testRetry {
maxRetries = userMaxQuarantineTestRetries
maxFailures = userMaxQuarantineTestRetryFailures
}
}
// This closure will copy JUnit XML files out of the sub-project's build directory and into
// a top-level build/junit-xml directory. This is necessary to avoid reporting on tests which
// were not run, but instead were restored via FROM-CACHE. See KAFKA-17479 for more details.
doLast {
if (ext.isGithubActions) {
def moduleDirPath = projectToJUnitXmlPath(project)
def dest = rootProject.layout.buildDirectory.dir("junit-xml/${moduleDirPath}/quarantinedTest").get().asFile
println "Copy JUnit XML for ${project.name} to $dest"
ant.copy(todir: "$dest", failonerror: "false") {
ant.fileset(dir: "${quarantinedTest.reports.junitXml.entryPoint}") {
ant.include(name: "**/*.xml")
}
}
}
}
}
task integrationTest(type: Test, dependsOn: compileJava) {
maxParallelForks = maxTestForks
ignoreFailures = userIgnoreFailures
// Increase heap size for integration tests
maxHeapSize = "2560m"
jvmArgs = defaultJvmArgs
testLogging {
events = userTestLoggingEvents ?: testLoggingEvents
showStandardStreams = userShowStandardStreams ?: testShowStandardStreams
exceptionFormat = testExceptionFormat
displayGranularity = 0
}
logTestStdout.rehydrate(delegate, owner, this)()
exclude testsToExclude
useJUnitPlatform {
includeTags "integration"
includeEngines 'junit-jupiter'
}
develocity {
testRetry {
maxRetries = userMaxTestRetries
maxFailures = userMaxTestRetryFailures
}
}
}
task unitTest(type: Test, dependsOn: compileJava) {
maxParallelForks = maxTestForks
ignoreFailures = userIgnoreFailures
maxHeapSize = defaultMaxHeapSize
jvmArgs = defaultJvmArgs
testLogging {
events = userTestLoggingEvents ?: testLoggingEvents
showStandardStreams = userShowStandardStreams ?: testShowStandardStreams
exceptionFormat = testExceptionFormat
displayGranularity = 0
}
logTestStdout.rehydrate(delegate, owner, this)()
exclude testsToExclude
useJUnitPlatform {
excludeTags "integration"
includeEngines 'junit-jupiter'
}
develocity {
testRetry {
maxRetries = userMaxTestRetries
maxFailures = userMaxTestRetryFailures
}
}
}
// remove test output from all test types
tasks.withType(Test).all { t ->
cleanTest {
delete t.reports.junitXml.outputLocation
delete t.reports.html.outputLocation
}
}
jar {
from "$rootDir/LICENSE"
from "$rootDir/NOTICE"
}
task srcJar(type: Jar) {
archiveClassifier = 'sources'
from "$rootDir/LICENSE"
from "$rootDir/NOTICE"
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
archiveClassifier = 'javadoc'
from "$rootDir/LICENSE"
from "$rootDir/NOTICE"
from javadoc.destinationDir
}
task docsJar(dependsOn: javadocJar)
test.dependsOn('javadoc')
task systemTestLibs(dependsOn: jar)
if (!sourceSets.test.allSource.isEmpty()) {
task testJar(type: Jar) {
archiveClassifier = 'test'
from "$rootDir/LICENSE"
from "$rootDir/NOTICE"
from sourceSets.test.output
// The junit-platform.properties file is used for configuring and customizing the behavior of the JUnit platform.
// It should only apply to Kafka's own JUnit tests, and should not exist in the test JAR.
// If we include it in the test JAR, it could lead to conflicts with user configurations.
exclude 'junit-platform.properties'
}
task testSrcJar(type: Jar, dependsOn: testJar) {
archiveClassifier = 'test-sources'
from "$rootDir/LICENSE"
from "$rootDir/NOTICE"
from sourceSets.test.allSource
}
}
plugins.withType(ScalaPlugin) {
scala {
zincVersion = versions.zinc
}
task scaladocJar(type:Jar, dependsOn: scaladoc) {
archiveClassifier = 'scaladoc'
from "$rootDir/LICENSE"
from "$rootDir/NOTICE"
from scaladoc.destinationDir
}
//documentation task should also trigger building scala doc jar
docsJar.dependsOn scaladocJar
}
tasks.withType(ScalaCompile) {
scalaCompileOptions.keepAliveMode = userKeepAliveMode
scalaCompileOptions.additionalParameters = [
"-deprecation:false",
"-unchecked",
"-encoding", "utf8",
"-Xlog-reflective-calls",
"-feature",
"-language:postfixOps",
"-language:implicitConversions",
"-language:existentials",
"-Ybackend-parallelism", maxScalacThreads.toString(),
"-Xlint:constant",
"-Xlint:delayedinit-select",
"-Xlint:doc-detached",
"-Xlint:missing-interpolator",
"-Xlint:nullary-unit",
"-Xlint:option-implicit",
"-Xlint:package-object-classes",
"-Xlint:poly-implicit-overload",
"-Xlint:private-shadow",
"-Xlint:stars-align",
"-Xlint:type-parameter-shadow",
"-Xlint:unused"
]
// See README.md for details on this option and the meaning of each value
if (userScalaOptimizerMode.equals("method"))
scalaCompileOptions.additionalParameters += ["-opt:l:method"]
else if (userScalaOptimizerMode.startsWith("inline-")) {
List<String> inlineFrom = ["-opt-inline-from:org.apache.kafka.**"]
if (project.name.equals('core'))
inlineFrom.add("-opt-inline-from:kafka.**")
if (userScalaOptimizerMode.equals("inline-scala"))
inlineFrom.add("-opt-inline-from:scala.**")
scalaCompileOptions.additionalParameters += ["-opt:l:inline"]
scalaCompileOptions.additionalParameters += inlineFrom
}
scalaCompileOptions.additionalParameters += ["-opt-warnings", "-Xlint:strict-unsealed-patmat"]
// Scala 2.13.2 introduces compiler warnings suppression, which is a pre-requisite for -Xfatal-warnings
scalaCompileOptions.additionalParameters += ["-Xfatal-warnings"]
scalaCompileOptions.additionalParameters += ["-release", String.valueOf(minJavaVersion)]
configureJavaCompiler(name, options)
configure(scalaCompileOptions.forkOptions) {
memoryMaximumSize = defaultMaxHeapSize
jvmArgs = defaultJvmArgs
}
}
checkstyle {
configDirectory = rootProject.layout.projectDirectory.dir("checkstyle")
configProperties = checkstyleConfigProperties("import-control.xml")
toolVersion = versions.checkstyle
}
configure(checkstyleMain) {
group = 'Verification'
description = 'Run checkstyle on all main Java sources'
}
configure(checkstyleTest) {
group = 'Verification'
description = 'Run checkstyle on all test Java sources'
}
test.dependsOn('checkstyleMain', 'checkstyleTest')
spotbugs {
toolVersion = versions.spotbugs
excludeFilter = file("$rootDir/gradle/spotbugs-exclude.xml")
ignoreFailures = false
}
test.dependsOn('spotbugsMain')
tasks.withType(com.github.spotbugs.snom.SpotBugsTask).configureEach {
reports.configure {
// Continue supporting `xmlFindBugsReport` for compatibility
xml.enabled(project.hasProperty('xmlSpotBugsReport') || project.hasProperty('xmlFindBugsReport'))
html.enabled(!project.hasProperty('xmlSpotBugsReport') && !project.hasProperty('xmlFindBugsReport'))
}
maxHeapSize = defaultMaxHeapSize
jvmArgs = defaultJvmArgs
}
// Ignore core since its a scala project
if (it.path != ':core') {
if (userEnableTestCoverage) {
apply plugin: "jacoco"
jacoco {
toolVersion = versions.jacoco
}
jacocoTestReport {
dependsOn tasks.test
sourceSets sourceSets.main
reports {
html.required = true
xml.required = true
csv.required = false
}
}
}
}
if (userEnableTestCoverage) {
def coverageGen = it.path == ':core' ? 'reportTestScoverage' : 'jacocoTestReport'
tasks.register('reportCoverage').configure { dependsOn(coverageGen) }
}
dependencyCheck {
suppressionFile = "$rootDir/gradle/resources/dependencycheck-suppressions.xml"
skipProjects = [ ":jmh-benchmarks", ":trogdor" ]
skipConfigurations = [ "zinc" ]
}
apply plugin: 'com.diffplug.spotless'
spotless {
java {
targetExclude('**/generated/**/*.java','**/generated-test/**/*.java')
importOrder('kafka', 'org.apache.kafka', 'com', 'net', 'org', 'java', 'javax', '', '\\#')
removeUnusedImports()
}
}
}
gradle.taskGraph.whenReady { taskGraph ->
taskGraph.getAllTasks().findAll { it.name.contains('spotbugsScoverage') || it.name.contains('spotbugsTest') }.each { task ->
task.enabled = false
}
}
def fineTuneEclipseClasspathFile(eclipse, project) {
eclipse.classpath.file {
beforeMerged { cp ->
cp.entries.clear()
// for the core project add the directories defined under test/scala as separate source directories
if (project.name.equals('core')) {
cp.entries.add(new org.gradle.plugins.ide.eclipse.model.SourceFolder("src/test/scala/integration", null))
cp.entries.add(new org.gradle.plugins.ide.eclipse.model.SourceFolder("src/test/scala/other", null))
cp.entries.add(new org.gradle.plugins.ide.eclipse.model.SourceFolder("src/test/scala/unit", null))
}
}
whenMerged { cp ->
// for the core project exclude the separate sub-directories defined under test/scala. These are added as source dirs above
if (project.name.equals('core')) {
cp.entries.findAll { it.kind == "src" && it.path.equals("src/test/scala") }*.excludes = ["integration/", "other/", "unit/"]
}
/*
* Set all eclipse build output to go to 'build_eclipse' directory. This is to ensure that gradle and eclipse use different
* build output directories, and also avoid using the eclipse default of 'bin' which clashes with some of our script directories.
* https://discuss.gradle.org/t/eclipse-generated-files-should-be-put-in-the-same-place-as-the-gradle-generated-files/6986/2
*/
cp.entries.findAll { it.kind == "output" }*.path = "build_eclipse"
/*
* Some projects have explicitly added test output dependencies. These are required for the gradle build but not required
* in Eclipse since the dependent projects are added as dependencies. So clean up these from the generated classpath.
*/
cp.entries.removeAll { it.kind == "lib" && it.path.matches(".*/build/(classes|resources)/test") }
}
}
}
def checkstyleConfigProperties(configFileName) {
[importControlFile: "$configFileName"]
}
if (userEnableTestCoverage) {
tasks.register('reportCoverage').configure { dependsOn(subprojects.reportCoverage) }
}
def connectPkgs = [
'connect:api',
'connect:basic-auth-extension',
'connect:file',
'connect:json',
'connect:runtime',
'connect:test-plugins',
'connect:transforms',
'connect:mirror',
'connect:mirror-client'
]
tasks.create(name: "jarConnect", dependsOn: connectPkgs.collect { it + ":jar" }) {}
tasks.create(name: "testConnect", dependsOn: connectPkgs.collect { it + ":test" }) {}
project(':server') {
base {
archivesName = "kafka-server"
}
dependencies {
implementation project(':clients')
implementation project(':metadata')
implementation project(':server-common')
implementation project(':storage')
implementation project(':group-coordinator')
implementation project(':transaction-coordinator')
implementation project(':raft')
implementation libs.metrics
implementation libs.jacksonDatabind
implementation libs.slf4jApi
compileOnly libs.reload4j
testImplementation project(':clients').sourceSets.test.output
testImplementation libs.mockitoCore
testImplementation libs.junitJupiter
testImplementation libs.slf4jReload4j
testRuntimeOnly runtimeTestLibs
}
task createVersionFile() {
def receiptFile = file("$buildDir/kafka/$buildVersionFileName")
inputs.property "commitId", commitId
inputs.property "version", version
outputs.file receiptFile
outputs.cacheIf { true }
doLast {
def data = [
commitId: commitId,
version: version,
]
receiptFile.parentFile.mkdirs()
def content = data.entrySet().collect { "$it.key=$it.value" }.sort().join("\n")
receiptFile.setText(content, "ISO-8859-1")
}
}
jar {
dependsOn createVersionFile
from("$buildDir") {
include "kafka/$buildVersionFileName"
}
}
clean.doFirst {
delete "$buildDir/kafka/"
}
checkstyle {
configProperties = checkstyleConfigProperties("import-control-server.xml")
}
javadoc {
enabled = false
}
}
project(':share') {
base {
archivesName = "kafka-share"
}
dependencies {
implementation project(':server-common')