private void lock() throws IOException, BlockStoreException { if (!semaphores.tryAcquire()) { throw new BlockStoreException("File in use"); } try { lock = file.getChannel().tryLock(); } catch (OverlappingFileLockException e) { semaphores.release(); lock = null; } if (lock == null) { try { this.file.close(); } finally { this.file = null; } throw new BlockStoreException("Could not lock file"); } }
/** * Locks the file, with a timeout (non-blocking). * @param timeout_ms timeout duration in milliseconds. * @throws IOException I/O exception occured. * @throws InterruptedException current thread interrupted. * @throws TimeoutException failed to obtain lock. */ public void obtain(long timeout_ms) throws IOException, InterruptedException, TimeoutException { Long quit_time = System.currentTimeMillis() + timeout_ms; if (fileLock != null && fileLock.isValid()) { // lock has already been obtained. return; } do { try { fileLock = fileToLock.tryLock(); return; } catch (OverlappingFileLockException e) { Thread.sleep(1000); } } while (System.currentTimeMillis() < quit_time); throw new TimeoutException(); }
/** * Attempts to acquire an exclusive lock on the directory. * * @return A lock object representing the newly-acquired lock or * <code>null</code> if directory is already locked. * @throws IOException if locking fails. */ @SuppressWarnings("resource") private FileLock tryLock(File dir) throws IOException { File lockF = new File(dir, FILE_LOCK); lockF.deleteOnExit(); RandomAccessFile file = new RandomAccessFile(lockF, "rws"); FileLock res = null; try { res = file.getChannel().tryLock(); } catch (OverlappingFileLockException oe) { file.close(); return null; } catch (IOException e) { LOGGER.error("Cannot create lock on " + lockF, e); file.close(); throw e; } return res; }
@Test public void shouldLockTaskStateDirectory() throws Exception { final TaskId taskId = new TaskId(0, 0); final File taskDirectory = directory.directoryForTask(taskId); directory.lock(taskId, 0); try ( final FileChannel channel = FileChannel.open( new File(taskDirectory, StateDirectory.LOCK_FILE_NAME).toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE) ) { channel.tryLock(); fail("shouldn't be able to lock already locked directory"); } catch (final OverlappingFileLockException e) { // pass } finally { directory.unlock(taskId); } }
@Override public boolean isPreUpgradableLayout(StorageDirectory sd) throws IOException { File oldF = new File(sd.getRoot(), "storage"); if (!oldF.exists()) { return false; } // check the layout version inside the storage file // Lock and Read old storage file try (RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws"); FileLock oldLock = oldFile.getChannel().tryLock()) { if (null == oldLock) { LOG.error("Unable to acquire file lock on path " + oldF.toString()); throw new OverlappingFileLockException(); } oldFile.seek(0); int oldVersion = oldFile.readInt(); if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION) { return false; } } return true; }
private void lock() throws IOException, BlockStoreException { if (!semaphores.tryAcquire(fileName)) { throw new BlockStoreException("File in use"); } try { lock = channel.tryLock(); } catch (OverlappingFileLockException e) { semaphores.release(fileName); lock = null; } if (lock == null) { try { this.file.close(); } finally { this.file = null; } throw new BlockStoreException("Could not lock file"); } }
private void lock() throws IOException, BlockStoreException { if (!semaphores.tryAcquire(fileName)) { throw new BlockStoreException("File in use"); } try { lock = file.getChannel().tryLock(); } catch (OverlappingFileLockException e) { semaphores.release(fileName); lock = null; } if (lock == null) { try { this.file.close(); } finally { this.file = null; } throw new BlockStoreException("Could not lock file"); } }
@Test(expected = OverlappingFileLockException.class) public void test_repate_restart() throws Exception { long totalMsgs = 100; QUEUE_TOTAL = 1; MessageBody = StoreMessage.getBytes(); MessageStoreConfig messageStoreConfig = new MessageStoreConfig(); messageStoreConfig.setMapedFileSizeCommitLog(1024 * 8); messageStoreConfig.setMapedFileSizeConsumeQueue(1024 * 4); messageStoreConfig.setMaxHashSlotNum(100); messageStoreConfig.setMaxIndexNum(100 * 10); MessageStore master = new DefaultMessageStore(messageStoreConfig, null, new MyMessageArrivingListener(), new BrokerConfig()); boolean load = master.load(); assertTrue(load); try { master.start(); master.start(); } finally { master.shutdown(); master.destroy(); } }
/** * Attempts to acquire an exclusive lock on the storage. * * @return A lock object representing the newly-acquired lock or * <code>null</code> if storage is already locked. * @throws IOException if locking fails. */ FileLock tryLock() throws IOException { File lockF = new File(root, STORAGE_FILE_LOCK); lockF.deleteOnExit(); RandomAccessFile file = new RandomAccessFile(lockF, "rws"); FileLock res = null; try { res = file.getChannel().tryLock(); } catch(OverlappingFileLockException oe) { file.close(); return null; } catch(IOException e) { LOG.error("Cannot create lock on " + lockF, e); file.close(); throw e; } return res; }
public void lock(Object key) throws IOException { if (key == null) { throw new NullPointerException("key should not be null"); } int hashCode = key.hashCode(); FileLock fileLock; for (;;) { try { fileLock = fileChannel.lock(hashCode, 1, false); break; } catch (OverlappingFileLockException e) { Thread.yield(); } catch (Throwable cause) { throw new RuntimeException("lock file fail", cause); } } FileLock old = fileLockThreadLocal.get(); if (old != null) { old.release(); } fileLockThreadLocal.set(fileLock); }
private static boolean lock(File directory) { String name = "node.lock"; File lockfile = new File(directory, name); lockfile.deleteOnExit(); try { FileChannel fc = (FileChannel) Channels.newChannel(new FileOutputStream(lockfile)); lock = fc.tryLock(); if (lock != null) { return true; } } catch (IOException x) { System.err.println(x.toString()); } catch (OverlappingFileLockException e) { System.err.println(e.toString()); } return false; }
void lockCLI(File lockPlace) throws Exception { if (lockPlace != null) { lockPlace.mkdirs(); if (serverLockFile == null) { File fileLock = new File(lockPlace, "cli.lock"); serverLockFile = new RandomAccessFile(fileLock, "rw"); } try { FileLock lock = serverLockFile.getChannel().tryLock(); if (lock == null) { throw new CLIException("Error: There is another process using the server at " + lockPlace + ". Cannot start the process!"); } serverLockLock = lock; } catch (OverlappingFileLockException e) { throw new CLIException("Error: There is another process using the server at " + lockPlace + ". Cannot start the process!"); } } }
public FileLock tryLock(Channel channel, long start, long size, boolean shared) throws IOException{ if(!channel.isOpen()) { throw new ClosedChannelException(); } Iterator<EphemeralFsFileLock> iter = locks.iterator(); while(iter.hasNext()) { EphemeralFsFileLock oldLock = iter.next(); if(!oldLock.isValid()) { iter.remove(); } else if(oldLock.overlaps(start, size)) { throw new OverlappingFileLockException(); } } EphemeralFsFileLock newLock = channel instanceof FileChannel ? new EphemeralFsFileLock((FileChannel) channel, start, size, shared) : new EphemeralFsFileLock((AsynchronousFileChannel) channel, start, size, shared); locks.add(newLock); return newLock; }
@Test public void testLockShared() throws Exception { Path file = root.resolve("locked"); Files.createFile(file); FileChannel channel = (FileChannel) Files.newByteChannel(file, StandardOpenOption.WRITE, StandardOpenOption.READ); try { FileLock lock = channel.tryLock(0, 5, true); assertNotNull(lock); assertTrue(lock.isShared()); assertTrue(lock.isValid()); try { lock = channel.tryLock(0, 5, true); fail(); } catch(OverlappingFileLockException e) { //pass } } finally { channel.close(); } }
synchronized void addLock(FileLock lock) throws OverlappingFileLockException { long lockEnd = lock.position() + lock.size(); for (Iterator<FileLock> keyItr = locks.iterator(); keyItr.hasNext();) { FileLock existingLock = keyItr.next(); if (existingLock.position() > lockEnd) { // This, and all remaining locks, start beyond our end (so // cannot overlap). break; } if (existingLock.overlaps(lock.position(), lock.size())) { throw new OverlappingFileLockException(); } } locks.add(lock); }
/** * @tests serialization/deserialization compatibility. */ @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "!SerializationSelf", args = {} ), @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "OverlappingFileLockException", args = {} ) }) public void testSerializationSelf() throws Exception { SerializationTest.verifySelf(new OverlappingFileLockException()); }
/** * @tests serialization/deserialization compatibility with RI. */ @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "!SerializationGolden", args = {} ), @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies serialization/deserialization compatibility.", method = "OverlappingFileLockException", args = {} ) }) public void testSerializationCompatibility() throws Exception { SerializationTest .verifyGolden(this, new OverlappingFileLockException()); }
boolean setLock(String rw, long beginIndex, long bytesNum, boolean s){ if(!this.exists()) return false; try{ raf = new RandomAccessFile(this, rw); fc = raf.getChannel(); flk = fc.lock(beginIndex, bytesNum, s); }catch(OverlappingFileLockException oe){ LogUtil.warn("[SetLock]", "[No effect]", "the region has already been locked"); return false; }catch(Exception e){ LogUtil.info("[SetLock]", "[No effect]", e); return false; } return true; }
/** * Acquire the lock for writing log file. * * @return the file lock or {@code null} if the lock cannot be obtained. */ public final FileLock acquireLock() { try { FileLock lock = null; int attempt = 0; while (lock == null && attempt++ < 10) { lock = this.out.getChannel().tryLock(); if (lock == null) { Thread.sleep(1000); } } if (lock == null) { LOG.trace("Obtained the lock for the log-file."); } else { LOG.trace("Did not get the lock for the log-file, " + "since it is already locked by another logger."); } return lock; } catch (OverlappingFileLockException | InterruptedException | IOException exc) { LOG.error("Failed to get the lock for the log-file.", exc); return null; } }
/** * To prevent 'buck kill' from deleting resources from underneath a 'live' buckd we hold on to the * FileLock for the entire lifetime of the process. We depend on the fact that on Linux and MacOS * Java FileLock is implemented using the same mechanism as the Python fcntl.lockf method. Should * this not be the case we'll simply have a small race between buckd start and `buck kill`. */ private static void obtainResourceFileLock() { if (resourcesFileLock != null) { return; } String resourceLockFilePath = System.getProperties().getProperty("buck.resource_lock_path"); if (resourceLockFilePath == null) { // Running from ant, no resource lock needed. return; } try { // R+W+A is equivalent to 'a+' in Python (which is how the lock file is opened in Python) // because WRITE in Java does not imply truncating the file. FileChannel fileChannel = FileChannel.open( Paths.get(resourceLockFilePath), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); resourcesFileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, true); } catch (IOException | OverlappingFileLockException e) { LOG.debug(e, "Error when attempting to acquire resources file lock."); } }
private FileLock getLock() throws OverlappingFileLockException, InterruptedException, IOException { File lockFile = localFs.pathToFile(new Path(lockPath, host + ".lock")); final boolean created = lockFile.createNewFile(); if (created == false && !lockFile.exists()) { // bail-out cleanly return null; } // invariant - file created (winner writes to this file) // caveat: closing lockChannel does close the file (do not double close) // JDK7 - TODO: use AsynchronousFileChannel instead of RandomAccessFile FileChannel lockChannel = new RandomAccessFile(lockFile, "rws") .getChannel(); FileLock xlock = null; xlock = lockChannel.tryLock(0, Long.MAX_VALUE, false); if (xlock != null) { return xlock; } lockChannel.close(); return null; }
/** * Attempts to acquire an exclusive lock on the storage. * * @return A lock object representing the newly-acquired lock or * <code>null</code> if storage is already locked. * @throws IOException if locking fails. */ FileLock tryLock() throws IOException { File lockF = new File(root, STORAGE_FILE_LOCK); lockF.deleteOnExit(); RandomAccessFile file = new RandomAccessFile(lockF, "rws"); FileLock res = null; try { res = file.getChannel().tryLock(); } catch(OverlappingFileLockException oe) { file.close(); return null; } catch(IOException e) { LOG.info(StringUtils.stringifyException(e)); file.close(); throw e; } return res; }