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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. package org.apache.archiva.maven.indexer;
  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. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. import org.apache.archiva.common.utils.FileUtils;
  20. import org.apache.archiva.common.utils.PathUtil;
  21. import org.apache.archiva.configuration.provider.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.maven.common.proxy.WagonFactory;
  29. import org.apache.archiva.maven.common.proxy.WagonFactoryException;
  30. import org.apache.archiva.maven.common.proxy.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.AssetType;
  40. import org.apache.archiva.repository.storage.fs.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.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 );
  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 );
  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. org.apache.archiva.repository.storage.util.StorageUtil.deleteRecursively(context.getPath());
  432. });
  433. try {
  434. Repository repo = context.getRepository();
  435. ctx = createContext(context.getRepository());
  436. if (repo instanceof EditableRepository) {
  437. ((EditableRepository)repo).setIndexingContext(ctx);
  438. }
  439. } catch (IndexCreationFailedException e) {
  440. throw new IndexUpdateFailedException("Could not create index");
  441. }
  442. return ctx;
  443. }
  444. @Override
  445. public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo) throws IndexCreationFailedException {
  446. if (context==null) {
  447. return null;
  448. }
  449. if (context.supports(IndexingContext.class)) {
  450. try {
  451. StorageAsset newPath = getIndexPath(repo);
  452. IndexingContext ctx = context.getBaseContext(IndexingContext.class);
  453. Path oldPath = ctx.getIndexDirectoryFile().toPath();
  454. Path newFilePath = newPath.getFilePath( );
  455. if (oldPath.equals(newFilePath)) {
  456. // Nothing to do, if path does not change
  457. return context;
  458. }
  459. if (!Files.exists(oldPath)) {
  460. return createContext(repo);
  461. } else if (context.isEmpty()) {
  462. context.close();
  463. return createContext(repo);
  464. } else {
  465. context.close(false);
  466. if (Files.exists( newFilePath )) {
  467. FileUtils.copyContent( oldPath, newFilePath );
  468. FileUtils.deleteDirectory( oldPath );
  469. } else
  470. {
  471. Files.move( oldPath, newFilePath );
  472. }
  473. return createContext(repo);
  474. }
  475. } catch (IOException e) {
  476. log.error("IOException while moving index directory {}", e.getMessage(), e);
  477. throw new IndexCreationFailedException("Could not recreated the index.", e);
  478. } catch (UnsupportedBaseContextException e) {
  479. throw new IndexCreationFailedException("The given context, is not a maven context.");
  480. }
  481. } else {
  482. throw new IndexCreationFailedException("Bad context type. This is not a maven context.");
  483. }
  484. }
  485. @Override
  486. public void updateLocalIndexPath(Repository repo) {
  487. if (repo.supportsFeature(IndexCreationFeature.class)) {
  488. IndexCreationFeature icf = repo.getFeature( IndexCreationFeature.class );
  489. try {
  490. icf.setLocalIndexPath(getIndexPath(repo));
  491. icf.setLocalPackedIndexPath(getPackedIndexPath(repo));
  492. } catch (IOException e) {
  493. log.error("Could not set local index path for {}. New URI: {}", repo.getId(), icf.getIndexPath());
  494. }
  495. }
  496. }
  497. @Override
  498. public ArchivaIndexingContext mergeContexts(Repository destinationRepo, List<ArchivaIndexingContext> contexts,
  499. boolean packIndex) throws UnsupportedOperationException,
  500. IndexCreationFailedException, IllegalArgumentException {
  501. if (!destinationRepo.supportsFeature(IndexCreationFeature.class)) {
  502. throw new IllegalArgumentException("The given repository does not support the indexcreation feature");
  503. }
  504. Path mergedIndexDirectory = null;
  505. try {
  506. mergedIndexDirectory = Files.createTempDirectory("archivaMergedIndex");
  507. } catch (IOException e) {
  508. log.error("Could not create temporary directory for merged index: {}", e.getMessage(), e);
  509. throw new IndexCreationFailedException("IO error while creating temporary directory for merged index: "+e.getMessage(), e);
  510. }
  511. IndexCreationFeature indexCreationFeature = destinationRepo.getFeature( IndexCreationFeature.class );
  512. if (indexCreationFeature.getLocalIndexPath()== null) {
  513. throw new IllegalArgumentException("The given repository does not have a local index path");
  514. }
  515. StorageAsset destinationPath = indexCreationFeature.getLocalIndexPath();
  516. String tempRepoId = mergedIndexDirectory.getFileName().toString();
  517. try
  518. {
  519. Path indexLocation = destinationPath.getFilePath();
  520. List<IndexingContext> members = contexts.stream( ).filter(ctx -> ctx.supports(IndexingContext.class)).map( ctx ->
  521. {
  522. try {
  523. return ctx.getBaseContext(IndexingContext.class);
  524. } catch (UnsupportedBaseContextException e) {
  525. // does not happen here
  526. return null;
  527. }
  528. }).filter( Objects::nonNull ).collect( Collectors.toList() );
  529. ContextMemberProvider memberProvider = new StaticContextMemberProvider(members);
  530. IndexingContext mergedCtx = indexer.createMergedIndexingContext( tempRepoId, tempRepoId, mergedIndexDirectory.toFile(),
  531. indexLocation.toFile(), true, memberProvider);
  532. mergedCtx.optimize();
  533. if ( packIndex )
  534. {
  535. IndexPackingRequest request = new IndexPackingRequest( mergedCtx, //
  536. mergedCtx.acquireIndexSearcher().getIndexReader(), //
  537. indexLocation.toFile() );
  538. indexPacker.packIndex( request );
  539. }
  540. return new MavenIndexContext(destinationRepo, mergedCtx);
  541. }
  542. catch ( IOException e)
  543. {
  544. throw new IndexCreationFailedException( "IO Error during index merge: "+ e.getMessage(), e );
  545. }
  546. }
  547. private StorageAsset getIndexPath(URI indexDirUri, RepositoryStorage repoStorage, String defaultDir) throws IOException
  548. {
  549. StorageAsset rootAsset = repoStorage.getRoot();
  550. RepositoryStorage storage = rootAsset.getStorage();
  551. Path indexDirectory;
  552. Path repositoryPath = rootAsset.getFilePath().toAbsolutePath();
  553. StorageAsset indexDir;
  554. if ( ! StringUtils.isEmpty(indexDirUri.toString( ) ) )
  555. {
  556. indexDirectory = PathUtil.getPathFromUri( indexDirUri );
  557. // not absolute so create it in repository directory
  558. if ( indexDirectory.isAbsolute( ) && !indexDirectory.startsWith(repositoryPath))
  559. {
  560. if (storage instanceof FilesystemStorage) {
  561. FilesystemStorage fsStorage = (FilesystemStorage) storage;
  562. FilesystemStorage indexStorage = new FilesystemStorage(indexDirectory.getParent(), fsStorage.getFileLockManager());
  563. indexDir = indexStorage.getAsset(indexDirectory.getFileName().toString());
  564. } else {
  565. throw new IOException("The given storage is not file based.");
  566. }
  567. } else if (indexDirectory.isAbsolute()) {
  568. indexDir = storage.getAsset(repositoryPath.relativize(indexDirectory).toString());
  569. }
  570. else
  571. {
  572. indexDir = storage.getAsset(indexDirectory.toString());
  573. }
  574. }
  575. else
  576. {
  577. indexDir = storage.getAsset( defaultDir );
  578. }
  579. if ( !indexDir.exists() )
  580. {
  581. indexDir.create( AssetType.CONTAINER );
  582. }
  583. return indexDir;
  584. }
  585. private StorageAsset getIndexPath( Repository repo) throws IOException {
  586. IndexCreationFeature icf = repo.getFeature( IndexCreationFeature.class );
  587. return getIndexPath( icf.getIndexPath(), repo, DEFAULT_INDEX_PATH);
  588. }
  589. private StorageAsset getPackedIndexPath(Repository repo) throws IOException {
  590. IndexCreationFeature icf = repo.getFeature( IndexCreationFeature.class );
  591. return getIndexPath(icf.getPackedIndexPath(), repo, DEFAULT_PACKED_INDEX_PATH);
  592. }
  593. private IndexingContext createRemoteContext(RemoteRepository remoteRepository ) throws IOException
  594. {
  595. String contextKey = "remote-" + remoteRepository.getId( );
  596. // create remote repository path
  597. Path repoDir = remoteRepository.getRoot().getFilePath();
  598. if ( !Files.exists( repoDir ) )
  599. {
  600. Files.createDirectories( repoDir );
  601. }
  602. StorageAsset indexDirectory;
  603. // is there configured indexDirectory ?
  604. if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
  605. {
  606. RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class );
  607. indexDirectory = getIndexPath(remoteRepository);
  608. String remoteIndexUrl = calculateIndexRemoteUrl( remoteRepository.getLocation( ), rif );
  609. try
  610. {
  611. return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
  612. }
  613. catch ( IndexFormatTooOldException e )
  614. {
  615. // existing index with an old lucene format so we need to delete it!!!
  616. // delete it first then recreate it.
  617. log.warn( "the index of repository {} is too old we have to delete and recreate it", //
  618. remoteRepository.getId( ) );
  619. org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory.getFilePath() );
  620. return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
  621. }
  622. }
  623. else
  624. {
  625. throw new IOException( "No remote index defined" );
  626. }
  627. }
  628. private IndexingContext getIndexingContext( Repository repository, String contextKey, Path repoDir, StorageAsset indexDirectory, String indexUrl ) throws IOException
  629. {
  630. try
  631. {
  632. if (!Files.exists(indexDirectory.getFilePath())) {
  633. Files.createDirectories(indexDirectory.getFilePath());
  634. }
  635. return indexer.createIndexingContext( contextKey, repository.getId( ), repoDir.toFile( ), indexDirectory.getFilePath( ).toFile( ),
  636. repository.getLocation( ) == null ? null : repository.getLocation( ).toString( ),
  637. indexUrl,
  638. true, false,
  639. indexCreators );
  640. } catch (Exception e) {
  641. log.error("Could not create index for asset {}", indexDirectory);
  642. throw new IOException(e);
  643. }
  644. }
  645. private IndexingContext createManagedContext( ManagedRepository repository ) throws IOException
  646. {
  647. IndexingContext context;
  648. // take care first about repository location as can be relative
  649. Path repositoryDirectory = repository.getRoot().getFilePath();
  650. if ( !Files.exists( repositoryDirectory ) )
  651. {
  652. try
  653. {
  654. Files.createDirectories( repositoryDirectory );
  655. }
  656. catch ( IOException e )
  657. {
  658. log.error( "Could not create directory {}", repositoryDirectory );
  659. }
  660. }
  661. StorageAsset indexDirectory;
  662. if ( repository.supportsFeature( IndexCreationFeature.class ) )
  663. {
  664. indexDirectory = getIndexPath(repository);
  665. log.debug( "Preparing index at {}", indexDirectory );
  666. String indexUrl = repositoryDirectory.toUri( ).toURL( ).toExternalForm( );
  667. try
  668. {
  669. context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
  670. context.setSearchable( repository.isScanned( ) );
  671. }
  672. catch ( IndexFormatTooOldException e )
  673. {
  674. // existing index with an old lucene format so we need to delete it!!!
  675. // delete it first then recreate it.
  676. log.warn( "the index of repository {} is too old we have to delete and recreate it", //
  677. repository.getId( ) );
  678. org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory.getFilePath() );
  679. context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
  680. context.setSearchable( repository.isScanned( ) );
  681. }
  682. return context;
  683. }
  684. else
  685. {
  686. throw new IOException( "No repository index defined" );
  687. }
  688. }
  689. private String calculateIndexRemoteUrl( URI baseUri, RemoteIndexFeature rif )
  690. {
  691. if ( rif.getIndexUri( ) == null )
  692. {
  693. return baseUri.resolve( "/"+DEFAULT_INDEX_PATH ).toString( );
  694. }
  695. else
  696. {
  697. URI rifUri = rif.getIndexUri( );
  698. if (rifUri.isAbsolute()) {
  699. return rifUri.toString( );
  700. } else
  701. {
  702. if (baseUri.getScheme().toLowerCase().equals( "file" )) {
  703. return Paths.get( baseUri ).resolve( rifUri.getPath() ).toUri( ).toString( );
  704. } else
  705. {
  706. String pathString = rifUri.getPath( ).startsWith( "/" ) ? rifUri.getPath( ) : "/" + rifUri.getPath( );
  707. return baseUri.resolve( pathString ).toString( );
  708. }
  709. }
  710. }
  711. }
  712. private static final class DownloadListener
  713. implements TransferListener
  714. {
  715. private Logger log = LoggerFactory.getLogger( getClass( ) );
  716. private String resourceName;
  717. private long startTime;
  718. private int totalLength = 0;
  719. @Override
  720. public void transferInitiated( TransferEvent transferEvent )
  721. {
  722. startTime = System.currentTimeMillis( );
  723. resourceName = transferEvent.getResource( ).getName( );
  724. log.debug( "initiate transfer of {}", resourceName );
  725. }
  726. @Override
  727. public void transferStarted( TransferEvent transferEvent )
  728. {
  729. this.totalLength = 0;
  730. resourceName = transferEvent.getResource( ).getName( );
  731. log.info( "start transfer of {}", transferEvent.getResource( ).getName( ) );
  732. }
  733. @Override
  734. public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
  735. {
  736. log.debug( "transfer of {} : {}/{}", transferEvent.getResource( ).getName( ), buffer.length, length );
  737. this.totalLength += length;
  738. }
  739. @Override
  740. public void transferCompleted( TransferEvent transferEvent )
  741. {
  742. resourceName = transferEvent.getResource( ).getName( );
  743. long endTime = System.currentTimeMillis( );
  744. log.info( "end of transfer file {} {} kb: {}s", transferEvent.getResource( ).getName( ),
  745. this.totalLength / 1024, ( endTime - startTime ) / 1000 );
  746. }
  747. @Override
  748. public void transferError( TransferEvent transferEvent )
  749. {
  750. log.info( "error of transfer file {}: {}", transferEvent.getResource( ).getName( ),
  751. transferEvent.getException( ).getMessage( ), transferEvent.getException( ) );
  752. }
  753. @Override
  754. public void debug( String message )
  755. {
  756. log.debug( "transfer debug {}", message );
  757. }
  758. }
  759. private static class WagonResourceFetcher
  760. implements ResourceFetcher
  761. {
  762. Logger log;
  763. Path tempIndexDirectory;
  764. Wagon wagon;
  765. RemoteRepository remoteRepository;
  766. private WagonResourceFetcher( Logger log, Path tempIndexDirectory, Wagon wagon,
  767. RemoteRepository remoteRepository )
  768. {
  769. this.log = log;
  770. this.tempIndexDirectory = tempIndexDirectory;
  771. this.wagon = wagon;
  772. this.remoteRepository = remoteRepository;
  773. }
  774. @Override
  775. public void connect( String id, String url ) {
  776. //no op
  777. }
  778. @Override
  779. public void disconnect( ) {
  780. // no op
  781. }
  782. @Override
  783. public InputStream retrieve( String name )
  784. throws IOException {
  785. try
  786. {
  787. log.info( "index update retrieve file, name:{}", name );
  788. Path file = tempIndexDirectory.resolve( name );
  789. Files.deleteIfExists( file );
  790. file.toFile( ).deleteOnExit( );
  791. wagon.get( addParameters( name, remoteRepository ), file.toFile( ) );
  792. return Files.newInputStream( file );
  793. }
  794. catch ( AuthorizationException | TransferFailedException e )
  795. {
  796. throw new IOException( e.getMessage( ), e );
  797. }
  798. catch ( ResourceDoesNotExistException e )
  799. {
  800. FileNotFoundException fnfe = new FileNotFoundException( e.getMessage( ) );
  801. fnfe.initCause( e );
  802. throw fnfe;
  803. }
  804. }
  805. // FIXME remove crappy copy/paste
  806. protected String addParameters( String path, RemoteRepository remoteRepository )
  807. {
  808. if ( remoteRepository.getExtraParameters( ).isEmpty( ) )
  809. {
  810. return path;
  811. }
  812. boolean question = false;
  813. StringBuilder res = new StringBuilder( path == null ? "" : path );
  814. for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters( ).entrySet( ) )
  815. {
  816. if ( !question )
  817. {
  818. res.append( '?' ).append( entry.getKey( ) ).append( '=' ).append( entry.getValue( ) );
  819. }
  820. }
  821. return res.toString( );
  822. }
  823. }
  824. }