Skip to content

Commit

Permalink
Use move strategy to be thread safe for file creation as well
Browse files Browse the repository at this point in the history
  • Loading branch information
dnestoro committed Nov 4, 2024
1 parent 5d84566 commit 97e96e6
Showing 1 changed file with 17 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -138,26 +138,38 @@ private void addDefaultAccessFilter() {
return;
}

String accessFilterPrefix = "access-filter";
String accessFilterSuffix = ".json";

String tempDir = System.getProperty("java.io.tmpdir");
Path agentDir = Path.of(tempDir).resolve("agent-config");
Path accessFilterFile = agentDir.resolve("access-filter.json");
Path accessFilterFile = agentDir.resolve(accessFilterPrefix + accessFilterSuffix);
if (Files.exists(accessFilterFile)) {
accessFilterFiles.add(accessFilterFile.toString());
return;
}

try(InputStream accessFilter = AgentConfiguration.class.getResourceAsStream(DEFAULT_ACCESS_FILTER_FILE)) {
if (accessFilter == null) {
try(InputStream accessFilterData = AgentConfiguration.class.getResourceAsStream(DEFAULT_ACCESS_FILTER_FILE)) {
if (accessFilterData == null) {
throw new IOException("Cannot find access-filter.json on default location: " + DEFAULT_ACCESS_FILTER_FILE);
}

try {
Files.createDirectory(agentDir);
} catch (FileAlreadyExistsException e) {
System.out.println("Agent directory already exists probably because other thread or process created it.");
System.out.println("Ignore directory creation because " + agentDir + " directory is already created.");
}

Path tmpAccessFilter = Files.createTempFile(agentDir, accessFilterPrefix, accessFilterSuffix);
Files.copy(accessFilterData, tmpAccessFilter);

try {
Files.move(tmpAccessFilter, accessFilterFile, StandardCopyOption.ATOMIC_MOVE);
} catch (FileAlreadyExistsException e) {
Files.delete(tmpAccessFilter);
System.out.println("Access-filter file already exists. Delete temporary one.");
}

Files.copy(accessFilter, accessFilterFile, StandardCopyOption.REPLACE_EXISTING);
accessFilterFiles.add(accessFilterFile.toString());
} catch (IOException e) {
throw new RuntimeException("Cannot add default access-filter.json" ,e);
Expand Down

0 comments on commit 97e96e6

Please sign in to comment.