You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MavenIndexManager.java 35KB

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