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

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