Search in sources :

Example 11 with OverlappingFileLockException

use of java.nio.channels.OverlappingFileLockException in project azure-tools-for-java by Microsoft.

the class FileTokenCache method acquireLock.

private FileLock acquireLock(RandomAccessFile raf) throws IOException, InterruptedException {
    // in case of multiprocess file access
    FileLock lock = null;
    int tryCount = 3;
    long sleepSec = 10;
    while (tryCount > 0) {
        try {
            lock = raf.getChannel().tryLock();
            break;
        } catch (OverlappingFileLockException ex) {
            log.log(Level.WARNING, String.format("The file has been locked by another process - waiting %s sec to release [%d attempt(s) left].", sleepSec, tryCount));
            Thread.sleep(sleepSec * 1000);
            tryCount--;
        }
    }
    return lock;
}
Also used : FileLock(java.nio.channels.FileLock) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException)

Example 12 with OverlappingFileLockException

use of java.nio.channels.OverlappingFileLockException in project ats-framework by Axway.

the class LocalFileSystemOperations method lockFile.

/**
     * <pre>
     * Acquires an exclusive lock on a file
     *
     * <b>Platform dependencies</b>
     *
     * - In Windows it works as expected
     * - In Linux it depends on the locking mechanism of the system. The file locking types are two - advisory and mandatory:
     *
     *    a) <b>Advisory locking</b> - advisory locking will work, only if the participating process are cooperative.
     *       Advisory locking sometimes also called as "unenforced" locking.
     *
     *    b) <b>Mandatory locking</b> - mandatory locking doesn’t require cooperation from the participating processes.
     *       It causes the kernel to check every open, read and write to verify that the calling process isn’t
     *       violating a lock on the given file. To enable mandatory locking in Linux, you need to enable it on
     *       a file system level and also on the individual files. The steps to be followed are:
     *           1. Mount the file system with "<i>-o mand</i>" option
     *           2. For the lock_file, turn on the set-group-ID bit and turn off the group-execute bit, to enable
     *              mandatory locking on that particular file. (This way has been chosen because when you turn off
     *              the group-execute bit, set-group-ID has no real meaning to it )
     *
     *       How to do mandatory locking:
     *           Note: You need to be root to execute the below command
     *           <i># mount -oremount,mand /</i>
     *           <i># touch mandatory.txt</i>
     *           <i># chmod g+s,g-x mandatory.txt</i>
     * </pre>
     *
     * @param fileName file name
     */
