merge REFACTORING-10_3 back to trunk
[platform/upstream/libzypp.git] / zypp / Fetcher.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/Fetcher.cc
10  *
11 */
12 #include <iostream>
13 #include <list>
14
15 #include "zypp/base/Logger.h"
16 #include "zypp/base/DefaultIntegral.h"
17 #include "zypp/Fetcher.h"
18 #include "zypp/base/UserRequestException.h"
19
20 using namespace std;
21
22 ///////////////////////////////////////////////////////////////////
23 namespace zypp
24 { /////////////////////////////////////////////////////////////////
25
26   /**
27    * Class to encapsulate the \ref OnMediaLocation object
28    * and the \ref FileChecker together
29    */
30   struct FetcherJob
31   {
32     FetcherJob( const OnMediaLocation &loc )
33       : location(loc)
34     {
35
36     }
37
38     OnMediaLocation location;
39     CompositeFileChecker checkers;
40   };
41
42   ///////////////////////////////////////////////////////////////////
43   //
44   //    CLASS NAME : Fetcher::Impl
45   //
46   /** Fetcher implementation. */
47   struct Fetcher::Impl
48   {
49
50   public:
51
52     void enqueue( const OnMediaLocation &resource, const FileChecker &checker  );
53     void enqueueDigested( const OnMediaLocation &resource, const FileChecker &checker );
54     void addCachePath( const Pathname &cache_dir );
55     void reset();
56     void start( const Pathname &dest_dir,
57                 MediaSetAccess &media,
58                 const ProgressData::ReceiverFnc & progress_receiver );
59
60     /** Offer default Impl. */
61     static shared_ptr<Impl> nullimpl()
62     {
63       static shared_ptr<Impl> _nullimpl( new Impl );
64       return _nullimpl;
65     }
66
67   private:
68     friend Impl * rwcowClone<Impl>( const Impl * rhs );
69     /** clone for RWCOW_pointer */
70     Impl * clone() const
71     { return new Impl( *this ); }
72
73     std::list<FetcherJob> _resources;
74     std::list<Pathname> _caches;
75   };
76   ///////////////////////////////////////////////////////////////////
77
78
79   void Fetcher::Impl::enqueueDigested( const OnMediaLocation &resource, const FileChecker &checker )
80   {
81     CompositeFileChecker composite;
82     composite.add(ChecksumFileChecker(resource.checksum()));
83     composite.add(checker);
84     enqueue(resource, composite);
85   }
86   
87   void Fetcher::Impl::enqueue( const OnMediaLocation &resource, const FileChecker &checker )
88   {
89     FetcherJob job(resource);
90     job.checkers.add(checker);
91     _resources.push_back(resource);
92   }
93
94   void Fetcher::Impl::reset()
95   {
96     _resources.clear();
97     _caches.clear();
98   }
99
100   void Fetcher::Impl::addCachePath( const Pathname &cache_dir )
101   {
102     PathInfo info(cache_dir);
103     if ( info.isDir() )
104     {
105       _caches.push_back(cache_dir);
106     }
107     else
108     {
109       // don't add bad cache directory, just log the error
110       ERR << "Not adding cache: '" << cache_dir << "'. Not a direcotry." << endl;
111     }
112   }
113
114   void Fetcher::Impl::start( const Pathname &dest_dir,
115                              MediaSetAccess &media,
116                              const ProgressData::ReceiverFnc & progress_receiver )
117   {
118     ProgressData progress(_resources.size());
119     progress.sendTo(progress_receiver);
120
121     for ( list<FetcherJob>::const_iterator it_res = _resources.begin(); it_res != _resources.end(); ++it_res )
122     {
123       bool got_from_cache = false;
124       for ( list<Pathname>::const_iterator it_cache = _caches.begin(); it_cache != _caches.end(); ++it_cache )
125       {
126         // does the current file exists in the current cache?
127         Pathname cached_file = *it_cache + (*it_res).location.filename();
128         if ( PathInfo( cached_file ).isExist() )
129         {
130           // check the checksum
131           if ( is_checksum( cached_file, (*it_res).location.checksum() ) )
132           {
133             // cached
134             MIL << "file " << (*it_res).location.filename() << " found in previous cache. Using cached copy." << endl;
135             // checksum is already checked.
136             // we could later implement double failover and try to download if file copy fails.
137
138             // replicate the complete path in the target directory
139             Pathname dest_full_path = dest_dir + (*it_res).location.filename();
140             if ( assert_dir( dest_full_path.dirname() ) != 0 )
141               ZYPP_THROW( Exception("Can't create " + dest_full_path.dirname().asString()));
142
143             if ( filesystem::copy(cached_file, dest_full_path ) != 0 )
144             { //copy_file2dir
145               //ZYPP_THROW(SourceIOException("Can't copy " + cached_file.asString() + " to " + destination.asString()));
146               ERR << "Can't copy " << cached_file + " to " + dest_dir << endl;
147               // try next cache
148               continue;
149             }
150
151             got_from_cache = true;
152             break;
153           }
154         }
155       }
156
157       if ( ! got_from_cache )
158       {
159         // try to get the file from the net
160         try
161         {
162           Pathname tmp_file = media.provideFile((*it_res).location);
163           Pathname dest_full_path = dest_dir + (*it_res).location.filename();
164           if ( assert_dir( dest_full_path.dirname() ) != 0 )
165                 ZYPP_THROW( Exception("Can't create " + dest_full_path.dirname().asString()));
166           if ( filesystem::copy(tmp_file, dest_full_path ) != 0 )
167           {
168             ZYPP_THROW( Exception("Can't copy " + tmp_file.asString() + " to " + dest_dir.asString()));
169           }
170           
171           
172         }
173         catch (const Exception & excpt_r)
174         {
175           ZYPP_CAUGHT(excpt_r);
176           ZYPP_THROW(Exception("Can't provide " + (*it_res).location.filename().asString() + " : " + excpt_r.msg() ));
177         }
178       }
179       else
180       {
181         // We got the file from cache
182         // continue with next file
183         continue;
184       }
185     
186       // no matter where did we got the file, try to validate it:
187       Pathname localfile = dest_dir + (*it_res).location.filename();
188       // call the checker function
189       try {
190        (*it_res).checkers(localfile);
191       }
192       catch ( const FileCheckException &e )
193       {
194         ZYPP_RETHROW(e);
195       }
196       catch ( const Exception &e )
197       {
198         ZYPP_RETHROW(e);
199       }
200       catch (...)
201       {
202         ZYPP_THROW(Exception("Unknown error while validating " + (*it_res).location.filename().asString()));
203       }
204
205       if ( ! progress.incr() )
206         ZYPP_THROW(AbortRequestException());
207     } // for each job
208   }
209
210   /** \relates Fetcher::Impl Stream output */
211   inline std::ostream & operator<<( std::ostream & str, const Fetcher::Impl & obj )
212   {
213     return str << "Fetcher::Impl";
214   }
215
216   ///////////////////////////////////////////////////////////////////
217   //
218   //    CLASS NAME : Fetcher
219   //
220   ///////////////////////////////////////////////////////////////////
221
222   ///////////////////////////////////////////////////////////////////
223   //
224   //    METHOD NAME : Fetcher::Fetcher
225   //    METHOD TYPE : Ctor
226   //
227   Fetcher::Fetcher()
228   : _pimpl( Impl::nullimpl() )
229   {}
230
231   ///////////////////////////////////////////////////////////////////
232   //
233   //    METHOD NAME : Fetcher::~Fetcher
234   //    METHOD TYPE : Dtor
235   //
236   Fetcher::~Fetcher()
237   {}
238
239   void Fetcher::enqueueDigested( const OnMediaLocation &resource, const FileChecker &checker )
240   {
241     _pimpl->enqueue(resource, checker);
242   }
243   
244   void Fetcher::enqueue( const OnMediaLocation &resource, const FileChecker &checker  )
245   {
246     _pimpl->enqueue(resource, checker);
247   }
248   
249   void Fetcher::addCachePath( const Pathname &cache_dir )
250   {
251     _pimpl->addCachePath(cache_dir);
252   }
253   
254   void Fetcher::reset()
255   {
256     _pimpl->reset();
257   }
258
259   void Fetcher::start( const Pathname &dest_dir,
260                        MediaSetAccess &media,
261                        const ProgressData::ReceiverFnc & progress_receiver )
262   {
263     _pimpl->start(dest_dir, media, progress_receiver);
264   }
265
266
267   /******************************************************************
268   **
269   **    FUNCTION NAME : operator<<
270   **    FUNCTION TYPE : std::ostream &
271   */
272   std::ostream & operator<<( std::ostream & str, const Fetcher & obj )
273   {
274     return str << *obj._pimpl;
275   }
276
277   /////////////////////////////////////////////////////////////////
278 } // namespace zypp
279 ///////////////////////////////////////////////////////////////////
280