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

ArchivaIndexManagerMock.java 34KB

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