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 javax.inject.Inject;
22  import javax.inject.Named;
23  import javax.inject.Singleton;
24  
25  import java.io.IOException;
26  import java.nio.file.Files;
27  import java.nio.file.Path;
28  import java.util.ArrayList;
29  import java.util.Collection;
30  import java.util.Collections;
31  import java.util.HashMap;
32  import java.util.IdentityHashMap;
33  import java.util.List;
34  import java.util.ListIterator;
35  import java.util.Map;
36  import java.util.Set;
37  import java.util.concurrent.ConcurrentHashMap;
38  
39  import org.eclipse.aether.ConfigurationProperties;
40  import org.eclipse.aether.Keys;
41  import org.eclipse.aether.RepositoryEvent;
42  import org.eclipse.aether.RepositoryEvent.EventType;
43  import org.eclipse.aether.RepositorySystemSession;
44  import org.eclipse.aether.RequestTrace;
45  import org.eclipse.aether.SyncContext;
46  import org.eclipse.aether.artifact.Artifact;
47  import org.eclipse.aether.impl.Installer;
48  import org.eclipse.aether.impl.MetadataGenerator;
49  import org.eclipse.aether.impl.MetadataGeneratorFactory;
50  import org.eclipse.aether.impl.RepositoryEventDispatcher;
51  import org.eclipse.aether.installation.InstallRequest;
52  import org.eclipse.aether.installation.InstallResult;
53  import org.eclipse.aether.installation.InstallationException;
54  import org.eclipse.aether.metadata.MergeableMetadata;
55  import org.eclipse.aether.metadata.Metadata;
56  import org.eclipse.aether.repository.LocalArtifactRegistration;
57  import org.eclipse.aether.repository.LocalMetadataRegistration;
58  import org.eclipse.aether.repository.LocalRepositoryManager;
59  import org.eclipse.aether.spi.artifact.generator.ArtifactGenerator;
60  import org.eclipse.aether.spi.artifact.generator.ArtifactGeneratorFactory;
61  import org.eclipse.aether.spi.artifact.transformer.ArtifactTransformer;
62  import org.eclipse.aether.spi.io.PathProcessor;
63  import org.eclipse.aether.spi.synccontext.SyncContextFactory;
64  import org.eclipse.aether.util.ConfigUtils;
65  import org.slf4j.Logger;
66  import org.slf4j.LoggerFactory;
67  
68  import static java.util.Objects.requireNonNull;
69  
70  /**
71   */
72  @Singleton
73  @Named
74  public class DefaultInstaller implements Installer {
75      private static final Object SESSION_HARDLINK_LOGGED = Keys.of(new Object() {
76          @Override
77          public String toString() {
78              return "installer.hardLinkLogged";
79          }
80      });
81  
82      private final Logger logger = LoggerFactory.getLogger(getClass());
83  
84      private final PathProcessor pathProcessor;
85  
86      private final RepositoryEventDispatcher repositoryEventDispatcher;
87  
88      private final Map<String, ArtifactGeneratorFactory> artifactFactories;
89  
90      private final Map<String, MetadataGeneratorFactory> metadataFactories;
91  
92      private final Map<String, ArtifactTransformer> artifactTransformers;
93  
94      private final SyncContextFactory syncContextFactory;
95  
96      @Inject
97      public DefaultInstaller(
98              PathProcessor pathProcessor,
99              RepositoryEventDispatcher repositoryEventDispatcher,
100             Map<String, ArtifactGeneratorFactory> artifactFactories,
101             Map<String, MetadataGeneratorFactory> metadataFactories,
102             Map<String, ArtifactTransformer> artifactTransformers,
103             SyncContextFactory syncContextFactory) {
104         this.pathProcessor = requireNonNull(pathProcessor, "path processor cannot be null");
105         this.repositoryEventDispatcher =
106                 requireNonNull(repositoryEventDispatcher, "repository event dispatcher cannot be null");
107         this.artifactFactories = Collections.unmodifiableMap(artifactFactories);
108         this.metadataFactories = Collections.unmodifiableMap(metadataFactories);
109         this.artifactTransformers = Collections.unmodifiableMap(artifactTransformers);
110         this.syncContextFactory = requireNonNull(syncContextFactory, "sync context factory cannot be null");
111     }
112 
113     @Override
114     public InstallResult install(RepositorySystemSession session, InstallRequest request) throws InstallationException {
115         requireNonNull(session, "session cannot be null");
116         requireNonNull(request, "request cannot be null");
117         for (ArtifactTransformer transformer : artifactTransformers.values()) {
118             request = transformer.transformInstallArtifacts(session, request);
119         }
120         try (SyncContext syncContext = syncContextFactory.newInstance(session, false)) {
121             return install(syncContext, session, request);
122         }
123     }
124 
125     private InstallResult install(SyncContext syncContext, RepositorySystemSession session, InstallRequest request)
126             throws InstallationException {
127         InstallResult result = new InstallResult(request);
128 
129         RequestTrace trace = RequestTrace.newChild(request.getTrace(), request);
130 
131         List<Artifact> artifacts = new ArrayList<>(request.getArtifacts());
132         List<? extends ArtifactGenerator> artifactGenerators =
133                 Utils.getArtifactGenerators(session, artifactFactories, request);
134         try {
135             List<Artifact> generatedArtifacts = new ArrayList<>();
136             for (ArtifactGenerator artifactGenerator : artifactGenerators) {
137                 Collection<? extends Artifact> generated = artifactGenerator.generate(generatedArtifacts);
138                 for (Artifact generatedArtifact : generated) {
139                     Map<String, String> properties = new HashMap<>(generatedArtifact.getProperties());
140                     properties.put(
141                             ArtifactGeneratorFactory.ARTIFACT_GENERATOR_ID,
142                             requireNonNull(artifactGenerator.generatorId(), "generatorId"));
143                     Artifact ga = generatedArtifact.setProperties(properties);
144                     generatedArtifacts.add(ga);
145                 }
146             }
147             artifacts.addAll(generatedArtifacts);
148 
149             List<? extends MetadataGenerator> metadataGenerators =
150                     Utils.getMetadataGenerators(session, metadataFactories, request);
151 
152             IdentityHashMap<Metadata, Object> processedMetadata = new IdentityHashMap<>();
153 
154             List<Metadata> metadatas = Utils.prepareMetadata(metadataGenerators, artifacts);
155 
156             syncContext.acquire(artifacts, Utils.combine(request.getMetadata(), metadatas));
157 
158             for (Metadata metadata : metadatas) {
159                 install(session, trace, metadata);
160                 processedMetadata.put(metadata, null);
161                 result.addMetadata(metadata);
162             }
163 
164             boolean hardLink = ConfigUtils.getBoolean(
165                     session,
166                     ConfigurationProperties.DEFAULT_INSTALLER_HARD_LINK,
167                     ConfigurationProperties.INSTALLER_HARD_LINK);
168 
169             Exception linkFailure = null;
170             for (ListIterator<Artifact> iterator = artifacts.listIterator(); iterator.hasNext(); ) {
171                 Artifact artifact = iterator.next();
172 
173                 for (MetadataGenerator generator : metadataGenerators) {
174                     artifact = generator.transformArtifact(artifact);
175                 }
176 
177                 iterator.set(artifact);
178 
179                 Exception failure = install(session, trace, artifact, hardLink);
180                 if (failure != null && linkFailure == null) {
181                     linkFailure = failure;
182                 } else if (failure != null) {
183                     linkFailure.addSuppressed(failure);
184                 }
185                 if (artifact.getProperty(ArtifactGeneratorFactory.ARTIFACT_GENERATOR_ID, null) == null) {
186                     result.addArtifact(artifact);
187                 }
188             }
189             if (linkFailure != null) {
190                 Path localRepoBasedir =
191                         session.getLocalRepositoryManager().getRepository().getBasePath();
192                 if (localRepoBasedir == null) {
193                     // No base path (custom or in-memory local repository manager) — log without dedup
194                     if (logger.isDebugEnabled()) {
195                         logger.info(
196                                 "Hard link not supported for local repository, falling back to file copy."
197                                         + " To suppress this message, set '{}=false'.",
198                                 ConfigurationProperties.INSTALLER_HARD_LINK,
199                                 linkFailure);
200                     } else {
201                         logger.info(
202                                 "Hard link not supported for local repository, falling back to file copy."
203                                         + " To suppress this message, set '{}=false'.",
204                                 ConfigurationProperties.INSTALLER_HARD_LINK);
205                     }
206                 } else {
207                     @SuppressWarnings("unchecked")
208                     Set<Path> logged = (Set<Path>) session.getData()
209                             .computeIfAbsent(
210                                     SESSION_HARDLINK_LOGGED,
211                                     () -> Collections.newSetFromMap(new ConcurrentHashMap<Path, Boolean>()));
212                     if (logged.add(localRepoBasedir)) {
213                         if (logger.isDebugEnabled()) {
214                             logger.info(
215                                     "Hard link not supported for local repository at {}, falling back to file copy."
216                                             + " To suppress this message, set '{}=false'.",
217                                     localRepoBasedir,
218                                     ConfigurationProperties.INSTALLER_HARD_LINK,
219                                     linkFailure);
220                         } else {
221                             logger.info(
222                                     "Hard link not supported for local repository at {}, falling back to file copy."
223                                             + " To suppress this message, set '{}=false'.",
224                                     localRepoBasedir,
225                                     ConfigurationProperties.INSTALLER_HARD_LINK);
226                         }
227                     }
228                 }
229             }
230 
231             metadatas = Utils.finishMetadata(metadataGenerators, artifacts);
232 
233             syncContext.acquire(null, metadatas);
234 
235             for (Metadata metadata : metadatas) {
236                 install(session, trace, metadata);
237                 processedMetadata.put(metadata, null);
238                 result.addMetadata(metadata);
239             }
240 
241             for (Metadata metadata : request.getMetadata()) {
242                 if (!processedMetadata.containsKey(metadata)) {
243                     install(session, trace, metadata);
244                     result.addMetadata(metadata);
245                 }
246             }
247 
248             return result;
249         } finally {
250             for (ArtifactGenerator artifactGenerator : artifactGenerators) {
251                 try {
252                     artifactGenerator.close();
253                 } catch (Exception e) {
254                     logger.warn("ArtifactGenerator close failure: {}", artifactGenerator.generatorId(), e);
255                 }
256             }
257         }
258     }
259 
260     /**
261      * Installs a single artifact. Returns the link failure exception if hard-linking was attempted but failed
262      * (caller logs it once after the loop), or {@code null} if the artifact was installed successfully via hard link
263      * or if {@code hardLink} is {@code false}.
264      */
265     private Exception install(RepositorySystemSession session, RequestTrace trace, Artifact artifact, boolean hardLink)
266             throws InstallationException {
267         final LocalRepositoryManager lrm = session.getLocalRepositoryManager();
268         final Path srcPath = artifact.getPath();
269         final Path dstPath = lrm.getAbsolutePathForLocalArtifact(artifact);
270 
271         artifactInstalling(session, trace, artifact, dstPath);
272 
273         Exception linkFailure = null;
274         Exception exception = null;
275         try {
276             if (dstPath.equals(srcPath)) {
277                 throw new IllegalStateException("cannot install " + dstPath + " to same path");
278             }
279 
280             if (hardLink) {
281                 Files.createDirectories(dstPath.getParent());
282                 if (Files.isDirectory(dstPath)) {
283                     throw new IOException("destination is a directory: " + dstPath);
284                 }
285                 try {
286                     Files.deleteIfExists(dstPath);
287                     Files.createLink(dstPath, srcPath);
288                 } catch (UnsupportedOperationException | IllegalArgumentException | IOException e) {
289                     // cross-device link (EXDEV), provider mismatch (e.g. Jimfs), or unsupported FS — fall back to copy
290                     linkFailure = e;
291                     pathProcessor.copyWithTimestamp(srcPath, dstPath);
292                 }
293             } else {
294                 pathProcessor.copyWithTimestamp(srcPath, dstPath);
295             }
296             lrm.add(session, new LocalArtifactRegistration(artifact));
297         } catch (Exception e) {
298             exception = e;
299             throw new InstallationException("Failed to install artifact " + artifact + ": " + e.getMessage(), e);
300         } finally {
301             artifactInstalled(session, trace, artifact, dstPath, exception);
302         }
303         return linkFailure;
304     }
305 
306     private void install(RepositorySystemSession session, RequestTrace trace, Metadata metadata)
307             throws InstallationException {
308         LocalRepositoryManager lrm = session.getLocalRepositoryManager();
309 
310         Path dstPath = lrm.getAbsolutePathForLocalMetadata(metadata);
311 
312         metadataInstalling(session, trace, metadata, dstPath);
313 
314         Exception exception = null;
315         try {
316             if (metadata instanceof MergeableMetadata) {
317                 ((MergeableMetadata) metadata).merge(dstPath, dstPath);
318             } else {
319                 if (dstPath.equals(metadata.getPath())) {
320                     throw new IllegalStateException("cannot install " + dstPath + " to same path");
321                 }
322                 pathProcessor.copy(metadata.getPath(), dstPath);
323             }
324 
325             lrm.add(session, new LocalMetadataRegistration(metadata));
326         } catch (Exception e) {
327             exception = e;
328             throw new InstallationException("Failed to install metadata " + metadata + ": " + e.getMessage(), e);
329         } finally {
330             metadataInstalled(session, trace, metadata, dstPath, exception);
331         }
332     }
333 
334     private void artifactInstalling(
335             RepositorySystemSession session, RequestTrace trace, Artifact artifact, Path dstPath) {
336         RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_INSTALLING);
337         event.setTrace(trace);
338         event.setArtifact(artifact);
339         event.setRepository(session.getLocalRepositoryManager().getRepository());
340         event.setPath(dstPath);
341 
342         repositoryEventDispatcher.dispatch(event.build());
343     }
344 
345     private void artifactInstalled(
346             RepositorySystemSession session, RequestTrace trace, Artifact artifact, Path dstPath, Exception exception) {
347         RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_INSTALLED);
348         event.setTrace(trace);
349         event.setArtifact(artifact);
350         event.setRepository(session.getLocalRepositoryManager().getRepository());
351         event.setPath(dstPath);
352         event.setException(exception);
353 
354         repositoryEventDispatcher.dispatch(event.build());
355     }
356 
357     private void metadataInstalling(
358             RepositorySystemSession session, RequestTrace trace, Metadata metadata, Path dstPath) {
359         RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INSTALLING);
360         event.setTrace(trace);
361         event.setMetadata(metadata);
362         event.setRepository(session.getLocalRepositoryManager().getRepository());
363         event.setPath(dstPath);
364 
365         repositoryEventDispatcher.dispatch(event.build());
366     }
367 
368     private void metadataInstalled(
369             RepositorySystemSession session, RequestTrace trace, Metadata metadata, Path dstPath, Exception exception) {
370         RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INSTALLED);
371         event.setTrace(trace);
372         event.setMetadata(metadata);
373         event.setRepository(session.getLocalRepositoryManager().getRepository());
374         event.setPath(dstPath);
375         event.setException(exception);
376 
377         repositoryEventDispatcher.dispatch(event.build());
378     }
379 }