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

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