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

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