-
Notifications
You must be signed in to change notification settings - Fork 324
Fixed race condition on dumping future cleanup. #9607
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 17 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
53f8800
Debug dump cancellation logic.
AlexeyKuznetsov-DD 88ceeb6
Debug dump cancellation logic.
AlexeyKuznetsov-DD 623bfcf
Debug dump cancellation logic.
AlexeyKuznetsov-DD 421ef58
WIP 4.
AlexeyKuznetsov-DD ac925ba
WIP 5.
AlexeyKuznetsov-DD 03d94c5
WIP 6.
AlexeyKuznetsov-DD f517caf
Merge branch 'master' into alexeyk/debug-dump-logic
AlexeyKuznetsov-DD 8417a81
WIP 7.
AlexeyKuznetsov-DD f15d8b2
WIP 8.
AlexeyKuznetsov-DD 6806086
WIP 9.
AlexeyKuznetsov-DD 2aab088
Merge branch 'master' into alexeyk/debug-dump-logic
AlexeyKuznetsov-DD d6a1e75
Merge branch 'master' into alexeyk/debug-dump-logic
AlexeyKuznetsov-DD 383fc15
WIP 10.
AlexeyKuznetsov-DD 274c614
Merge branch 'master' into alexeyk/debug-dump-logic
AlexeyKuznetsov-DD 370d08e
Refactored to Kotlin plugin
AlexeyKuznetsov-DD 4132ac3
Merge branch 'master' into alexeyk/debug-dump-logic
AlexeyKuznetsov-DD cd4d8d3
Refactored to use Gradle lifecycle.
AlexeyKuznetsov-DD 424563b
Merge branch 'master' into alexeyk/debug-dump-logic
AlexeyKuznetsov-DD 059ce54
Applied review comments and covered with tests.
AlexeyKuznetsov-DD e1ce1f1
Fixed review notes.
AlexeyKuznetsov-DD 6a92882
Merge branch 'master' into alexeyk/debug-dump-logic
AlexeyKuznetsov-DD File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
159 changes: 159 additions & 0 deletions
159
buildSrc/src/main/kotlin/datadog/gradle/plugin/dump/DumpHangedTestPlugin.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| package datadog.gradle.plugin.dump | ||
|
|
||
| import org.gradle.api.Plugin | ||
| import org.gradle.api.Project | ||
| import org.gradle.api.provider.Provider | ||
| import org.gradle.api.services.BuildService | ||
| import org.gradle.api.services.BuildServiceParameters | ||
| import org.gradle.api.tasks.testing.Test | ||
| import org.gradle.kotlin.dsl.withType | ||
| import java.io.File | ||
| import java.lang.ProcessBuilder.Redirect | ||
| import java.time.Duration | ||
| import java.util.concurrent.Executors | ||
| import java.util.concurrent.ScheduledExecutorService | ||
| import java.util.concurrent.ScheduledFuture | ||
| import java.util.concurrent.TimeUnit | ||
|
|
||
| /** | ||
| * Plugin to collect thread and heap dumps for hanged tests. | ||
| */ | ||
| class DumpHangedTestPlugin : Plugin<Project> { | ||
| companion object { | ||
| private const val DUMP_FUTURE_KEY = "dumping_future" | ||
| } | ||
|
|
||
| /** Executor wrapped with proper Gradle lifecycle. */ | ||
| abstract class DumpSchedulerService : BuildService<BuildServiceParameters.None>, AutoCloseable { | ||
| private val executor: ScheduledExecutorService = | ||
| Executors.newSingleThreadScheduledExecutor { r -> Thread(r, "hanged-test-dump").apply { isDaemon = true } } | ||
|
|
||
| fun schedule(task: () -> Unit, delay: Duration): ScheduledFuture<*> = | ||
| executor.schedule(task, delay.toMillis(), TimeUnit.MILLISECONDS) | ||
|
|
||
| override fun close() { | ||
| executor.shutdownNow() | ||
| } | ||
| } | ||
AlexeyKuznetsov-DD marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| override fun apply(project: Project) { | ||
AlexeyKuznetsov-DD marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| val scheduler = project.gradle.sharedServices | ||
| .registerIfAbsent("dumpHangedTestScheduler", DumpSchedulerService::class.java) | ||
|
|
||
| fun configure(p: Project) { | ||
| p.tasks.withType<Test>().configureEach { | ||
| val t = this | ||
AlexeyKuznetsov-DD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| t.doFirst { schedule(t, scheduler) } | ||
| t.doLast { cleanup(t) } | ||
| } | ||
| } | ||
|
|
||
| configure(project) | ||
|
|
||
| if (project == project.rootProject) { | ||
| project.subprojects(::configure) | ||
| } | ||
AlexeyKuznetsov-DD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private fun schedule(t: Test, scheduler: Provider<DumpSchedulerService>) { | ||
AlexeyKuznetsov-DD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| val taskName = t.path | ||
|
|
||
| if (t.extensions.extraProperties.has(DUMP_FUTURE_KEY)) { | ||
AlexeyKuznetsov-DD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| t.logger.lifecycle("Taking dumps already scheduled for: $taskName") | ||
AlexeyKuznetsov-DD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return | ||
| } | ||
|
|
||
| if (!t.timeout.isPresent) { | ||
| t.logger.lifecycle("Taking dumps has no timeout configured for: $taskName") | ||
| return | ||
| } | ||
|
|
||
| t.logger.lifecycle("Taking dumps scheduled for: $taskName") | ||
|
|
||
| // Calculate delay for taking dumps as test timeout minus 1 minute, but no less than 1 minute. | ||
| val delay = t.timeout.get().minusMinutes(1).coerceAtLeast(Duration.ofMinutes(1)) | ||
|
|
||
| val future = scheduler.get().schedule({ | ||
| t.logger.lifecycle("Taking dumps after ${delay.toMinutes()} minutes delay for: $taskName") | ||
|
|
||
| takeDump(t) | ||
| }, delay) | ||
|
|
||
| t.extensions.extraProperties.set(DUMP_FUTURE_KEY, future) | ||
| } | ||
|
|
||
| private fun takeDump(t: Test) { | ||
| try { | ||
| // Use Gradle's build dir and adjust for CI artifacts collection if needed. | ||
| val dumpsDir: File = t.project.layout.buildDirectory | ||
| .dir("dumps") | ||
| .map { dir -> | ||
| if (t.project.providers.environmentVariable("CI").isPresent) { | ||
| // Move reports into the folder collected by the collect_reports.sh script. | ||
| File( | ||
| dir.asFile.absolutePath.replace( | ||
| "dd-trace-java/dd-java-agent", | ||
| "dd-trace-java/workspace/dd-java-agent" | ||
| ) | ||
| ) | ||
| } else { | ||
| dir.asFile | ||
| } | ||
| } | ||
| .get() | ||
|
|
||
| dumpsDir.mkdirs() | ||
|
|
||
| fun file(name: String): File { | ||
| val parts = name.split('.') | ||
| return File(dumpsDir, "${parts.first()}-${System.currentTimeMillis()}.${parts.last()}") | ||
| } | ||
|
|
||
| // For simplicity, use `0` as the PID, which collects all thread dumps across JVMs. | ||
| val allThreadsFile = file("all-thread-dumps.log") | ||
| runCmd(Redirect.to(allThreadsFile), "jcmd", "0", "Thread.print", "-l") | ||
|
|
||
| // Collect all JVMs pids. | ||
| val allJavaProcessesFile = file("all-java-processes.log") | ||
| runCmd(Redirect.to(allJavaProcessesFile), "jcmd", "-l") | ||
|
|
||
| // Collect pids for 'Gradle Test Executor'. | ||
| val pids = allJavaProcessesFile.readLines() | ||
| .filter { it.contains("Gradle Test Executor") } | ||
| .map { it.substringBefore(' ') } | ||
|
|
||
| pids.forEach { pid -> | ||
| // Collect heap dump by pid. | ||
| val heapDumpPath = file("${pid}-heap-dump.hprof").absolutePath | ||
| runCmd(Redirect.INHERIT, "jcmd", pid, "GC.heap_dump", heapDumpPath) | ||
|
|
||
| // Collect thread dump by pid. | ||
| val threadDumpFile = file("${pid}-thread-dump.log") | ||
| runCmd(Redirect.to(threadDumpFile), "jcmd", pid, "Thread.print", "-l") | ||
| } | ||
| } catch (e: Throwable) { | ||
| t.logger.warn("Taking dumps failed with error: ${e.message}, for: ${t.path}") | ||
| } | ||
| } | ||
|
|
||
| private fun cleanup(t: Test) { | ||
| val future = t.extensions.extraProperties | ||
| .takeIf { it.has(DUMP_FUTURE_KEY) } | ||
| ?.get(DUMP_FUTURE_KEY) as? ScheduledFuture<*> | ||
|
|
||
| if (future != null && !future.isDone) { | ||
| t.logger.lifecycle("Taking dump canceled with remaining delay of ${future.getDelay(TimeUnit.SECONDS)} seconds for: ${t.path}") | ||
| future.cancel(false) | ||
| } | ||
| } | ||
|
|
||
| private fun runCmd( | ||
| redirectTo: Redirect, | ||
| vararg cmd: String | ||
| ): Int = | ||
| ProcessBuilder(*cmd) | ||
| .redirectErrorStream(true) | ||
| .redirectOutput(redirectTo) | ||
| .start() | ||
| .waitFor() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.