- remember the cause of the RepoException when refreshing metadata
[platform/upstream/libzypp.git] / zypp / RepoManager.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/RepoManager.cc
10  *
11 */
12
13 #include <iostream>
14 #include <fstream>
15 #include <list>
16 #include <algorithm>
17 #include "zypp/base/InputStream.h"
18 #include "zypp/base/Logger.h"
19 #include "zypp/base/Gettext.h"
20 #include "zypp/base/Function.h"
21 #include "zypp/PathInfo.h"
22 #include "zypp/TmpPath.h"
23
24 #include "zypp/repo/RepoException.h"
25 #include "zypp/RepoManager.h"
26
27 #include "zypp/cache/CacheStore.h"
28 #include "zypp/repo/cached/RepoImpl.h"
29 #include "zypp/media/MediaManager.h"
30 #include "zypp/MediaSetAccess.h"
31
32 #include "zypp/parser/RepoFileReader.h"
33 #include "zypp/repo/yum/Downloader.h"
34 #include "zypp/parser/yum/RepoParser.h"
35 #include "zypp/parser/plaindir/RepoParser.h"
36 #include "zypp/repo/susetags/Downloader.h"
37 #include "zypp/parser/susetags/RepoParser.h"
38
39 #include "zypp/ZYppCallbacks.h"
40
41 using namespace std;
42 using namespace zypp;
43 using namespace zypp::repo;
44 using namespace zypp::filesystem;
45
46 using namespace zypp::repo;
47
48 ///////////////////////////////////////////////////////////////////
49 namespace zypp
50 { /////////////////////////////////////////////////////////////////
51
52   ///////////////////////////////////////////////////////////////////
53   //
54   //    CLASS NAME : RepoManagerOptions
55   //
56   ///////////////////////////////////////////////////////////////////
57
58   RepoManagerOptions::RepoManagerOptions()
59   {
60     repoCachePath    = ZConfig::instance().repoCachePath();
61     repoRawCachePath = ZConfig::instance().repoMetadataPath();
62     knownReposPath   = ZConfig::instance().knownReposPath();
63   }
64
65   ////////////////////////////////////////////////////////////////////////////
66
67   /**
68     * \short Simple callback to collect the results
69     *
70     * Classes like RepoFileParser call the callback
71     * once per each repo in a file.
72     *
73     * Passing this functor as callback, you can collect
74     * all resuls at the end, without dealing with async
75     * code.
76     */
77     struct RepoCollector
78     {
79       RepoCollector()
80       {
81         MIL << endl;
82       }
83
84       ~RepoCollector()
85       {
86         MIL << endl;
87       }
88
89       bool collect( const RepoInfo &repo )
90       {
91         //MIL << "here in collector: " << repo.alias() << endl;
92         repos.push_back(repo);
93         //MIL << "added: " << repo.alias() << endl;
94         return true;
95       }
96
97       RepoInfoList repos;
98     };
99
100   ////////////////////////////////////////////////////////////////////////////
101
102    /**
103     * \short Internal version of clean cache
104     *
105     * Takes an extra CacheStore reference, so we avoid internally
106     * having 2 CacheStores writing to the same database.
107     */
108   static void cleanCacheInternal( cache::CacheStore &store,
109                                   const RepoInfo &info,
110                                   const ProgressData::ReceiverFnc & progressrcv = ProgressData::ReceiverFnc() )
111   {
112     ProgressData progress;
113     callback::SendReport<ProgressReport> report;
114     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
115     progress.name(str::form(_("Cleaning repository '%s' cache"), info.name().c_str()));
116
117     if ( !store.isCached(info.alias()) )
118       return;
119    
120     MIL << info.alias() << " cleaning cache..." << endl;
121     data::RecordId id = store.lookupRepository(info.alias());
122     
123     CombinedProgressData subprogrcv(progress);
124     
125     store.cleanRepository(id, subprogrcv);
126   }
127   
128   ////////////////////////////////////////////////////////////////////////////
129   
130   /**
131    * Reads RepoInfo's from a repo file.
132    *
133    * \param file pathname of the file to read.
134    */
135   static std::list<RepoInfo> repositories_in_file( const Pathname & file )
136   {
137     MIL << "repo file: " << file << endl;
138     RepoCollector collector;
139     parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
140     return collector.repos;
141   }
142
143   ////////////////////////////////////////////////////////////////////////////
144
145   std::list<RepoInfo> readRepoFile(const Url & repo_file)
146    {
147      // no interface to download a specific file, using workaround:
148      //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
149      Url url(repo_file);
150      Pathname path(url.getPathName());
151      url.setPathName ("/");
152      MediaSetAccess access(url);
153      Pathname local = access.provideFile(path);
154
155      DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
156
157      return repositories_in_file(local);
158    }
159
160   ////////////////////////////////////////////////////////////////////////////
161
162   /**
163    * \short List of RepoInfo's from a directory
164    *
165    * Goes trough every file in a directory and adds all
166    * RepoInfo's contained in that file.
167    *
168    * \param dir pathname of the directory to read.
169    */
170   static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
171   {
172     MIL << "directory " << dir << endl;
173     list<RepoInfo> repos;
174     list<Pathname> entries;
175     if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
176       ZYPP_THROW(Exception("failed to read directory"));
177
178     for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
179     {
180       list<RepoInfo> tmp = repositories_in_file( *it );
181       repos.insert( repos.end(), tmp.begin(), tmp.end() );
182
183       //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
184       //MIL << "ok" << endl;
185     }
186     return repos;
187   }
188
189   ////////////////////////////////////////////////////////////////////////////
190
191   static void assert_alias( const RepoInfo &info )
192   {
193     if (info.alias().empty())
194         ZYPP_THROW(RepoNoAliasException());
195   }
196
197   ////////////////////////////////////////////////////////////////////////////
198
199   static void assert_urls( const RepoInfo &info )
200   {
201     if (info.baseUrlsEmpty())
202         ZYPP_THROW(RepoNoUrlException());
203   }
204
205   ////////////////////////////////////////////////////////////////////////////
206
207   /**
208    * \short Calculates the raw cache path for a repository
209    */
210   static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
211   {
212     assert_alias(info);
213     return opt.repoRawCachePath + info.alias();
214   }
215
216   ///////////////////////////////////////////////////////////////////
217   //
218   //    CLASS NAME : RepoManager::Impl
219   //
220   ///////////////////////////////////////////////////////////////////
221
222   /**
223    * \short RepoManager implementation.
224    */
225   struct RepoManager::Impl
226   {
227     Impl( const RepoManagerOptions &opt )
228       : options(opt)
229     {
230
231     }
232
233     Impl()
234     {
235
236     }
237
238     RepoManagerOptions options;
239
240   public:
241     /** Offer default Impl. */
242     static shared_ptr<Impl> nullimpl()
243     {
244       static shared_ptr<Impl> _nullimpl( new Impl );
245       return _nullimpl;
246     }
247     
248   private:
249     friend Impl * rwcowClone<Impl>( const Impl * rhs );
250     /** clone for RWCOW_pointer */
251     Impl * clone() const
252     { return new Impl( *this ); }
253   };
254   ///////////////////////////////////////////////////////////////////
255
256   /** \relates RepoManager::Impl Stream output */
257   inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
258   {
259     return str << "RepoManager::Impl";
260   }
261
262   ///////////////////////////////////////////////////////////////////
263   //
264   //    CLASS NAME : RepoManager
265   //
266   ///////////////////////////////////////////////////////////////////
267
268   RepoManager::RepoManager( const RepoManagerOptions &opt )
269   : _pimpl( new Impl(opt) )
270   {}
271
272   ////////////////////////////////////////////////////////////////////////////
273
274   RepoManager::~RepoManager()
275   {}
276
277   ////////////////////////////////////////////////////////////////////////////
278
279   std::list<RepoInfo> RepoManager::knownRepositories() const
280   {
281     MIL << endl;
282
283     if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
284     {
285       RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
286       for ( RepoInfoList::iterator it = repos.begin();
287             it != repos.end();
288             ++it )
289       {
290         // set the metadata path for the repo
291         Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
292         (*it).setMetadataPath(metadata_path);
293       }
294       return repos;
295     }
296     else
297       return std::list<RepoInfo>();
298
299     MIL << endl;
300   }
301
302   ////////////////////////////////////////////////////////////////////////////
303
304   RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
305   {
306     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
307     RepoType repokind = info.type();
308     RepoStatus status;
309
310     switch ( repokind.toEnum() )
311     {
312       case RepoType::NONE_e:
313       // unknown, probe the local metadata
314         repokind = probe(rawpath.asUrl());
315       break;
316       default:
317       break;
318     }
319
320     switch ( repokind.toEnum() )
321     {
322       case RepoType::RPMMD_e :
323       {
324         status = RepoStatus( rawpath + "/repodata/repomd.xml");
325       }
326       break;
327
328       case RepoType::YAST2_e :
329       {
330         status = (RepoStatus( rawpath + "/media.1/media") && RepoStatus( rawpath + "/content") );
331       }
332       break;
333
334       case RepoType::RPMPLAINDIR_e :
335       {
336         if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
337           status = RepoStatus( rawpath + "/cookie");
338       }
339       break;
340
341       case RepoType::NONE_e :
342         // Return default RepoStatus in case of RepoType::NONE
343         // indicating it should be created?
344         // ZYPP_THROW(RepoUnknownTypeException());
345         break;
346     }
347     return status;
348   }
349
350   void RepoManager::touchIndexFile(const RepoInfo & info)
351   {
352     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
353
354     RepoType repokind = info.type();
355     if ( repokind.toEnum() == RepoType::NONE_e )
356       // unknown, probe the local metadata
357       repokind = probe(rawpath.asUrl());
358     // if still unknown, just return
359     if (repokind == RepoType::NONE_e)
360       return;
361
362     Pathname p;
363     switch ( repokind.toEnum() )
364     {
365       case RepoType::RPMMD_e :
366         p = Pathname(rawpath + "/repodata/repomd.xml");
367         break;
368
369       case RepoType::YAST2_e :
370         p = Pathname(rawpath + "/content");
371         break;
372
373       case RepoType::RPMPLAINDIR_e :
374         p = Pathname(rawpath + "/cookie");
375         break;
376
377       case RepoType::NONE_e :
378       default:
379         break;
380     }
381
382     // touch the file, ignore error (they are logged anyway)
383     filesystem::touch(p);
384   }
385
386   bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
387                                               const Url &url,
388                                               RawMetadataRefreshPolicy policy )
389   {
390     assert_alias(info);
391
392     RepoStatus oldstatus;
393     RepoStatus newstatus;
394
395     try
396     {
397       MIL << "Going to try to check whether refresh is needed for " << url << endl;
398
399       repo::RepoType repokind = info.type();
400
401       // if the type is unknown, try probing.
402       switch ( repokind.toEnum() )
403       {
404         case RepoType::NONE_e:
405           // unknown, probe it
406           repokind = probe(url);
407         break;
408         default:
409         break;
410       }
411
412       Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
413       filesystem::assert_dir(rawpath);
414       oldstatus = metadataStatus(info);
415
416       // now we've got the old (cached) status, we can decide repo.refresh.delay
417       if (policy != RefreshForced)
418       {
419         // difference in seconds
420         double diff = difftime(
421           (Date::ValueType)Date::now(),
422           (Date::ValueType)oldstatus.timestamp()) / 60;
423
424         DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
425         DBG << "current time: " << (Date::ValueType)Date::now() << endl;
426         DBG << "last refresh = " << diff << " minutes ago" << endl;
427
428         if (diff < ZConfig::instance().repo_refresh_delay())
429         {
430           MIL << "Repository '" << info.alias()
431               << "' has been refreshed less than repo.refresh.delay ("
432               << ZConfig::instance().repo_refresh_delay()
433               << ") minutes ago. Advising to skip refresh" << endl;
434           return false;
435         }
436       }
437
438       // create temp dir as sibling of rawpath
439       filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
440
441       if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
442            ( repokind.toEnum() == RepoType::YAST2_e ) )
443       {
444         MediaSetAccess media(url);
445         shared_ptr<repo::Downloader> downloader_ptr;
446
447         if ( repokind.toEnum() == RepoType::RPMMD_e )
448           downloader_ptr.reset(new yum::Downloader(info.path()));
449         else
450           downloader_ptr.reset( new susetags::Downloader(info.path()));
451
452         RepoStatus newstatus = downloader_ptr->status(media);
453         bool refresh = false;
454         if ( oldstatus.checksum() == newstatus.checksum() )
455         {
456           MIL << "repo has not changed" << endl;
457           if ( policy == RefreshForced )
458           {
459             MIL << "refresh set to forced" << endl;
460             refresh = true;
461           }
462         }
463         else
464         {
465           MIL << "repo has changed, going to refresh" << endl;
466           refresh = true;
467         }
468
469         if (!refresh)
470           touchIndexFile(info);
471
472         return refresh;
473       }
474       else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
475       {
476         RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
477         bool refresh = false;
478         if ( oldstatus.checksum() == newstatus.checksum() )
479         {
480           MIL << "repo has not changed" << endl;
481           if ( policy == RefreshForced )
482           {
483             MIL << "refresh set to forced" << endl;
484             refresh = true;
485           }
486         }
487         else
488         {
489           MIL << "repo has changed, going to refresh" << endl;
490           refresh = true;
491         }
492
493         if (!refresh)
494           touchIndexFile(info);
495
496         return refresh;
497       }
498       else
499       {
500         ZYPP_THROW(RepoUnknownTypeException());
501       }
502     }
503     catch ( const Exception &e )
504     {
505       ZYPP_CAUGHT(e);
506       ERR << "refresh check failed for " << url << endl;
507       ZYPP_RETHROW(e);
508     }
509     
510     return true; // default
511   }
512
513   void RepoManager::refreshMetadata( const RepoInfo &info,
514                                      RawMetadataRefreshPolicy policy,
515                                      const ProgressData::ReceiverFnc & progress )
516   {
517     assert_alias(info);
518     assert_urls(info);
519
520     // we will throw this later if no URL checks out fine
521     RepoException rexception(_("Valid metadata not found at specified URL(s)"));
522
523     // try urls one by one
524     for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
525     {
526       try
527       {
528         Url url(*it);
529
530         // check whether to refresh metadata
531         // if the check fails for this url, it throws, so another url will be checked
532         if (!checkIfToRefreshMetadata(info, url, policy))
533           return;
534
535         MIL << "Going to refresh metadata from " << url << endl;
536
537         repo::RepoType repokind = info.type();
538
539         // if the type is unknown, try probing.
540         switch ( repokind.toEnum() )
541         {
542           case RepoType::NONE_e:
543             // unknown, probe it
544             repokind = probe(*it);
545           break;
546           default:
547           break;
548         }
549
550         Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
551         filesystem::assert_dir(rawpath);
552
553         // create temp dir as sibling of rawpath
554         filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
555
556         if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
557              ( repokind.toEnum() == RepoType::YAST2_e ) )
558         {
559           MediaSetAccess media(url);
560           shared_ptr<repo::Downloader> downloader_ptr;
561
562           if ( repokind.toEnum() == RepoType::RPMMD_e )
563             downloader_ptr.reset(new yum::Downloader(info.path()));
564           else
565             downloader_ptr.reset( new susetags::Downloader(info.path()));
566
567           /**
568            * Given a downloader, sets the other repos raw metadata
569            * path as cache paths for the fetcher, so if another
570            * repo has the same file, it will not download it
571            * but copy it from the other repository
572            */
573           std::list<RepoInfo> repos = knownRepositories();
574           for ( std::list<RepoInfo>::const_iterator it = repos.begin();
575                 it != repos.end();
576                 ++it )
577           {
578             downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
579           }
580
581           downloader_ptr->download( media, tmpdir.path());
582         }
583         else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
584         {
585           RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
586
587           std::ofstream file(( tmpdir.path() + "/cookie").c_str());
588           if (!file) {
589             ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
590           }
591           file << url << endl;
592           file << newstatus.checksum() << endl;
593
594           file.close();
595         }
596         else
597         {
598           ZYPP_THROW(RepoUnknownTypeException());
599         }
600
601         // ok we have the metadata, now exchange
602         // the contents
603         TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
604         filesystem::rename( rawpath, oldmetadata.path() );
605         // move the just downloaded there
606         filesystem::rename( tmpdir.path(), rawpath );
607         // we are done.
608         return;
609       }
610       catch ( const Exception &e )
611       {
612         ZYPP_CAUGHT(e);
613         ERR << "Trying another url..." << endl;
614         
615         // remember the exception caught for the *first URL*
616         // if all other URLs fail, the rexception will be thrown with the
617         // cause of the problem of the first URL remembered
618         if (it == info.baseUrlsBegin())
619           rexception.remember(e);
620       }
621     } // for every url
622     ERR << "No more urls..." << endl;
623     ZYPP_THROW(rexception);
624   }
625
626   ////////////////////////////////////////////////////////////////////////////
627
628   void RepoManager::cleanMetadata( const RepoInfo &info,
629                                    const ProgressData::ReceiverFnc & progressfnc )
630   {
631     ProgressData progress(100);
632     progress.sendTo(progressfnc);
633
634     filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
635     progress.toMax();
636   }
637
638   void RepoManager::buildCache( const RepoInfo &info,
639                                 CacheBuildPolicy policy,
640                                 const ProgressData::ReceiverFnc & progressrcv )
641   {
642     assert_alias(info);
643     Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
644
645     cache::CacheStore store(_pimpl->options.repoCachePath);
646
647     RepoStatus raw_metadata_status = metadataStatus(info);
648     if ( raw_metadata_status.empty() )
649     {
650       ZYPP_THROW(RepoMetadataException(info));
651     }
652
653     bool needs_cleaning = false;
654     if ( store.isCached( info.alias() ) )
655     {
656       MIL << info.alias() << " is already cached." << endl;
657       data::RecordId id = store.lookupRepository(info.alias());
658       RepoStatus cache_status = store.repositoryStatus(id);
659
660       if ( cache_status.checksum() == raw_metadata_status.checksum() )
661       {
662         MIL << info.alias() << " cache is up to date with metadata." << endl;
663         if ( policy == BuildIfNeeded ) {
664           return;
665         }
666         else {
667           MIL << info.alias() << " cache rebuild is forced" << endl;
668         }
669       }
670       
671       needs_cleaning = true;
672     }
673
674     ProgressData progress(100);
675     callback::SendReport<ProgressReport> report;
676     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
677     progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
678     progress.toMin();
679
680     if (needs_cleaning)
681       cleanCacheInternal( store, info);
682
683     MIL << info.alias() << " building cache..." << endl;
684     data::RecordId id = store.lookupOrAppendRepository(info.alias());
685     // do we have type?
686     repo::RepoType repokind = info.type();
687
688     // if the type is unknown, try probing.
689     switch ( repokind.toEnum() )
690     {
691       case RepoType::NONE_e:
692         // unknown, probe the local metadata
693         repokind = probe(rawpath.asUrl());
694       break;
695       default:
696       break;
697     }
698
699     
700     switch ( repokind.toEnum() )
701     {
702       case RepoType::RPMMD_e :
703       {
704         CombinedProgressData subprogrcv( progress, 100);
705         parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
706         parser.parse(rawpath);
707           // no error
708       }
709       break;
710       case RepoType::YAST2_e :
711       {
712         CombinedProgressData subprogrcv( progress, 100);
713         parser::susetags::RepoParser parser(id, store, subprogrcv);
714         parser.parse(rawpath);
715         // no error
716       }
717       break;
718       case RepoType::RPMPLAINDIR_e :
719       {
720         CombinedProgressData subprogrcv( progress, 100);
721         InputStream is(rawpath + "cookie");
722         string buffer;
723         getline( is.stream(), buffer);
724         Url url(buffer);
725         parser::plaindir::RepoParser parser(id, store, subprogrcv);
726         parser.parse(url.getPathName());
727       }
728       break;
729       default:
730         ZYPP_THROW(RepoUnknownTypeException());
731     }
732
733     // update timestamp and checksum
734     store.updateRepositoryStatus(id, raw_metadata_status);
735
736     MIL << "Commit cache.." << endl;
737     store.commit();
738     //progress.toMax();
739   }
740
741   ////////////////////////////////////////////////////////////////////////////
742
743   repo::RepoType RepoManager::probe( const Url &url ) const
744   {
745     if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
746     {
747       // Handle non existing local directory in advance, as
748       // MediaSetAccess does not support it.
749       return repo::RepoType::NONE;
750     }
751
752     try
753     {
754       MediaSetAccess access(url);
755       if ( access.doesFileExist("/repodata/repomd.xml") )
756         return repo::RepoType::RPMMD;
757       if ( access.doesFileExist("/content") )
758         return repo::RepoType::YAST2;
759   
760       // if it is a local url of type dir
761       if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
762       {
763         Pathname path = Pathname(url.getPathName());
764         if ( PathInfo(path).isDir() )
765         {
766           // allow empty dirs for now
767           return repo::RepoType::RPMPLAINDIR;
768         }
769       }
770     }
771     catch ( const media::MediaException &e )
772     {
773       ZYPP_CAUGHT(e);
774       RepoException enew("Error trying to read from " + url.asString());
775       enew.remember(e);
776       ZYPP_THROW(enew);
777     }
778     catch ( const Exception &e )
779     {
780       ZYPP_CAUGHT(e);
781       Exception enew("Unknown error reading from " + url.asString());
782       enew.remember(e);
783       ZYPP_THROW(enew);
784     }
785
786     return repo::RepoType::NONE;
787   }
788     
789   ////////////////////////////////////////////////////////////////////////////
790   
791   void RepoManager::cleanCache( const RepoInfo &info,
792                                 const ProgressData::ReceiverFnc & progressrcv )
793   {
794     cache::CacheStore store(_pimpl->options.repoCachePath);
795     cleanCacheInternal( store, info, progressrcv );
796     store.commit();
797   }
798
799   ////////////////////////////////////////////////////////////////////////////
800
801   bool RepoManager::isCached( const RepoInfo &info ) const
802   {
803     cache::CacheStore store(_pimpl->options.repoCachePath);
804     return store.isCached(info.alias());
805   }
806
807   RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
808   {
809     cache::CacheStore store(_pimpl->options.repoCachePath);
810     data::RecordId id = store.lookupRepository(info.alias());
811     RepoStatus cache_status = store.repositoryStatus(id);
812     return cache_status;
813   }
814
815   Repository RepoManager::createFromCache( const RepoInfo &info,
816                                            const ProgressData::ReceiverFnc & progressrcv )
817   {
818     callback::SendReport<ProgressReport> report;
819     ProgressData progress;
820     progress.sendTo(ProgressReportAdaptor( progressrcv, report ));
821     //progress.sendTo( progressrcv );
822     progress.name(str::form(_("Reading repository '%s' cache"), info.name().c_str()));
823     
824     cache::CacheStore store(_pimpl->options.repoCachePath);
825
826     if ( ! store.isCached( info.alias() ) )
827       ZYPP_THROW(RepoNotCachedException());
828
829     MIL << "Repository " << info.alias() << " is cached" << endl;
830
831     data::RecordId id = store.lookupRepository(info.alias());
832     
833     CombinedProgressData subprogrcv(progress);
834     
835     repo::cached::RepoOptions opts( info, _pimpl->options.repoCachePath, id );
836     opts.readingResolvablesProgress = subprogrcv;
837     repo::cached::RepoImpl::Ptr repoimpl =
838         new repo::cached::RepoImpl( opts );
839
840     repoimpl->resolvables();
841     // read the resolvables from cache
842     return Repository(repoimpl);
843   }
844
845   ////////////////////////////////////////////////////////////////////////////
846
847   /**
848    * Generate a non existing filename in a directory, using a base
849    * name. For example if a directory contains 3 files
850    *
851    * |-- bar
852    * |-- foo
853    * `-- moo
854    *
855    * If you try to generate a unique filename for this directory,
856    * based on "ruu" you will get "ruu", but if you use the base
857    * "foo" you will get "foo_1"
858    *
859    * \param dir Directory where the file needs to be unique
860    * \param basefilename string to base the filename on.
861    */
862   static Pathname generate_non_existing_name( const Pathname &dir,
863                                               const std::string &basefilename )
864   {
865     string final_filename = basefilename;
866     int counter = 1;
867     while ( PathInfo(dir + final_filename).isExist() )
868     {
869       final_filename = basefilename + "_" + str::numstring(counter);
870       counter++;
871     }
872     return dir + Pathname(final_filename);
873   }
874
875   ////////////////////////////////////////////////////////////////////////////
876
877   /**
878    * \short Generate a related filename from a repo info
879    *
880    * From a repo info, it will try to use the alias as a filename
881    * escaping it if necessary. Other fallbacks can be added to
882    * this function in case there is no way to use the alias
883    */
884   static std::string generate_filename( const RepoInfo &info )
885   {
886     std::string fnd="/";
887     std::string rep="_";
888     std::string filename = info.alias();
889     // replace slashes with underscores
890     size_t pos = filename.find(fnd);
891     while(pos!=string::npos)
892     {
893       filename.replace(pos,fnd.length(),rep);
894       pos = filename.find(fnd,pos+rep.length());
895     }
896     filename = Pathname(filename).extend(".repo").asString();
897     MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
898     return filename;
899   }
900
901
902   ////////////////////////////////////////////////////////////////////////////
903
904   void RepoManager::addRepository( const RepoInfo &info,
905                                    const ProgressData::ReceiverFnc & progressrcv )
906   {
907     assert_alias(info);
908
909     ProgressData progress(100);
910     callback::SendReport<ProgressReport> report;
911     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
912     progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
913     progress.toMin();
914
915     std::list<RepoInfo> repos = knownRepositories();
916     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
917           it != repos.end();
918           ++it )
919     {
920       if ( info.alias() == (*it).alias() )
921         ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
922     }
923
924     RepoInfo tosave = info;
925     
926     // check the first url for now
927     if ( ZConfig::instance().repo_add_probe() || ( tosave.type() == RepoType::NONE ) )
928     {
929       RepoType probedtype;
930       probedtype = probe(*tosave.baseUrlsBegin());
931       if ( tosave.baseUrlsSize() > 0 )
932       {
933         if ( probedtype == RepoType::NONE )
934           ZYPP_THROW(RepoUnknownTypeException());
935         else
936           tosave.setType(probedtype);
937       }
938     }
939     
940     progress.set(50);
941
942     // assert the directory exists
943     filesystem::assert_dir(_pimpl->options.knownReposPath);
944
945     Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
946                                                     generate_filename(tosave));
947     // now we have a filename that does not exists
948     MIL << "Saving repo in " << repofile << endl;
949
950     std::ofstream file(repofile.c_str());
951     if (!file) {
952       ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
953     }
954
955     tosave.dumpRepoOn(file);
956     progress.toMax();
957     MIL << "done" << endl;
958   }
959
960   void RepoManager::addRepositories( const Url &url,
961                                      const ProgressData::ReceiverFnc & progressrcv )
962   {
963     std::list<RepoInfo> knownrepos = knownRepositories();
964     std::list<RepoInfo> repos = readRepoFile(url);
965     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
966           it != repos.end();
967           ++it )
968     {
969       // look if the alias is in the known repos.
970       for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
971           kit != knownrepos.end();
972           ++kit )
973       {
974         if ( (*it).alias() == (*kit).alias() )
975         {
976           ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
977           ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
978         }
979       }
980     }
981
982     string filename = Pathname(url.getPathName()).basename();
983
984     if ( filename == Pathname() )
985       ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
986
987     // assert the directory exists
988     filesystem::assert_dir(_pimpl->options.knownReposPath);
989
990     Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
991     // now we have a filename that does not exists
992     MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
993
994     std::ofstream file(repofile.c_str());
995     if (!file) {
996       ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
997     }
998
999     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1000           it != repos.end();
1001           ++it )
1002     {
1003       MIL << "Saving " << (*it).alias() << endl;
1004       (*it).dumpRepoOn(file);
1005     }
1006     MIL << "done" << endl;
1007   }
1008
1009   ////////////////////////////////////////////////////////////////////////////
1010
1011   void RepoManager::removeRepository( const RepoInfo & info,
1012                                       const ProgressData::ReceiverFnc & progressrcv)
1013   {
1014     ProgressData progress;
1015     callback::SendReport<ProgressReport> report;
1016     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1017     progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1018     
1019     MIL << "Going to delete repo " << info.alias() << endl;
1020
1021     std::list<RepoInfo> repos = knownRepositories();
1022     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1023           it != repos.end();
1024           ++it )
1025     {
1026       // they can be the same only if the provided is empty, that means
1027       // the provided repo has no alias
1028       // then skip
1029       if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1030         continue;
1031
1032       // TODO match by url
1033
1034       // we have a matcing repository, now we need to know
1035       // where it does come from.
1036       RepoInfo todelete = *it;
1037       if (todelete.filepath().empty())
1038       {
1039         ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1040       }
1041       else
1042       {
1043         // figure how many repos are there in the file:
1044         std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1045         if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1046         {
1047           // easy, only this one, just delete the file
1048           if ( filesystem::unlink(todelete.filepath()) != 0 )
1049           {
1050             ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1051           }
1052           MIL << todelete.alias() << " sucessfully deleted." << endl;
1053         }
1054         else
1055         {
1056           // there are more repos in the same file
1057           // write them back except the deleted one.
1058           //TmpFile tmp;
1059           //std::ofstream file(tmp.path().c_str());
1060
1061           // assert the directory exists
1062           filesystem::assert_dir(todelete.filepath().dirname());
1063
1064           std::ofstream file(todelete.filepath().c_str());
1065           if (!file) {
1066             //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1067             ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1068           }
1069           for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1070                 fit != filerepos.end();
1071                 ++fit )
1072           {
1073             if ( (*fit).alias() != todelete.alias() )
1074               (*fit).dumpRepoOn(file);
1075           }
1076         }
1077
1078         CombinedProgressData subprogrcv(progress, 70);
1079         CombinedProgressData cleansubprogrcv(progress, 30);
1080         // now delete it from cache
1081         cleanCache( todelete, subprogrcv);
1082         // now delete metadata (#301037)
1083         cleanMetadata( todelete, cleansubprogrcv);
1084         MIL << todelete.alias() << " sucessfully deleted." << endl;
1085         return;
1086       } // else filepath is empty
1087
1088     }
1089     // should not be reached on a sucess workflow
1090     ZYPP_THROW(RepoNotFoundException(info));
1091   }
1092
1093   ////////////////////////////////////////////////////////////////////////////
1094
1095   void RepoManager::modifyRepository( const std::string &alias,
1096                                       const RepoInfo & newinfo,
1097                                       const ProgressData::ReceiverFnc & progressrcv )
1098   {
1099     RepoInfo toedit = getRepositoryInfo(alias);
1100
1101     if (toedit.filepath().empty())
1102     {
1103       ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1104     }
1105     else
1106     {
1107       // figure how many repos are there in the file:
1108       std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1109
1110       // there are more repos in the same file
1111       // write them back except the deleted one.
1112       //TmpFile tmp;
1113       //std::ofstream file(tmp.path().c_str());
1114
1115       // assert the directory exists
1116       filesystem::assert_dir(toedit.filepath().dirname());
1117
1118       std::ofstream file(toedit.filepath().c_str());
1119       if (!file) {
1120         //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1121         ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1122       }
1123       for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1124             fit != filerepos.end();
1125             ++fit )
1126       {
1127           // if the alias is different, dump the original
1128           // if it is the same, dump the provided one
1129           if ( (*fit).alias() != toedit.alias() )
1130             (*fit).dumpRepoOn(file);
1131           else
1132             newinfo.dumpRepoOn(file);
1133       }
1134     }
1135   }
1136
1137   ////////////////////////////////////////////////////////////////////////////
1138
1139   RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1140                                            const ProgressData::ReceiverFnc & progressrcv )
1141   {
1142     std::list<RepoInfo> repos = knownRepositories();
1143     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1144           it != repos.end();
1145           ++it )
1146     {
1147       if ( (*it).alias() == alias )
1148         return *it;
1149     }
1150     RepoInfo info;
1151     info.setAlias(info.alias());
1152     ZYPP_THROW(RepoNotFoundException(info));
1153   }
1154
1155   ////////////////////////////////////////////////////////////////////////////
1156
1157   RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1158                                            const url::ViewOption & urlview,
1159                                            const ProgressData::ReceiverFnc & progressrcv )
1160   {
1161     std::list<RepoInfo> repos = knownRepositories();
1162     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1163           it != repos.end();
1164           ++it )
1165     {
1166       for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1167           urlit != (*it).baseUrlsEnd();
1168           ++urlit)
1169       {
1170         if ((*urlit).asString(urlview) == url.asString(urlview))
1171           return *it;
1172       }
1173     }
1174     RepoInfo info;
1175     info.setAlias(info.alias());
1176     info.setBaseUrl(url);
1177     ZYPP_THROW(RepoNotFoundException(info));
1178   }
1179
1180   ////////////////////////////////////////////////////////////////////////////
1181
1182   std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1183   {
1184     return str << *obj._pimpl;
1185   }
1186
1187   /////////////////////////////////////////////////////////////////
1188 } // namespace zypp
1189 ///////////////////////////////////////////////////////////////////