001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.named.providers;
020
021import javax.inject.Named;
022import javax.inject.Singleton;
023
024import java.io.IOException;
025import java.io.UncheckedIOException;
026import java.nio.channels.FileChannel;
027import java.nio.file.AccessDeniedException;
028import java.nio.file.Files;
029import java.nio.file.Path;
030import java.nio.file.Paths;
031import java.nio.file.StandardOpenOption;
032import java.util.concurrent.ConcurrentHashMap;
033import java.util.concurrent.ConcurrentMap;
034
035import org.eclipse.aether.named.support.FileLockNamedLock;
036import org.eclipse.aether.named.support.NamedLockFactorySupport;
037import org.eclipse.aether.named.support.NamedLockSupport;
038
039import static org.eclipse.aether.named.support.Retry.retry;
040
041/**
042 * Named locks factory of {@link FileLockNamedLock}s. This is a bit special implementation, as it
043 * expects locks names to be fully qualified absolute file system paths.
044 *
045 * @since 1.7.3
046 */
047@Singleton
048@Named(FileLockNamedLockFactory.NAME)
049public class FileLockNamedLockFactory extends NamedLockFactorySupport {
050    public static final String NAME = "file-lock";
051
052    /**
053     * Tweak: on Windows, the presence of {@link StandardOpenOption#DELETE_ON_CLOSE} causes concurrency issues. This
054     * flag allows to have it removed from effective flags, at the cost that lockfile directory becomes crowded
055     * with 0 byte sized lock files that are never cleaned up. Default value is {@code true}.
056     *
057     * @see <a href="https://bugs.openjdk.org/browse/JDK-8252883">JDK-8252883</a>
058     */
059    private static final boolean DELETE_LOCK_FILES =
060            Boolean.parseBoolean(System.getProperty("aether.named.file-lock.deleteLockFiles", Boolean.TRUE.toString()));
061
062    /**
063     * Tweak: on Windows, the presence of {@link StandardOpenOption#DELETE_ON_CLOSE} causes concurrency issues. This
064     * flag allows to implement similar fix as referenced JDK bug report: retry and hope the best. Default value is
065     * 5 attempts (will retry 4 times).
066     *
067     * @see <a href="https://bugs.openjdk.org/browse/JDK-8252883">JDK-8252883</a>
068     */
069    private static final int ATTEMPTS = Integer.parseInt(System.getProperty("aether.named.file-lock.attempts", "5"));
070
071    /**
072     * Tweak: When {@link #ATTEMPTS} used, the amount of milliseconds to sleep between subsequent retries. Default
073     * value is 50 milliseconds.
074     */
075    private static final long SLEEP_MILLIS =
076            Long.parseLong(System.getProperty("aether.named.file-lock.sleepMillis", "50"));
077
078    private final ConcurrentMap<String, FileChannel> fileChannels;
079
080    public FileLockNamedLockFactory() {
081        this.fileChannels = new ConcurrentHashMap<>();
082    }
083
084    @Override
085    protected NamedLockSupport createLock(final String name) {
086        Path path = Paths.get(name);
087        FileChannel fileChannel = fileChannels.computeIfAbsent(name, k -> {
088            try {
089                Files.createDirectories(path.getParent());
090                FileChannel channel = retry(
091                        ATTEMPTS,
092                        SLEEP_MILLIS,
093                        () -> {
094                            try {
095                                if (DELETE_LOCK_FILES) {
096                                    return FileChannel.open(
097                                            path,
098                                            StandardOpenOption.READ,
099                                            StandardOpenOption.WRITE,
100                                            StandardOpenOption.CREATE,
101                                            StandardOpenOption.DELETE_ON_CLOSE);
102                                } else {
103                                    return FileChannel.open(
104                                            path,
105                                            StandardOpenOption.READ,
106                                            StandardOpenOption.WRITE,
107                                            StandardOpenOption.CREATE);
108                                }
109                            } catch (AccessDeniedException e) {
110                                return null;
111                            }
112                        },
113                        null,
114                        null);
115
116                if (channel == null) {
117                    throw new IllegalStateException("Could not open file channel for '" + name + "' after " + ATTEMPTS
118                            + " attempts; giving up");
119                }
120                return channel;
121            } catch (InterruptedException e) {
122                Thread.currentThread().interrupt();
123                throw new RuntimeException("Interrupted while opening file channel for '" + name + "'", e);
124            } catch (IOException e) {
125                throw new UncheckedIOException("Failed to open file channel for '" + name + "'", e);
126            }
127        });
128        return new FileLockNamedLock(name, fileChannel, this);
129    }
130
131    @Override
132    protected void destroyLock(final String name) {
133        FileChannel fileChannel = fileChannels.remove(name);
134        if (fileChannel == null) {
135            throw new IllegalStateException("File channel expected, but does not exist: " + name);
136        }
137
138        try {
139            fileChannel.close();
140        } catch (IOException e) {
141            throw new UncheckedIOException("Failed to close file channel for '" + name + "'", e);
142        }
143    }
144}