1 package org.apache.archiva.indexer.maven;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.beans.NetworkProxy;
24 import org.apache.archiva.admin.model.networkproxy.NetworkProxyAdmin;
25 import org.apache.archiva.common.utils.PathUtil;
26 import org.apache.archiva.configuration.ArchivaConfiguration;
27 import org.apache.archiva.indexer.ArchivaIndexManager;
28 import org.apache.archiva.indexer.ArchivaIndexingContext;
29 import org.apache.archiva.indexer.IndexCreationFailedException;
30 import org.apache.archiva.indexer.IndexUpdateFailedException;
31 import org.apache.archiva.indexer.UnsupportedBaseContextException;
32 import org.apache.archiva.model.ArtifactReference;
33 import org.apache.archiva.proxy.common.WagonFactory;
34 import org.apache.archiva.proxy.common.WagonFactoryException;
35 import org.apache.archiva.proxy.common.WagonFactoryRequest;
36 import org.apache.archiva.repository.ManagedRepository;
37 import org.apache.archiva.repository.PasswordCredentials;
38 import org.apache.archiva.repository.RemoteRepository;
39 import org.apache.archiva.repository.Repository;
40 import org.apache.archiva.repository.RepositoryType;
41 import org.apache.archiva.repository.UnsupportedRepositoryTypeException;
42 import org.apache.archiva.repository.features.IndexCreationFeature;
43 import org.apache.archiva.repository.features.RemoteIndexFeature;
44 import org.apache.commons.lang.StringUtils;
45 import org.apache.maven.index.DefaultScannerListener;
46 import org.apache.maven.index.Indexer;
47 import org.apache.maven.index.IndexerEngine;
48 import org.apache.maven.index.Scanner;
49 import org.apache.maven.index.ScanningRequest;
50 import org.apache.maven.index.ScanningResult;
51 import org.apache.maven.index.context.IndexCreator;
52 import org.apache.maven.index.context.IndexingContext;
53 import org.apache.maven.index.packer.IndexPacker;
54 import org.apache.maven.index.packer.IndexPackingRequest;
55 import org.apache.maven.index.updater.IndexUpdateRequest;
56 import org.apache.maven.index.updater.IndexUpdater;
57 import org.apache.maven.index.updater.ResourceFetcher;
58 import org.apache.maven.index_shaded.lucene.index.IndexFormatTooOldException;
59 import org.apache.maven.wagon.ConnectionException;
60 import org.apache.maven.wagon.ResourceDoesNotExistException;
61 import org.apache.maven.wagon.StreamWagon;
62 import org.apache.maven.wagon.TransferFailedException;
63 import org.apache.maven.wagon.Wagon;
64 import org.apache.maven.wagon.authentication.AuthenticationException;
65 import org.apache.maven.wagon.authentication.AuthenticationInfo;
66 import org.apache.maven.wagon.authorization.AuthorizationException;
67 import org.apache.maven.wagon.events.TransferEvent;
68 import org.apache.maven.wagon.events.TransferListener;
69 import org.apache.maven.wagon.proxy.ProxyInfo;
70 import org.apache.maven.wagon.shared.http.AbstractHttpClientWagon;
71 import org.apache.maven.wagon.shared.http.HttpConfiguration;
72 import org.apache.maven.wagon.shared.http.HttpMethodConfiguration;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.springframework.stereotype.Service;
77 import javax.inject.Inject;
78 import java.io.FileNotFoundException;
79 import java.io.IOException;
80 import java.io.InputStream;
81 import java.net.MalformedURLException;
83 import java.nio.file.Files;
84 import java.nio.file.Path;
85 import java.nio.file.Paths;
86 import java.util.List;
88 import java.util.concurrent.ConcurrentSkipListSet;
91 * Maven implementation of index manager
93 @Service( "archivaIndexManager#maven" )
94 public class MavenIndexManager implements ArchivaIndexManager
97 private static final Logger log = LoggerFactory.getLogger( MavenIndexManager.class );
100 private Indexer indexer;
103 private IndexerEngine indexerEngine;
106 private List<? extends IndexCreator> indexCreators;
109 private IndexPacker indexPacker;
112 private Scanner scanner;
115 private ArchivaConfiguration archivaConfiguration;
118 private WagonFactory wagonFactory;
121 private NetworkProxyAdmin networkProxyAdmin;
124 private IndexUpdater indexUpdater;
126 private ConcurrentSkipListSet<Path> activeContexts = new ConcurrentSkipListSet<>( );
128 private static final int WAIT_TIME = 100;
129 private static final int MAX_WAIT = 10;
132 IndexingContext getMvnContext( ArchivaIndexingContext context ) throws UnsupportedBaseContextException
134 if ( !context.supports( IndexingContext.class ) )
136 log.error( "The provided archiva index context does not support the maven IndexingContext" );
137 throw new UnsupportedBaseContextException( "The context does not support the Maven IndexingContext" );
139 return context.getBaseContext( IndexingContext.class );
142 private Path getIndexPath( ArchivaIndexingContext ctx )
144 return PathUtil.getPathFromUri( ctx.getPath( ) );
148 interface IndexUpdateConsumer
151 void accept( IndexingContext indexingContext ) throws IndexUpdateFailedException;
154 private void executeUpdateFunction( ArchivaIndexingContext context, IndexUpdateConsumer function ) throws IndexUpdateFailedException
156 IndexingContext indexingContext = null;
159 indexingContext = getMvnContext( context );
161 catch ( UnsupportedBaseContextException e )
163 throw new IndexUpdateFailedException( "Maven index is not supported by this context", e );
165 final Path ctxPath = getIndexPath( context );
167 boolean active = false;
168 while ( loop-- > 0 && !active )
170 active = activeContexts.add( ctxPath );
173 Thread.currentThread( ).sleep( WAIT_TIME );
175 catch ( InterruptedException e )
184 function.accept( indexingContext );
188 activeContexts.remove( ctxPath );
193 throw new IndexUpdateFailedException( "Timeout while waiting for index release on context " + context.getId( ) );
198 public void pack( final ArchivaIndexingContext context ) throws IndexUpdateFailedException
200 executeUpdateFunction( context, indexingContext -> {
203 IndexPackingRequest request = new IndexPackingRequest( indexingContext,
204 indexingContext.acquireIndexSearcher( ).getIndexReader( ),
205 indexingContext.getIndexDirectoryFile( ) );
206 indexPacker.packIndex( request );
207 indexingContext.updateTimestamp( true );
209 catch ( IOException e )
211 log.error( "IOException while packing index of context " + context.getId( ) + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ) );
212 throw new IndexUpdateFailedException( "IOException during update of " + context.getId( ), e );
220 public void scan( final ArchivaIndexingContext context, final boolean update ) throws IndexUpdateFailedException
222 executeUpdateFunction( context, indexingContext -> {
223 DefaultScannerListener listener = new DefaultScannerListener( indexingContext, indexerEngine, update, null );
224 ScanningRequest request = new ScanningRequest( indexingContext, listener );
225 ScanningResult result = scanner.scan( request );
226 if ( result.hasExceptions( ) )
228 log.error( "Exceptions occured during index scan of " + context.getId( ) );
229 result.getExceptions( ).stream( ).map( e -> e.getMessage( ) ).distinct( ).limit( 5 ).forEach(
230 s -> log.error( "Message: " + s )
238 public void update( final ArchivaIndexingContext context, final URI remoteUpdateUri, final boolean fullUpdate ) throws IndexUpdateFailedException
240 log.info( "start download remote index for remote repository {}", context.getRepository( ).getId( ) );
242 if ( !( context.getRepository( ) instanceof RemoteRepository ) )
244 throw new IndexUpdateFailedException( "The context is not associated to a remote repository " + context.getId( ) );
246 final RemoteRepository remoteRepository = (RemoteRepository) context.getRepository( );
248 executeUpdateFunction( context,
252 // create a temp directory to download files
253 Path tempIndexDirectory = Paths.get( indexingContext.getIndexDirectoryFile( ).getParent( ), ".tmpIndex" );
254 Path indexCacheDirectory = Paths.get( indexingContext.getIndexDirectoryFile( ).getParent( ), ".indexCache" );
255 Files.createDirectories( indexCacheDirectory );
256 if ( Files.exists( tempIndexDirectory ) )
258 org.apache.archiva.common.utils.FileUtils.deleteDirectory( tempIndexDirectory );
260 Files.createDirectories( tempIndexDirectory );
261 tempIndexDirectory.toFile( ).deleteOnExit( );
262 String baseIndexUrl = indexingContext.getIndexUpdateUrl( );
264 String wagonProtocol = remoteUpdateUri.toURL( ).getProtocol( );
266 NetworkProxy networkProxy = null;
267 if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
269 RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
270 if ( StringUtils.isNotBlank( rif.getProxyId( ) ) )
274 networkProxy = networkProxyAdmin.getNetworkProxy( rif.getProxyId( ) );
276 catch ( RepositoryAdminException e )
278 log.error( "Error occured while retrieving proxy {}", e.getMessage( ) );
280 if ( networkProxy == null )
283 "your remote repository is configured to download remote index trought a proxy we cannot find id:{}",
288 final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
289 new WagonFactoryRequest( wagonProtocol, remoteRepository.getExtraHeaders( ) ).networkProxy(
292 int readTimeout = (int) rif.getDownloadTimeout( ).toMillis( ) * 1000;
293 wagon.setReadTimeout( readTimeout );
294 wagon.setTimeout( (int) remoteRepository.getTimeout( ).toMillis( ) * 1000 );
296 if ( wagon instanceof AbstractHttpClientWagon )
298 HttpConfiguration httpConfiguration = new HttpConfiguration( );
299 HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration( );
300 httpMethodConfiguration.setUsePreemptive( true );
301 httpMethodConfiguration.setReadTimeout( readTimeout );
302 httpConfiguration.setGet( httpMethodConfiguration );
303 AbstractHttpClientWagon.class.cast( wagon ).setHttpConfiguration( httpConfiguration );
306 wagon.addTransferListener( new DownloadListener( ) );
307 ProxyInfo proxyInfo = null;
308 if ( networkProxy != null )
310 proxyInfo = new ProxyInfo( );
311 proxyInfo.setType( networkProxy.getProtocol( ) );
312 proxyInfo.setHost( networkProxy.getHost( ) );
313 proxyInfo.setPort( networkProxy.getPort( ) );
314 proxyInfo.setUserName( networkProxy.getUsername( ) );
315 proxyInfo.setPassword( networkProxy.getPassword( ) );
317 AuthenticationInfo authenticationInfo = null;
318 if ( remoteRepository.getLoginCredentials( ) != null && ( remoteRepository.getLoginCredentials( ) instanceof PasswordCredentials ) )
320 PasswordCredentials creds = (PasswordCredentials) remoteRepository.getLoginCredentials( );
321 authenticationInfo = new AuthenticationInfo( );
322 authenticationInfo.setUserName( creds.getUsername( ) );
323 authenticationInfo.setPassword( new String( creds.getPassword( ) ) );
325 wagon.connect( new org.apache.maven.wagon.repository.Repository( remoteRepository.getId( ), baseIndexUrl ), authenticationInfo,
328 Path indexDirectory = indexingContext.getIndexDirectoryFile( ).toPath( );
329 if ( !Files.exists( indexDirectory ) )
331 Files.createDirectories( indexDirectory );
334 ResourceFetcher resourceFetcher =
335 new WagonResourceFetcher( log, tempIndexDirectory, wagon, remoteRepository );
336 IndexUpdateRequest request = new IndexUpdateRequest( indexingContext, resourceFetcher );
337 request.setForceFullUpdate( fullUpdate );
338 request.setLocalIndexCacheDir( indexCacheDirectory.toFile( ) );
340 indexUpdater.fetchAndUpdateIndex( request );
342 indexingContext.updateTimestamp( true );
346 catch ( AuthenticationException e )
348 log.error( "Could not login to the remote proxy for updating index of {}", remoteRepository.getId( ), e );
349 throw new IndexUpdateFailedException( "Login in to proxy failed while updating remote repository " + remoteRepository.getId( ), e );
351 catch ( ConnectionException e )
353 log.error( "Connection error during index update for remote repository {}", remoteRepository.getId( ), e );
354 throw new IndexUpdateFailedException( "Connection error during index update for remote repository " + remoteRepository.getId( ), e );
356 catch ( MalformedURLException e )
358 log.error( "URL for remote index update of remote repository {} is not correct {}", remoteRepository.getId( ), remoteUpdateUri, e );
359 throw new IndexUpdateFailedException( "URL for remote index update of repository is not correct " + remoteUpdateUri, e );
361 catch ( IOException e )
363 log.error( "IOException during index update of remote repository {}: {}", remoteRepository.getId( ), e.getMessage( ), e );
364 throw new IndexUpdateFailedException( "IOException during index update of remote repository " + remoteRepository.getId( )
365 + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ), e );
367 catch ( WagonFactoryException e )
369 log.error( "Wagon for remote index download of {} could not be created: {}", remoteRepository.getId( ), e.getMessage( ), e );
370 throw new IndexUpdateFailedException( "Error while updating the remote index of " + remoteRepository.getId( ), e );
377 public void addArtifactToIndex( ArchivaIndexingContext context, ArtifactReference artifactReference ) throws IndexUpdateFailedException
383 public void removeArtifactFromIndex( ArchivaIndexingContext context, ArtifactReference artifactReference ) throws IndexUpdateFailedException
389 public boolean supportsRepository( RepositoryType type )
391 return type == RepositoryType.MAVEN;
395 public ArchivaIndexingContext createContext( Repository repository ) throws IndexCreationFailedException
398 if ( repository.getType( ) != RepositoryType.MAVEN )
400 throw new UnsupportedRepositoryTypeException( repository.getType( ) );
402 IndexingContext mvnCtx = null;
405 if ( repository instanceof RemoteRepository )
407 mvnCtx = createRemoteContext( (RemoteRepository) repository );
409 else if ( repository instanceof ManagedRepository )
411 mvnCtx = createManagedContext( (ManagedRepository) repository );
414 catch ( IOException e )
416 log.error( "IOException during context creation " + e.getMessage( ), e );
417 throw new IndexCreationFailedException( "Could not create index context for repository " + repository.getId( )
418 + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ), e );
420 MavenIndexContext context = new MavenIndexContext( repository, mvnCtx );
424 private IndexingContext createRemoteContext( RemoteRepository remoteRepository ) throws IOException
426 Path appServerBase = archivaConfiguration.getAppServerBaseDir( );
428 String contextKey = "remote-" + remoteRepository.getId( );
430 // create remote repository path
431 Path repoDir = appServerBase.resolve( "data" ).resolve( "remotes" ).resolve( remoteRepository.getId( ) );
432 if ( !Files.exists( repoDir ) )
434 Files.createDirectories( repoDir );
439 // is there configured indexDirectory ?
440 if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
442 RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
443 indexDirectory = PathUtil.getPathFromUri( rif.getIndexUri( ) );
444 if ( !indexDirectory.isAbsolute( ) )
446 indexDirectory = repoDir.resolve( indexDirectory );
449 // if not configured use a default value
450 if ( indexDirectory == null )
452 indexDirectory = repoDir.resolve( ".index" );
454 if ( !Files.exists( indexDirectory ) )
456 Files.createDirectories( indexDirectory );
459 String remoteIndexUrl = calculateIndexRemoteUrl( remoteRepository.getLocation( ), rif );
463 return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
465 catch ( IndexFormatTooOldException e )
467 // existing index with an old lucene format so we need to delete it!!!
468 // delete it first then recreate it.
469 log.warn( "the index of repository {} is too old we have to delete and recreate it", //
470 remoteRepository.getId( ) );
471 org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory );
472 return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
478 throw new IOException( "No remote index defined" );
482 private IndexingContext getIndexingContext( Repository repository, String contextKey, Path repoDir, Path indexDirectory, String indexUrl ) throws IOException
484 return indexer.createIndexingContext( contextKey, repository.getId( ), repoDir.toFile( ), indexDirectory.toFile( ),
485 repository.getLocation( ) == null ? null : repository.getLocation( ).toString( ),
491 private IndexingContext createManagedContext( ManagedRepository repository ) throws IOException
494 IndexingContext context;
495 // take care first about repository location as can be relative
496 Path repositoryDirectory = PathUtil.getPathFromUri( repository.getLocation( ) );
498 if ( !repositoryDirectory.isAbsolute( ) )
500 repositoryDirectory =
501 repositoryDirectory.resolve( "repositories" ).resolve( repositoryDirectory );
504 if ( !Files.exists( repositoryDirectory ) )
508 Files.createDirectories( repositoryDirectory );
510 catch ( IOException e )
512 log.error( "Could not create directory {}", repositoryDirectory );
517 if ( repository.supportsFeature( IndexCreationFeature.class ) )
519 IndexCreationFeature icf = repository.getFeature( IndexCreationFeature.class ).get( );
520 URI indexDir = icf.getIndexPath( );
521 //File managedRepository = new File( repository.getLocation() );
523 Path indexDirectory = null;
524 if ( indexDir != null && !"".equals( indexDir.toString( ) ) )
527 indexDirectory = PathUtil.getPathFromUri( indexDir );
528 // not absolute so create it in repository directory
529 if ( !indexDirectory.isAbsolute( ) )
531 indexDirectory = repositoryDirectory.resolve( indexDirectory );
533 icf.setIndexPath( indexDirectory.normalize( ).toUri( ) );
537 indexDirectory = repositoryDirectory.resolve( ".indexer" );
538 icf.setIndexPath( indexDirectory.toUri( ) );
541 if ( !Files.exists( indexDirectory ) )
543 Files.createDirectories( indexDirectory );
546 String indexUrl = repositoryDirectory.toUri( ).toURL( ).toExternalForm( );
549 context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
550 context.setSearchable( repository.isScanned( ) );
552 catch ( IndexFormatTooOldException e )
554 // existing index with an old lucene format so we need to delete it!!!
555 // delete it first then recreate it.
556 log.warn( "the index of repository {} is too old we have to delete and recreate it", //
557 repository.getId( ) );
558 org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory );
559 context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
560 context.setSearchable( repository.isScanned( ) );
566 throw new IOException( "No repository index defined" );
570 private String calculateIndexRemoteUrl( URI baseUri, RemoteIndexFeature rif )
572 if ( rif.getIndexUri( ) == null )
574 return baseUri.resolve( ".index" ).toString( );
578 return baseUri.resolve( rif.getIndexUri( ) ).toString( );
582 private static final class DownloadListener
583 implements TransferListener
585 private Logger log = LoggerFactory.getLogger( getClass( ) );
587 private String resourceName;
589 private long startTime;
591 private int totalLength = 0;
594 public void transferInitiated( TransferEvent transferEvent )
596 startTime = System.currentTimeMillis( );
597 resourceName = transferEvent.getResource( ).getName( );
598 log.debug( "initiate transfer of {}", resourceName );
602 public void transferStarted( TransferEvent transferEvent )
604 this.totalLength = 0;
605 resourceName = transferEvent.getResource( ).getName( );
606 log.info( "start transfer of {}", transferEvent.getResource( ).getName( ) );
610 public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
612 log.debug( "transfer of {} : {}/{}", transferEvent.getResource( ).getName( ), buffer.length, length );
613 this.totalLength += length;
617 public void transferCompleted( TransferEvent transferEvent )
619 resourceName = transferEvent.getResource( ).getName( );
620 long endTime = System.currentTimeMillis( );
621 log.info( "end of transfer file {} {} kb: {}s", transferEvent.getResource( ).getName( ),
622 this.totalLength / 1024, ( endTime - startTime ) / 1000 );
626 public void transferError( TransferEvent transferEvent )
628 log.info( "error of transfer file {}: {}", transferEvent.getResource( ).getName( ),
629 transferEvent.getException( ).getMessage( ), transferEvent.getException( ) );
633 public void debug( String message )
635 log.debug( "transfer debug {}", message );
639 private static class WagonResourceFetcher
640 implements ResourceFetcher
645 Path tempIndexDirectory;
649 RemoteRepository remoteRepository;
651 private WagonResourceFetcher( Logger log, Path tempIndexDirectory, Wagon wagon,
652 RemoteRepository remoteRepository )
655 this.tempIndexDirectory = tempIndexDirectory;
657 this.remoteRepository = remoteRepository;
661 public void connect( String id, String url )
668 public void disconnect( )
675 public InputStream retrieve( String name )
676 throws IOException, FileNotFoundException
680 log.info( "index update retrieve file, name:{}", name );
681 Path file = tempIndexDirectory.resolve( name );
682 Files.deleteIfExists( file );
683 file.toFile( ).deleteOnExit( );
684 wagon.get( addParameters( name, remoteRepository ), file.toFile( ) );
685 return Files.newInputStream( file );
687 catch ( AuthorizationException | TransferFailedException e )
689 throw new IOException( e.getMessage( ), e );
691 catch ( ResourceDoesNotExistException e )
693 FileNotFoundException fnfe = new FileNotFoundException( e.getMessage( ) );
699 // FIXME remove crappy copy/paste
700 protected String addParameters( String path, RemoteRepository remoteRepository )
702 if ( remoteRepository.getExtraParameters( ).isEmpty( ) )
707 boolean question = false;
709 StringBuilder res = new StringBuilder( path == null ? "" : path );
711 for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters( ).entrySet( ) )
715 res.append( '?' ).append( entry.getKey( ) ).append( '=' ).append( entry.getValue( ) );
719 return res.toString( );