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