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