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

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