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

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