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.synccontext.named;
020
021import java.util.ArrayDeque;
022import java.util.Collection;
023import java.util.Deque;
024import java.util.concurrent.TimeUnit;
025import java.util.concurrent.atomic.AtomicBoolean;
026import java.util.stream.Collectors;
027
028import org.eclipse.aether.ConfigurationProperties;
029import org.eclipse.aether.RepositorySystemSession;
030import org.eclipse.aether.SyncContext;
031import org.eclipse.aether.artifact.Artifact;
032import org.eclipse.aether.internal.impl.named.DefaultNamedLockFactorySelector;
033import org.eclipse.aether.metadata.Metadata;
034import org.eclipse.aether.named.NamedLock;
035import org.eclipse.aether.named.NamedLockFactory;
036import org.eclipse.aether.named.NamedLockKey;
037import org.eclipse.aether.named.providers.FileLockNamedLockFactory;
038import org.eclipse.aether.util.ConfigUtils;
039import org.eclipse.aether.util.artifact.ArtifactIdUtils;
040import org.slf4j.Logger;
041import org.slf4j.LoggerFactory;
042
043import static java.util.Objects.requireNonNull;
044
045/**
046 * Adapter to adapt {@link NamedLockFactory} and {@link NamedLock} to {@link SyncContext}.
047 */
048public final class NamedLockFactoryAdapter {
049    public static final String CONFIG_PROPS_PREFIX = ConfigurationProperties.PREFIX_SYNC_CONTEXT + "named.";
050
051    /**
052     * The maximum of time amount to be blocked to obtain lock.
053     * <strong>Deprecated: use {@code aether.system.named...} configuration instead.</strong>
054     *
055     * @since 1.7.0
056     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
057     * @configurationType {@link java.lang.Long}
058     * @deprecated Use {@code aether.system.named.time} instead.
059     */
060    @Deprecated
061    public static final String CONFIG_PROP_TIME = CONFIG_PROPS_PREFIX + "time";
062
063    /**
064     * @deprecated Use {@link DefaultNamedLockFactorySelector#DEFAULT_LOCK_WAIT_TIME} instead.
065     */
066    @Deprecated
067    public static final long DEFAULT_TIME = DefaultNamedLockFactorySelector.DEFAULT_LOCK_WAIT_TIME;
068
069    /**
070     * The unit of maximum time amount to be blocked to obtain lock. Use TimeUnit enum names.
071     * <strong>Deprecated: use {@code aether.system.named...} configuration instead.</strong>
072     *
073     * @since 1.7.0
074     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
075     * @configurationType {@link java.lang.String}
076     * @deprecated Use {@code aether.system.named.timeUnit} instead.
077     */
078    @Deprecated
079    public static final String CONFIG_PROP_TIME_UNIT = CONFIG_PROPS_PREFIX + "time.unit";
080
081    /**
082     * @deprecated Use {@link DefaultNamedLockFactorySelector#DEFAULT_LOCK_WAIT_TIME_UNIT} instead.
083     */
084    @Deprecated
085    public static final String DEFAULT_TIME_UNIT = DefaultNamedLockFactorySelector.DEFAULT_LOCK_WAIT_TIME_UNIT;
086
087    /**
088     * The amount of retries on time-out.
089     *
090     * @since 1.7.0
091     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
092     * @configurationType {@link java.lang.Integer}
093     * @configurationDefaultValue {@link #DEFAULT_RETRY}
094     */
095    public static final String CONFIG_PROP_RETRY = CONFIG_PROPS_PREFIX + "retry";
096
097    public static final int DEFAULT_RETRY = 1;
098
099    /**
100     * The amount of milliseconds to wait between retries on time-out.
101     *
102     * @since 1.7.0
103     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
104     * @configurationType {@link java.lang.Long}
105     * @configurationDefaultValue {@link #DEFAULT_RETRY_WAIT}
106     */
107    public static final String CONFIG_PROP_RETRY_WAIT = CONFIG_PROPS_PREFIX + "retry.wait";
108
109    public static final long DEFAULT_RETRY_WAIT = 200L;
110
111    private final NameMapper nameMapper;
112
113    private final NamedLockFactory namedLockFactory;
114
115    private final long lockWait;
116
117    private final TimeUnit lockWaitUnit;
118
119    public NamedLockFactoryAdapter(
120            final NameMapper nameMapper,
121            final NamedLockFactory namedLockFactory,
122            long lockWait,
123            TimeUnit lockWaitUnit) {
124        this.nameMapper = requireNonNull(nameMapper);
125        this.namedLockFactory = requireNonNull(namedLockFactory);
126        this.lockWait = lockWait;
127        this.lockWaitUnit = requireNonNull(lockWaitUnit);
128        // TODO: this is ad-hoc "validation", experimental and likely to change
129        if (this.namedLockFactory instanceof FileLockNamedLockFactory && !this.nameMapper.isFileSystemFriendly()) {
130            throw new IllegalArgumentException(
131                    "Misconfiguration: FileLockNamedLockFactory lock factory requires FS friendly NameMapper");
132        }
133    }
134
135    public SyncContext newInstance(final RepositorySystemSession session, final boolean shared) {
136        return new AdaptedLockSyncContext(session, shared, nameMapper, namedLockFactory, lockWait, lockWaitUnit);
137    }
138
139    /**
140     * @since 1.9.1
141     */
142    public NameMapper getNameMapper() {
143        return nameMapper;
144    }
145
146    /**
147     * @since 1.9.1
148     */
149    public NamedLockFactory getNamedLockFactory() {
150        return namedLockFactory;
151    }
152
153    public String toString() {
154        return getClass().getSimpleName()
155                + "(nameMapper=" + nameMapper
156                + ", namedLockFactory=" + namedLockFactory
157                + ")";
158    }
159
160    private static class AdaptedLockSyncContext implements SyncContext {
161        private static final Logger LOGGER = LoggerFactory.getLogger(AdaptedLockSyncContext.class);
162
163        private final RepositorySystemSession session;
164
165        private final boolean shared;
166
167        private final NameMapper lockNaming;
168
169        private final NamedLockFactory namedLockFactory;
170
171        private final long time;
172
173        private final TimeUnit timeUnit;
174
175        private final int retry;
176
177        private final long retryWait;
178
179        private final Deque<NamedLock> locks;
180
181        private final AtomicBoolean closed;
182
183        private AdaptedLockSyncContext(
184                final RepositorySystemSession session,
185                final boolean shared,
186                final NameMapper lockNaming,
187                final NamedLockFactory namedLockFactory,
188                final long lockWait,
189                final TimeUnit lockWaitUnit) {
190            this.session = session;
191            this.shared = shared;
192            this.lockNaming = lockNaming;
193            this.namedLockFactory = namedLockFactory;
194            this.time = lockWait;
195            this.timeUnit = lockWaitUnit;
196            this.retry = getRetry(session);
197            this.retryWait = getRetryWait(session);
198            this.locks = new ArrayDeque<>();
199            this.closed = new AtomicBoolean(false);
200
201            if (retry < 0L) {
202                throw new IllegalArgumentException(CONFIG_PROP_RETRY + " value cannot be negative");
203            }
204            if (retryWait < 0L) {
205                throw new IllegalArgumentException(CONFIG_PROP_RETRY_WAIT + " value cannot be negative");
206            }
207        }
208
209        private int getRetry(final RepositorySystemSession session) {
210            return ConfigUtils.getInteger(session, DEFAULT_RETRY, CONFIG_PROP_RETRY);
211        }
212
213        private long getRetryWait(final RepositorySystemSession session) {
214            return ConfigUtils.getLong(session, DEFAULT_RETRY_WAIT, CONFIG_PROP_RETRY_WAIT);
215        }
216
217        @Override
218        public void acquire(Collection<? extends Artifact> artifacts, Collection<? extends Metadata> metadatas) {
219            if (closed.get()) {
220                throw new IllegalStateException("sync context is already closed");
221            }
222            Collection<NamedLockKey> keys = lockNaming.nameLocks(session, artifacts, metadatas);
223            if (keys.isEmpty()) {
224                return;
225            }
226
227            final String timeStr = time + " " + timeUnit;
228            final String lockKind = shared ? "shared" : "exclusive";
229            final NamedLock namedLock = namedLockFactory.getLock(keys);
230            if (LOGGER.isTraceEnabled()) {
231                LOGGER.trace(
232                        "Need {} lock for {} from {}",
233                        lockKind,
234                        namedLock.key().resources(),
235                        namedLock.key().name());
236            }
237
238            final int attempts = retry + 1;
239            for (int attempt = 1; attempt <= attempts; attempt++) {
240                if (LOGGER.isTraceEnabled()) {
241                    LOGGER.trace(
242                            "Attempt {}: Acquire {} lock from {}",
243                            attempt,
244                            lockKind,
245                            namedLock.key().name());
246                }
247                try {
248                    if (attempt > 1) {
249                        Thread.sleep(retryWait);
250                    }
251                    boolean locked;
252                    if (shared) {
253                        locked = namedLock.lockShared(time, timeUnit);
254                    } else {
255                        locked = namedLock.lockExclusively(time, timeUnit);
256                    }
257
258                    if (locked) {
259                        // we are done, get out
260                        locks.push(namedLock);
261                        return;
262                    }
263
264                    // we failed; retry
265                    if (LOGGER.isTraceEnabled()) {
266                        LOGGER.trace(
267                                "Failed to acquire {} lock for '{}' in {}",
268                                lockKind,
269                                namedLock.key().name(),
270                                timeStr);
271                    }
272                } catch (InterruptedException e) {
273                    // if we are here, means we were interrupted: fail
274                    try {
275                        namedLock.close();
276                    } finally {
277                        close();
278                    }
279                    Thread.currentThread().interrupt();
280                    throw new RuntimeException(e);
281                }
282            }
283            // if we are here, means all attempts were unsuccessful: fail
284            try {
285                namedLock.close();
286            } finally {
287                close();
288            }
289            String message = "Could not acquire " + lockKind + " lock for "
290                    + lockSubjects(artifacts, metadatas) + " in " + timeStr
291                    + "; consider using '" + CONFIG_PROP_TIME
292                    + "' property to increase lock timeout to a value that fits your environment";
293            FailedToAcquireLockException ex = new FailedToAcquireLockException(shared, message);
294            throw namedLockFactory.onFailure(ex);
295        }
296
297        private String lockSubjects(
298                Collection<? extends Artifact> artifacts, Collection<? extends Metadata> metadatas) {
299            StringBuilder builder = new StringBuilder();
300            if (artifacts != null && !artifacts.isEmpty()) {
301                builder.append("artifacts: ")
302                        .append(artifacts.stream().map(ArtifactIdUtils::toId).collect(Collectors.joining(", ")));
303            }
304            if (metadatas != null && !metadatas.isEmpty()) {
305                if (builder.length() != 0) {
306                    builder.append("; ");
307                }
308                builder.append("metadata: ")
309                        .append(metadatas.stream().map(this::metadataSubjects).collect(Collectors.joining(", ")));
310            }
311            return builder.toString();
312        }
313
314        private String metadataSubjects(Metadata metadata) {
315            String name = "";
316            if (!metadata.getGroupId().isEmpty()) {
317                name += metadata.getGroupId();
318                if (!metadata.getArtifactId().isEmpty()) {
319                    name += ":" + metadata.getArtifactId();
320                    if (!metadata.getVersion().isEmpty()) {
321                        name += ":" + metadata.getVersion();
322                    }
323                }
324            }
325            if (!metadata.getType().isEmpty()) {
326                name += (name.isEmpty() ? "" : ":") + metadata.getType();
327            }
328            return name;
329        }
330
331        @Override
332        public void close() {
333            if (closed.compareAndSet(false, true)) {
334                while (!locks.isEmpty()) {
335                    try (NamedLock namedLock = locks.pop()) {
336                        namedLock.unlock();
337                        if (LOGGER.isTraceEnabled()) {
338                            LOGGER.trace(
339                                    "Unlocked and closed {} lock of {}",
340                                    shared ? "shared" : "exclusive",
341                                    namedLock.key());
342                        }
343                    }
344                }
345            }
346        }
347    }
348}