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