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.

ArchivaIndexManagerMock.java 35KB

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