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.

DownloadRemoteIndexTask.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package org.apache.archiva.scheduler.indexing.maven;
  2. /*
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. */
  20. import org.apache.archiva.proxy.maven.WagonFactory;
  21. import org.apache.archiva.proxy.maven.WagonFactoryRequest;
  22. import org.apache.archiva.proxy.model.NetworkProxy;
  23. import org.apache.archiva.repository.base.PasswordCredentials;
  24. import org.apache.archiva.repository.RemoteRepository;
  25. import org.apache.archiva.repository.RepositoryException;
  26. import org.apache.archiva.repository.RepositoryType;
  27. import org.apache.archiva.repository.features.RemoteIndexFeature;
  28. import org.apache.commons.lang3.time.StopWatch;
  29. import org.apache.maven.index.context.IndexingContext;
  30. import org.apache.maven.index.updater.IndexUpdateRequest;
  31. import org.apache.maven.index.updater.IndexUpdateResult;
  32. import org.apache.maven.index.updater.IndexUpdater;
  33. import org.apache.maven.index.updater.ResourceFetcher;
  34. import org.apache.maven.index_shaded.lucene.index.IndexNotFoundException;
  35. import org.apache.maven.wagon.ResourceDoesNotExistException;
  36. import org.apache.maven.wagon.StreamWagon;
  37. import org.apache.maven.wagon.TransferFailedException;
  38. import org.apache.maven.wagon.Wagon;
  39. import org.apache.maven.wagon.authentication.AuthenticationInfo;
  40. import org.apache.maven.wagon.authorization.AuthorizationException;
  41. import org.apache.maven.wagon.events.TransferEvent;
  42. import org.apache.maven.wagon.events.TransferListener;
  43. import org.apache.maven.wagon.proxy.ProxyInfo;
  44. import org.apache.maven.wagon.repository.Repository;
  45. import org.apache.maven.wagon.shared.http.AbstractHttpClientWagon;
  46. import org.apache.maven.wagon.shared.http.HttpConfiguration;
  47. import org.apache.maven.wagon.shared.http.HttpMethodConfiguration;
  48. import org.slf4j.Logger;
  49. import org.slf4j.LoggerFactory;
  50. import java.io.FileNotFoundException;
  51. import java.io.IOException;
  52. import java.io.InputStream;
  53. import java.nio.file.Files;
  54. import java.nio.file.Path;
  55. import java.nio.file.Paths;
  56. import java.util.List;
  57. import java.util.Map;
  58. /**
  59. * @author Olivier Lamy
  60. * @since 1.4-M1
  61. */
  62. public class DownloadRemoteIndexTask
  63. implements Runnable
  64. {
  65. private Logger log = LoggerFactory.getLogger( getClass() );
  66. private RemoteRepository remoteRepository;
  67. private WagonFactory wagonFactory;
  68. private NetworkProxy networkProxy;
  69. private boolean fullDownload;
  70. private List<String> runningRemoteDownloadIds;
  71. private IndexUpdater indexUpdater;
  72. public DownloadRemoteIndexTask( DownloadRemoteIndexTaskRequest downloadRemoteIndexTaskRequest,
  73. List<String> runningRemoteDownloadIds )
  74. {
  75. this.remoteRepository = downloadRemoteIndexTaskRequest.getRemoteRepository();
  76. this.wagonFactory = downloadRemoteIndexTaskRequest.getWagonFactory();
  77. this.networkProxy = downloadRemoteIndexTaskRequest.getNetworkProxy();
  78. this.fullDownload = downloadRemoteIndexTaskRequest.isFullDownload();
  79. this.runningRemoteDownloadIds = runningRemoteDownloadIds;
  80. this.indexUpdater = downloadRemoteIndexTaskRequest.getIndexUpdater();
  81. }
  82. @Override
  83. public void run()
  84. {
  85. // so short lock : not sure we need it
  86. synchronized ( this.runningRemoteDownloadIds )
  87. {
  88. if ( this.runningRemoteDownloadIds.contains( this.remoteRepository.getId() ) )
  89. {
  90. // skip it as it's running
  91. log.info( "skip download index remote for repo {} it's already running",
  92. this.remoteRepository.getId() );
  93. return;
  94. }
  95. this.runningRemoteDownloadIds.add( this.remoteRepository.getId() );
  96. }
  97. Path tempIndexDirectory = null;
  98. StopWatch stopWatch = new StopWatch();
  99. stopWatch.start();
  100. try
  101. {
  102. log.info( "start download remote index for remote repository {}", this.remoteRepository.getId() );
  103. if (this.remoteRepository.getIndexingContext()==null) {
  104. throw new IndexNotFoundException("No index context set for repository "+remoteRepository.getId());
  105. }
  106. if (this.remoteRepository.getType()!= RepositoryType.MAVEN) {
  107. throw new RepositoryException("Bad repository type");
  108. }
  109. if (!this.remoteRepository.supportsFeature(RemoteIndexFeature.class)) {
  110. throw new RepositoryException("Repository does not support RemotIndexFeature "+remoteRepository.getId());
  111. }
  112. RemoteIndexFeature rif = this.remoteRepository.getFeature(RemoteIndexFeature.class).get();
  113. IndexingContext indexingContext = this.remoteRepository.getIndexingContext().getBaseContext(IndexingContext.class);
  114. // create a temp directory to download files
  115. tempIndexDirectory = Paths.get(indexingContext.getIndexDirectoryFile().getParent(), ".tmpIndex" );
  116. Path indexCacheDirectory = Paths.get( indexingContext.getIndexDirectoryFile().getParent(), ".indexCache" );
  117. Files.createDirectories( indexCacheDirectory );
  118. if ( Files.exists(tempIndexDirectory) )
  119. {
  120. org.apache.archiva.common.utils.FileUtils.deleteDirectory( tempIndexDirectory );
  121. }
  122. Files.createDirectories( tempIndexDirectory );
  123. tempIndexDirectory.toFile().deleteOnExit();
  124. String baseIndexUrl = indexingContext.getIndexUpdateUrl();
  125. String wagonProtocol = this.remoteRepository.getLocation().getScheme();
  126. final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
  127. new WagonFactoryRequest( wagonProtocol, this.remoteRepository.getExtraHeaders() ).networkProxy(
  128. this.networkProxy )
  129. );
  130. // FIXME olamy having 2 config values
  131. wagon.setReadTimeout( (int)rif.getDownloadTimeout().toMillis());
  132. wagon.setTimeout( (int)remoteRepository.getTimeout().toMillis());
  133. if ( wagon instanceof AbstractHttpClientWagon )
  134. {
  135. HttpConfiguration httpConfiguration = new HttpConfiguration();
  136. HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration();
  137. httpMethodConfiguration.setUsePreemptive( true );
  138. httpMethodConfiguration.setReadTimeout( (int)rif.getDownloadTimeout().toMillis() );
  139. httpConfiguration.setGet( httpMethodConfiguration );
  140. AbstractHttpClientWagon.class.cast( wagon ).setHttpConfiguration( httpConfiguration );
  141. }
  142. wagon.addTransferListener( new DownloadListener() );
  143. ProxyInfo proxyInfo = null;
  144. if ( this.networkProxy != null )
  145. {
  146. proxyInfo = new ProxyInfo();
  147. proxyInfo.setType( this.networkProxy.getProtocol() );
  148. proxyInfo.setHost( this.networkProxy.getHost() );
  149. proxyInfo.setPort( this.networkProxy.getPort() );
  150. proxyInfo.setUserName( this.networkProxy.getUsername() );
  151. proxyInfo.setPassword( new String(this.networkProxy.getPassword()) );
  152. }
  153. AuthenticationInfo authenticationInfo = null;
  154. if ( this.remoteRepository.getLoginCredentials()!=null && this.remoteRepository.getLoginCredentials() instanceof PasswordCredentials )
  155. {
  156. PasswordCredentials creds = (PasswordCredentials) this.remoteRepository.getLoginCredentials();
  157. authenticationInfo = new AuthenticationInfo();
  158. authenticationInfo.setUserName( creds.getUsername());
  159. authenticationInfo.setPassword( new String(creds.getPassword()) );
  160. }
  161. log.debug("Connection to {}, authInfo={}", this.remoteRepository.getId(), authenticationInfo);
  162. wagon.connect( new Repository( this.remoteRepository.getId(), baseIndexUrl ), authenticationInfo,
  163. proxyInfo );
  164. Path indexDirectory = indexingContext.getIndexDirectoryFile().toPath();
  165. if ( !Files.exists(indexDirectory) )
  166. {
  167. Files.createDirectories( indexDirectory );
  168. }
  169. log.debug("Downloading index file to {}", indexDirectory);
  170. log.debug("Index cache dir {}", indexCacheDirectory);
  171. ResourceFetcher resourceFetcher =
  172. new WagonResourceFetcher( log, tempIndexDirectory, wagon, remoteRepository );
  173. IndexUpdateRequest request = new IndexUpdateRequest( indexingContext, resourceFetcher );
  174. request.setForceFullUpdate( this.fullDownload );
  175. request.setLocalIndexCacheDir( indexCacheDirectory.toFile() );
  176. IndexUpdateResult result = this.indexUpdater.fetchAndUpdateIndex(request);
  177. log.debug("Update result success: {}", result.isSuccessful());
  178. stopWatch.stop();
  179. log.info( "time update index from remote for repository {}: {}ms", this.remoteRepository.getId(),
  180. ( stopWatch.getTime() ) );
  181. // index packing optionnal ??
  182. //IndexPackingRequest indexPackingRequest =
  183. // new IndexPackingRequest( indexingContext, indexingContext.getIndexDirectoryFile() );
  184. //indexPacker.packIndex( indexPackingRequest );
  185. indexingContext.updateTimestamp( true );
  186. }
  187. catch ( Exception e )
  188. {
  189. log.error( e.getMessage(), e );
  190. throw new RuntimeException( e.getMessage(), e );
  191. }
  192. finally
  193. {
  194. deleteDirectoryQuiet( tempIndexDirectory );
  195. this.runningRemoteDownloadIds.remove( this.remoteRepository.getId() );
  196. }
  197. log.info( "end download remote index for remote repository {}", this.remoteRepository.getId() );
  198. }
  199. private void deleteDirectoryQuiet( Path f )
  200. {
  201. try
  202. {
  203. org.apache.archiva.common.utils.FileUtils.deleteDirectory( f );
  204. }
  205. catch ( IOException e )
  206. {
  207. log.warn( "skip error delete {} : {}", f, e.getMessage() );
  208. }
  209. }
  210. private static final class DownloadListener
  211. implements TransferListener
  212. {
  213. private Logger log = LoggerFactory.getLogger( getClass() );
  214. private String resourceName;
  215. private long startTime;
  216. private int totalLength = 0;
  217. @Override
  218. public void transferInitiated( TransferEvent transferEvent )
  219. {
  220. startTime = System.currentTimeMillis();
  221. resourceName = transferEvent.getResource().getName();
  222. log.debug( "initiate transfer of {}", resourceName );
  223. }
  224. @Override
  225. public void transferStarted( TransferEvent transferEvent )
  226. {
  227. this.totalLength = 0;
  228. resourceName = transferEvent.getResource().getName();
  229. log.info("Transferring: {}, {}", transferEvent.getResource().getContentLength(), transferEvent.getLocalFile().toString());
  230. log.info( "start transfer of {}", transferEvent.getResource().getName() );
  231. }
  232. @Override
  233. public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
  234. {
  235. log.debug( "transfer of {} : {}/{}", transferEvent.getResource().getName(), buffer.length, length );
  236. this.totalLength += length;
  237. }
  238. @Override
  239. public void transferCompleted( TransferEvent transferEvent )
  240. {
  241. resourceName = transferEvent.getResource().getName();
  242. long endTime = System.currentTimeMillis();
  243. log.info( "end of transfer file {}: {}b, {}ms", transferEvent.getResource().getName(),
  244. this.totalLength, ( endTime - startTime ) );
  245. }
  246. @Override
  247. public void transferError( TransferEvent transferEvent )
  248. {
  249. log.info( "error of transfer file {}: {}", transferEvent.getResource().getName(),
  250. transferEvent.getException().getMessage(), transferEvent.getException() );
  251. }
  252. @Override
  253. public void debug( String message )
  254. {
  255. log.debug( "transfer debug {}", message );
  256. }
  257. }
  258. private static class WagonResourceFetcher
  259. implements ResourceFetcher
  260. {
  261. Logger log;
  262. Path tempIndexDirectory;
  263. Wagon wagon;
  264. RemoteRepository remoteRepository;
  265. private WagonResourceFetcher( Logger log, Path tempIndexDirectory, Wagon wagon,
  266. RemoteRepository remoteRepository )
  267. {
  268. this.log = log;
  269. this.tempIndexDirectory = tempIndexDirectory;
  270. this.wagon = wagon;
  271. this.remoteRepository = remoteRepository;
  272. }
  273. @Override
  274. public void connect( String id, String url )
  275. throws IOException
  276. {
  277. //no op
  278. }
  279. @Override
  280. public void disconnect()
  281. throws IOException
  282. {
  283. // no op
  284. }
  285. @Override
  286. public InputStream retrieve( String name )
  287. throws IOException, FileNotFoundException
  288. {
  289. try
  290. {
  291. log.info( "index update retrieve file, name:{}", name );
  292. Path file = tempIndexDirectory.resolve( name );
  293. Files.deleteIfExists( file );
  294. file.toFile().deleteOnExit();
  295. wagon.get( addParameters( name, this.remoteRepository ), file.toFile() );
  296. return Files.newInputStream( file );
  297. }
  298. catch ( AuthorizationException | TransferFailedException e )
  299. {
  300. throw new IOException( e.getMessage(), e );
  301. }
  302. catch ( ResourceDoesNotExistException e )
  303. {
  304. FileNotFoundException fnfe = new FileNotFoundException( e.getMessage() );
  305. fnfe.initCause( e );
  306. throw fnfe;
  307. }
  308. }
  309. // FIXME remove crappy copy/paste
  310. protected String addParameters( String path, RemoteRepository remoteRepository )
  311. {
  312. if ( remoteRepository.getExtraParameters().isEmpty() )
  313. {
  314. return path;
  315. }
  316. boolean question = false;
  317. StringBuilder res = new StringBuilder( path == null ? "" : path );
  318. for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters().entrySet() )
  319. {
  320. if ( !question )
  321. {
  322. res.append( '?' ).append( entry.getKey() ).append( '=' ).append( entry.getValue() );
  323. }
  324. }
  325. return res.toString();
  326. }
  327. }
  328. }