Skip to content

Commit 6730e44

Browse files
committed
Remove cleanup-on-shutdown for temporary files
1 parent bd7a9c8 commit 6730e44

File tree

3 files changed

+31
-42
lines changed

3 files changed

+31
-42
lines changed

dd-java-agent/agent-profiling/profiling-controller-openjdk/src/main/java/com/datadog/profiling/controller/openjdk/OpenJdkController.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,8 @@ private static String getJfrRepositoryBase(ConfigProvider configProvider) {
263263
ProfilingConfig.PROFILING_JFR_REPOSITORY_BASE,
264264
ProfilingConfig.PROFILING_TEMP_DIR);
265265
}
266-
Path repositoryPath = TempLocationManager.getInstance().getTempDir().resolve("jfr");
266+
TempLocationManager tempLocationManager = TempLocationManager.getInstance();
267+
Path repositoryPath = tempLocationManager.getTempDir().resolve("jfr");
267268
if (!Files.exists(repositoryPath)) {
268269
try {
269270
Files.createDirectories(repositoryPath);

dd-java-agent/agent-profiling/profiling-controller/src/main/java/com/datadog/profiling/controller/TempLocationManager.java

+25-36
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.datadog.profiling.controller;
22

33
import static datadog.trace.api.telemetry.LogCollector.SEND_TELEMETRY;
4-
import static datadog.trace.util.AgentThreadFactory.AGENT_THREAD_GROUP;
54

65
import datadog.trace.api.config.ProfilingConfig;
76
import datadog.trace.bootstrap.config.provider.ConfigProvider;
@@ -19,7 +18,9 @@
1918
import java.nio.file.attribute.PosixFilePermissions;
2019
import java.time.Instant;
2120
import java.time.temporal.ChronoUnit;
21+
import java.util.Map;
2222
import java.util.Set;
23+
import java.util.concurrent.ConcurrentHashMap;
2324
import java.util.concurrent.CountDownLatch;
2425
import java.util.concurrent.TimeUnit;
2526
import java.util.regex.Pattern;
@@ -67,22 +68,20 @@ default FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOE
6768
return null;
6869
}
6970

70-
default void onCleanupStart(boolean selfCleanup, long timeout, TimeUnit unit) {}
71+
default void onCleanupStart(long timeout, TimeUnit unit) {}
7172
}
7273

