-
Notifications
You must be signed in to change notification settings - Fork 355
Expand file tree
/
Copy pathbuild.gradle
More file actions
698 lines (604 loc) · 28.3 KB
/
Copy pathbuild.gradle
File metadata and controls
698 lines (604 loc) · 28.3 KB
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
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import java.util.concurrent.atomic.AtomicBoolean
import java.util.jar.JarFile
plugins {
id 'com.gradleup.shadow'
}
description = 'dd-java-agent'
apply from: "$rootDir/gradle/java.gradle"
apply from: "$rootDir/gradle/publish.gradle"
configurations {
shadowInclude
sharedShadowInclude
traceShadowInclude
}
def includedAgentDir = project.layout.buildDirectory.dir("generated/included")
def includedJarFileTree = fileTree(includedAgentDir)
// Populated automatically by includeShadowJar for every product dir registered in this build.
// Used by verifyAgentJarContents to check that all included products land in the assembled jar.
ext.includedProductPrefixes = objects.setProperty(String)
def pomPropertiesDir = project.layout.buildDirectory.dir("generated/maven-metadata")
def pomPropertiesFileTree = fileTree(pomPropertiesDir)
tasks.named("processResources") {
dependsOn(includedJarFileTree)
dependsOn(pomPropertiesFileTree)
}
tasks.named("sourcesJar") {
dependsOn(pomPropertiesFileTree)
}
sourceSets {
// The special pre-check must be compiled with Java 6 to detect unsupported
// Java versions and prevent issues for users that still using them.
"main_java6" {
java.srcDirs "${project.projectDir}/src/main/java6"
}
// Additional checks that use the Java 11 API.
"main_java11" {
java.srcDirs "${project.projectDir}/src/main/java11"
}
main.resources.srcDirs(includedAgentDir, pomPropertiesDir)
}
def java6CompileTask = tasks.named("compileMain_java6Java") {
configureCompiler(it, 8, JavaVersion.VERSION_1_6)
}
def java11CompileTask = tasks.named("compileMain_java11Java") {
configureCompiler(it, 11)
}
tasks.named("compileJava") {
dependsOn(java6CompileTask)
dependsOn(java11CompileTask)
}
dependencies {
implementation sourceSets.main_java11.output
main_java11CompileOnly libs.forbiddenapis
main_java6CompileOnly project(':components:annotations')
main_java6CompileOnly libs.forbiddenapis
testImplementation sourceSets.main_java6.output
}
/*
* Several shadow jars are created
* - The main "dd-java-agent" jar that also has the bootstrap project
* - Major feature jars (trace, instrumentation, jmxfetch, profiling, appsec, iast, debugger, ci-visibility)
* - A shared dependencies jar
* This general config is shared by all of them
*/
def generalShadowJarConfig(ShadowJar shadowJarTask) {
shadowJarTask.with {
mergeServiceFiles()
addMultiReleaseAttribute = false
duplicatesStrategy = DuplicatesStrategy.FAIL
// Service descriptors are intentionally merged by mergeServiceFiles(); let
// duplicate service entries reach that transformer instead of failing first.
filesMatching('META-INF/services/**') {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
}
// Vendored dependencies often repeat license/notice metadata. Keep one copy
// while still failing on unexpected duplicate runtime resources and classes.
filesMatching([
'META-INF/LICENSE*',
'META-INF/NOTICE*',
'META-INF/AL2.0',
'META-INF/LGPL2.1',
]) {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
// Remove some cruft from the final jar.
// These patterns should NOT include **/META-INF/maven/**/pom.properties, which is
// used to report our own dependencies, but we should remove the top-level metadata
// of vendored packages because those could trigger unwanted framework checks.
exclude '/META-INF/maven/org.slf4j/**'
exclude '/META-INF/maven/org.snakeyaml/**'
exclude '**/META-INF/maven/**/pom.xml'
exclude '**/META-INF/proguard/'
exclude '**/META-INF/*.kotlin_module'
exclude '**/module-info.class'
exclude '**/liblz4-java.so'
exclude '**/liblz4-java.dylib'
exclude '**/inst/META-INF/versions/**'
exclude '**/META-INF/versions/*/org/yaml/**'
exclude '**/package.html'
exclude '**/about.html'
// Used to generate Java code during build, no need to include original file
exclude '**/*.trie'
// Replaced by 'instrumenter.index', no need to include original service file
exclude '**/META-INF/services/datadog.trace.agent.tooling.InstrumenterModule'
// Prevents conflict with other SLF4J instances. Important for premain.
relocate 'org.slf4j', 'datadog.slf4j'
// Prevent conflicts with flat class-path when using GraalVM native-images
relocate 'org.jctools', 'datadog.jctools'
relocate 'net.jpountz', 'datadog.jpountz'
// rewrite dependencies calling Logger.getLogger
relocate 'java.util.logging.Logger', 'datadog.trace.bootstrap.PatchLogger'
// patch JFFI loading mechanism to maintain isolation
exclude '**/com/kenai/jffi/Init.class'
relocate('com.kenai.jffi.Init', 'com.kenai.jffi.PatchInit')
// patch OkHttp to avoid premain provider lookup and use daemon threads
exclude '**/okhttp3/internal/platform/Platform.class'
exclude '**/okhttp3/internal/Util$*.class'
exclude '**/okhttp3/internal/Util.class'
relocate('okhttp3.internal.platform.Platform', 'datadog.okhttp3.internal.platform.PatchPlatform')
relocate('okhttp3.internal.Util', 'datadog.okhttp3.internal.PatchUtil')
// use dd-instrument-java's embedded copy of asm
relocate('org.objectweb.asm', 'datadog.instrument.asm')
// Minimize and relocate the airlift compressor dependency for ZSTD
exclude '**/io/airlift/compress/bzip2/**'
exclude '**/io/airlift/compress/deflate/**'
exclude '**/io/airlift/compress/gzip/**'
exclude '**/io/airlift/compress/hadoop/**'
exclude '**/io/airlift/compress/lz4/**'
exclude '**/io/airlift/compress/lzo/**'
exclude '**/io/airlift/compress/snappy/**'
relocate 'io.airlift', 'datadog.io.airlift'
// Minimize JNA, removing native libraries for unsupported environments
exclude '**/com/sun/jna/aix-*/**'
exclude '**/com/sun/jna/freebsd-*/**'
exclude '**/com/sun/jna/linux-armel/**'
exclude '**/com/sun/jna/linux-mips64el/**'
exclude '**/com/sun/jna/linux-ppc/**'
exclude '**/com/sun/jna/linux-ppc64le/**'
exclude '**/com/sun/jna/linux-riscv64/**'
exclude '**/com/sun/jna/linux-s390x/**'
exclude '**/com/sun/jna/openbsd-*/**'
exclude '**/com/sun/jna/sunos-*/**'
// Minimize JFFI, removing native libraries for unsupported environments
exclude '**/jni/*-AIX/**'
exclude '**/jni/*-DragonFlyBSD/**'
exclude '**/jni/*-FreeBSD/**'
exclude '**/jni/loongarch64-Linux/**'
exclude '**/jni/mips64el-Linux/**'
exclude '**/jni/ppc64-Linux/**'
exclude '**/jni/ppc64le-Linux/**'
exclude '**/jni/s390x-Linux/**'
exclude '**/jni/sparcv9-Linux/**'
exclude '**/jni/*-OpenBSD/**'
exclude '**/jni/*-SunOS/**'
final String projectName = "${project.name}"
// Prevents conflict with other instances, but doesn't relocate instrumentation
if (!projectName.equals('instrumentation')) {
relocate 'org.snakeyaml.engine', 'datadog.snakeyaml.engine'
relocate 'org.yaml.snakeyaml.Yaml', 'datadog.trace.agent.jmxfetch.LegacyYaml'
relocate 'okhttp3', 'datadog.okhttp3'
relocate 'okio', 'datadog.okio'
// embed an extra copy of our otel-shim for drop-in/extension support
// extensions are remapped to avoid classpath conflicts; use same mapping here
relocate 'io.opentelemetry.api', 'datadog.trace.bootstrap.otel.api'
relocate 'io.opentelemetry.context', 'datadog.trace.bootstrap.otel.context'
relocate 'datadog.opentelemetry.shim', 'datadog.trace.bootstrap.otel.shim'
}
if (!project.hasProperty("disableShadowRelocate") || !disableShadowRelocate) {
// shadow OT impl to prevent casts to implementation
relocate 'datadog.trace.common', 'datadog.trace.agent.common'
relocate 'datadog.trace.core', 'datadog.trace.agent.core'
relocate 'datadog.opentracing', 'datadog.trace.agent.ot'
// shadow logging-utils that has slf4j in the API and is accessed from core
relocate 'datadog.logging', 'datadog.trace.agent.logging'
}
}
}
def includeShadowJar(TaskProvider<ShadowJar> includedShadowJarTask, String agentDir, FileTree includedJarFileTree) {
includedProductPrefixes.add(agentDir)
def expandTask = project.tasks.register("expandAgentShadowJar${agentDir.capitalize()}", Sync) {
it.group = LifecycleBasePlugin.BUILD_GROUP
it.description = "Expand the included shadow jar into the agent jar under ${agentDir}"
def opentracingFound = new AtomicBoolean()
it.doFirst("detect-open-tracing") {
eachFile {
// We seem unlikely to use this name somewhere else.
if (it.path.contains("opentracing") && it.name.contains("Format\$Builtin")) {
opentracingFound.set(true)
}
}
}
it.doLast("fail-on-detected-opentracing") {
if (opentracingFound.get()) {
throw new GradleException("OpenTracing direct dependency found!")
}
}
it.into providers.provider { new File(includedJarFileTree.dir, agentDir) }
it.from(zipTree(includedShadowJarTask.map { it.archiveFile })) {
rename '(^.*)\\.class$', '$1.classdata'
// Rename LICENSE file since it clashes with license dir on non-case sensitive FSs (i.e. Mac)
rename '^LICENSE$', 'LICENSE.renamed'
if (agentDir == 'inst') {
// byte-buddy now ships classes optimized for Java8+ under META-INF/versions/9
// since we target Java8+ we can promote these classes over the pre-Java8 ones
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
eachFile {
if (it.path.contains('META-INF/versions/9/net/bytebuddy')) {
it.path = it.path.replace('META-INF/versions/9/', '')
}
}
}
}
it.dependsOn includedShadowJarTask
}
includedJarFileTree.builtBy(expandTask)
includedShadowJarTask.configure {
generalShadowJarConfig(it as ShadowJar)
}
}
def includeSubprojShadowJar(Project includedProjectJar, String destinationDir, FileTree includedJarFileTree) {
evaluationDependsOn(includedProjectJar.path)
includeShadowJar(includedProjectJar.tasks.named("shadowJar", ShadowJar), destinationDir, includedJarFileTree)
}
includeSubprojShadowJar(project(':dd-java-agent:instrumentation'), 'inst', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:agent-jmxfetch'), 'jmxfetch', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:agent-profiling'), 'profiling', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:appsec'), 'appsec', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:agent-aiguard'), 'aiguard', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:agent-iast'), 'iast', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:agent-debugger'), 'debugger', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:agent-ci-visibility'), 'ci-visibility', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:agent-llmobs'), 'llm-obs', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:agent-logs-intake'), 'logs-intake', includedJarFileTree)
includeSubprojShadowJar(project(':dd-java-agent:cws-tls'), 'cws-tls', includedJarFileTree)
// Include metrics-lib directly (metrics-agent classes stay in bootstrap via agent-bootstrap)
includeSubprojShadowJar(project(':products:metrics:metrics-lib'), 'metrics', includedJarFileTree)
includeSubprojShadowJar(project(':products:feature-flagging:feature-flagging-agent'), 'feature-flagging', includedJarFileTree)
def sharedShadowJar = tasks.register('sharedShadowJar', ShadowJar) {
it.configurations.add(project.configurations.named('sharedShadowInclude'))
// Put the jar in a different directory so we don't overwrite the normal shadow jar and
// break caching, and also to not interfere with CI scripts that copy everything in the
// libs directory
it.destinationDirectory.set(project.layout.buildDirectory.dir("shared-lib"))
// Add a classifier so we don't confuse the jar file with the normal shadow jar
it.archiveClassifier = 'shared'
it.dependencies {
exclude(project(':dd-java-agent:agent-bootstrap'))
exclude(project(':dd-java-agent:agent-logging'))
exclude(project(':dd-trace-api'))
exclude(project(':internal-api'))
exclude(project(':components:context'))
exclude(project(':utils:config-utils'))
exclude(project(':utils:logging-utils'))
exclude(project(':utils:time-utils'))
exclude(project(':products:metrics:metrics-api'))
exclude(project(':products:metrics:metrics-agent'))
exclude(dependency('org.slf4j:.*:.*'))
// use dd-instrument-java's embedded copy of asm
exclude(dependency('org.ow2.asm:asm:.*'))
}
}
includeShadowJar(sharedShadowJar, 'shared', includedJarFileTree)
// place the tracer in its own shadow jar separate to instrumentation
def traceShadowJar = tasks.register('traceShadowJar', ShadowJar) {
it.configurations.add(project.configurations.named('traceShadowInclude'))
it.destinationDirectory.set(project.layout.buildDirectory.dir("trace-lib"))
it.archiveClassifier = 'trace'
it.dependencies deps.excludeShared
}
includeShadowJar(traceShadowJar, 'trace', includedJarFileTree)
tasks.named("shadowJar", ShadowJar) {
// Include AgentPreCheck compiled with Java 6.
from sourceSets.main_java6.output
// Include additional checks compiled with Java 11.
from sourceSets.main_java11.output
generalShadowJarConfig(it)
// The default shadowJar task has a runtimeClasspath convention. Replace it
// instead of adding to it, otherwise runtimeClasspath would be bundled too.
configurations.empty()
configurations.add(project.configurations.named('shadowInclude'))
archiveClassifier = ''
manifest {
attributes(
"Main-Class": "datadog.trace.bootstrap.AgentBootstrap",
"Agent-Class": "datadog.trace.bootstrap.AgentBootstrap",
"Premain-Class": "datadog.trace.bootstrap.AgentPreCheck",
"Can-Redefine-Classes": true,
"Can-Retransform-Classes": true,
)
}
}
// temporary config to add slf4j-simple so we get logging while indexing
project.configurations.register('slf4j-simple') {
it.dependencies.add(project.dependencyFactory.create("org.slf4j:slf4j-simple:${libs.versions.slf4j.get()}"))
}
def generateAgentJarIndex = tasks.register('generateAgentJarIndex', JavaExec) {
def destinationDir = project.layout.buildDirectory.dir("generated/${it.name}")
it.group = LifecycleBasePlugin.BUILD_GROUP
it.description = "Generate dd-java-agent.index"
it.mainClass = 'datadog.trace.bootstrap.AgentJarIndex$IndexGenerator'
it.inputs.files(includedJarFileTree)
.withPropertyName("includedAgentFiles")
.withPathSensitivity(PathSensitivity.RELATIVE)
it.outputs.dir(destinationDir)
.withPropertyName("agentJarIndex")
it.outputs.cacheIf { true }
it.classpath = objects.fileCollection().tap {
it.from(project.configurations.named("shadowInclude"))
it.from(project.configurations.named('slf4j-simple'))
}
// debuggable within gradle using:
// it.jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005")
it.argumentProviders.add(new CommandLineArgumentProvider() {
@Override
Iterable<String> asArguments() {
return [includedAgentDir.get().asFile.path, destinationDir.get().asFile.path,]
}
})
}
sourceSets.main.resources.srcDir(generateAgentJarIndex)
def generatePomProperties = tasks.register('generatePomProperties', WriteProperties) {
destinationFile = pomPropertiesDir.map { it.file("META-INF/maven/com.datadoghq/dd-java-agent/pom.properties") }
property("groupId", "com.datadoghq")
property("artifactId", "dd-java-agent")
property("version", project.providers.provider { project.version.toString() })
}
pomPropertiesFileTree.builtBy(generatePomProperties)
subprojects { Project subProj ->
// Don't need javadoc task run for internal projects.
subProj.tasks.withType(Javadoc).configureEach { enabled = false }
}
// We don't want bundled dependencies to show up in the pom.
tasks.withType(GenerateMavenPom).configureEach { task ->
doFirst {
task.pom.withXml { XmlProvider provider ->
Node dependencies = provider.asNode().dependencies[0]
dependencies.children().clear()
}
}
}
dependencies {
implementation project(path: ':components:json')
// Depend on the bootstrap-specific shadow configuration to avoid having the same component reused by both bootstrap and agent
implementation project(path: ':components:environment', configuration: 'shadow')
modules {
module("com.squareup.okio:okio") {
replacedBy("com.datadoghq.okio:okio") // embed our patched fork
}
}
testImplementation(project(':dd-java-agent:agent-bootstrap')) {
exclude group: 'com.datadoghq', module: 'agent-logging'
}
testImplementation project(':dd-trace-api')
testImplementation project(':dd-trace-core')
testImplementation project(':utils:test-utils')
testImplementation group: 'com.squareup.okhttp3', name: 'mockwebserver', version: libs.versions.okhttp.legacy.get()
testImplementation project(':utils:test-agent-utils:decoder')
testImplementation libs.bundles.test.logging
testImplementation libs.guava
testImplementation libs.okhttp
testImplementation group: 'io.opentracing', name: 'opentracing-util', version: '0.31.0'
// Includes for the top level shadow jar
shadowInclude project(path: ':components:environment', configuration: 'shadow')
shadowInclude project(path: ':dd-java-agent:agent-bootstrap')
shadowInclude project(path: ':dd-java-agent:agent-debugger:debugger-bootstrap')
shadowInclude project(path: ':dd-java-agent:agent-otel:otel-bootstrap', configuration: 'shadow')
// embed an extra copy of our otel-shim for drop-in/extension support
shadowInclude project(path: ':dd-java-agent:agent-otel:otel-shim')
shadowInclude project(path: ':products:feature-flagging:feature-flagging-bootstrap')
// Includes for the shared internal shadow jar
sharedShadowInclude deps.shared
// force a controlled version of ASM that is used by Debugger while pulled transitively by jnr
sharedShadowInclude libs.bundles.asm
sharedShadowInclude project(':communication'), {
transitive = false
// do not bring along slf4j and dependent subprojects
// (which are loaded on the bootstrap cl)
}
sharedShadowInclude group: 'com.datadoghq', name: 'sketches-java', version: '0.8.3'
sharedShadowInclude project(':telemetry'), {
transitive = false
// do not bring along slf4j and dependent subprojects
// (which are loaded on the bootstrap cl)
}
sharedShadowInclude project(':utils:flare-utils'), {
transitive = false
}
sharedShadowInclude libs.bundles.cafe.crypto
sharedShadowInclude project(':remote-config:remote-config-api'), {
transitive = false
}
sharedShadowInclude project(':remote-config:remote-config-core'), {
transitive = false
}
sharedShadowInclude project(':utils:container-utils'), {
transitive = false
}
sharedShadowInclude project(':utils:socket-utils'), {
transitive = false
}
sharedShadowInclude project(':utils:queue-utils'), {
transitive = false
}
sharedShadowInclude project(':utils:version-utils'), {
transitive = false
}
sharedShadowInclude project(':utils:logging-utils'), {
transitive = false
}
sharedShadowInclude project(':dd-java-agent:agent-crashtracking'), {
transitive = false
}
sharedShadowInclude project(path: ':dd-java-agent:ddprof-lib', configuration: 'shadow'), {
transitive = false
}
traceShadowInclude project(':dd-trace-core')
}
tasks.withType(Test).configureEach {
jvmArgs "-Ddd.service.name=java-agent-tests"
jvmArgs "-Ddd.writer.type=LoggingWriter"
// Multi-threaded logging seems to be causing deadlocks with Gradle's log capture.
// jvmArgs "-Ddatadog.slf4j.simpleLogger.defaultLogLevel=debug"
// jvmArgs "-Dorg.slf4j.simpleLogger.defaultLogLevel=debug"
doFirst {
// Defining here to allow jacoco to be first on the command line.
jvmArgs "-javaagent:${shadowJar.archiveFile.get()}"
}
testLogging {
events "started"
}
if (project.hasProperty("disableShadowRelocate") && disableShadowRelocate) {
exclude 'datadog/trace/agent/integration/classloading/ShadowPackageRenamingTest.class'
}
dependsOn "shadowJar"
}
def agentJarChecksProps = rootProject.file('metadata/agent-jar-checks.properties')
tasks.register('verifyAgentJarContents') {
group = LifecycleBasePlugin.VERIFICATION_GROUP
description = 'Verify the agent jar contains required entries and meets structural invariants'
def jarProvider = tasks.named('shadowJar', ShadowJar).flatMap { it.archiveFile }
inputs.file(jarProvider)
inputs.file(agentJarChecksProps)
inputs.property('productPrefixes', includedProductPrefixes)
outputs.file(project.layout.buildDirectory.file("tmp/${it.name}/.verified"))
doLast {
def props = new Properties()
agentJarChecksProps.withInputStream { props.load(it) }
File jarFile = jarProvider.get().asFile
List<String> failures = []
Map<String, Long> entries = [:]
// Jar size budget — raise only when the growth is intentional
def sizeBudget = Long.parseLong(props['jar.size.budget'])
if (jarFile.length() > sizeBudget) {
failures.add("Jar size ${jarFile.length()} B exceeds budget ${sizeBudget} B")
}
// Inspect jar content
new JarFile(jarFile).withCloseable { jf ->
jf.entries().each { ze -> entries[ze.name] = ze.size }
}
// Required entries
[
// Runtime index, loaded at startup to resolve classdata paths
// Generated by :dd-java-agent:generateAgentJarIndex
'dd-java-agent.index',
// Premain-Class: Java 6 pre check
'datadog/trace/bootstrap/AgentPreCheck.class',
// Agent-Class: main bootstrap entry point
'datadog/trace/bootstrap/AgentBootstrap.class',
// Additional checks for Java 11
'datadog/trace/bootstrap/AdvancedAgentChecks.class',
// Instrumentation indexes
// * :dd-java-agent:instrumentation:generateInstrumenterIndex
// * :dd-java-agent:instrumentation:generateKnownTypesIndex
// Without instrumenter.index, zero instrumentations load at runtime.
'inst/instrumenter.index',
'inst/known-types.index',
// OTel drop-in support, embedded via otel-bootstrap + otel-shim shadowInclude
'datadog/trace/bootstrap/otel/api/',
'datadog/trace/bootstrap/otel/context/',
'datadog/trace/bootstrap/otel/shim/',
'META-INF/maven/com.datadoghq/dd-java-agent/pom.properties',
].each { required ->
if (!entries.containsKey(required)) {
failures.add("Missing required entry: ${required}")
}
}
// Sanity check on the minimum number of classes; see metadata/agent-jar-checks.properties.
def classCount = entries.keySet().count { it.endsWith('.class') || it.endsWith('.classdata') }
def classFloor = Integer.parseInt(props['classes.minimum.guard'])
if (classCount < classFloor) {
failures.add("Class count ${classCount} is below floor ${classFloor}")
}
// Each registered product must contribute at least one .classdata entry.
// Catches a product wired into the build but producing no classes.
def classdataPrefixes = entries.keySet()
.findAll { it.endsWith('.classdata') }
.collect { it.split('/')[0] }
.toSet()
includedProductPrefixes.get().each { dir ->
if (!classdataPrefixes.contains(dir)) {
failures.add("Product '${dir}' has no .classdata entries in the assembled jar")
}
}
// All *.index files in the jar must be non-empty
entries.findAll { name, size -> name.endsWith('.index') && size == 0 }.each { name, _ ->
failures.add("Empty index file: ${name}")
}
// Packages that must not appear anywhere in the jar after relocation.
// NOTE: Hardcoded to catch accidental removal of relocate() calls in generalShadowJarConfig or in a nested shadow jar.
def productPrefixes = includedProductPrefixes.get()
['org/slf4j/', 'org/jctools/', 'net/jpountz/', 'org/objectweb/asm/', 'io/airlift/'].each { pkg ->
def leaked = entries.keySet().findAll { entry ->
entry.startsWith(pkg) || productPrefixes.any { prefix -> entry.startsWith("${prefix}/${pkg}") }
}
if (!leaked.empty) {
def sample = leaked.take(3).toString()
failures.add("Unrelocated package '${pkg}': ${sample}${leaked.size() > 3 ? ' ...' : ''}")
}
}
if (!failures.empty) {
throw new GradleException(
"Agent jar verification failed (${failures.size()} issue(s)):\n" +
failures.collect { " - ${it}" }.join('\n'))
}
def marker = outputs.files.singleFile
marker.parentFile.mkdirs()
marker.text = 'verified'
}
}
tasks.register('verifyAgentJarIntegrations', JavaExec) {
group = LifecycleBasePlugin.VERIFICATION_GROUP
description = 'Verify the agent jar lists exactly the integrations in metadata/agent-jar-checks.properties'
def jarProvider = tasks.named('shadowJar', ShadowJar).flatMap { it.archiveFile }
inputs.file(jarProvider)
inputs.file(agentJarChecksProps)
outputs.file(project.layout.buildDirectory.file("tmp/${it.name}/.verified"))
// Run the assembled agent jar directly — this exercises dd-java-agent.index,
// inst/instrumenter.index, and instrumentation class loading end-to-end.
mainClass = 'datadog.trace.bootstrap.AgentBootstrap'
classpath = objects.fileCollection().from(jarProvider)
args = ['--list-integrations']
// Capture both stdout and stderr: InstrumenterIndex.buildModule() logs ERROR and returns null when a module
// fails to load, while the process exits with status 0.
def capturedOutput = new ByteArrayOutputStream()
def capturedError = new ByteArrayOutputStream()
standardOutput = capturedOutput
errorOutput = capturedError
doLast {
def stderr = capturedError.toString()
if (!stderr.isBlank()) {
throw new GradleException(
"--list-integrations produced unexpected stderr output " +
"(likely a module load failure; see InstrumenterIndex.buildModule):\n${stderr}")
}
def props = new Properties()
agentJarChecksProps.withInputStream { props.load(it) }
def actual = capturedOutput.toString().readLines().findAll { !it.isBlank() }.toSorted()
def expected = props.getProperty('expected.integrations').split(',').collect { it.trim() }.toSorted()
def added = actual - expected
def removed = expected - actual
if (added || removed) {
def msg = new StringBuilder('Integration list differs from metadata/agent-jar-checks.properties.')
msg.append(" Run './gradlew :dd-java-agent:updateAgentJarIntegrationsGoldenFile' to update it.\n")
added.each { msg.append(" + ${it}\n") }
removed.each { msg.append(" - ${it}\n") }
throw new GradleException(msg.toString())
}
def marker = outputs.files.singleFile
marker.parentFile.mkdirs()
marker.text = 'verified'
}
}
// Manual run after adding/removing integrations; rewrites the expected.integrations block in
// metadata/agent-jar-checks.properties while preserving all other properties and comments.
tasks.register('updateAgentJarIntegrationsGoldenFile', JavaExec) {
group = LifecycleBasePlugin.VERIFICATION_GROUP
description = 'Regenerate expected.integrations in metadata/agent-jar-checks.properties from the current agent jar'
def jarProvider = tasks.named('shadowJar', ShadowJar).flatMap { it.archiveFile }
inputs.file(jarProvider)
mainClass = 'datadog.trace.bootstrap.AgentBootstrap'
classpath = objects.fileCollection().from(jarProvider)
args = ['--list-integrations']
def capturedOutput = new ByteArrayOutputStream()
standardOutput = capturedOutput
doLast {
def integrations = capturedOutput.toString().readLines().findAll { !it.isBlank() }.toSorted()
def entryLines = integrations.withIndex().collect { name, i ->
def prefix = (i == 0) ? 'expected.integrations = ' : ' '
def suffix = (i < integrations.size() - 1) ? ',\\' : ''
"${prefix}${name}${suffix}"
}
// Replace everything between the BEGIN/END markers (inclusive) with the fresh value.
def BEGIN = '# BEGIN expected.integrations'
def END = '# END expected.integrations'
def allLines = agentJarChecksProps.readLines()
def before = allLines.subList(0, allLines.findIndexOf { it.startsWith(BEGIN) })
def after = allLines.subList(allLines.findIndexOf { it.startsWith(END) } + 1, allLines.size())
agentJarChecksProps.text = (before + [BEGIN] + entryLines + [END] + after).join('\n') + '\n'
logger.lifecycle("Updated metadata/agent-jar-checks.properties with ${integrations.size()} integrations")
}
}
tasks.named('check') {
dependsOn 'verifyAgentJarContents', 'verifyAgentJarIntegrations'
}