in agent/agent-tooling/src/main/java/com/microsoft/applicationinsights/agent/internal/localstorage/LocalFileLoader.java [69:140]
PersistedFile loadTelemetriesFromDisk() {
String filenameToBeLoaded = localFileCache.poll();
if (filenameToBeLoaded == null) {
return null;
}
// when reading a file from the disk, loader renames the source file to "*.tmp" to prevent other
// threads from processing the same file over and over again. this will prevent same data gets
// sent to Application Insights more than once. after reading raw bytes from the .tmp file,
// loader will delete the temp file when http
// response confirms it is sent successfully; otherwise, temp file will get renamed back to the
// source file extension.
File tempFile;
File sourceFile;
try {
sourceFile = new File(telemetryFolder, filenameToBeLoaded);
if (!sourceFile.exists()) {
return null;
}
tempFile =
new File(
telemetryFolder,
FilenameUtils.getBaseName(filenameToBeLoaded) + TEMPORARY_FILE_EXTENSION);
FileUtils.moveFile(sourceFile, tempFile);
} catch (IOException e) {
operationLogger.recordFailure(
"Failed to change "
+ filenameToBeLoaded
+ " to have "
+ TEMPORARY_FILE_EXTENSION
+ " extension: ",
e);
incrementReadFailureCount();
return null;
}
if (tempFile.length() <= 36) {
if (LocalStorageUtils.deleteFileWithRetries(tempFile)) {
operationLogger.recordFailure(
"Fail to delete a corrupted persisted file: length is " + tempFile.length());
}
return null;
}
byte[] ikeyBytes = new byte[36];
int rawByteLength = (int) tempFile.length() - 36;
byte[] telemetryBytes = new byte[rawByteLength];
String instrumentationKey;
try (FileInputStream fileInputStream = new FileInputStream(tempFile)) {
readFully(fileInputStream, ikeyBytes, 36);
instrumentationKey = new String(ikeyBytes, UTF_8);
if (!isInstrumentationKeyValid(instrumentationKey)) {
fileInputStream.close(); // need to close FileInputStream before delete
if (!LocalStorageUtils.deleteFileWithRetries(tempFile)) {
operationLogger.recordFailure(
"Fail to delete the old persisted file with an invalid instrumentation key "
+ tempFile.getName());
}
return null;
}
readFully(fileInputStream, telemetryBytes, rawByteLength);
} catch (IOException ex) {
operationLogger.recordFailure("Fail to read telemetry from " + tempFile.getName(), ex);
incrementReadFailureCount();
return null;
}
operationLogger.recordSuccess();
return new PersistedFile(tempFile, instrumentationKey, ByteBuffer.wrap(telemetryBytes));
}