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 39KB

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