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