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.internal.impl;
020
021import java.io.File;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.io.UncheckedIOException;
026import java.nio.file.Files;
027import java.nio.file.NoSuchFileException;
028import java.nio.file.Path;
029import java.nio.file.StandardOpenOption;
030import java.util.Map;
031import java.util.Properties;
032import java.util.concurrent.TimeUnit;
033
034import org.eclipse.aether.named.NamedLock;
035import org.eclipse.aether.named.NamedLockFactory;
036import org.eclipse.aether.named.NamedLockKey;
037import org.eclipse.aether.spi.io.PathProcessor;
038import org.eclipse.aether.util.StringDigestUtil;
039import org.slf4j.Logger;
040import org.slf4j.LoggerFactory;
041
042/**
043 * Manages access to a properties file using named locks.
044 * <p>
045 * This implementation uses {@link NamedLock} to protect tracking files from concurrent access, and can be used
046 * when it is single "modern" Maven version used to access same local repository concurrently.
047 *
048 * @since 2.0.17
049 * @see LegacyTrackingFileManager
050 * @see TrackingFileManagerSupplier
051 */
052public final class NamedLocksTrackingFileManager implements TrackingFileManager {
053    private static final Logger LOGGER = LoggerFactory.getLogger(NamedLocksTrackingFileManager.class);
054
055    private final NamedLockFactory namedLockFactory;
056    private final PathProcessor pathProcessor;
057    private final long time;
058    private final TimeUnit unit;
059
060    public NamedLocksTrackingFileManager(NamedLockFactory namedLockFactory, long time, TimeUnit unit) {
061        this(namedLockFactory, new DefaultPathProcessor(), time, unit);
062    }
063
064    public NamedLocksTrackingFileManager(
065            NamedLockFactory namedLockFactory, PathProcessor pathProcessor, long time, TimeUnit unit) {
066        this.namedLockFactory = namedLockFactory;
067        this.pathProcessor = pathProcessor;
068        this.time = time;
069        this.unit = unit;
070    }
071
072    @Deprecated
073    @Override
074    public Properties read(File file) {
075        return read(file.toPath());
076    }
077
078    @Override
079    public Properties read(Path path) {
080        try (NamedLock namedLock = namedLock(path)) {
081            if (namedLock.lockShared(time, unit)) {
082                try {
083                    Properties props = new Properties();
084                    try (InputStream in = Files.newInputStream(path)) {
085                        props.load(in);
086                    }
087                    return props;
088                } catch (NoSuchFileException e) {
089                    LOGGER.debug("No such file to read {}: {}", path, e.getMessage());
090                    return null;
091                } catch (IOException e) {
092                    LOGGER.warn("Failed to read tracking file '{}'", path, e);
093                    throw new UncheckedIOException(e);
094                } finally {
095                    namedLock.unlock();
096                }
097            }
098            throw new IllegalStateException("Failed to lock for read the tracking file " + path);
099        } 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}