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.internal.impl;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.OutputStream;
25  import java.io.UncheckedIOException;
26  import java.nio.file.Files;
27  import java.nio.file.NoSuchFileException;
28  import java.nio.file.Path;
29  import java.nio.file.StandardOpenOption;
30  import java.util.Map;
31  import java.util.Properties;
32  import java.util.concurrent.TimeUnit;
33  
34  import org.eclipse.aether.named.NamedLock;
35  import org.eclipse.aether.named.NamedLockFactory;
36  import org.eclipse.aether.named.NamedLockKey;
37  import org.eclipse.aether.spi.io.PathProcessor;
38  import org.eclipse.aether.util.StringDigestUtil;
39  import org.slf4j.Logger;
40  import org.slf4j.LoggerFactory;
41  
42  /**
43   * Manages access to a properties file using named locks.
44   * <p>
45   * This implementation uses {@link NamedLock} to protect tracking files from concurrent access, and can be used
46   * when it is single "modern" Maven version used to access same local repository concurrently.
47   *
48   * @since 2.0.17
49   * @see LegacyTrackingFileManager
50   * @see TrackingFileManagerSupplier
51   */
52  public final class NamedLocksTrackingFileManager implements TrackingFileManager {
53      private static final Logger LOGGER = LoggerFactory.getLogger(NamedLocksTrackingFileManager.class);
54  
55      private final NamedLockFactory namedLockFactory;
56      private final PathProcessor pathProcessor;
57      private final long time;
58      private final TimeUnit unit;
59  
60      public NamedLocksTrackingFileManager(NamedLockFactory namedLockFactory, long time, TimeUnit unit) {
61          this(namedLockFactory, new DefaultPathProcessor(), time, unit);
62      }
63  
64      public NamedLocksTrackingFileManager(
65              NamedLockFactory namedLockFactory, PathProcessor pathProcessor, long time, TimeUnit unit) {
66          this.namedLockFactory = namedLockFactory;
67          this.pathProcessor = pathProcessor;
68          this.time = time;
69          this.unit = unit;
70      }
71  
72      @Deprecated
73      @Override
74      public Properties read(File file) {
75          return read(file.toPath());
76      }
77  
78      @Override
79      public Properties read(Path path) {
80          try (NamedLock namedLock = namedLock(path)) {
81              if (namedLock.lockShared(time, unit)) {
82                  try {
83                      Properties props = new Properties();
84                      try (InputStream in = Files.newInputStream(path)) {
85                          props.load(in);
86                      }
87                      return props;
88                  } catch (NoSuchFileException e) {
89                      LOGGER.debug("No such file to read {}: {}", path, e.getMessage());
90                      return null;
91                  } catch (IOException e) {
92                      LOGGER.warn("Failed to read tracking file '{}'", path, e);
93                      throw new UncheckedIOException(e);
94                  } finally {
95                      namedLock.unlock();
96                  }
97              }
98              throw new IllegalStateException("Failed to lock for read the tracking file " + path);
99          } catch (InterruptedException e) {
100             Thread.currentThread().interrupt();
101             throw new IllegalStateException("Interrupted while reading tracking file " + path, e);
102         }
103     }
104 
105     @Deprecated
106     @Override
107     public Properties update(File file, Map<String, String> updates) {
108         return update(file.toPath(), updates);
109     }
110 
111     @Override
112     public Properties update(Path path, Map<String, String> updates) {
113         try {
114             Path parent = path.getParent();
115             if (parent != null) {
116                 Files.createDirectories(parent);
117             }
118         } catch (IOException e) {
119             LOGGER.warn("Failed to create tracking file parent '{}'", path, e);
120             throw new UncheckedIOException(e);
121         }
122         try (NamedLock lock = namedLock(path)) {
123             if (lock.lockExclusively(time, unit)) {
124                 try {
125                     Properties props = new Properties();
126                     if (Files.isRegularFile(path)) {
127                         try (InputStream stream = Files.newInputStream(path, StandardOpenOption.READ)) {
128                             props.load(stream);
129                         }
130                     }
131                     for (Map.Entry<String, String> update : updates.entrySet()) {
132                         if (update.getValue() == null) {
133                             props.remove(update.getKey());
134                         } else {
135                             props.setProperty(update.getKey(), update.getValue());
136                         }
137                     }
138                     LOGGER.debug("Writing tracking file '{}'", path);
139                     // write atomically: a truncated tracking file would make artifacts look untracked
140                     try (PathProcessor.CollocatedTempFile tempFile = pathProcessor.newTempFile(path)) {
141                         try (OutputStream out = Files.newOutputStream(tempFile.getPath())) {
142                             props.store(
143                                     out,
144                                     "NOTE: This is a Maven Resolver internal implementation file"
145                                             + ", its format can be changed without prior notice.");
146                         }
147                         tempFile.move();
148                     }
149                     return props;
150                 } catch (IOException e) {
151                     LOGGER.warn("Failed to write tracking file '{}'", path, e);
152                     throw new UncheckedIOException(e);
153                 } finally {
154                     lock.unlock();
155                 }
156             }
157             throw new IllegalStateException("Failed to lock for update the tracking file " + path);
158         } catch (InterruptedException e) {
159             Thread.currentThread().interrupt();
160             throw new IllegalStateException("Interrupted while updating tracking file " + path, e);
161         }
162     }
163 
164     @Deprecated
165     @Override
166     public boolean delete(File file) {
167         return delete(file.toPath());
168     }
169 
170     @Override
171     public boolean delete(Path path) {
172         try (NamedLock lock = namedLock(path)) {
173             if (lock.lockExclusively(time, unit)) {
174                 try {
175                     return Files.deleteIfExists(path);
176                 } catch (NoSuchFileException e) {
177                     LOGGER.debug("No such file to delete {}: {}", path, e.getMessage());
178                     return false;
179                 } catch (IOException e) {
180                     LOGGER.warn("Failed to delete tracking file '{}'", path, e);
181                     throw new UncheckedIOException(e);
182                 } finally {
183                     lock.unlock();
184                 }
185             }
186             throw new IllegalStateException("Failed to lock for delete the tracking file " + path);
187         } catch (InterruptedException e) {
188             Thread.currentThread().interrupt();
189             throw new IllegalStateException("Interrupted while deleting tracking file " + path, e);
190         }
191     }
192 
193     /**
194      * Creates unique named lock for given path with name that is unique for paths, but carries some extra
195      * information useful for debugging.
196      * <p>
197      * Note: it is important that created named lock names remain (and carry) file friendly URLs, as this makes it
198      * work with all lock factories, even the file one. Using non-file friendly names would make it work it with
199      * all <strong>except the file lock factory</strong>.
200      */
201     private NamedLock namedLock(Path path) {
202         Path canonical = canonicalPath(path);
203         // Place lock file next to the tracking file, using its hash as filename
204         Path lockPath = canonical.resolveSibling("tracking-" + StringDigestUtil.sha1(canonical.toString()) + ".lock");
205         return namedLockFactory.getLock(
206                 NamedLockKey.of(lockPath.toAbsolutePath().toUri().toASCIIString(), path.toString()));
207     }
208 
209     /**
210      * Tries the best it can to figure out actual file the workload is about, while resolving cases like symlinked
211      * local repository etc.
212      */
213     private static Path canonicalPath(Path path) {
214         try {
215             return path.toRealPath();
216         } catch (IOException e) {
217             return path.getParent() != null
218                     ? canonicalPath(path.getParent()).resolve(path.getFileName())
219                     : path.toAbsolutePath();
220         }
221     }
222 }