@Override
public void lockFile(String fileName) {
    synchronized (lockedFiles) {
        if (lockedFiles.containsKey(fileName)) {
            log.warn("File '" + fileName + "' is already locked");
        } else {
            try {
                File fileToLock = new File(fileName);
                @SuppressWarnings("resource") FileChannel //keep lock to the file
                channel = new RandomAccessFile(fileToLock, "rw").getChannel();
                FileLock fileLock = channel.lock();
                lockedFiles.put(fileName, fileLock);
            } catch (FileNotFoundException fnfe) {
                throw new FileSystemOperationException("File '" + fileName + "' is not found", fnfe);
            } catch (OverlappingFileLockException ofle) {
                throw new FileSystemOperationException("File '" + fileName + "' is already locked in the current JVM" + ", but not from this class, so we can't unlock it later.", ofle);
            } catch (Exception e) {
                throw new FileSystemOperationException("Could not lock file '" + fileName + "'", e);
            }
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) FileNotFoundException(java.io.FileNotFoundException) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) AttributeNotSupportedException(com.axway.ats.core.filesystem.exceptions.AttributeNotSupportedException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) FileDoesNotExistException(com.axway.ats.core.filesystem.exceptions.FileDoesNotExistException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 13 with OverlappingFileLockException

use of java.nio.channels.OverlappingFileLockException in project ignite by apache.

the class MarshallerMappingFileStore method writeMapping.

/**
     * @param platformId Platform id.
     * @param typeId Type id.
     * @param typeName Type name.
     */
void writeMapping(byte platformId, int typeId, String typeName) {
    String fileName = getFileName(platformId, typeId);
    Lock lock = fileLock(fileName);
    lock.lock();
    try {
        File file = new File(workDir, fileName);
        try (FileOutputStream out = new FileOutputStream(file)) {
            FileLock fileLock = fileLock(out.getChannel(), false);
            assert fileLock != null : fileName;
            try (Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
                writer.write(typeName);
                writer.flush();
            }
        } catch (IOException e) {
            U.error(log, "Failed to write class name to file [platformId=" + platformId + "id=" + typeId + ", clsName=" + typeName + ", file=" + file.getAbsolutePath() + ']', e);
        } catch (OverlappingFileLockException ignored) {
            if (log.isDebugEnabled())
                log.debug("File already locked (will ignore): " + file.getAbsolutePath());
        } catch (IgniteInterruptedCheckedException e) {
            U.error(log, "Interrupted while waiting for acquiring file lock: " + file, e);
        }
    } finally {
        lock.unlock();
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) FileLock(java.nio.channels.FileLock) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) File(java.io.File) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) FileLock(java.nio.channels.FileLock) GridStripedLock(org.apache.ignite.internal.util.GridStripedLock) Lock(java.util.concurrent.locks.Lock)

Example 14 with OverlappingFileLockException

use of java.nio.channels.OverlappingFileLockException in project jackrabbit by apache.

the class RepositoryLock method tryLock.

/**
     * Try to lock the random access file.
     *
     * @throws RepositoryException
     */
private void tryLock() throws RepositoryException {
    try {
        randomAccessFile = new RandomAccessFile(file, "rw");
        lock = randomAccessFile.getChannel().tryLock();
    } catch (IOException e) {
        throw new RepositoryException("Unable to create or lock file " + file, e);
    } catch (OverlappingFileLockException e) {
        // JCR-912: OverlappingFileLockException with JRE 1.6
        throw new RepositoryException("The repository home " + directory + " appears to be in use" + " since the file named " + file.getName() + " is already locked by the current process.");
    }
    if (lock == null) {
        throw new RepositoryException("The repository home " + directory + " appears to be in use" + " since the file named " + file.getName() + " is locked by another process.");
    }
    // held by *this* jvm process
    synchronized (identifier) {
        if (null != System.getProperty(identifier)) {
            // as well
            throw new RepositoryException("The repository home " + directory + " appears to be" + " already locked by the current process.");
        } else {
            try {
                System.setProperty(identifier, identifier);
            } catch (SecurityException e) {
                LOG.warn("Unable to set system property: " + identifier, e);
            }
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) RepositoryException(javax.jcr.RepositoryException) IOException(java.io.IOException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException)

Example 15 with OverlappingFileLockException

use of java.nio.channels.OverlappingFileLockException in project ice by JBEI.

the class BlastPlus method rebuildDatabase.

/**
     * Re-builds the blast database, using a lock file to prevent concurrent rebuilds.
     * The lock file has a "life-span" of 1 day after which it is deleted.
     * <p/>
     * Also, a rebuild can be forced even if a lock file exists which is less than a day old
     *
     * @param force set to true to force a rebuild. Use with caution
     * @throws BlastException
     */
public static void rebuildDatabase(boolean force) throws BlastException {
    String blastInstallDir = Utils.getConfigValue(ConfigurationKey.BLAST_INSTALL_DIR);
    if (StringUtils.isEmpty(blastInstallDir)) {
        Logger.warn("Blast install directory not available. Aborting blast rebuild");
        return;
    }
    Path blastDir = Paths.get(blastInstallDir);
    if (!Files.exists(blastDir))
        throw new BlastException("Could not locate Blast installation in " + blastInstallDir);
    String dataDir = Utils.getConfigValue(ConfigurationKey.DATA_DIRECTORY);
    final Path blastFolder = Paths.get(dataDir, BLAST_DB_FOLDER);
    File lockFile = Paths.get(blastFolder.toString(), LOCK_FILE_NAME).toFile();
    if (lockFile.exists()) {
        if (lockFile.lastModified() <= (System.currentTimeMillis() - (1000 * 60 * 60 * 24))) {
            if (!lockFile.delete()) {
                Logger.warn("Could not delete outdated blast lockfile. Delete the following file manually: " + lockFile.getAbsolutePath());
                return;
            }
        } else {
            Logger.info("Blast db locked (lockfile - " + lockFile.getAbsolutePath() + "). Rebuild aborted!");
            return;
        }
    }
    try {
        if (!Files.exists(blastFolder)) {
            Logger.info("Blast folder (" + blastFolder.toString() + ") does not exist. Creating...");
            try {
                Files.createDirectories(blastFolder);
            } catch (Exception e) {
                Logger.warn("Could not create blast folder. Create it manually or all blast runs will fail");
                return;
            }
        }
        if (!force && blastDatabaseExists()) {
            Logger.info("Blast database found in " + blastFolder.toAbsolutePath().toString());
            return;
        }
        if (!lockFile.createNewFile()) {
            Logger.warn("Could not create lock file for blast rebuild");
            return;
        }
        FileOutputStream fos = new FileOutputStream(lockFile);
        try (FileLock lock = fos.getChannel().tryLock()) {
            if (lock == null)
                return;
            Logger.info("Rebuilding blast database");
            rebuildSequenceDatabase(blastDir, blastFolder, false);
            Logger.info("Blast database rebuild complete");
        }
    } catch (OverlappingFileLockException l) {
        Logger.warn("Could not obtain lock file for blast at " + blastFolder.toString());
    } catch (IOException eio) {
        FileUtils.deleteQuietly(lockFile);
        throw new BlastException(eio);
    }
    FileUtils.deleteQuietly(lockFile);
}
Also used : FileLock(java.nio.channels.FileLock) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) IllegalAlphabetException(org.biojava.bio.symbol.IllegalAlphabetException) IllegalSymbolException(org.biojava.bio.symbol.IllegalSymbolException)

Aggregations

OverlappingFileLockException (java.nio.channels.OverlappingFileLockException)28 IOException (java.io.IOException)15 FileLock (java.nio.channels.FileLock)15 File (java.io.File)11 FileChannel (java.nio.channels.FileChannel)10 RandomAccessFile (java.io.RandomAccessFile)7 FileOutputStream (java.io.FileOutputStream)3 TaskId (org.apache.kafka.streams.processor.TaskId)3 Test (org.junit.Test)3 Path (java.nio.file.Path)2 IllegalAlphabetException (org.biojava.bio.symbol.IllegalAlphabetException)2 IllegalSymbolException (org.biojava.bio.symbol.IllegalSymbolException)2 FileSystemOperationException (com.axway.ats.common.filesystem.FileSystemOperationException)1 AttributeNotSupportedException (com.axway.ats.core.filesystem.exceptions.AttributeNotSupportedException)1 FileDoesNotExistException (com.axway.ats.core.filesystem.exceptions.FileDoesNotExistException)1 ParallelTest (com.hazelcast.test.annotation.ParallelTest)1 QuickTest (com.hazelcast.test.annotation.QuickTest)1 LogException (io.mycat.backend.mysql.xa.recovery.LogException)1 EOFException (java.io.EOFException)1 FileNotFoundException (java.io.FileNotFoundException)1