From ced34d91d4be20b13ae84cda00e8056021104717 Mon Sep 17 00:00:00 2001 From: Michael Walker Date: Fri, 14 Jul 2017 10:37:50 +0100 Subject: [PATCH] Delete temporary files created by Tar on close The SwapJob creates temporary files indirectly through Tar.bz2.zip. These files are deleted with File.deleteOnExit, but there is no other deletion mechanism. This means that temporary files will build up as the git bridge runs, only being deleted when the JVM finally terminates. Instead, we can delete these temporary files as soon as they are no longer needed. The files are wrapped in a FileInputStream and not directly exposed, so we can simply delete the underlying file when the stream is closed, as then the file is inaccessible. --- .../util/DeletingFileInputStream.java | 41 +++++++++++++++++++ .../java/uk/ac/ic/wlgitbridge/util/Tar.java | 2 +- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 services/git-bridge/src/main/java/uk/ac/ic/wlgitbridge/util/DeletingFileInputStream.java diff --git a/services/git-bridge/src/main/java/uk/ac/ic/wlgitbridge/util/DeletingFileInputStream.java b/services/git-bridge/src/main/java/uk/ac/ic/wlgitbridge/util/DeletingFileInputStream.java new file mode 100644 index 0000000000..a8fbb18a49 --- /dev/null +++ b/services/git-bridge/src/main/java/uk/ac/ic/wlgitbridge/util/DeletingFileInputStream.java @@ -0,0 +1,41 @@ +package uk.ac.ic.wlgitbridge.util; + +import java.io.*; + +/** + * A {@link java.io.FileInputStream} which deletes the underlying + * {@link java.io.File} on close. + * + * @author Michael Walker (barrucadu) {@literal } + */ +public class DeletingFileInputStream extends FileInputStream { + private File file; + + /** + * Creates a {@link java.io.FileInputStream} by opening a + * connection to an actual file, the file named by the + * {@link java.io.File} object file in the file system. + * + * When the {@link close} method is called, the {@code File} will + * be deleted. + */ + public DeletingFileInputStream(File file) throws FileNotFoundException { + super(file); + this.file = file; + } + + /** + * Closes this input stream and deletes the underlying file. + */ + @Override + public void close() throws IOException { + try { + super.close(); + } finally { + if(file != null) { + file.delete(); + file = null; + } + } + } +} diff --git a/services/git-bridge/src/main/java/uk/ac/ic/wlgitbridge/util/Tar.java b/services/git-bridge/src/main/java/uk/ac/ic/wlgitbridge/util/Tar.java index d394070d13..5ca710e51e 100644 --- a/services/git-bridge/src/main/java/uk/ac/ic/wlgitbridge/util/Tar.java +++ b/services/git-bridge/src/main/java/uk/ac/ic/wlgitbridge/util/Tar.java @@ -46,7 +46,7 @@ public class Tar { if (sizePtr != null) { sizePtr[0] = tmp.length(); } - return new FileInputStream(tmp); + return new DeletingFileInputStream(tmp); } public static void unzip(