- Provide an api to get the metadata path. Needed to fix #293428
[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   Pathname RepoManager::metadataPath( const RepoInfo &info ) const
305   {
306     return rawcache_path_for_repoinfo(_pimpl->options, info );
307   }
308
309   ////////////////////////////////////////////////////////////////////////////
310       
311   RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
312   {
313     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
314     RepoType repokind = info.type();
315     RepoStatus status;
316
317     switch ( repokind.toEnum() )
318     {
319       case RepoType::NONE_e:
320       // unknown, probe the local metadata
321         repokind = probe(rawpath.asUrl());
322       break;
323       default:
324       break;
325     }
326
327     switch ( repokind.toEnum() )
328     {
329       case RepoType::RPMMD_e :
330       {
331         status = RepoStatus( rawpath + "/repodata/repomd.xml");
332       }
333       break;
334
335       case RepoType::YAST2_e :
336       {
337         // the order of RepoStatus && RepoStatus matters! (#304310)
338         status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
339       }
340       break;
341
342       case RepoType::RPMPLAINDIR_e :
343       {
344         if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
345           status = RepoStatus( rawpath + "/cookie");
346       }
347       break;
348
349       case RepoType::NONE_e :
350         // Return default RepoStatus in case of RepoType::NONE
351         // indicating it should be created?
352         // ZYPP_THROW(RepoUnknownTypeException());
353         break;
354     }
355     return status;
356   }
357
358   void RepoManager::touchIndexFile(const RepoInfo & info)
359   {
360     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
361
362     RepoType repokind = info.type();
363     if ( repokind.toEnum() == RepoType::NONE_e )
364       // unknown, probe the local metadata
365       repokind = probe(rawpath.asUrl());
366     // if still unknown, just return
367     if (repokind == RepoType::NONE_e)
368       return;
369
370     Pathname p;
371     switch ( repokind.toEnum() )
372     {
373       case RepoType::RPMMD_e :
374         p = Pathname(rawpath + "/repodata/repomd.xml");
375         break;
376
377       case RepoType::YAST2_e :
378         p = Pathname(rawpath + "/content");
379         break;
380
381       case RepoType::RPMPLAINDIR_e :
382         p = Pathname(rawpath + "/cookie");
383         break;
384
385       case RepoType::NONE_e :
386       default:
387         break;
388     }
389
390     // touch the file, ignore error (they are logged anyway)
391     filesystem::touch(p);
392   }
393
394   bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
395                                               const Url &url,
396                                               RawMetadataRefreshPolicy policy )
397   {
398     assert_alias(info);
399
400     RepoStatus oldstatus;
401     RepoStatus newstatus;
402
403     try
404     {
405       MIL << "Going to try to check whether refresh is needed for " << url << endl;
406
407       repo::RepoType repokind = info.type();
408
409       // if the type is unknown, try probing.
410       switch ( repokind.toEnum() )
411       {
412         case RepoType::NONE_e:
413           // unknown, probe it
414           repokind = probe(url);
415         break;
416         default:
417         break;
418       }
419
420       Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
421       filesystem::assert_dir(rawpath);
422       oldstatus = metadataStatus(info);
423
424       // now we've got the old (cached) status, we can decide repo.refresh.delay
425       if (policy != RefreshForced)
426       {
427         // difference in seconds
428         double diff = difftime(
429           (Date::ValueType)Date::now(),
430           (Date::ValueType)oldstatus.timestamp()) / 60;
431
432         DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
433         DBG << "current time: " << (Date::ValueType)Date::now() << endl;
434         DBG << "last refresh = " << diff << " minutes ago" << endl;
435
436         if (diff < ZConfig::instance().repo_refresh_delay())
437         {
438           MIL << "Repository '" << info.alias()
439               << "' has been refreshed less than repo.refresh.delay ("
440               << ZConfig::instance().repo_refresh_delay()
441               << ") minutes ago. Advising to skip refresh" << endl;
442           return false;
443         }
444       }
445
446       // create temp dir as sibling of rawpath
447       filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
448
449       if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
450            ( repokind.toEnum() == RepoType::YAST2_e ) )
451       {
452         MediaSetAccess media(url);
453         shared_ptr<repo::Downloader> downloader_ptr;
454
455         if ( repokind.toEnum() == RepoType::RPMMD_e )
456           downloader_ptr.reset(new yum::Downloader(info.path()));
457         else
458           downloader_ptr.reset( new susetags::Downloader(info.path()));
459
460         RepoStatus newstatus = downloader_ptr->status(media);
461         bool refresh = false;
462         if ( oldstatus.checksum() == newstatus.checksum() )
463         {
464           MIL << "repo has not changed" << endl;
465           if ( policy == RefreshForced )
466           {
467             MIL << "refresh set to forced" << endl;
468             refresh = true;
469           }
470         }
471         else
472         {
473           MIL << "repo has changed, going to refresh" << endl;
474           refresh = true;
475         }
476
477         if (!refresh)
478           touchIndexFile(info);
479
480         return refresh;
481       }
482       else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
483       {
484         RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
485         bool refresh = false;
486         if ( oldstatus.checksum() == newstatus.checksum() )
487         {
488           MIL << "repo has not changed" << endl;
489           if ( policy == RefreshForced )
490           {
491             MIL << "refresh set to forced" << endl;
492             refresh = true;
493           }
494         }
495         else
496         {
497           MIL << "repo has changed, going to refresh" << endl;
498           refresh = true;
499         }
500
501         if (!refresh)
502           touchIndexFile(info);
503
504         return refresh;
505       }
506       else
507       {
508         ZYPP_THROW(RepoUnknownTypeException());
509       }
510     }
511     catch ( const Exception &e )
512     {
513       ZYPP_CAUGHT(e);
514       ERR << "refresh check failed for " << url << endl;
515       ZYPP_RETHROW(e);
516     }
517     
518     return true; // default
519   }
520
521   void RepoManager::refreshMetadata( const RepoInfo &info,
522                                      RawMetadataRefreshPolicy policy,
523                                      const ProgressData::ReceiverFnc & progress )
524   {
525     assert_alias(info);
526     assert_urls(info);
527
528     // we will throw this later if no URL checks out fine
529     RepoException rexception(_("Valid metadata not found at specified URL(s)"));
530
531     // try urls one by one
532     for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
533     {
534       try
535       {
536         Url url(*it);
537
538         // check whether to refresh metadata
539         // if the check fails for this url, it throws, so another url will be checked
540         if (!checkIfToRefreshMetadata(info, url, policy))
541           return;
542
543         MIL << "Going to refresh metadata from " << url << endl;
544
545         repo::RepoType repokind = info.type();
546
547         // if the type is unknown, try probing.
548         switch ( repokind.toEnum() )
549         {
550           case RepoType::NONE_e:
551             // unknown, probe it
552             repokind = probe(*it);
553           break;
554           default:
555           break;
556         }
557
558         Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
559         filesystem::assert_dir(rawpath);
560
561         // create temp dir as sibling of rawpath
562         filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
563
564         if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
565              ( repokind.toEnum() == RepoType::YAST2_e ) )
566         {
567           MediaSetAccess media(url);
568           shared_ptr<repo::Downloader> downloader_ptr;
569
570           if ( repokind.toEnum() == RepoType::RPMMD_e )
571             downloader_ptr.reset(new yum::Downloader(info.path()));
572           else
573             downloader_ptr.reset( new susetags::Downloader(info.path()));
574
575           /**
576            * Given a downloader, sets the other repos raw metadata
577            * path as cache paths for the fetcher, so if another
578            * repo has the same file, it will not download it
579            * but copy it from the other repository
580            */
581           std::list<RepoInfo> repos = knownRepositories();
582           for ( std::list<RepoInfo>::const_iterator it = repos.begin();
583                 it != repos.end();
584                 ++it )
585           {
586             downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
587           }
588
589           downloader_ptr->download( media, tmpdir.path());
590         }
591         else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
592         {
593           RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
594
595           std::ofstream file(( tmpdir.path() + "/cookie").c_str());
596           if (!file) {
597             ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
598           }
599           file << url << endl;
600           file << newstatus.checksum() << endl;
601
602           file.close();
603         }
604         else
605         {
606           ZYPP_THROW(RepoUnknownTypeException());
607         }
608
609         // ok we have the metadata, now exchange
610         // the contents
611         TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
612         filesystem::rename( rawpath, oldmetadata.path() );
613         // move the just downloaded there
614         filesystem::rename( tmpdir.path(), rawpath );
615         // we are done.
616         return;
617       }
618       catch ( const Exception &e )
619       {
620         ZYPP_CAUGHT(e);
621         ERR << "Trying another url..." << endl;
622         
623         // remember the exception caught for the *first URL*
624         // if all other URLs fail, the rexception will be thrown with the
625         // cause of the problem of the first URL remembered
626         if (it == info.baseUrlsBegin())
627           rexception.remember(e);
628       }
629     } // for every url
630     ERR << "No more urls..." << endl;
631     ZYPP_THROW(rexception);
632   }
633
634   ////////////////////////////////////////////////////////////////////////////
635
636   void RepoManager::cleanMetadata( const RepoInfo &info,
637                                    const ProgressData::ReceiverFnc & progressfnc )
638   {
639     ProgressData progress(100);
640     progress.sendTo(progressfnc);
641
642     filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
643     progress.toMax();
644   }
645
646   void RepoManager::buildCache( const RepoInfo &info,
647                                 CacheBuildPolicy policy,
648                                 const ProgressData::ReceiverFnc & progressrcv )
649   {
650     assert_alias(info);
651     Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
652
653     cache::CacheStore store(_pimpl->options.repoCachePath);
654
655     RepoStatus raw_metadata_status = metadataStatus(info);
656     if ( raw_metadata_status.empty() )
657     {
658       ZYPP_THROW(RepoMetadataException(info));
659     }
660
661     bool needs_cleaning = false;
662     if ( store.isCached( info.alias() ) )
663     {
664       MIL << info.alias() << " is already cached." << endl;
665       data::RecordId id = store.lookupRepository(info.alias());
666       RepoStatus cache_status = store.repositoryStatus(id);
667
668       if ( cache_status.checksum() == raw_metadata_status.checksum() )
669       {
670         MIL << info.alias() << " cache is up to date with metadata." << endl;
671         if ( policy == BuildIfNeeded ) {
672           return;
673         }
674         else {
675           MIL << info.alias() << " cache rebuild is forced" << endl;
676         }
677       }
678       
679       needs_cleaning = true;
680     }
681
682     ProgressData progress(100);
683     callback::SendReport<ProgressReport> report;
684     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
685     progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
686     progress.toMin();
687
688     if (needs_cleaning)
689       cleanCacheInternal( store, info);
690
691     MIL << info.alias() << " building cache..." << endl;
692     data::RecordId id = store.lookupOrAppendRepository(info.alias());
693     // do we have type?
694     repo::RepoType repokind = info.type();
695
696     // if the type is unknown, try probing.
697     switch ( repokind.toEnum() )
698     {
699       case RepoType::NONE_e:
700         // unknown, probe the local metadata
701         repokind = probe(rawpath.asUrl());
702       break;
703       default:
704       break;
705     }
706
707     
708     switch ( repokind.toEnum() )
709     {
710       case RepoType::RPMMD_e :
711       {
712         CombinedProgressData subprogrcv( progress, 100);
713         parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
714         parser.parse(rawpath);
715           // no error
716       }
717       break;
718       case RepoType::YAST2_e :
719       {
720         CombinedProgressData subprogrcv( progress, 100);
721         parser::susetags::RepoParser parser(id, store, subprogrcv);
722         parser.parse(rawpath);
723         // no error
724       }
725       break;
726       case RepoType::RPMPLAINDIR_e :
727       {
728         CombinedProgressData subprogrcv( progress, 100);
729         InputStream is(rawpath + "cookie");
730         string buffer;
731         getline( is.stream(), buffer);
732         Url url(buffer);
733         parser::plaindir::RepoParser parser(id, store, subprogrcv);
734         parser.parse(url.getPathName());
735       }
736       break;
737       default:
738         ZYPP_THROW(RepoUnknownTypeException());
739     }
740
741     // update timestamp and checksum
742     store.updateRepositoryStatus(id, raw_metadata_status);
743
744     MIL << "Commit cache.." << endl;
745     store.commit();
746     //progress.toMax();
747   }
748
749   ////////////////////////////////////////////////////////////////////////////
750
751   repo::RepoType RepoManager::probe( const Url &url ) const
752   {
753     if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
754     {
755       // Handle non existing local directory in advance, as
756       // MediaSetAccess does not support it.
757       return repo::RepoType::NONE;
758     }
759
760     try
761     {
762       MediaSetAccess access(url);
763       if ( access.doesFileExist("/repodata/repomd.xml") )
764         return repo::RepoType::RPMMD;
765       if ( access.doesFileExist("/content") )
766         return repo::RepoType::YAST2;
767   
768       // if it is a local url of type dir
769       if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
770       {
771         Pathname path = Pathname(url.getPathName());
772         if ( PathInfo(path).isDir() )
773         {
774           // allow empty dirs for now
775           return repo::RepoType::RPMPLAINDIR;
776         }
777       }
778     }
779     catch ( const media::MediaException &e )
780     {
781       ZYPP_CAUGHT(e);
782       RepoException enew("Error trying to read from " + url.asString());
783       enew.remember(e);
784       ZYPP_THROW(enew);
785     }
786     catch ( const Exception &e )
787     {
788       ZYPP_CAUGHT(e);
789       Exception enew("Unknown error reading from " + url.asString());
790       enew.remember(e);
791       ZYPP_THROW(enew);
792     }
793
794     return repo::RepoType::NONE;
795   }
796     
797   ////////////////////////////////////////////////////////////////////////////
798   
799   void RepoManager::cleanCache( const RepoInfo &info,
800                                 const ProgressData::ReceiverFnc & progressrcv )
801   {
802     cache::CacheStore store(_pimpl->options.repoCachePath);
803     cleanCacheInternal( store, info, progressrcv );
804     store.commit();
805   }
806
807   ////////////////////////////////////////////////////////////////////////////
808
809   bool RepoManager::isCached( const RepoInfo &info ) const
810   {
811     cache::CacheStore store(_pimpl->options.repoCachePath);
812     return store.isCached(info.alias());
813   }
814
815   RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
816   {
817     cache::CacheStore store(_pimpl->options.repoCachePath);
818     data::RecordId id = store.lookupRepository(info.alias());
819     RepoStatus cache_status = store.repositoryStatus(id);
820     return cache_status;
821   }
822
823   Repository RepoManager::createFromCache( const RepoInfo &info,
824                                            const ProgressData::ReceiverFnc & progressrcv )
825   {
826     callback::SendReport<ProgressReport> report;
827     ProgressData progress;
828     progress.sendTo(ProgressReportAdaptor( progressrcv, report ));
829     //progress.sendTo( progressrcv );
830     progress.name(str::form(_("Reading repository '%s' cache"), info.name().c_str()));
831     
832     cache::CacheStore store(_pimpl->options.repoCachePath);
833
834     if ( ! store.isCached( info.alias() ) )
835       ZYPP_THROW(RepoNotCachedException());
836
837     MIL << "Repository " << info.alias() << " is cached" << endl;
838
839     data::RecordId id = store.lookupRepository(info.alias());
840     
841     CombinedProgressData subprogrcv(progress);
842     
843     repo::cached::RepoOptions opts( info, _pimpl->options.repoCachePath, id );
844     opts.readingResolvablesProgress = subprogrcv;
845     repo::cached::RepoImpl::Ptr repoimpl =
846         new repo::cached::RepoImpl( opts );
847
848     repoimpl->resolvables();
849     // read the resolvables from cache
850     return Repository(repoimpl);
851   }
852
853   ////////////////////////////////////////////////////////////////////////////
854
855   /**
856    * Generate a non existing filename in a directory, using a base
857    * name. For example if a directory contains 3 files
858    *
859    * |-- bar
860    * |-- foo
861    * `-- moo
862    *
863    * If you try to generate a unique filename for this directory,
864    * based on "ruu" you will get "ruu", but if you use the base
865    * "foo" you will get "foo_1"
866    *
867    * \param dir Directory where the file needs to be unique
868    * \param basefilename string to base the filename on.
869    */
870   static Pathname generate_non_existing_name( const Pathname &dir,
871                                               const std::string &basefilename )
872   {
873     string final_filename = basefilename;
874     int counter = 1;
875     while ( PathInfo(dir + final_filename).isExist() )
876     {
877       final_filename = basefilename + "_" + str::numstring(counter);
878       counter++;
879     }
880     return dir + Pathname(final_filename);
881   }
882
883   ////////////////////////////////////////////////////////////////////////////
884
885   /**
886    * \short Generate a related filename from a repo info
887    *
888    * From a repo info, it will try to use the alias as a filename
889    * escaping it if necessary. Other fallbacks can be added to
890    * this function in case there is no way to use the alias
891    */
892   static std::string generate_filename( const RepoInfo &info )
893   {
894     std::string fnd="/";
895     std::string rep="_";
896     std::string filename = info.alias();
897     // replace slashes with underscores
898     size_t pos = filename.find(fnd);
899     while(pos!=string::npos)
900     {
901       filename.replace(pos,fnd.length(),rep);
902       pos = filename.find(fnd,pos+rep.length());
903     }
904     filename = Pathname(filename).extend(".repo").asString();
905     MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
906     return filename;
907   }
908
909
910   ////////////////////////////////////////////////////////////////////////////
911
912   void RepoManager::addRepository( const RepoInfo &info,
913                                    const ProgressData::ReceiverFnc & progressrcv )
914   {
915     assert_alias(info);
916
917     ProgressData progress(100);
918     callback::SendReport<ProgressReport> report;
919     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
920     progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
921     progress.toMin();
922
923     std::list<RepoInfo> repos = knownRepositories();
924     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
925           it != repos.end();
926           ++it )
927     {
928       if ( info.alias() == (*it).alias() )
929         ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
930     }
931
932     RepoInfo tosave = info;
933
934     // check the first url for now
935     if ( ZConfig::instance().repo_add_probe()
936         || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
937     {
938       DBG << "unknown repository type, probing" << endl;
939
940       RepoType probedtype;
941       probedtype = probe(*tosave.baseUrlsBegin());
942       if ( tosave.baseUrlsSize() > 0 )
943       {
944         if ( probedtype == RepoType::NONE )
945           ZYPP_THROW(RepoUnknownTypeException());
946         else
947           tosave.setType(probedtype);
948       }
949     }
950
951     progress.set(50);
952
953     // assert the directory exists
954     filesystem::assert_dir(_pimpl->options.knownReposPath);
955
956     Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
957                                                     generate_filename(tosave));
958     // now we have a filename that does not exists
959     MIL << "Saving repo in " << repofile << endl;
960
961     std::ofstream file(repofile.c_str());
962     if (!file) {
963       ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
964     }
965
966     tosave.dumpRepoOn(file);
967     progress.toMax();
968     MIL << "done" << endl;
969   }
970
971   void RepoManager::addRepositories( const Url &url,
972                                      const ProgressData::ReceiverFnc & progressrcv )
973   {
974     std::list<RepoInfo> knownrepos = knownRepositories();
975     std::list<RepoInfo> repos = readRepoFile(url);
976     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
977           it != repos.end();
978           ++it )
979     {
980       // look if the alias is in the known repos.
981       for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
982           kit != knownrepos.end();
983           ++kit )
984       {
985         if ( (*it).alias() == (*kit).alias() )
986         {
987           ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
988           ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
989         }
990       }
991     }
992
993     string filename = Pathname(url.getPathName()).basename();
994
995     if ( filename == Pathname() )
996       ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
997
998     // assert the directory exists
999     filesystem::assert_dir(_pimpl->options.knownReposPath);
1000
1001     Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1002     // now we have a filename that does not exists
1003     MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1004
1005     std::ofstream file(repofile.c_str());
1006     if (!file) {
1007       ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1008     }
1009
1010     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1011           it != repos.end();
1012           ++it )
1013     {
1014       MIL << "Saving " << (*it).alias() << endl;
1015       (*it).dumpRepoOn(file);
1016     }
1017     MIL << "done" << endl;
1018   }
1019
1020   ////////////////////////////////////////////////////////////////////////////
1021
1022   void RepoManager::removeRepository( const RepoInfo & info,
1023                                       const ProgressData::ReceiverFnc & progressrcv)
1024   {
1025     ProgressData progress;
1026     callback::SendReport<ProgressReport> report;
1027     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1028     progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1029     
1030     MIL << "Going to delete repo " << info.alias() << endl;
1031
1032     std::list<RepoInfo> repos = knownRepositories();
1033     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1034           it != repos.end();
1035           ++it )
1036     {
1037       // they can be the same only if the provided is empty, that means
1038       // the provided repo has no alias
1039       // then skip
1040       if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1041         continue;
1042
1043       // TODO match by url
1044
1045       // we have a matcing repository, now we need to know
1046       // where it does come from.
1047       RepoInfo todelete = *it;
1048       if (todelete.filepath().empty())
1049       {
1050         ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1051       }
1052       else
1053       {
1054         // figure how many repos are there in the file:
1055         std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1056         if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1057         {
1058           // easy, only this one, just delete the file
1059           if ( filesystem::unlink(todelete.filepath()) != 0 )
1060           {
1061             ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1062           }
1063           MIL << todelete.alias() << " sucessfully deleted." << endl;
1064         }
1065         else
1066         {
1067           // there are more repos in the same file
1068           // write them back except the deleted one.
1069           //TmpFile tmp;
1070           //std::ofstream file(tmp.path().c_str());
1071
1072           // assert the directory exists
1073           filesystem::assert_dir(todelete.filepath().dirname());
1074
1075           std::ofstream file(todelete.filepath().c_str());
1076           if (!file) {
1077             //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1078             ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1079           }
1080           for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1081                 fit != filerepos.end();
1082                 ++fit )
1083           {
1084             if ( (*fit).alias() != todelete.alias() )
1085               (*fit).dumpRepoOn(file);
1086           }
1087         }
1088
1089         CombinedProgressData subprogrcv(progress, 70);
1090         CombinedProgressData cleansubprogrcv(progress, 30);
1091         // now delete it from cache
1092         cleanCache( todelete, subprogrcv);
1093         // now delete metadata (#301037)
1094         cleanMetadata( todelete, cleansubprogrcv);
1095         MIL << todelete.alias() << " sucessfully deleted." << endl;
1096         return;
1097       } // else filepath is empty
1098
1099     }
1100     // should not be reached on a sucess workflow
1101     ZYPP_THROW(RepoNotFoundException(info));
1102   }
1103
1104   ////////////////////////////////////////////////////////////////////////////
1105
1106   void RepoManager::modifyRepository( const std::string &alias,
1107                                       const RepoInfo & newinfo,
1108                                       const ProgressData::ReceiverFnc & progressrcv )
1109   {
1110     RepoInfo toedit = getRepositoryInfo(alias);
1111
1112     if (toedit.filepath().empty())
1113     {
1114       ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1115     }
1116     else
1117     {
1118       // figure how many repos are there in the file:
1119       std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1120
1121       // there are more repos in the same file
1122       // write them back except the deleted one.
1123       //TmpFile tmp;
1124       //std::ofstream file(tmp.path().c_str());
1125
1126       // assert the directory exists
1127       filesystem::assert_dir(toedit.filepath().dirname());
1128
1129       std::ofstream file(toedit.filepath().c_str());
1130       if (!file) {
1131         //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1132         ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1133       }
1134       for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1135             fit != filerepos.end();
1136             ++fit )
1137       {
1138           // if the alias is different, dump the original
1139           // if it is the same, dump the provided one
1140           if ( (*fit).alias() != toedit.alias() )
1141             (*fit).dumpRepoOn(file);
1142           else
1143             newinfo.dumpRepoOn(file);
1144       }
1145     }
1146   }
1147
1148   ////////////////////////////////////////////////////////////////////////////
1149
1150   RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1151                                            const ProgressData::ReceiverFnc & progressrcv )
1152   {
1153     std::list<RepoInfo> repos = knownRepositories();
1154     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1155           it != repos.end();
1156           ++it )
1157     {
1158       if ( (*it).alias() == alias )
1159         return *it;
1160     }
1161     RepoInfo info;
1162     info.setAlias(info.alias());
1163     ZYPP_THROW(RepoNotFoundException(info));
1164   }
1165
1166   ////////////////////////////////////////////////////////////////////////////
1167
1168   RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1169                                            const url::ViewOption & urlview,
1170                                            const ProgressData::ReceiverFnc & progressrcv )
1171   {
1172     std::list<RepoInfo> repos = knownRepositories();
1173     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1174           it != repos.end();
1175           ++it )
1176     {
1177       for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1178           urlit != (*it).baseUrlsEnd();
1179           ++urlit)
1180       {
1181         if ((*urlit).asString(urlview) == url.asString(urlview))
1182           return *it;
1183       }
1184     }
1185     RepoInfo info;
1186     info.setAlias(info.alias());
1187     info.setBaseUrl(url);
1188     ZYPP_THROW(RepoNotFoundException(info));
1189   }
1190
1191   ////////////////////////////////////////////////////////////////////////////
1192
1193   std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1194   {
1195     return str << *obj._pimpl;
1196   }
1197
1198   /////////////////////////////////////////////////////////////////
1199 } // namespace zypp
1200 ///////////////////////////////////////////////////////////////////