001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.component.file.strategy;
018
019import java.io.File;
020
021import org.apache.camel.Exchange;
022import org.apache.camel.LoggingLevel;
023import org.apache.camel.component.file.FileComponent;
024import org.apache.camel.component.file.GenericFile;
025import org.apache.camel.component.file.GenericFileEndpoint;
026import org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy;
027import org.apache.camel.component.file.GenericFileOperations;
028import org.apache.camel.util.FileUtil;
029import org.apache.camel.util.StopWatch;
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032
033/**
034 * Acquires read lock to the given file using a marker file so other Camel consumers wont acquire the same file.
035 * This is the default behavior in Camel 1.x.
036 */
037public class MarkerFileExclusiveReadLockStrategy implements GenericFileExclusiveReadLockStrategy<File> {
038    private static final Logger LOG = LoggerFactory.getLogger(MarkerFileExclusiveReadLockStrategy.class);
039
040    private boolean markerFile = true;
041
042    @Override
043    public void prepareOnStartup(GenericFileOperations<File> operations, GenericFileEndpoint<File> endpoint) {
044        String dir = endpoint.getConfiguration().getDirectory();
045        File file = new File(dir);
046
047        LOG.debug("Prepare on startup by deleting orphaned lock files from: {}", dir);
048
049        StopWatch watch = new StopWatch();
050        deleteLockFiles(file, endpoint.isRecursive());
051
052        // log anything that takes more than a second
053        if (watch.taken() > 1000) {
054            LOG.info("Prepared on startup by deleting orphaned lock files from: {} took {} millis to complete.", dir, watch.taken());
055        }
056    }
057
058    @Override
059    public boolean acquireExclusiveReadLock(GenericFileOperations<File> operations,
060                                            GenericFile<File> file, Exchange exchange) throws Exception {
061
062        if (!markerFile) {
063            // if not using marker file then we assume acquired
064            return true;
065        }
066
067        String lockFileName = getLockFileName(file);
068        LOG.trace("Locking the file: {} using the lock file name: {}", file, lockFileName);
069
070        // create a plain file as marker filer for locking (do not use FileLock)
071        boolean acquired = FileUtil.createNewFile(new File(lockFileName));
072        exchange.setProperty(Exchange.FILE_LOCK_FILE_ACQUIRED, acquired);
073        exchange.setProperty(Exchange.FILE_LOCK_FILE_NAME, lockFileName);
074
075        return acquired;
076    }
077
078    @Override
079    public void releaseExclusiveReadLock(GenericFileOperations<File> operations,
080                                         GenericFile<File> file, Exchange exchange) throws Exception {
081        if (!markerFile) {
082            // if not using marker file then nothing to release
083            return;
084        }
085
086        // only release the file if camel get the lock before
087        if (exchange.getProperty(Exchange.FILE_LOCK_FILE_ACQUIRED, false, Boolean.class)) {
088            String lockFileName = exchange.getProperty(Exchange.FILE_LOCK_FILE_NAME, getLockFileName(file), String.class);
089            File lock = new File(lockFileName);
090
091            if (lock.exists()) {
092                LOG.trace("Unlocking file: {}", lockFileName);
093                boolean deleted = FileUtil.deleteFile(lock);
094                LOG.trace("Lock file: {} was deleted: {}", lockFileName, deleted);
095            }
096        }
097    }
098
099    @Override
100    public void setTimeout(long timeout) {
101        // noop
102    }
103
104    @Override
105    public void setCheckInterval(long checkInterval) {
106        // noop
107    }
108
109    @Override
110    public void setReadLockLoggingLevel(LoggingLevel readLockLoggingLevel) {
111        // noop
112    }
113
114    @Override
115    public void setMarkerFiler(boolean markerFile) {
116        this.markerFile = markerFile;
117    }
118
119    private static void deleteLockFiles(File dir, boolean recursive) {
120        File[] files = dir.listFiles();
121        if (files == null || files.length == 0) {
122            return;
123        }
124
125        for (File file : files) {
126            if (file.getName().startsWith(".")) {
127                // files starting with dot should be skipped
128                continue;
129            } else if (file.getName().endsWith(FileComponent.DEFAULT_LOCK_FILE_POSTFIX)) {
130                LOG.warn("Deleting orphaned lock file: " + file);
131                FileUtil.deleteFile(file);
132            } else if (recursive && file.isDirectory()) {
133                deleteLockFiles(file, true);
134            }
135        }
136    }
137
138    private static String getLockFileName(GenericFile<File> file) {
139        return file.getAbsoluteFilePath() + FileComponent.DEFAULT_LOCK_FILE_POSTFIX;
140    }
141
142}