19 package org.sleuthkit.datamodel;
22 import java.io.IOException;
23 import java.io.RandomAccessFile;
24 import java.nio.channels.FileChannel;
25 import java.nio.channels.FileLock;
26 import java.nio.channels.OverlappingFileLockException;
31 class LockResources
implements AutoCloseable {
33 private static final String LOCK_FILE_PREFIX =
".lock_";
35 private File lockFile = null;
36 private RandomAccessFile lockFileRaf = null;
37 private FileChannel lockFileChannel = null;
38 private FileLock lockFileLock = null;
48 LockResources(File lockFile, RandomAccessFile lockFileRaf, FileChannel lockFileChannel, FileLock lockFileLock) {
49 this.lockFile = lockFile;
50 this.lockFileRaf = lockFileRaf;
51 this.lockFileChannel = lockFileChannel;
52 this.lockFileLock = lockFileLock;
68 static LockResources tryAcquireFileLock(String caseDir, String dbName, String applicationName)
throws ConcurrentDbAccessException, IOException, OverlappingFileLockException {
70 String lockFileName = LOCK_FILE_PREFIX + (dbName == null ?
"tskdb" : dbName);
71 File lockFile =
new File(caseDir, lockFileName);
73 lockFile.getParentFile().mkdirs();
76 if (lockFile.isFile() && !lockFile.canWrite()) {
78 RandomAccessFile lockFileRaf =
new RandomAccessFile(lockFile,
"r");
79 throw ConcurrentDbAccessException.createForFile(lockFile.getAbsolutePath(), lockFileRaf);
81 RandomAccessFile lockFileRaf =
new RandomAccessFile(lockFile,
"rw");
82 FileChannel lockFileChannel = lockFileRaf.getChannel();
83 FileLock lockFileLock = lockFileChannel == null
85 : lockFileChannel.tryLock(1024L, 1L,
false);
87 if (lockFileLock != null) {
88 lockFileRaf.setLength(0);
89 String limitedAppName = applicationName.length() > 500 ? applicationName.substring(0, 500) : applicationName;
90 lockFileRaf.writeChars(limitedAppName);
91 return new LockResources(lockFile, lockFileRaf, lockFileChannel, lockFileLock);
93 throw ConcurrentDbAccessException.createForFile(lockFile.getAbsolutePath(), lockFileRaf);
99 public void close() throws Exception {
101 if (this.lockFileLock != null) {
102 this.lockFileLock.close();
103 this.lockFileLock = null;
106 if (this.lockFileChannel != null) {
107 this.lockFileChannel.close();
108 this.lockFileChannel = null;
111 if (this.lockFileRaf != null) {
112 this.lockFileRaf.close();
113 this.lockFileRaf = null;
116 if (this.lockFile != null) {
117 this.lockFile.delete();
118 this.lockFile = null;