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.net.URI;
027import java.nio.channels.FileChannel;
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.NamedLock;
036import org.eclipse.aether.named.NamedLockKey;
037import org.eclipse.aether.named.support.FileLockNamedLock;
038import org.eclipse.aether.named.support.NamedLockFactorySupport;
039import org.eclipse.aether.named.support.NamedLockSupport;
040
041import static org.eclipse.aether.named.support.Retry.retry;
042
043/**
044 * Named locks factory of {@link FileLockNamedLock}s. This is a bit of special implementation, as it
045 * expects locks names to be proper URI string representations (use {@code file:} protocol for default
046 * file system).
047 *
048 * @since 1.7.3
049 */
050@Singleton
051@Named(FileLockNamedLockFactory.NAME)
052public class FileLockNamedLockFactory extends NamedLockFactorySupport {
053    public static final String NAME = "file-lock";
054
055    // Logic borrowed from Commons-Lang3: we really need only this, to decide do we "delete on close" or not
056    private static final boolean IS_WINDOWS =
057            System.getProperty("os.name", "unknown").startsWith("Windows");
058
059    /**
060     * Tweak: on Windows, the presence of <em>StandardOpenOption#DELETE_ON_CLOSE</em> causes concurrency issues. This
061     * flag allows to have it removed from effective flags, at the cost that lockfile directory becomes crowded
062     * with 0 byte sized lock files that are never cleaned up. Default value is {@code true} on non-Windows OS.
063     * See <a href="https://bugs.openjdk.org/browse/JDK-8252883">JDK-8252883</a> for Windows related bug. Users
064     * on Windows can still force "delete on close" by explicitly setting this property to {@code true}.
065     *
066     * @see <a href="https://bugs.openjdk.org/browse/JDK-8252883">JDK-8252883</a>
067     * @configurationSource {@link System#getProperty(String, String)}
068     * @configurationType {@link java.lang.Boolean}
069     * @configurationDefaultValue true
070     */
071    public static final String SYSTEM_PROP_DELETE_LOCK_FILES = "aether.named.file-lock.deleteLockFiles";
072
073    private static final boolean DELETE_LOCK_FILES =
074            Boolean.parseBoolean(System.getProperty(SYSTEM_PROP_DELETE_LOCK_FILES, Boolean.toString(!IS_WINDOWS)));
075
076    /**
077     * Tweak: on Windows, the presence of <em>StandardOpenOption#DELETE_ON_CLOSE</em> causes concurrency issues. This
078     * flag allows to implement similar fix as referenced JDK bug report: retry and hope the best. Default value is
079     * 5 attempts (will retry 4 times).
080     *
081     * @see <a href="https://bugs.openjdk.org/browse/JDK-8252883">JDK-8252883</a>
082     * @configurationSource {@link System#getProperty(String, String)}
083     * @configurationType {@link java.lang.Integer}
084     * @configurationDefaultValue 5
085     */
086    public static final String SYSTEM_PROP_ATTEMPTS = "aether.named.file-lock.attempts";
087
088    private static final int ATTEMPTS = Integer.parseInt(System.getProperty(SYSTEM_PROP_ATTEMPTS, "5"));
089
090    /**
091     * Tweak: When {@link #SYSTEM_PROP_ATTEMPTS} used, the amount of milliseconds to sleep between subsequent retries. Default
092     * value is 50 milliseconds.
093     *
094     * @configurationSource {@link System#getProperty(String, String)}
095     * @configurationType {@link java.lang.Long}
096     * @configurationDefaultValue 50
097     */
098    public static final String SYSTEM_PROP_SLEEP_MILLIS = "aether.named.file-lock.sleepMillis";
099
100    private static final long SLEEP_MILLIS = Long.parseLong(System.getProperty(SYSTEM_PROP_SLEEP_MILLIS, "50"));
101
102    private final ConcurrentMap<NamedLockKey, FileChannel> fileChannels;
103
104    public FileLockNamedLockFactory() {
105        this.fileChannels = new ConcurrentHashMap<>();
106    }
107
108    @Override
109    protected NamedLockSupport createLock(final NamedLockKey key) {
110        Path path = Paths.get(URI.create(key.name()));
111        FileChannel fileChannel = fileChannels.computeIfAbsent(key, k -> {
112            try {
113                Files.createDirectories(path.getParent());
114                FileChannel channel = retry(
115                        ATTEMPTS,
116                        SLEEP_MILLIS,
117                        () -> {
118                            if (DELETE_LOCK_FILES) {
119                                return FileChannel.open(
120                                        path,
121                                        StandardOpenOption.READ,
122                                        StandardOpenOption.WRITE,
123                                        StandardOpenOption.CREATE,
124                                        StandardOpenOption.DELETE_ON_CLOSE);
125                            } else {
126                                return FileChannel.open(
127                                        path,
128                                        StandardOpenOption.READ,
129                                        StandardOpenOption.WRITE,
130                                        StandardOpenOption.CREATE);
131                            }
132                        },
133                        null,
134                        null);
135
136                if (channel == null) {
137                    throw new IllegalStateException(
138                            "Could not open file channel for '" + key + "' after " + ATTEMPTS + " attempts; giving up");
139                }
140                return channel;
141            } catch (InterruptedException e) {
142                Thread.currentThread().interrupt();
143                throw new RuntimeException("Interrupted while opening file channel for '" + key + "'", e);
144            } catch (IOException e) {
145                throw new UncheckedIOException("Failed to open file channel for '" + key + "'", e);
146            }
147        });
148        return new FileLockNamedLock(key, fileChannel, this);
149    }
150
151    @Override
152    protected void destroyLock(final NamedLock namedLock) {
153        if (namedLock instanceof FileLockNamedLock) {
154            final NamedLockKey key = namedLock.key();
155            FileChannel fileChannel = fileChannels.remove(key);
156            if (fileChannel == null) {
157                throw new IllegalStateException("File channel expected, but does not exist: " + key);
158            }
159
160            try {
161                fileChannel.close();
162            } catch (IOException e) {
163                throw new UncheckedIOException("Failed to close file channel for '" + key + "'", e);
164            }
165        }
166    }
167}