View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.named.providers;
20  
21  import javax.inject.Named;
22  import javax.inject.Singleton;
23  
24  import java.io.IOException;
25  import java.io.UncheckedIOException;
26  import java.nio.channels.FileChannel;
27  import java.nio.file.AccessDeniedException;
28  import java.nio.file.Files;
29  import java.nio.file.Path;
30  import java.nio.file.Paths;
31  import java.nio.file.StandardOpenOption;
32  import java.util.concurrent.ConcurrentHashMap;
33  import java.util.concurrent.ConcurrentMap;
34  
35  import org.eclipse.aether.named.support.FileLockNamedLock;
36  import org.eclipse.aether.named.support.NamedLockFactorySupport;
37  import org.eclipse.aether.named.support.NamedLockSupport;
38  
39  import static org.eclipse.aether.named.support.Retry.retry;
40  
41  /**
42   * Named locks factory of {@link FileLockNamedLock}s. This is a bit special implementation, as it
43   * expects locks names to be fully qualified absolute file system paths.
44   *
45   * @since 1.7.3
46   */
47  @Singleton
48  @Named(FileLockNamedLockFactory.NAME)
49  public class FileLockNamedLockFactory extends NamedLockFactorySupport {
50      public static final String NAME = "file-lock";
51  
52      /**
53       * Tweak: on Windows, the presence of {@link StandardOpenOption#DELETE_ON_CLOSE} causes concurrency issues. This
54       * flag allows to have it removed from effective flags, at the cost that lockfile directory becomes crowded
55       * with 0 byte sized lock files that are never cleaned up. Default value is {@code true}.
56       *
57       * @see <a href="https://bugs.openjdk.org/browse/JDK-8252883">JDK-8252883</a>
58       */
59      private static final boolean DELETE_LOCK_FILES =
60              Boolean.parseBoolean(System.getProperty("aether.named.file-lock.deleteLockFiles", Boolean.TRUE.toString()));
61  
62      /**
63       * Tweak: on Windows, the presence of {@link StandardOpenOption#DELETE_ON_CLOSE} causes concurrency issues. This
64       * flag allows to implement similar fix as referenced JDK bug report: retry and hope the best. Default value is
65       * 5 attempts (will retry 4 times).
66       *
67       * @see <a href="https://bugs.openjdk.org/browse/JDK-8252883">JDK-8252883</a>
68       */
69      private static final int ATTEMPTS = Integer.parseInt(System.getProperty("aether.named.file-lock.attempts", "5"));
70  
71      /**
72       * Tweak: When {@link #ATTEMPTS} used, the amount of milliseconds to sleep between subsequent retries. Default
73       * value is 50 milliseconds.
74       */
75      private static final long SLEEP_MILLIS =
76              Long.parseLong(System.getProperty("aether.named.file-lock.sleepMillis", "50"));
77  
78      private final ConcurrentMap<String, FileChannel> fileChannels;
79  
80      public FileLockNamedLockFactory() {
81          this.fileChannels = new ConcurrentHashMap<>();
82      }
83  
84      @Override
85      protected NamedLockSupport createLock(final String name) {
86          Path path = Paths.get(name);
87          FileChannel fileChannel = fileChannels.computeIfAbsent(name, k -> {
88              try {
89                  Files.createDirectories(path.getParent());
90                  FileChannel channel = retry(
91                          ATTEMPTS,
92                          SLEEP_MILLIS,
93                          () -> {
94                              try {
95                                  if (DELETE_LOCK_FILES) {
96                                      return FileChannel.open(
97                                              path,
98                                              StandardOpenOption.READ,
99                                              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 }