You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MavenIndexManager.java 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. package org.apache.archiva.indexer.maven;
  2. /*
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. */
  20. import org.apache.archiva.admin.model.RepositoryAdminException;
  21. import org.apache.archiva.common.utils.FileUtils;
  22. import org.apache.archiva.common.utils.PathUtil;
  23. import org.apache.archiva.configuration.ArchivaConfiguration;
  24. import org.apache.archiva.indexer.ArchivaIndexManager;
  25. import org.apache.archiva.indexer.ArchivaIndexingContext;
  26. import org.apache.archiva.indexer.IndexCreationFailedException;
  27. import org.apache.archiva.indexer.IndexUpdateFailedException;
  28. import org.apache.archiva.indexer.UnsupportedBaseContextException;
  29. import org.apache.archiva.proxy.ProxyRegistry;
  30. import org.apache.archiva.proxy.maven.WagonFactory;
  31. import org.apache.archiva.proxy.maven.WagonFactoryException;
  32. import org.apache.archiva.proxy.maven.WagonFactoryRequest;
  33. import org.apache.archiva.proxy.model.NetworkProxy;
  34. import org.apache.archiva.repository.EditableRepository;
  35. import org.apache.archiva.repository.ManagedRepository;
  36. import org.apache.archiva.repository.PasswordCredentials;
  37. import org.apache.archiva.repository.RemoteRepository;
  38. import org.apache.archiva.repository.Repository;
  39. import org.apache.archiva.repository.RepositoryType;
  40. import org.apache.archiva.repository.UnsupportedRepositoryTypeException;
  41. import org.apache.archiva.repository.features.IndexCreationFeature;
  42. import org.apache.archiva.repository.features.RemoteIndexFeature;
  43. import org.apache.commons.lang.StringUtils;
  44. import org.apache.maven.index.ArtifactContext;
  45. import org.apache.maven.index.ArtifactContextProducer;
  46. import org.apache.maven.index.DefaultScannerListener;
  47. import org.apache.maven.index.Indexer;
  48. import org.apache.maven.index.IndexerEngine;
  49. import org.apache.maven.index.Scanner;
  50. import org.apache.maven.index.ScanningRequest;
  51. import org.apache.maven.index.ScanningResult;
  52. import org.apache.maven.index.context.IndexCreator;
  53. import org.apache.maven.index.context.IndexingContext;
  54. import org.apache.maven.index.packer.IndexPacker;
  55. import org.apache.maven.index.packer.IndexPackingRequest;
  56. import org.apache.maven.index.updater.IndexUpdateRequest;
  57. import org.apache.maven.index.updater.IndexUpdater;
  58. import org.apache.maven.index.updater.ResourceFetcher;
  59. import org.apache.maven.index_shaded.lucene.index.IndexFormatTooOldException;
  60. import org.apache.maven.wagon.ConnectionException;
  61. import org.apache.maven.wagon.ResourceDoesNotExistException;
  62. import org.apache.maven.wagon.StreamWagon;
  63. import org.apache.maven.wagon.TransferFailedException;
  64. import org.apache.maven.wagon.Wagon;
  65. import org.apache.maven.wagon.authentication.AuthenticationException;
  66. import org.apache.maven.wagon.authentication.AuthenticationInfo;
  67. import org.apache.maven.wagon.authorization.AuthorizationException;
  68. import org.apache.maven.wagon.events.TransferEvent;
  69. import org.apache.maven.wagon.events.TransferListener;
  70. import org.apache.maven.wagon.proxy.ProxyInfo;
  71. import org.apache.maven.wagon.shared.http.AbstractHttpClientWagon;
  72. import org.apache.maven.wagon.shared.http.HttpConfiguration;
  73. import org.apache.maven.wagon.shared.http.HttpMethodConfiguration;
  74. import org.slf4j.Logger;
  75. import org.slf4j.LoggerFactory;
  76. 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;
  82. import java.net.URI;
  83. import java.nio.file.Files;
  84. import java.nio.file.Path;
  85. import java.nio.file.Paths;
  86. import java.util.Collection;
  87. import java.util.List;
  88. import java.util.Map;
  89. import java.util.concurrent.ConcurrentSkipListSet;
  90. import java.util.stream.Collectors;
  91. /**
  92. * Maven implementation of index manager.
  93. * The index manager is a singleton, so we try to make sure, that index operations are not running
  94. * parallel by synchronizing on the index path.
  95. * A update operation waits for parallel running methods to finish before starting, but after a certain
  96. * time of retries a IndexUpdateFailedException is thrown.
  97. */
  98. @Service( "archivaIndexManager#maven" )
  99. public class MavenIndexManager implements ArchivaIndexManager {
  100. private static final Logger log = LoggerFactory.getLogger( MavenIndexManager.class );
  101. @Inject
  102. private Indexer indexer;
  103. @Inject
  104. private IndexerEngine indexerEngine;
  105. @Inject
  106. private List<? extends IndexCreator> indexCreators;
  107. @Inject
  108. private IndexPacker indexPacker;
  109. @Inject
  110. private Scanner scanner;
  111. @Inject
  112. private ArchivaConfiguration archivaConfiguration;
  113. @Inject
  114. private WagonFactory wagonFactory;
  115. @Inject
  116. private IndexUpdater indexUpdater;
  117. @Inject
  118. private ArtifactContextProducer artifactContextProducer;
  119. @Inject
  120. private ProxyRegistry proxyRegistry;
  121. public static final String DEFAULT_INDEXER_DIR = ".indexer";
  122. public static final String DEFAULT_PACKED_INDEX_DIR = ".index";
  123. private ConcurrentSkipListSet<Path> activeContexts = new ConcurrentSkipListSet<>( );
  124. private static final int WAIT_TIME = 100;
  125. private static final int MAX_WAIT = 10;
  126. public static IndexingContext getMvnContext( ArchivaIndexingContext context ) throws UnsupportedBaseContextException
  127. {
  128. if ( !context.supports( IndexingContext.class ) )
  129. {
  130. log.error( "The provided archiva index context does not support the maven IndexingContext" );
  131. throw new UnsupportedBaseContextException( "The context does not support the Maven IndexingContext" );
  132. }
  133. return context.getBaseContext( IndexingContext.class );
  134. }
  135. private Path getIndexPath( ArchivaIndexingContext ctx )
  136. {
  137. return PathUtil.getPathFromUri( ctx.getPath( ) );
  138. }
  139. @FunctionalInterface
  140. interface IndexUpdateConsumer
  141. {
  142. void accept( IndexingContext indexingContext ) throws IndexUpdateFailedException;
  143. }
  144. /*
  145. * This method is used to do some actions around the update execution code. And to make sure, that no other
  146. * method is running on the same index.
  147. */
  148. private void executeUpdateFunction( ArchivaIndexingContext context, IndexUpdateConsumer function ) throws IndexUpdateFailedException
  149. {
  150. IndexingContext indexingContext = null;
  151. try
  152. {
  153. indexingContext = getMvnContext( context );
  154. }
  155. catch ( UnsupportedBaseContextException e )
  156. {
  157. throw new IndexUpdateFailedException( "Maven index is not supported by this context", e );
  158. }
  159. final Path ctxPath = getIndexPath( context );
  160. int loop = MAX_WAIT;
  161. boolean active = false;
  162. while ( loop-- > 0 && !active )
  163. {
  164. active = activeContexts.add( ctxPath );
  165. try
  166. {
  167. Thread.currentThread( ).sleep( WAIT_TIME );
  168. }
  169. catch ( InterruptedException e )
  170. {
  171. // Ignore this
  172. }
  173. }
  174. if ( active )
  175. {
  176. try
  177. {
  178. function.accept( indexingContext );
  179. }
  180. finally
  181. {
  182. activeContexts.remove( ctxPath );
  183. }
  184. }
  185. else
  186. {
  187. throw new IndexUpdateFailedException( "Timeout while waiting for index release on context " + context.getId( ) );
  188. }
  189. }
  190. @Override
  191. public void pack( final ArchivaIndexingContext context ) throws IndexUpdateFailedException
  192. {
  193. executeUpdateFunction( context, indexingContext -> {
  194. try
  195. {
  196. IndexPackingRequest request = new IndexPackingRequest( indexingContext,
  197. indexingContext.acquireIndexSearcher( ).getIndexReader( ),
  198. indexingContext.getIndexDirectoryFile( ) );
  199. indexPacker.packIndex( request );
  200. indexingContext.updateTimestamp( true );
  201. }
  202. catch ( IOException e )
  203. {
  204. log.error( "IOException while packing index of context " + context.getId( ) + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ) );
  205. throw new IndexUpdateFailedException( "IOException during update of " + context.getId( ), e );
  206. }
  207. }
  208. );
  209. }
  210. @Override
  211. public void scan(final ArchivaIndexingContext context) throws IndexUpdateFailedException
  212. {
  213. executeUpdateFunction( context, indexingContext -> {
  214. DefaultScannerListener listener = new DefaultScannerListener( indexingContext, indexerEngine, true, null );
  215. ScanningRequest request = new ScanningRequest( indexingContext, listener );
  216. ScanningResult result = scanner.scan( request );
  217. if ( result.hasExceptions( ) )
  218. {
  219. log.error( "Exceptions occured during index scan of " + context.getId( ) );
  220. result.getExceptions( ).stream( ).map( e -> e.getMessage( ) ).distinct( ).limit( 5 ).forEach(
  221. s -> log.error( "Message: " + s )
  222. );
  223. }
  224. } );
  225. }
  226. @Override
  227. public void update(final ArchivaIndexingContext context, final boolean fullUpdate) throws IndexUpdateFailedException
  228. {
  229. log.info( "start download remote index for remote repository {}", context.getRepository( ).getId( ) );
  230. URI remoteUpdateUri;
  231. if ( !( context.getRepository( ) instanceof RemoteRepository ) || !(context.getRepository().supportsFeature(RemoteIndexFeature.class)) )
  232. {
  233. throw new IndexUpdateFailedException( "The context is not associated to a remote repository with remote index " + context.getId( ) );
  234. } else {
  235. RemoteIndexFeature rif = context.getRepository().getFeature(RemoteIndexFeature.class).get();
  236. remoteUpdateUri = context.getRepository().getLocation().resolve(rif.getIndexUri());
  237. }
  238. final RemoteRepository remoteRepository = (RemoteRepository) context.getRepository( );
  239. executeUpdateFunction( context,
  240. indexingContext -> {
  241. try
  242. {
  243. // create a temp directory to download files
  244. Path tempIndexDirectory = Paths.get( indexingContext.getIndexDirectoryFile( ).getParent( ), ".tmpIndex" );
  245. Path indexCacheDirectory = Paths.get( indexingContext.getIndexDirectoryFile( ).getParent( ), ".indexCache" );
  246. Files.createDirectories( indexCacheDirectory );
  247. if ( Files.exists( tempIndexDirectory ) )
  248. {
  249. org.apache.archiva.common.utils.FileUtils.deleteDirectory( tempIndexDirectory );
  250. }
  251. Files.createDirectories( tempIndexDirectory );
  252. tempIndexDirectory.toFile( ).deleteOnExit( );
  253. String baseIndexUrl = indexingContext.getIndexUpdateUrl( );
  254. String wagonProtocol = remoteUpdateUri.toURL( ).getProtocol( );
  255. NetworkProxy networkProxy = null;
  256. if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
  257. {
  258. RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
  259. if ( StringUtils.isNotBlank( rif.getProxyId( ) ) )
  260. {
  261. networkProxy = proxyRegistry.getNetworkProxy( rif.getProxyId( ) );
  262. if ( networkProxy == null )
  263. {
  264. log.warn(
  265. "your remote repository is configured to download remote index trought a proxy we cannot find id:{}",
  266. rif.getProxyId( ) );
  267. }
  268. }
  269. final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
  270. new WagonFactoryRequest( wagonProtocol, remoteRepository.getExtraHeaders( ) ).networkProxy(
  271. networkProxy )
  272. );
  273. int readTimeout = (int) rif.getDownloadTimeout( ).toMillis( ) * 1000;
  274. wagon.setReadTimeout( readTimeout );
  275. wagon.setTimeout( (int) remoteRepository.getTimeout( ).toMillis( ) * 1000 );
  276. if ( wagon instanceof AbstractHttpClientWagon )
  277. {
  278. HttpConfiguration httpConfiguration = new HttpConfiguration( );
  279. HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration( );
  280. httpMethodConfiguration.setUsePreemptive( true );
  281. httpMethodConfiguration.setReadTimeout( readTimeout );
  282. httpConfiguration.setGet( httpMethodConfiguration );
  283. AbstractHttpClientWagon.class.cast( wagon ).setHttpConfiguration( httpConfiguration );
  284. }
  285. wagon.addTransferListener( new DownloadListener( ) );
  286. ProxyInfo proxyInfo = null;
  287. if ( networkProxy != null )
  288. {
  289. proxyInfo = new ProxyInfo( );
  290. proxyInfo.setType( networkProxy.getProtocol( ) );
  291. proxyInfo.setHost( networkProxy.getHost( ) );
  292. proxyInfo.setPort( networkProxy.getPort( ) );
  293. proxyInfo.setUserName( networkProxy.getUsername( ) );
  294. proxyInfo.setPassword( networkProxy.getPassword( ) );
  295. }
  296. AuthenticationInfo authenticationInfo = null;
  297. if ( remoteRepository.getLoginCredentials( ) != null && ( remoteRepository.getLoginCredentials( ) instanceof PasswordCredentials ) )
  298. {
  299. PasswordCredentials creds = (PasswordCredentials) remoteRepository.getLoginCredentials( );
  300. authenticationInfo = new AuthenticationInfo( );
  301. authenticationInfo.setUserName( creds.getUsername( ) );
  302. authenticationInfo.setPassword( new String( creds.getPassword( ) ) );
  303. }
  304. wagon.connect( new org.apache.maven.wagon.repository.Repository( remoteRepository.getId( ), baseIndexUrl ), authenticationInfo,
  305. proxyInfo );
  306. Path indexDirectory = indexingContext.getIndexDirectoryFile( ).toPath( );
  307. if ( !Files.exists( indexDirectory ) )
  308. {
  309. Files.createDirectories( indexDirectory );
  310. }
  311. ResourceFetcher resourceFetcher =
  312. new WagonResourceFetcher( log, tempIndexDirectory, wagon, remoteRepository );
  313. IndexUpdateRequest request = new IndexUpdateRequest( indexingContext, resourceFetcher );
  314. request.setForceFullUpdate( fullUpdate );
  315. request.setLocalIndexCacheDir( indexCacheDirectory.toFile( ) );
  316. indexUpdater.fetchAndUpdateIndex( request );
  317. indexingContext.updateTimestamp( true );
  318. }
  319. }
  320. catch ( AuthenticationException e )
  321. {
  322. log.error( "Could not login to the remote proxy for updating index of {}", remoteRepository.getId( ), e );
  323. throw new IndexUpdateFailedException( "Login in to proxy failed while updating remote repository " + remoteRepository.getId( ), e );
  324. }
  325. catch ( ConnectionException e )
  326. {
  327. log.error( "Connection error during index update for remote repository {}", remoteRepository.getId( ), e );
  328. throw new IndexUpdateFailedException( "Connection error during index update for remote repository " + remoteRepository.getId( ), e );
  329. }
  330. catch ( MalformedURLException e )
  331. {
  332. log.error( "URL for remote index update of remote repository {} is not correct {}", remoteRepository.getId( ), remoteUpdateUri, e );
  333. throw new IndexUpdateFailedException( "URL for remote index update of repository is not correct " + remoteUpdateUri, e );
  334. }
  335. catch ( IOException e )
  336. {
  337. log.error( "IOException during index update of remote repository {}: {}", remoteRepository.getId( ), e.getMessage( ), e );
  338. throw new IndexUpdateFailedException( "IOException during index update of remote repository " + remoteRepository.getId( )
  339. + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ), e );
  340. }
  341. catch ( WagonFactoryException e )
  342. {
  343. log.error( "Wagon for remote index download of {} could not be created: {}", remoteRepository.getId( ), e.getMessage( ), e );
  344. throw new IndexUpdateFailedException( "Error while updating the remote index of " + remoteRepository.getId( ), e );
  345. }
  346. } );
  347. }
  348. @Override
  349. public void addArtifactsToIndex( final ArchivaIndexingContext context, final Collection<URI> artifactReference ) throws IndexUpdateFailedException
  350. {
  351. final URI ctxUri = context.getPath();
  352. executeUpdateFunction(context, indexingContext -> {
  353. Collection<ArtifactContext> artifacts = artifactReference.stream().map(r -> artifactContextProducer.getArtifactContext(indexingContext, Paths.get(ctxUri.resolve(r)).toFile())).collect(Collectors.toList());
  354. try {
  355. indexer.addArtifactsToIndex(artifacts, indexingContext);
  356. } catch (IOException e) {
  357. log.error("IOException while adding artifact {}", e.getMessage(), e);
  358. throw new IndexUpdateFailedException("Error occured while adding artifact to index of "+context.getId()
  359. + (StringUtils.isNotEmpty(e.getMessage()) ? ": "+e.getMessage() : ""));
  360. }
  361. });
  362. }
  363. @Override
  364. public void removeArtifactsFromIndex( ArchivaIndexingContext context, Collection<URI> artifactReference ) throws IndexUpdateFailedException
  365. {
  366. final URI ctxUri = context.getPath();
  367. executeUpdateFunction(context, indexingContext -> {
  368. Collection<ArtifactContext> artifacts = artifactReference.stream().map(r -> artifactContextProducer.getArtifactContext(indexingContext, Paths.get(ctxUri.resolve(r)).toFile())).collect(Collectors.toList());
  369. try {
  370. indexer.deleteArtifactsFromIndex(artifacts, indexingContext);
  371. } catch (IOException e) {
  372. log.error("IOException while removing artifact {}", e.getMessage(), e);
  373. throw new IndexUpdateFailedException("Error occured while removing artifact from index of "+context.getId()
  374. + (StringUtils.isNotEmpty(e.getMessage()) ? ": "+e.getMessage() : ""));
  375. }
  376. });
  377. }
  378. @Override
  379. public boolean supportsRepository( RepositoryType type )
  380. {
  381. return type == RepositoryType.MAVEN;
  382. }
  383. @Override
  384. public ArchivaIndexingContext createContext( Repository repository ) throws IndexCreationFailedException
  385. {
  386. log.debug("Creating context for repo {}, type: {}", repository.getId(), repository.getType());
  387. if ( repository.getType( ) != RepositoryType.MAVEN )
  388. {
  389. throw new UnsupportedRepositoryTypeException( repository.getType( ) );
  390. }
  391. IndexingContext mvnCtx = null;
  392. try
  393. {
  394. if ( repository instanceof RemoteRepository )
  395. {
  396. mvnCtx = createRemoteContext( (RemoteRepository) repository );
  397. }
  398. else if ( repository instanceof ManagedRepository )
  399. {
  400. mvnCtx = createManagedContext( (ManagedRepository) repository );
  401. }
  402. }
  403. catch ( IOException e )
  404. {
  405. log.error( "IOException during context creation " + e.getMessage( ), e );
  406. throw new IndexCreationFailedException( "Could not create index context for repository " + repository.getId( )
  407. + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ), e );
  408. }
  409. MavenIndexContext context = new MavenIndexContext( repository, mvnCtx );
  410. return context;
  411. }
  412. @Override
  413. public ArchivaIndexingContext reset(ArchivaIndexingContext context) throws IndexUpdateFailedException {
  414. ArchivaIndexingContext ctx;
  415. executeUpdateFunction(context, indexingContext -> {
  416. try {
  417. indexingContext.close(true);
  418. } catch (IOException e) {
  419. log.warn("Index close failed");
  420. }
  421. try {
  422. FileUtils.deleteDirectory(Paths.get(context.getPath()));
  423. } catch (IOException e) {
  424. throw new IndexUpdateFailedException("Could not delete index files");
  425. }
  426. });
  427. try {
  428. Repository repo = context.getRepository();
  429. ctx = createContext(context.getRepository());
  430. if (repo instanceof EditableRepository) {
  431. ((EditableRepository)repo).setIndexingContext(ctx);
  432. }
  433. } catch (IndexCreationFailedException e) {
  434. throw new IndexUpdateFailedException("Could not create index");
  435. }
  436. return ctx;
  437. }
  438. @Override
  439. public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo) throws IndexCreationFailedException {
  440. if (context==null) {
  441. return null;
  442. }
  443. if (context.supports(IndexingContext.class)) {
  444. try {
  445. Path newPath = getIndexPath(repo);
  446. IndexingContext ctx = context.getBaseContext(IndexingContext.class);
  447. Path oldPath = ctx.getIndexDirectoryFile().toPath();
  448. if (oldPath.equals(newPath)) {
  449. // Nothing to do, if path does not change
  450. return context;
  451. }
  452. if (!Files.exists(oldPath)) {
  453. return createContext(repo);
  454. } else if (context.isEmpty()) {
  455. context.close();
  456. return createContext(repo);
  457. } else {
  458. context.close(false);
  459. Files.move(oldPath, newPath);
  460. return createContext(repo);
  461. }
  462. } catch (IOException e) {
  463. log.error("IOException while moving index directory {}", e.getMessage(), e);
  464. throw new IndexCreationFailedException("Could not recreated the index.", e);
  465. } catch (UnsupportedBaseContextException e) {
  466. throw new IndexCreationFailedException("The given context, is not a maven context.");
  467. }
  468. } else {
  469. throw new IndexCreationFailedException("Bad context type. This is not a maven context.");
  470. }
  471. }
  472. @Override
  473. public void updateLocalIndexPath(Repository repo) {
  474. if (repo.supportsFeature(IndexCreationFeature.class)) {
  475. IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
  476. try {
  477. icf.setLocalIndexPath(getIndexPath(repo));
  478. icf.setLocalPackedIndexPath(getPackedIndexPath(repo));
  479. } catch (IOException e) {
  480. log.error("Could not set local index path for {}. New URI: {}", repo.getId(), icf.getIndexPath());
  481. }
  482. }
  483. }
  484. private Path getIndexPath(Repository repo) throws IOException {
  485. IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
  486. Path repoDir = repo.getLocalPath();
  487. URI indexDir = icf.getIndexPath();
  488. Path indexDirectory = null;
  489. if ( ! StringUtils.isEmpty(indexDir.toString( ) ) )
  490. {
  491. indexDirectory = PathUtil.getPathFromUri( indexDir );
  492. // not absolute so create it in repository directory
  493. if ( !indexDirectory.isAbsolute( ) )
  494. {
  495. indexDirectory = repoDir.resolve( indexDirectory );
  496. }
  497. }
  498. else
  499. {
  500. indexDirectory = repoDir.resolve( DEFAULT_INDEXER_DIR );
  501. }
  502. if ( !Files.exists( indexDirectory ) )
  503. {
  504. Files.createDirectories( indexDirectory );
  505. }
  506. return indexDirectory;
  507. }
  508. private Path getPackedIndexPath(Repository repo) throws IOException {
  509. IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
  510. Path repoDir = repo.getLocalPath();
  511. URI indexDir = icf.getPackedIndexPath();
  512. Path indexDirectory = null;
  513. if ( ! StringUtils.isEmpty(indexDir.toString( ) ) )
  514. {
  515. indexDirectory = PathUtil.getPathFromUri( indexDir );
  516. // not absolute so create it in repository directory
  517. if ( !indexDirectory.isAbsolute( ) )
  518. {
  519. indexDirectory = repoDir.resolve( indexDirectory );
  520. }
  521. }
  522. else
  523. {
  524. indexDirectory = repoDir.resolve( DEFAULT_PACKED_INDEX_DIR );
  525. }
  526. if ( !Files.exists( indexDirectory ) )
  527. {
  528. Files.createDirectories( indexDirectory );
  529. }
  530. return indexDirectory;
  531. }
  532. private IndexingContext createRemoteContext(RemoteRepository remoteRepository ) throws IOException
  533. {
  534. Path appServerBase = archivaConfiguration.getAppServerBaseDir( );
  535. String contextKey = "remote-" + remoteRepository.getId( );
  536. // create remote repository path
  537. Path repoDir = remoteRepository.getLocalPath();
  538. if ( !Files.exists( repoDir ) )
  539. {
  540. Files.createDirectories( repoDir );
  541. }
  542. Path indexDirectory = null;
  543. // is there configured indexDirectory ?
  544. if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
  545. {
  546. RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
  547. indexDirectory = getIndexPath(remoteRepository);
  548. String remoteIndexUrl = calculateIndexRemoteUrl( remoteRepository.getLocation( ), rif );
  549. try
  550. {
  551. return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
  552. }
  553. catch ( IndexFormatTooOldException e )
  554. {
  555. // existing index with an old lucene format so we need to delete it!!!
  556. // delete it first then recreate it.
  557. log.warn( "the index of repository {} is too old we have to delete and recreate it", //
  558. remoteRepository.getId( ) );
  559. org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory );
  560. return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
  561. }
  562. }
  563. else
  564. {
  565. throw new IOException( "No remote index defined" );
  566. }
  567. }
  568. private IndexingContext getIndexingContext( Repository repository, String contextKey, Path repoDir, Path indexDirectory, String indexUrl ) throws IOException
  569. {
  570. return indexer.createIndexingContext( contextKey, repository.getId( ), repoDir.toFile( ), indexDirectory.toFile( ),
  571. repository.getLocation( ) == null ? null : repository.getLocation( ).toString( ),
  572. indexUrl,
  573. true, false,
  574. indexCreators );
  575. }
  576. private IndexingContext createManagedContext( ManagedRepository repository ) throws IOException
  577. {
  578. IndexingContext context;
  579. // take care first about repository location as can be relative
  580. Path repositoryDirectory = repository.getLocalPath();
  581. if ( !Files.exists( repositoryDirectory ) )
  582. {
  583. try
  584. {
  585. Files.createDirectories( repositoryDirectory );
  586. }
  587. catch ( IOException e )
  588. {
  589. log.error( "Could not create directory {}", repositoryDirectory );
  590. }
  591. }
  592. Path indexDirectory = null;
  593. if ( repository.supportsFeature( IndexCreationFeature.class ) )
  594. {
  595. indexDirectory = getIndexPath(repository);
  596. String indexUrl = repositoryDirectory.toUri( ).toURL( ).toExternalForm( );
  597. try
  598. {
  599. context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
  600. context.setSearchable( repository.isScanned( ) );
  601. }
  602. catch ( IndexFormatTooOldException e )
  603. {
  604. // existing index with an old lucene format so we need to delete it!!!
  605. // delete it first then recreate it.
  606. log.warn( "the index of repository {} is too old we have to delete and recreate it", //
  607. repository.getId( ) );
  608. org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory );
  609. context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
  610. context.setSearchable( repository.isScanned( ) );
  611. }
  612. return context;
  613. }
  614. else
  615. {
  616. throw new IOException( "No repository index defined" );
  617. }
  618. }
  619. private String calculateIndexRemoteUrl( URI baseUri, RemoteIndexFeature rif )
  620. {
  621. if ( rif.getIndexUri( ) == null )
  622. {
  623. return baseUri.resolve( DEFAULT_INDEXER_DIR ).toString( );
  624. }
  625. else
  626. {
  627. return baseUri.resolve( rif.getIndexUri( ) ).toString( );
  628. }
  629. }
  630. private static final class DownloadListener
  631. implements TransferListener
  632. {
  633. private Logger log = LoggerFactory.getLogger( getClass( ) );
  634. private String resourceName;
  635. private long startTime;
  636. private int totalLength = 0;
  637. @Override
  638. public void transferInitiated( TransferEvent transferEvent )
  639. {
  640. startTime = System.currentTimeMillis( );
  641. resourceName = transferEvent.getResource( ).getName( );
  642. log.debug( "initiate transfer of {}", resourceName );
  643. }
  644. @Override
  645. public void transferStarted( TransferEvent transferEvent )
  646. {
  647. this.totalLength = 0;
  648. resourceName = transferEvent.getResource( ).getName( );
  649. log.info( "start transfer of {}", transferEvent.getResource( ).getName( ) );
  650. }
  651. @Override
  652. public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
  653. {
  654. log.debug( "transfer of {} : {}/{}", transferEvent.getResource( ).getName( ), buffer.length, length );
  655. this.totalLength += length;
  656. }
  657. @Override
  658. public void transferCompleted( TransferEvent transferEvent )
  659. {
  660. resourceName = transferEvent.getResource( ).getName( );
  661. long endTime = System.currentTimeMillis( );
  662. log.info( "end of transfer file {} {} kb: {}s", transferEvent.getResource( ).getName( ),
  663. this.totalLength / 1024, ( endTime - startTime ) / 1000 );
  664. }
  665. @Override
  666. public void transferError( TransferEvent transferEvent )
  667. {
  668. log.info( "error of transfer file {}: {}", transferEvent.getResource( ).getName( ),
  669. transferEvent.getException( ).getMessage( ), transferEvent.getException( ) );
  670. }
  671. @Override
  672. public void debug( String message )
  673. {
  674. log.debug( "transfer debug {}", message );
  675. }
  676. }
  677. private static class WagonResourceFetcher
  678. implements ResourceFetcher
  679. {
  680. Logger log;
  681. Path tempIndexDirectory;
  682. Wagon wagon;
  683. RemoteRepository remoteRepository;
  684. private WagonResourceFetcher( Logger log, Path tempIndexDirectory, Wagon wagon,
  685. RemoteRepository remoteRepository )
  686. {
  687. this.log = log;
  688. this.tempIndexDirectory = tempIndexDirectory;
  689. this.wagon = wagon;
  690. this.remoteRepository = remoteRepository;
  691. }
  692. @Override
  693. public void connect( String id, String url )
  694. throws IOException
  695. {
  696. //no op
  697. }
  698. @Override
  699. public void disconnect( )
  700. throws IOException
  701. {
  702. // no op
  703. }
  704. @Override
  705. public InputStream retrieve( String name )
  706. throws IOException, FileNotFoundException
  707. {
  708. try
  709. {
  710. log.info( "index update retrieve file, name:{}", name );
  711. Path file = tempIndexDirectory.resolve( name );
  712. Files.deleteIfExists( file );
  713. file.toFile( ).deleteOnExit( );
  714. wagon.get( addParameters( name, remoteRepository ), file.toFile( ) );
  715. return Files.newInputStream( file );
  716. }
  717. catch ( AuthorizationException | TransferFailedException e )
  718. {
  719. throw new IOException( e.getMessage( ), e );
  720. }
  721. catch ( ResourceDoesNotExistException e )
  722. {
  723. FileNotFoundException fnfe = new FileNotFoundException( e.getMessage( ) );
  724. fnfe.initCause( e );
  725. throw fnfe;
  726. }
  727. }
  728. // FIXME remove crappy copy/paste
  729. protected String addParameters( String path, RemoteRepository remoteRepository )
  730. {
  731. if ( remoteRepository.getExtraParameters( ).isEmpty( ) )
  732. {
  733. return path;
  734. }
  735. boolean question = false;
  736. StringBuilder res = new StringBuilder( path == null ? "" : path );
  737. for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters( ).entrySet( ) )
  738. {
  739. if ( !question )
  740. {
  741. res.append( '?' ).append( entry.getKey( ) ).append( '=' ).append( entry.getValue( ) );
  742. }
  743. }
  744. return res.toString( );
  745. }
  746. }
  747. }