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

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