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