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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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.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.proxy.maven.WagonFactory;
  30. import org.apache.archiva.proxy.maven.WagonFactoryException;
  31. import org.apache.archiva.proxy.maven.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.FilesystemAsset;
  41. import org.apache.archiva.repository.storage.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.archiva.repository.storage.StorageUtil;
  46. import org.apache.commons.lang3.StringUtils;
  47. import org.apache.maven.index.ArtifactContext;
  48. import org.apache.maven.index.ArtifactContextProducer;
  49. import org.apache.maven.index.DefaultScannerListener;
  50. import org.apache.maven.index.Indexer;
  51. import org.apache.maven.index.IndexerEngine;
  52. import org.apache.maven.index.Scanner;
  53. import org.apache.maven.index.ScanningRequest;
  54. import org.apache.maven.index.ScanningResult;
  55. import org.apache.maven.index.context.IndexCreator;
  56. import org.apache.maven.index.context.IndexingContext;
  57. import org.apache.maven.index.packer.IndexPacker;
  58. import org.apache.maven.index.packer.IndexPackingRequest;
  59. import org.apache.maven.index.updater.IndexUpdateRequest;
  60. import org.apache.maven.index.updater.ResourceFetcher;
  61. import org.apache.maven.index_shaded.lucene.index.IndexFormatTooOldException;
  62. import org.apache.maven.wagon.ConnectionException;
  63. import org.apache.maven.wagon.ResourceDoesNotExistException;
  64. import org.apache.maven.wagon.StreamWagon;
  65. import org.apache.maven.wagon.TransferFailedException;
  66. import org.apache.maven.wagon.Wagon;
  67. import org.apache.maven.wagon.authentication.AuthenticationException;
  68. import org.apache.maven.wagon.authentication.AuthenticationInfo;
  69. import org.apache.maven.wagon.authorization.AuthorizationException;
  70. import org.apache.maven.wagon.events.TransferEvent;
  71. import org.apache.maven.wagon.events.TransferListener;
  72. import org.apache.maven.wagon.proxy.ProxyInfo;
  73. import org.apache.maven.wagon.shared.http.AbstractHttpClientWagon;
  74. import org.apache.maven.wagon.shared.http.HttpConfiguration;
  75. import org.apache.maven.wagon.shared.http.HttpMethodConfiguration;
  76. import org.slf4j.Logger;
  77. import org.slf4j.LoggerFactory;
  78. import org.springframework.stereotype.Service;
  79. import javax.inject.Inject;
  80. import java.io.FileNotFoundException;
  81. import java.io.IOException;
  82. import java.io.InputStream;
  83. import java.net.MalformedURLException;
  84. import java.net.URI;
  85. import java.nio.file.Files;
  86. import java.nio.file.Path;
  87. import java.nio.file.Paths;
  88. import java.util.Collection;
  89. import java.util.List;
  90. import java.util.Map;
  91. import java.util.concurrent.ConcurrentSkipListSet;
  92. import java.util.stream.Collectors;
  93. @Service("archivaIndexManager#maven")
  94. public class ArchivaIndexManagerMock implements ArchivaIndexManager {
  95. private static final Logger log = LoggerFactory.getLogger( ArchivaIndexManagerMock.class );
  96. @Inject
  97. private Indexer indexer;
  98. @Inject
  99. private IndexerEngine indexerEngine;
  100. @Inject
  101. private List<? extends IndexCreator> indexCreators;
  102. @Inject
  103. private IndexPacker indexPacker;
  104. @Inject
  105. private Scanner scanner;
  106. @Inject
  107. private ArchivaConfiguration archivaConfiguration;
  108. @Inject
  109. private WagonFactory wagonFactory;
  110. @Inject
  111. ProxyRegistry proxyRegistry;
  112. @Inject
  113. private ArtifactContextProducer artifactContextProducer;
  114. private ConcurrentSkipListSet<Path> activeContexts = new ConcurrentSkipListSet<>( );
  115. private static final int WAIT_TIME = 100;
  116. private static final int MAX_WAIT = 10;
  117. public static IndexingContext getMvnContext(ArchivaIndexingContext context ) throws UnsupportedBaseContextException
  118. {
  119. if ( !context.supports( IndexingContext.class ) )
  120. {
  121. log.error( "The provided archiva index context does not support the maven IndexingContext" );
  122. throw new UnsupportedBaseContextException( "The context does not support the Maven IndexingContext" );
  123. }
  124. return context.getBaseContext( IndexingContext.class );
  125. }
  126. private Path getIndexPath( ArchivaIndexingContext ctx )
  127. {
  128. return ctx.getPath( ).getFilePath();
  129. }
  130. @FunctionalInterface
  131. interface IndexUpdateConsumer
  132. {
  133. void accept( IndexingContext indexingContext ) throws IndexUpdateFailedException;
  134. }
  135. /*
  136. * This method is used to do some actions around the update execution code. And to make sure, that no other
  137. * method is running on the same index.
  138. */
  139. private void executeUpdateFunction( ArchivaIndexingContext context, IndexUpdateConsumer function ) throws IndexUpdateFailedException
  140. {
  141. IndexingContext indexingContext = null;
  142. try
  143. {
  144. indexingContext = getMvnContext( context );
  145. }
  146. catch ( UnsupportedBaseContextException e )
  147. {
  148. throw new IndexUpdateFailedException( "Maven index is not supported by this context", e );
  149. }
  150. final Path ctxPath = getIndexPath( context );
  151. int loop = MAX_WAIT;
  152. boolean active = false;
  153. while ( loop-- > 0 && !active )
  154. {
  155. active = activeContexts.add( ctxPath );
  156. try
  157. {
  158. Thread.currentThread( ).sleep( WAIT_TIME );
  159. }
  160. catch ( InterruptedException e )
  161. {
  162. // Ignore this
  163. }
  164. }
  165. if ( active )
  166. {
  167. try
  168. {
  169. function.accept( indexingContext );
  170. }
  171. finally
  172. {
  173. activeContexts.remove( ctxPath );
  174. }
  175. }
  176. else
  177. {
  178. throw new IndexUpdateFailedException( "Timeout while waiting for index release on context " + context.getId( ) );
  179. }
  180. }
  181. @Override
  182. public void pack( final ArchivaIndexingContext context ) throws IndexUpdateFailedException
  183. {
  184. executeUpdateFunction( context, indexingContext -> {
  185. try
  186. {
  187. IndexPackingRequest request = new IndexPackingRequest( indexingContext,
  188. indexingContext.acquireIndexSearcher( ).getIndexReader( ),
  189. indexingContext.getIndexDirectoryFile( ) );
  190. indexPacker.packIndex( request );
  191. indexingContext.updateTimestamp( true );
  192. }
  193. catch ( IOException e )
  194. {
  195. log.error( "IOException while packing index of context " + context.getId( ) + ( StringUtils.isNotEmpty( e.getMessage( ) ) ? ": " + e.getMessage( ) : "" ) );
  196. throw new IndexUpdateFailedException( "IOException during update of " + context.getId( ), e );
  197. }
  198. }
  199. );
  200. }
  201. @Override
  202. public void scan(final ArchivaIndexingContext context) throws IndexUpdateFailedException
  203. {
  204. executeUpdateFunction( context, indexingContext -> {
  205. DefaultScannerListener listener = new DefaultScannerListener( indexingContext, indexerEngine, true, null );
  206. ScanningRequest request = new ScanningRequest( indexingContext, listener );
  207. ScanningResult result = scanner.scan( request );
  208. if ( result.hasExceptions( ) )
  209. {
  210. log.error( "Exceptions occured during index scan of " + context.getId( ) );
  211. result.getExceptions( ).stream( ).map( e -> e.getMessage( ) ).distinct( ).limit( 5 ).forEach(
  212. 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).get();
  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 ).get( );
  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.class.cast( 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. try {
  413. StorageUtil.deleteRecursively(context.getPath());
  414. } catch (IOException e) {
  415. throw new IndexUpdateFailedException("Could not delete index files");
  416. }
  417. });
  418. try {
  419. Repository repo = context.getRepository();
  420. ctx = createContext(context.getRepository());
  421. if (repo instanceof EditableRepository) {
  422. ((EditableRepository)repo).setIndexingContext(ctx);
  423. }
  424. } catch (IndexCreationFailedException e) {
  425. throw new IndexUpdateFailedException("Could not create index");
  426. }
  427. return ctx;
  428. }
  429. @Override
  430. public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo) throws IndexCreationFailedException {
  431. if (context==null) {
  432. return null;
  433. }
  434. if (context.supports(IndexingContext.class)) {
  435. try {
  436. StorageAsset newPath = getIndexPath(repo);
  437. IndexingContext ctx = context.getBaseContext(IndexingContext.class);
  438. Path oldPath = ctx.getIndexDirectoryFile().toPath();
  439. if (oldPath.equals(newPath)) {
  440. // Nothing to do, if path does not change
  441. return context;
  442. }
  443. if (!Files.exists(oldPath)) {
  444. return createContext(repo);
  445. } else if (context.isEmpty()) {
  446. context.close();
  447. return createContext(repo);
  448. } else {
  449. context.close(false);
  450. Files.move(oldPath, newPath.getFilePath());
  451. return createContext(repo);
  452. }
  453. } catch (IOException e) {
  454. log.error("IOException while moving index directory {}", e.getMessage(), e);
  455. throw new IndexCreationFailedException("Could not recreated the index.", e);
  456. } catch (UnsupportedBaseContextException e) {
  457. throw new IndexCreationFailedException("The given context, is not a maven context.");
  458. }
  459. } else {
  460. throw new IndexCreationFailedException("Bad context type. This is not a maven context.");
  461. }
  462. }
  463. @Override
  464. public void updateLocalIndexPath(Repository repo) {
  465. if (repo.supportsFeature(IndexCreationFeature.class)) {
  466. IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
  467. try {
  468. icf.setLocalIndexPath(getIndexPath(repo));
  469. } catch (IOException e) {
  470. log.error("Could not set local index path for {}. New URI: {}", repo.getId(), icf.getIndexPath());
  471. }
  472. }
  473. }
  474. @Override
  475. public ArchivaIndexingContext mergeContexts(Repository destinationRepo, List<ArchivaIndexingContext> contexts, boolean packIndex) throws UnsupportedOperationException, IndexCreationFailedException {
  476. return null;
  477. }
  478. private StorageAsset getIndexPath( Repository repo) throws IOException {
  479. IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
  480. Path repoDir = repo.getAsset("").getFilePath();
  481. URI indexDir = icf.getIndexPath();
  482. String indexPath = indexDir.getPath();
  483. Path indexDirectory = null;
  484. FilesystemStorage filesystemStorage = (FilesystemStorage) repo.getAsset("").getStorage();
  485. if ( ! StringUtils.isEmpty(indexDir.toString( ) ) )
  486. {
  487. indexDirectory = PathUtil.getPathFromUri( indexDir );
  488. // not absolute so create it in repository directory
  489. if ( indexDirectory.isAbsolute( ) )
  490. {
  491. indexPath = indexDirectory.getFileName().toString();
  492. filesystemStorage = new FilesystemStorage(indexDirectory.getParent(), new DefaultFileLockManager());
  493. }
  494. else
  495. {
  496. indexDirectory = repoDir.resolve( indexDirectory );
  497. }
  498. }
  499. else
  500. {
  501. indexDirectory = repoDir.resolve( ".index" );
  502. indexPath = ".index";
  503. }
  504. if ( !Files.exists( indexDirectory ) )
  505. {
  506. Files.createDirectories( indexDirectory );
  507. }
  508. return new FilesystemAsset( filesystemStorage, indexPath, indexDirectory);
  509. }
  510. private IndexingContext createRemoteContext(RemoteRepository remoteRepository ) throws IOException
  511. {
  512. Path appServerBase = archivaConfiguration.getAppServerBaseDir( );
  513. String contextKey = "remote-" + remoteRepository.getId( );
  514. // create remote repository path
  515. Path repoDir = remoteRepository.getAsset("").getFilePath();
  516. if ( !Files.exists( repoDir ) )
  517. {
  518. Files.createDirectories( repoDir );
  519. }
  520. StorageAsset indexDirectory = null;
  521. // is there configured indexDirectory ?
  522. if ( remoteRepository.supportsFeature( RemoteIndexFeature.class ) )
  523. {
  524. RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
  525. indexDirectory = getIndexPath(remoteRepository);
  526. String remoteIndexUrl = calculateIndexRemoteUrl( remoteRepository.getLocation( ), rif );
  527. try
  528. {
  529. return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
  530. }
  531. catch ( IndexFormatTooOldException e )
  532. {
  533. // existing index with an old lucene format so we need to delete it!!!
  534. // delete it first then recreate it.
  535. log.warn( "the index of repository {} is too old we have to delete and recreate it", //
  536. remoteRepository.getId( ) );
  537. org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory.getFilePath() );
  538. return getIndexingContext( remoteRepository, contextKey, repoDir, indexDirectory, remoteIndexUrl );
  539. }
  540. }
  541. else
  542. {
  543. throw new IOException( "No remote index defined" );
  544. }
  545. }
  546. private IndexingContext getIndexingContext( Repository repository, String contextKey, Path repoDir, StorageAsset indexDirectory, String indexUrl ) throws IOException
  547. {
  548. return indexer.createIndexingContext( contextKey, repository.getId( ), repoDir.toFile( ), indexDirectory.getFilePath().toFile( ),
  549. repository.getLocation( ) == null ? null : repository.getLocation( ).toString( ),
  550. indexUrl,
  551. true, false,
  552. indexCreators );
  553. }
  554. private IndexingContext createManagedContext( ManagedRepository repository ) throws IOException
  555. {
  556. IndexingContext context;
  557. // take care first about repository location as can be relative
  558. Path repositoryDirectory = repository.getAsset("").getFilePath();
  559. if ( !Files.exists( repositoryDirectory ) )
  560. {
  561. try
  562. {
  563. Files.createDirectories( repositoryDirectory );
  564. }
  565. catch ( IOException e )
  566. {
  567. log.error( "Could not create directory {}", repositoryDirectory );
  568. }
  569. }
  570. StorageAsset indexDirectory = null;
  571. if ( repository.supportsFeature( IndexCreationFeature.class ) )
  572. {
  573. indexDirectory = getIndexPath(repository);
  574. String indexUrl = repositoryDirectory.toUri( ).toURL( ).toExternalForm( );
  575. try
  576. {
  577. context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
  578. context.setSearchable( repository.isScanned( ) );
  579. }
  580. catch ( IndexFormatTooOldException e )
  581. {
  582. // existing index with an old lucene format so we need to delete it!!!
  583. // delete it first then recreate it.
  584. log.warn( "the index of repository {} is too old we have to delete and recreate it", //
  585. repository.getId( ) );
  586. org.apache.archiva.common.utils.FileUtils.deleteDirectory( indexDirectory.getFilePath() );
  587. context = getIndexingContext( repository, repository.getId( ), repositoryDirectory, indexDirectory, indexUrl );
  588. context.setSearchable( repository.isScanned( ) );
  589. }
  590. return context;
  591. }
  592. else
  593. {
  594. throw new IOException( "No repository index defined" );
  595. }
  596. }
  597. private String calculateIndexRemoteUrl( URI baseUri, RemoteIndexFeature rif )
  598. {
  599. if ( rif.getIndexUri( ) == null )
  600. {
  601. return baseUri.resolve( ".index" ).toString( );
  602. }
  603. else
  604. {
  605. return baseUri.resolve( rif.getIndexUri( ) ).toString( );
  606. }
  607. }
  608. private static final class DownloadListener
  609. implements TransferListener
  610. {
  611. private Logger log = LoggerFactory.getLogger( getClass( ) );
  612. private String resourceName;
  613. private long startTime;
  614. private int totalLength = 0;
  615. @Override
  616. public void transferInitiated( TransferEvent transferEvent )
  617. {
  618. startTime = System.currentTimeMillis( );
  619. resourceName = transferEvent.getResource( ).getName( );
  620. log.debug( "initiate transfer of {}", resourceName );
  621. }
  622. @Override
  623. public void transferStarted( TransferEvent transferEvent )
  624. {
  625. this.totalLength = 0;
  626. resourceName = transferEvent.getResource( ).getName( );
  627. log.info( "start transfer of {}", transferEvent.getResource( ).getName( ) );
  628. }
  629. @Override
  630. public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
  631. {
  632. log.debug( "transfer of {} : {}/{}", transferEvent.getResource( ).getName( ), buffer.length, length );
  633. this.totalLength += length;
  634. }
  635. @Override
  636. public void transferCompleted( TransferEvent transferEvent )
  637. {
  638. resourceName = transferEvent.getResource( ).getName( );
  639. long endTime = System.currentTimeMillis( );
  640. log.info( "end of transfer file {} {} kb: {}s", transferEvent.getResource( ).getName( ),
  641. this.totalLength / 1024, ( endTime - startTime ) / 1000 );
  642. }
  643. @Override
  644. public void transferError( TransferEvent transferEvent )
  645. {
  646. log.info( "error of transfer file {}: {}", transferEvent.getResource( ).getName( ),
  647. transferEvent.getException( ).getMessage( ), transferEvent.getException( ) );
  648. }
  649. @Override
  650. public void debug( String message )
  651. {
  652. log.debug( "transfer debug {}", message );
  653. }
  654. }
  655. private static class WagonResourceFetcher
  656. implements ResourceFetcher
  657. {
  658. Logger log;
  659. Path tempIndexDirectory;
  660. Wagon wagon;
  661. RemoteRepository remoteRepository;
  662. private WagonResourceFetcher( Logger log, Path tempIndexDirectory, Wagon wagon,
  663. RemoteRepository remoteRepository )
  664. {
  665. this.log = log;
  666. this.tempIndexDirectory = tempIndexDirectory;
  667. this.wagon = wagon;
  668. this.remoteRepository = remoteRepository;
  669. }
  670. @Override
  671. public void connect( String id, String url )
  672. throws IOException
  673. {
  674. //no op
  675. }
  676. @Override
  677. public void disconnect( )
  678. throws IOException
  679. {
  680. // no op
  681. }
  682. @Override
  683. public InputStream retrieve(String name )
  684. throws IOException, FileNotFoundException
  685. {
  686. try
  687. {
  688. log.info( "index update retrieve file, name:{}", name );
  689. Path file = tempIndexDirectory.resolve( name );
  690. Files.deleteIfExists( file );
  691. file.toFile( ).deleteOnExit( );
  692. wagon.get( addParameters( name, remoteRepository ), file.toFile( ) );
  693. return Files.newInputStream( file );
  694. }
  695. catch ( AuthorizationException | TransferFailedException e )
  696. {
  697. throw new IOException( e.getMessage( ), e );
  698. }
  699. catch ( ResourceDoesNotExistException e )
  700. {
  701. FileNotFoundException fnfe = new FileNotFoundException( e.getMessage( ) );
  702. fnfe.initCause( e );
  703. throw fnfe;
  704. }
  705. }
  706. // FIXME remove crappy copy/paste
  707. protected String addParameters( String path, RemoteRepository remoteRepository )
  708. {
  709. if ( remoteRepository.getExtraParameters( ).isEmpty( ) )
  710. {
  711. return path;
  712. }
  713. boolean question = false;
  714. StringBuilder res = new StringBuilder( path == null ? "" : path );
  715. for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters( ).entrySet( ) )
  716. {
  717. if ( !question )
  718. {
  719. res.append( '?' ).append( entry.getKey( ) ).append( '=' ).append( entry.getValue( ) );
  720. }
  721. }
  722. return res.toString( );
  723. }
  724. }
  725. }