7374
private final class CleanupVisitor implements FileVisitor<Path> {
7475
private boolean shouldClean;
7576

7677
private Set<String> pidSet;
7778

78-
private final boolean cleanSelf;
7979
private final Instant cutoff;
8080
private final Instant timeoutTarget;
8181

8282
private boolean terminated = false;
8383

84-
CleanupVisitor(boolean cleanSelf, long timeout, TimeUnit unit) {
85-
this.cleanSelf = cleanSelf;
84+
CleanupVisitor(long timeout, TimeUnit unit) {
8685
this.cutoff = Instant.now().minus(cutoffSeconds, ChronoUnit.SECONDS);
8786
this.timeoutTarget =
8887
timeout > -1
@@ -106,10 +105,6 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
106105
terminated = true;
107106
return FileVisitResult.TERMINATE;
108107
}
109-
if (cleanSelf && JFR_DIR_PATTERN.matcher(dir.getFileName().toString()).matches()) {
110-
// do not delete JFR repository on 'self-cleanup' - it conflicts with the JFR's own cleanup
111-
return FileVisitResult.SKIP_SUBTREE;
112-
}
113108

114109
cleanupTestHook.preVisitDirectory(dir, attrs);
115110

@@ -120,9 +115,7 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
120115
// the JFR repository directories are under <basedir>/pid_<pid>
121116
String pid = fileName.startsWith(TEMPDIR_PREFIX) ? fileName.substring(4) : null;
122117
boolean isSelfPid = pid != null && pid.equals(PidHelper.getPid());
123-
if (cleanSelf) {
124-
shouldClean |= isSelfPid;
125-
} else if (!isSelfPid) {
118+
if (!isSelfPid) {
126119
if (pidSet == null) {
127120
pidSet = PidHelper.getJavaPids(); // only fork jps when required
128121
}
@@ -200,7 +193,7 @@ private final class CleanupTask implements Runnable {
200193
@Override
201194
public void run() {
202195
try {
203-
cleanup(false);
196+
cleanup();
204197
} catch (OutOfMemoryError oom) {
205198
throw oom;
206199
} catch (Throwable t) {
@@ -226,6 +219,8 @@ boolean await(long timeout, TimeUnit unit) throws Throwable {
226219
private final CleanupTask cleanupTask = new CleanupTask();
227220
private final CleanupHook cleanupTestHook;
228221

222+
private final Map<Path, Path> ignoredPaths = new ConcurrentHashMap<>();
223+
229224
/**
230225
* Get the singleton instance of the TempLocationManager. It will run the cleanup task in the
231226
* background.
@@ -303,20 +298,6 @@ private TempLocationManager() {
303298
// do not execute the background cleanup task when running in tests
304299
AgentTaskScheduler.INSTANCE.execute(cleanupTask);
305300
}
306-
307-
Thread selfCleanup =
308-
new Thread(
309-
AGENT_THREAD_GROUP,
310-
() -> {
311-
if (!waitForCleanup(1, TimeUnit.SECONDS)) {
312-
log.info(
313-
"Cleanup task timed out. {} temp directory might not have been cleaned up properly",
314-
tempDir);
315-
}
316-
cleanup(true);
317-
},
318-
"Temp Location Manager Cleanup");
319-
Runtime.getRuntime().addShutdownHook(selfCleanup);
320301
}
321302

322303
// @VisibleForTesting
@@ -381,30 +362,38 @@ public Path getTempDir(Path subPath, boolean create) {
381362
return rslt;
382363
}
383364

365+
public void ignore(Path path) {
366+
if (path.startsWith(baseTempDir)) {
367+
// ignore the path if it is a child of the base temp directory
368+
ignoredPaths.put(path, path);
369+
} else {
370+
log.debug(
371+
"Path {} which is not a child of the base temp directory {} can not be ignored",
372+
path,
373+
baseTempDir);
374+
}
375+
}
376+
384377
/**
385378
* Walk the base temp directory recursively and remove all inactive per-process entries. No
386379
* timeout is applied.
387380
*
388-
* @param cleanSelf {@literal true} will call only this process' temp directory, {@literal false}
389-
* only the other processes will be cleaned up
390381
* @return {@literal true} if cleanup fully succeeded or {@literal false} otherwise (eg.
391382
* interruption etc.)
392383
*/
393-
boolean cleanup(boolean cleanSelf) {
394-
return cleanup(cleanSelf, -1, TimeUnit.SECONDS);
384+
boolean cleanup() {
385+
return cleanup(-1, TimeUnit.SECONDS);
395386
}
396387

397388
/**
398389
* Walk the base temp directory recursively and remove all inactive per-process entries
399390
*
400-
* @param cleanSelf {@literal true} will call only this process' temp directory, {@literal false}
401-
* only the other processes will be cleaned up
402391
* @param timeout the task timeout; may be {@literal -1} to signal no timeout
403392
* @param unit the task timeout unit
404393
* @return {@literal true} if cleanup fully succeeded or {@literal false} otherwise (timeout,
405394
* interruption etc.)
406395
*/
407-
boolean cleanup(boolean cleanSelf, long timeout, TimeUnit unit) {
396+
boolean cleanup(long timeout, TimeUnit unit) {
408397
try {
409398
if (!Files.exists(baseTempDir)) {
410399
// not even the main temp location exists; nothing to clean up
@@ -419,8 +408,8 @@ boolean cleanup(boolean cleanSelf, long timeout, TimeUnit unit) {
419408
return true;
420409
}
421410
}
422-
cleanupTestHook.onCleanupStart(cleanSelf, timeout, unit);
423-
CleanupVisitor visitor = new CleanupVisitor(cleanSelf, timeout, unit);
411+
cleanupTestHook.onCleanupStart(timeout, unit);
412+
CleanupVisitor visitor = new CleanupVisitor(timeout, unit);
424413
Files.walkFileTree(baseTempDir, visitor);
425414
return !visitor.isTerminated();
426415
} catch (IOException e) {

dd-java-agent/agent-profiling/profiling-controller/src/test/java/com/datadog/profiling/controller/TempLocationManagerTest.java

+4-5
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ void testCleanup(String subPath) throws Exception {
112112
Path tmpFile = Files.createFile(fakeTempDir.resolve("test.txt"));
113113
tmpFile.toFile().deleteOnExit(); // make sure this is deleted at exit
114114
fakeTempDir.toFile().deleteOnExit(); // also this one
115-
boolean rslt = tempLocationManager.cleanup(false);
115+
boolean rslt = tempLocationManager.cleanup();
116116
// fake temp location should be deleted
117117
// real temp location should be kept
118118
assertFalse(rslt && Files.exists(fakeTempDir));
@@ -241,8 +241,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
241241
Files.createFile(mytempdir.resolve("dummy"));
242242
Files.createFile(otherTempdir.resolve("dummy"));
243243
boolean rslt =
244-
instance.cleanup(
245-
selfCleanup, (long) (timeoutMs * (shouldSucceed ? 20 : 0.5d)), TimeUnit.MILLISECONDS);
244+
instance.cleanup((long) (timeoutMs * (shouldSucceed ? 20 : 0.5d)), TimeUnit.MILLISECONDS);
246245
assertEquals(shouldSucceed, rslt);
247246
}
248247

@@ -256,15 +255,15 @@ void testShortCircuit() throws Exception {
256255
TempLocationManager.CleanupHook hook =
257256
new TempLocationManager.CleanupHook() {
258257
@Override
259-
public void onCleanupStart(boolean selfCleanup, long timeout, TimeUnit unit) {
258+
public void onCleanupStart(long timeout, TimeUnit unit) {
260259
executed.set(true);
261260
}
262261
};
263262
TempLocationManager instance = instance(baseDir, false, hook);
264263

265264
instance.createDirStructure();
266265

267-
boolean ret = instance.cleanup(false);
266+
boolean ret = instance.cleanup();
268267
assertTrue(ret);
269268
assertFalse(executed.get());
270269
}

0 commit comments

Comments
 (0)