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 javax.inject.Inject; 022import javax.inject.Named; 023import javax.inject.Singleton; 024 025import java.io.IOException; 026import java.nio.file.Files; 027import java.nio.file.Path; 028import java.util.ArrayList; 029import java.util.Collection; 030import java.util.Collections; 031import java.util.HashMap; 032import java.util.IdentityHashMap; 033import java.util.List; 034import java.util.ListIterator; 035import java.util.Map; 036import java.util.Set; 037import java.util.concurrent.ConcurrentHashMap; 038 039import org.eclipse.aether.ConfigurationProperties; 040import org.eclipse.aether.Keys; 041import org.eclipse.aether.RepositoryEvent; 042import org.eclipse.aether.RepositoryEvent.EventType; 043import org.eclipse.aether.RepositorySystemSession; 044import org.eclipse.aether.RequestTrace; 045import org.eclipse.aether.SyncContext; 046import org.eclipse.aether.artifact.Artifact; 047import org.eclipse.aether.impl.Installer; 048import org.eclipse.aether.impl.MetadataGenerator; 049import org.eclipse.aether.impl.MetadataGeneratorFactory; 050import org.eclipse.aether.impl.RepositoryEventDispatcher; 051import org.eclipse.aether.installation.InstallRequest; 052import org.eclipse.aether.installation.InstallResult; 053import org.eclipse.aether.installation.InstallationException; 054import org.eclipse.aether.metadata.MergeableMetadata; 055import org.eclipse.aether.metadata.Metadata; 056import org.eclipse.aether.repository.LocalArtifactRegistration; 057import org.eclipse.aether.repository.LocalMetadataRegistration; 058import org.eclipse.aether.repository.LocalRepositoryManager; 059import org.eclipse.aether.spi.artifact.generator.ArtifactGenerator; 060import org.eclipse.aether.spi.artifact.generator.ArtifactGeneratorFactory; 061import org.eclipse.aether.spi.artifact.transformer.ArtifactTransformer; 062import org.eclipse.aether.spi.io.PathProcessor; 063import org.eclipse.aether.spi.synccontext.SyncContextFactory; 064import org.eclipse.aether.util.ConfigUtils; 065import org.slf4j.Logger; 066import org.slf4j.LoggerFactory; 067 068import static java.util.Objects.requireNonNull; 069 070/** 071 */ 072@Singleton 073@Named 074public class DefaultInstaller implements Installer { 075 private static final Object SESSION_HARDLINK_LOGGED = Keys.of(new Object() { 076 @Override 077 public String toString() { 078 return "installer.hardLinkLogged"; 079 } 080 }); 081 082 private final Logger logger = LoggerFactory.getLogger(getClass()); 083 084 private final PathProcessor pathProcessor; 085 086 private final RepositoryEventDispatcher repositoryEventDispatcher; 087 088 private final Map<String, ArtifactGeneratorFactory> artifactFactories; 089 090 private final Map<String, MetadataGeneratorFactory> metadataFactories; 091 092 private final Map<String, ArtifactTransformer> artifactTransformers; 093 094 private final SyncContextFactory syncContextFactory; 095 096 @Inject 097 public DefaultInstaller( 098 PathProcessor pathProcessor, 099 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}