]> source.dussan.org Git - archiva.git/blob
436e7bb0bf9e10dc1e0ba64934b961df2d5eec97
[archiva.git] /
1 package org.apache.archiva.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  *
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
21 import org.apache.archiva.admin.model.RepositoryAdminException;
22 import org.apache.archiva.admin.model.beans.NetworkProxy;
23 import org.apache.archiva.admin.model.beans.RemoteRepository;
24 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
25 import org.apache.archiva.proxy.common.WagonFactory;
26 import org.apache.archiva.proxy.common.WagonFactoryException;
27 import org.apache.archiva.proxy.common.WagonFactoryRequest;
28 import org.apache.commons.io.FileUtils;
29 import org.apache.commons.lang.time.StopWatch;
30 import org.apache.maven.index.context.IndexingContext;
31 import org.apache.maven.index.updater.IndexUpdateRequest;
32 import org.apache.maven.index.updater.IndexUpdater;
33 import org.apache.maven.index.updater.ResourceFetcher;
34 import org.apache.maven.wagon.ConnectionException;
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.AuthenticationException;
40 import org.apache.maven.wagon.authentication.AuthenticationInfo;
41 import org.apache.maven.wagon.authorization.AuthorizationException;
42 import org.apache.maven.wagon.events.TransferEvent;
43 import org.apache.maven.wagon.events.TransferListener;
44 import org.apache.maven.wagon.providers.http.AbstractHttpClientWagon;
45 import org.apache.maven.wagon.providers.http.HttpConfiguration;
46 import org.apache.maven.wagon.providers.http.HttpMethodConfiguration;
47 import org.apache.maven.wagon.proxy.ProxyInfo;
48 import org.apache.maven.wagon.repository.Repository;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 import java.io.File;
53 import java.io.FileNotFoundException;
54 import java.io.IOException;
55 import java.io.InputStream;
56 import java.net.MalformedURLException;
57 import java.net.URL;
58 import java.nio.file.Files;
59 import java.util.List;
60 import java.util.Map;
61
62 /**
63  * @author Olivier Lamy
64  * @since 1.4-M1
65  */
66 public class DownloadRemoteIndexTask
67     implements Runnable
68 {
69     private Logger log = LoggerFactory.getLogger( getClass() );
70
71     private RemoteRepository remoteRepository;
72
73     private RemoteRepositoryAdmin remoteRepositoryAdmin;
74
75     private WagonFactory wagonFactory;
76
77     private NetworkProxy networkProxy;
78
79     private boolean fullDownload;
80
81     private List<String> runningRemoteDownloadIds;
82
83     private IndexUpdater indexUpdater;
84
85
86     public DownloadRemoteIndexTask( DownloadRemoteIndexTaskRequest downloadRemoteIndexTaskRequest,
87                                     List<String> runningRemoteDownloadIds )
88     {
89         this.remoteRepository = downloadRemoteIndexTaskRequest.getRemoteRepository();
90         this.wagonFactory = downloadRemoteIndexTaskRequest.getWagonFactory();
91         this.networkProxy = downloadRemoteIndexTaskRequest.getNetworkProxy();
92         this.fullDownload = downloadRemoteIndexTaskRequest.isFullDownload();
93         this.runningRemoteDownloadIds = runningRemoteDownloadIds;
94         this.indexUpdater = downloadRemoteIndexTaskRequest.getIndexUpdater();
95         this.remoteRepositoryAdmin = downloadRemoteIndexTaskRequest.getRemoteRepositoryAdmin();
96     }
97
98     @Override
99     public void run()
100     {
101
102         // so short lock : not sure we need it
103         synchronized ( this.runningRemoteDownloadIds )
104         {
105             if ( this.runningRemoteDownloadIds.contains( this.remoteRepository.getId() ) )
106             {
107                 // skip it as it's running
108                 log.info( "skip download index remote for repo {} it's already running",
109                           this.remoteRepository.getId() );
110                 return;
111             }
112             this.runningRemoteDownloadIds.add( this.remoteRepository.getId() );
113         }
114         File tempIndexDirectory = null;
115         StopWatch stopWatch = new StopWatch();
116         stopWatch.start();
117         try
118         {
119             log.info( "start download remote index for remote repository {}", this.remoteRepository.getId() );
120             IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( this.remoteRepository );
121
122             // create a temp directory to download files
123             tempIndexDirectory = new File( indexingContext.getIndexDirectoryFile().getParent(), ".tmpIndex" );
124             File indexCacheDirectory = new File( indexingContext.getIndexDirectoryFile().getParent(), ".indexCache" );
125             indexCacheDirectory.mkdirs();
126             if ( tempIndexDirectory.exists() )
127             {
128                 FileUtils.deleteDirectory( tempIndexDirectory );
129             }
130             tempIndexDirectory.mkdirs();
131             tempIndexDirectory.deleteOnExit();
132             String baseIndexUrl = indexingContext.getIndexUpdateUrl();
133
134             String wagonProtocol = new URL( this.remoteRepository.getUrl() ).getProtocol();
135
136             final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
137                 new WagonFactoryRequest( wagonProtocol, this.remoteRepository.getExtraHeaders() ).networkProxy(
138                     this.networkProxy )
139             );
140             // FIXME olamy having 2 config values
141             wagon.setReadTimeout( remoteRepository.getRemoteDownloadTimeout() * 1000 );
142             wagon.setTimeout( remoteRepository.getTimeout() * 1000 );
143
144             if ( wagon instanceof AbstractHttpClientWagon )
145             {
146                 HttpConfiguration httpConfiguration = new HttpConfiguration();
147                 HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration();
148                 httpMethodConfiguration.setUsePreemptive( true );
149                 httpMethodConfiguration.setReadTimeout( remoteRepository.getRemoteDownloadTimeout() * 1000 );
150                 httpConfiguration.setGet( httpMethodConfiguration );
151                 AbstractHttpClientWagon.class.cast( wagon ).setHttpConfiguration( httpConfiguration );
152             }
153
154             wagon.addTransferListener( new DownloadListener() );
155             ProxyInfo proxyInfo = null;
156             if ( this.networkProxy != null )
157             {
158                 proxyInfo = new ProxyInfo();
159                 proxyInfo.setType( this.networkProxy.getProtocol() );
160                 proxyInfo.setHost( this.networkProxy.getHost() );
161                 proxyInfo.setPort( this.networkProxy.getPort() );
162                 proxyInfo.setUserName( this.networkProxy.getUsername() );
163                 proxyInfo.setPassword( this.networkProxy.getPassword() );
164             }
165             AuthenticationInfo authenticationInfo = null;
166             if ( this.remoteRepository.getUserName() != null )
167             {
168                 authenticationInfo = new AuthenticationInfo();
169                 authenticationInfo.setUserName( this.remoteRepository.getUserName() );
170                 authenticationInfo.setPassword( this.remoteRepository.getPassword() );
171             }
172             wagon.connect( new Repository( this.remoteRepository.getId(), baseIndexUrl ), authenticationInfo,
173                            proxyInfo );
174
175             File indexDirectory = indexingContext.getIndexDirectoryFile();
176             if ( !indexDirectory.exists() )
177             {
178                 indexDirectory.mkdirs();
179             }
180
181             ResourceFetcher resourceFetcher =
182                 new WagonResourceFetcher( log, tempIndexDirectory, wagon, remoteRepository );
183             IndexUpdateRequest request = new IndexUpdateRequest( indexingContext, resourceFetcher );
184             request.setForceFullUpdate( this.fullDownload );
185             request.setLocalIndexCacheDir( indexCacheDirectory );
186
187             this.indexUpdater.fetchAndUpdateIndex( request );
188             stopWatch.stop();
189             log.info( "time update index from remote for repository {}: {} s", this.remoteRepository.getId(),
190                       ( stopWatch.getTime() / 1000 ) );
191
192             // index packing optionnal ??
193             //IndexPackingRequest indexPackingRequest =
194             //    new IndexPackingRequest( indexingContext, indexingContext.getIndexDirectoryFile() );
195             //indexPacker.packIndex( indexPackingRequest );
196             indexingContext.updateTimestamp( true );
197
198         }
199         catch ( Exception e )
200         {
201             log.error( e.getMessage(), e );
202             throw new RuntimeException( e.getMessage(), e );
203         }
204         finally
205         {
206             deleteDirectoryQuiet( tempIndexDirectory );
207             this.runningRemoteDownloadIds.remove( this.remoteRepository.getId() );
208         }
209         log.info( "end download remote index for remote repository {}", this.remoteRepository.getId() );
210     }
211
212     private void deleteDirectoryQuiet( File f )
213     {
214         try
215         {
216             FileUtils.deleteDirectory( f );
217         }
218         catch ( IOException e )
219         {
220             log.warn( "skip error delete {} : {}", f, e.getMessage() );
221         }
222     }
223
224
225     private static final class DownloadListener
226         implements TransferListener
227     {
228         private Logger log = LoggerFactory.getLogger( getClass() );
229
230         private String resourceName;
231
232         private long startTime;
233
234         private int totalLength = 0;
235
236         @Override
237         public void transferInitiated( TransferEvent transferEvent )
238         {
239             startTime = System.currentTimeMillis();
240             resourceName = transferEvent.getResource().getName();
241             log.debug( "initiate transfer of {}", resourceName );
242         }
243
244         @Override
245         public void transferStarted( TransferEvent transferEvent )
246         {
247             this.totalLength = 0;
248             resourceName = transferEvent.getResource().getName();
249             log.info( "start transfer of {}", transferEvent.getResource().getName() );
250         }
251
252         @Override
253         public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
254         {
255             log.debug( "transfer of {} : {}/{}", transferEvent.getResource().getName(), buffer.length, length );
256             this.totalLength += length;
257         }
258
259         @Override
260         public void transferCompleted( TransferEvent transferEvent )
261         {
262             resourceName = transferEvent.getResource().getName();
263             long endTime = System.currentTimeMillis();
264             log.info( "end of transfer file {} {} kb: {}s", transferEvent.getResource().getName(),
265                       this.totalLength / 1024, ( endTime - startTime ) / 1000 );
266         }
267
268         @Override
269         public void transferError( TransferEvent transferEvent )
270         {
271             log.info( "error of transfer file {}: {}", transferEvent.getResource().getName(),
272                       transferEvent.getException().getMessage(), transferEvent.getException() );
273         }
274
275         @Override
276         public void debug( String message )
277         {
278             log.debug( "transfer debug {}", message );
279         }
280     }
281
282     private static class WagonResourceFetcher
283         implements ResourceFetcher
284     {
285
286         Logger log;
287
288         File tempIndexDirectory;
289
290         Wagon wagon;
291
292         RemoteRepository remoteRepository;
293
294         private WagonResourceFetcher( Logger log, File tempIndexDirectory, Wagon wagon,
295                                       RemoteRepository remoteRepository )
296         {
297             this.log = log;
298             this.tempIndexDirectory = tempIndexDirectory;
299             this.wagon = wagon;
300             this.remoteRepository = remoteRepository;
301         }
302
303         @Override
304         public void connect( String id, String url )
305             throws IOException
306         {
307             //no op  
308         }
309
310         @Override
311         public void disconnect()
312             throws IOException
313         {
314             // no op
315         }
316
317         @Override
318         public InputStream retrieve( String name )
319             throws IOException, FileNotFoundException
320         {
321             try
322             {
323                 log.info( "index update retrieve file, name:{}", name );
324                 File file = new File( tempIndexDirectory, name );
325                 Files.deleteIfExists( file.toPath() );
326                 file.deleteOnExit();
327                 wagon.get( addParameters( name, this.remoteRepository ), file );
328                 return Files.newInputStream( file.toPath() );
329             }
330             catch ( AuthorizationException | TransferFailedException e )
331             {
332                 throw new IOException( e.getMessage(), e );
333             }
334             catch ( ResourceDoesNotExistException e )
335             {
336                 FileNotFoundException fnfe = new FileNotFoundException( e.getMessage() );
337                 fnfe.initCause( e );
338                 throw fnfe;
339             }
340         }
341
342         // FIXME remove crappy copy/paste
343         protected String addParameters( String path, RemoteRepository remoteRepository )
344         {
345             if ( remoteRepository.getExtraParameters().isEmpty() )
346             {
347                 return path;
348             }
349
350             boolean question = false;
351
352             StringBuilder res = new StringBuilder( path == null ? "" : path );
353
354             for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters().entrySet() )
355             {
356                 if ( !question )
357                 {
358                     res.append( '?' ).append( entry.getKey() ).append( '=' ).append( entry.getValue() );
359                 }
360             }
361
362             return res.toString();
363         }
364
365     }
366
367
368 }
369