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.synccontext.named;
20  
21  import java.util.ArrayDeque;
22  import java.util.Collection;
23  import java.util.Deque;
24  import java.util.concurrent.TimeUnit;
25  import java.util.concurrent.atomic.AtomicBoolean;
26  import java.util.stream.Collectors;
27  
28  import org.eclipse.aether.ConfigurationProperties;
29  import org.eclipse.aether.RepositorySystemSession;
30  import org.eclipse.aether.SyncContext;
31  import org.eclipse.aether.artifact.Artifact;
32  import org.eclipse.aether.internal.impl.named.DefaultNamedLockFactorySelector;
33  import org.eclipse.aether.metadata.Metadata;
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.named.providers.FileLockNamedLockFactory;
38  import org.eclipse.aether.util.ConfigUtils;
39  import org.eclipse.aether.util.artifact.ArtifactIdUtils;
40  import org.slf4j.Logger;
41  import org.slf4j.LoggerFactory;
42  
43  import static java.util.Objects.requireNonNull;
44  
45  /**
46   * Adapter to adapt {@link NamedLockFactory} and {@link NamedLock} to {@link SyncContext}.
47   */
48  public final class NamedLockFactoryAdapter {
49      public static final String CONFIG_PROPS_PREFIX = ConfigurationProperties.PREFIX_SYNC_CONTEXT + "named.";
50  
51      /**
52       * The maximum of time amount to be blocked to obtain lock.
53       * <strong>Deprecated: use {@code aether.system.named...} configuration instead.</strong>
54       *
55       * @since 1.7.0
56       * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
57       * @configurationType {@link java.lang.Long}
58       * @deprecated Use {@code aether.system.named.time} instead.
59       */
60      @Deprecated
61      public static final String CONFIG_PROP_TIME = CONFIG_PROPS_PREFIX + "time";
62  
63      /**
64       * @deprecated Use {@link DefaultNamedLockFactorySelector#DEFAULT_LOCK_WAIT_TIME} instead.
65       */
66      @Deprecated
67      public static final long DEFAULT_TIME = DefaultNamedLockFactorySelector.DEFAULT_LOCK_WAIT_TIME;
68  
69      /**
70       * The unit of maximum time amount to be blocked to obtain lock. Use TimeUnit enum names.
71       * <strong>Deprecated: use {@code aether.system.named...} configuration instead.</strong>
72       *
73       * @since 1.7.0
74       * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
75       * @configurationType {@link java.lang.String}
76       * @deprecated Use {@code aether.system.named.timeUnit} instead.
77       */
78      @Deprecated
79      public static final String CONFIG_PROP_TIME_UNIT = CONFIG_PROPS_PREFIX + "time.unit";
80  
81      /**
82       * @deprecated Use {@link DefaultNamedLockFactorySelector#DEFAULT_LOCK_WAIT_TIME_UNIT} instead.
83       */
84      @Deprecated
85      public static final String DEFAULT_TIME_UNIT = DefaultNamedLockFactorySelector.DEFAULT_LOCK_WAIT_TIME_UNIT;
86  
87      /**
88       * The amount of retries on time-out.
89       *
90       * @since 1.7.0
91       * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
92       * @configurationType {@link java.lang.Integer}
93       * @configurationDefaultValue {@link #DEFAULT_RETRY}
94       */
95      public static final String CONFIG_PROP_RETRY = CONFIG_PROPS_PREFIX + "retry";
96  
97      public static final int DEFAULT_RETRY = 1;
98  
99      /**
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 }