error message
[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/media/MediaManager.h"
32 #include "zypp/MediaSetAccess.h"
33 #include "zypp/ExternalProgram.h"
34 #include "zypp/ManagedFile.h"
35
36 #include "zypp/parser/RepoFileReader.h"
37 #include "zypp/repo/yum/Downloader.h"
38 #include "zypp/parser/yum/RepoParser.h"
39 #include "zypp/repo/susetags/Downloader.h"
40 #include "zypp/parser/susetags/RepoParser.h"
41
42 #include "zypp/ZYppCallbacks.h"
43
44 #include "sat/Pool.h"
45 #include "satsolver/pool.h"
46 #include "satsolver/repo.h"
47 #include "satsolver/repo_solv.h"
48
49 using namespace std;
50 using namespace zypp;
51 using namespace zypp::repo;
52 using namespace zypp::filesystem;
53
54 using namespace zypp::repo;
55
56 ///////////////////////////////////////////////////////////////////
57 namespace zypp
58 { /////////////////////////////////////////////////////////////////
59
60   ///////////////////////////////////////////////////////////////////
61   //
62   //    CLASS NAME : RepoManagerOptions
63   //
64   ///////////////////////////////////////////////////////////////////
65
66   RepoManagerOptions::RepoManagerOptions()
67   {
68     repoCachePath    = ZConfig::instance().repoCachePath();
69     repoRawCachePath = ZConfig::instance().repoMetadataPath();
70     repoPackagesCachePath = ZConfig::instance().repoPackagesPath();
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    * Reads RepoInfo's from a repo file.
113    *
114    * \param file pathname of the file to read.
115    */
116   static std::list<RepoInfo> repositories_in_file( const Pathname & file )
117   {
118     MIL << "repo file: " << file << endl;
119     RepoCollector collector;
120     parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
121     return collector.repos;
122   }
123
124   ////////////////////////////////////////////////////////////////////////////
125
126   std::list<RepoInfo> readRepoFile(const Url & repo_file)
127    {
128      // no interface to download a specific file, using workaround:
129      //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
130      Url url(repo_file);
131      Pathname path(url.getPathName());
132      url.setPathName ("/");
133      MediaSetAccess access(url);
134      Pathname local = access.provideFile(path);
135
136      DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
137
138      return repositories_in_file(local);
139    }
140
141   ////////////////////////////////////////////////////////////////////////////
142
143   /**
144    * \short List of RepoInfo's from a directory
145    *
146    * Goes trough every file ending with ".repo" in a directory and adds all
147    * RepoInfo's contained in that file.
148    *
149    * \param dir pathname of the directory to read.
150    */
151   static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
152   {
153     MIL << "directory " << dir << endl;
154     list<RepoInfo> repos;
155     list<Pathname> entries;
156     if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
157       ZYPP_THROW(Exception("failed to read directory"));
158
159     str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
160     for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
161     {
162       if (str::regex_match(it->extension(), allowedRepoExt))
163       {
164         list<RepoInfo> tmp = repositories_in_file( *it );
165         repos.insert( repos.end(), tmp.begin(), tmp.end() );
166
167         //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
168         //MIL << "ok" << endl;
169       }
170     }
171     return repos;
172   }
173
174   ////////////////////////////////////////////////////////////////////////////
175
176   static void assert_alias( const RepoInfo &info )
177   {
178     if (info.alias().empty())
179         ZYPP_THROW(RepoNoAliasException());
180   }
181
182   ////////////////////////////////////////////////////////////////////////////
183
184   static void assert_urls( const RepoInfo &info )
185   {
186     if (info.baseUrlsEmpty())
187         ZYPP_THROW(RepoNoUrlException());
188   }
189
190   ////////////////////////////////////////////////////////////////////////////
191
192   /**
193    * \short Calculates the raw cache path for a repository
194    */
195   static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
196   {
197     assert_alias(info);
198     return opt.repoRawCachePath + info.alias();
199   }
200
201   /**
202    * \short Calculates the packages cache path for a repository
203    */
204   static Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
205   {
206     assert_alias(info);
207     return opt.repoPackagesCachePath + info.alias();
208   }
209
210   ///////////////////////////////////////////////////////////////////
211   //
212   //    CLASS NAME : RepoManager::Impl
213   //
214   ///////////////////////////////////////////////////////////////////
215
216   /**
217    * \short RepoManager implementation.
218    */
219   struct RepoManager::Impl
220   {
221     Impl( const RepoManagerOptions &opt )
222       : options(opt)
223     {
224
225     }
226
227     Impl()
228     {
229
230     }
231
232     RepoManagerOptions options;
233
234     map<string, RepoInfo> _repoinfos;
235
236   public:
237     /** Offer default Impl. */
238     static shared_ptr<Impl> nullimpl()
239     {
240       static shared_ptr<Impl> _nullimpl( new Impl );
241       return _nullimpl;
242     }
243
244   private:
245     friend Impl * rwcowClone<Impl>( const Impl * rhs );
246     /** clone for RWCOW_pointer */
247     Impl * clone() const
248     { return new Impl( *this ); }
249   };
250
251   ///////////////////////////////////////////////////////////////////
252
253   /** \relates RepoManager::Impl Stream output */
254   inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
255   {
256     return str << "RepoManager::Impl";
257   }
258
259   ///////////////////////////////////////////////////////////////////
260   //
261   //    CLASS NAME : RepoManager
262   //
263   ///////////////////////////////////////////////////////////////////
264
265   RepoManager::RepoManager( const RepoManagerOptions &opt )
266   : _pimpl( new Impl(opt) )
267   {}
268
269   ////////////////////////////////////////////////////////////////////////////
270
271   RepoManager::~RepoManager()
272   {}
273
274   ////////////////////////////////////////////////////////////////////////////
275
276   std::list<RepoInfo> RepoManager::knownRepositories() const
277   {
278     MIL << endl;
279
280     if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
281     {
282       RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
283       for ( RepoInfoList::iterator it = repos.begin();
284             it != repos.end();
285             ++it )
286       {
287         // set the metadata path for the repo
288         Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
289         (*it).setMetadataPath(metadata_path);
290         
291         // set the downloaded packages path for the repo
292         Pathname packages_path = packagescache_path_for_repoinfo(_pimpl->options, (*it));
293         (*it).setPackagesPath(packages_path);
294       }
295       return repos;
296     }
297     else
298       return std::list<RepoInfo>();
299
300     MIL << endl;
301   }
302
303   ////////////////////////////////////////////////////////////////////////////
304
305   Pathname RepoManager::metadataPath( const RepoInfo &info ) const
306   {
307     return rawcache_path_for_repoinfo(_pimpl->options, info );
308   }
309
310   ////////////////////////////////////////////////////////////////////////////
311
312   RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
313   {
314     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
315     RepoType repokind = info.type();
316     RepoStatus status;
317
318     switch ( repokind.toEnum() )
319     {
320       case RepoType::NONE_e:
321       // unknown, probe the local metadata
322         repokind = probe(rawpath.asUrl());
323       break;
324       default:
325       break;
326     }
327
328     switch ( repokind.toEnum() )
329     {
330       case RepoType::RPMMD_e :
331       {
332         status = RepoStatus( rawpath + "/repodata/repomd.xml");
333       }
334       break;
335
336       case RepoType::YAST2_e :
337       {
338         // the order of RepoStatus && RepoStatus matters! (#304310)
339         status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
340       }
341       break;
342
343       case RepoType::RPMPLAINDIR_e :
344       {
345         if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
346           status = RepoStatus( rawpath + "/cookie");
347       }
348       break;
349
350       case RepoType::NONE_e :
351         // Return default RepoStatus in case of RepoType::NONE
352         // indicating it should be created?
353         // ZYPP_THROW(RepoUnknownTypeException());
354         break;
355     }
356     return status;
357   }
358
359   void RepoManager::touchIndexFile(const RepoInfo & info)
360   {
361     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
362
363     RepoType repokind = info.type();
364     if ( repokind.toEnum() == RepoType::NONE_e )
365       // unknown, probe the local metadata
366       repokind = probe(rawpath.asUrl());
367     // if still unknown, just return
368     if (repokind == RepoType::NONE_e)
369       return;
370
371     Pathname p;
372     switch ( repokind.toEnum() )
373     {
374       case RepoType::RPMMD_e :
375         p = Pathname(rawpath + "/repodata/repomd.xml");
376         break;
377
378       case RepoType::YAST2_e :
379         p = Pathname(rawpath + "/content");
380         break;
381
382       case RepoType::RPMPLAINDIR_e :
383         p = Pathname(rawpath + "/cookie");
384         break;
385
386       case RepoType::NONE_e :
387       default:
388         break;
389     }
390
391     // touch the file, ignore error (they are logged anyway)
392     filesystem::touch(p);
393   }
394
395   bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
396                                               const Url &url,
397                                               RawMetadataRefreshPolicy policy )
398   {
399     assert_alias(info);
400
401     RepoStatus oldstatus;
402     RepoStatus newstatus;
403
404     try
405     {
406       MIL << "Going to try to check whether refresh is needed for " << url << endl;
407
408       repo::RepoType repokind = info.type();
409
410       // if the type is unknown, try probing.
411       switch ( repokind.toEnum() )
412       {
413         case RepoType::NONE_e:
414           // unknown, probe it
415           repokind = probe(url);
416         break;
417         default:
418         break;
419       }
420
421       Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
422       filesystem::assert_dir(rawpath);
423       oldstatus = metadataStatus(info);
424
425       // now we've got the old (cached) status, we can decide repo.refresh.delay
426       if (policy != RefreshForced)
427       {
428         // difference in seconds
429         double diff = difftime(
430           (Date::ValueType)Date::now(),
431           (Date::ValueType)oldstatus.timestamp()) / 60;
432
433         DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
434         DBG << "current time: " << (Date::ValueType)Date::now() << endl;
435         DBG << "last refresh = " << diff << " minutes ago" << endl;
436
437         if (diff < ZConfig::instance().repo_refresh_delay())
438         {
439           MIL << "Repository '" << info.alias()
440               << "' has been refreshed less than repo.refresh.delay ("
441               << ZConfig::instance().repo_refresh_delay()
442               << ") minutes ago. Advising to skip refresh" << endl;
443           return false;
444         }
445       }
446
447       // create temp dir as sibling of rawpath
448       filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
449
450       if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
451            ( repokind.toEnum() == RepoType::YAST2_e ) )
452       {
453         MediaSetAccess media(url);
454         shared_ptr<repo::Downloader> downloader_ptr;
455
456         if ( repokind.toEnum() == RepoType::RPMMD_e )
457           downloader_ptr.reset(new yum::Downloader(info.path()));
458         else
459           downloader_ptr.reset( new susetags::Downloader(info.path()));
460
461         RepoStatus newstatus = downloader_ptr->status(media);
462         bool refresh = false;
463         if ( oldstatus.checksum() == newstatus.checksum() )
464         {
465           MIL << "repo has not changed" << endl;
466           if ( policy == RefreshForced )
467           {
468             MIL << "refresh set to forced" << endl;
469             refresh = true;
470           }
471         }
472         else
473         {
474           MIL << "repo has changed, going to refresh" << endl;
475           refresh = true;
476         }
477
478         if (!refresh)
479           touchIndexFile(info);
480
481         return refresh;
482       }
483 #if 0
484       else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
485       {
486         RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
487         bool refresh = false;
488         if ( oldstatus.checksum() == newstatus.checksum() )
489         {
490           MIL << "repo has not changed" << endl;
491           if ( policy == RefreshForced )
492           {
493             MIL << "refresh set to forced" << endl;
494             refresh = true;
495           }
496         }
497         else
498         {
499           MIL << "repo has changed, going to refresh" << endl;
500           refresh = true;
501         }
502
503         if (!refresh)
504           touchIndexFile(info);
505
506         return refresh;
507       }
508 #endif
509       else
510       {
511         ZYPP_THROW(RepoUnknownTypeException());
512       }
513     }
514     catch ( const Exception &e )
515     {
516       ZYPP_CAUGHT(e);
517       ERR << "refresh check failed for " << url << endl;
518       ZYPP_RETHROW(e);
519     }
520
521     return true; // default
522   }
523
524   void RepoManager::refreshMetadata( const RepoInfo &info,
525                                      RawMetadataRefreshPolicy policy,
526                                      const ProgressData::ReceiverFnc & progress )
527   {
528     assert_alias(info);
529     assert_urls(info);
530
531     // we will throw this later if no URL checks out fine
532     RepoException rexception(_("Valid metadata not found at specified URL(s)"));
533
534     // try urls one by one
535     for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
536     {
537       try
538       {
539         Url url(*it);
540
541         // check whether to refresh metadata
542         // if the check fails for this url, it throws, so another url will be checked
543         if (!checkIfToRefreshMetadata(info, url, policy))
544           return;
545
546         MIL << "Going to refresh metadata from " << url << endl;
547
548         repo::RepoType repokind = info.type();
549
550         // if the type is unknown, try probing.
551         switch ( repokind.toEnum() )
552         {
553           case RepoType::NONE_e:
554             // unknown, probe it
555             repokind = probe(*it);
556           break;
557           default:
558           break;
559         }
560
561         Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
562         filesystem::assert_dir(rawpath);
563
564         // create temp dir as sibling of rawpath
565         filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
566
567         if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
568              ( repokind.toEnum() == RepoType::YAST2_e ) )
569         {
570           MediaSetAccess media(url);
571           shared_ptr<repo::Downloader> downloader_ptr;
572
573           if ( repokind.toEnum() == RepoType::RPMMD_e )
574             downloader_ptr.reset(new yum::Downloader(info.path()));
575           else
576             downloader_ptr.reset( new susetags::Downloader(info.path()));
577
578           /**
579            * Given a downloader, sets the other repos raw metadata
580            * path as cache paths for the fetcher, so if another
581            * repo has the same file, it will not download it
582            * but copy it from the other repository
583            */
584           std::list<RepoInfo> repos = knownRepositories();
585           for ( std::list<RepoInfo>::const_iterator it = repos.begin();
586                 it != repos.end();
587                 ++it )
588           {
589             downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
590           }
591
592           downloader_ptr->download( media, tmpdir.path());
593         }
594 #if 0
595         else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
596         {
597           RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
598
599           std::ofstream file(( tmpdir.path() + "/cookie").c_str());
600           if (!file) {
601             ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
602           }
603           file << url << endl;
604           file << newstatus.checksum() << endl;
605
606           file.close();
607         }
608 #endif
609         else
610         {
611           ZYPP_THROW(RepoUnknownTypeException());
612         }
613
614         // ok we have the metadata, now exchange
615         // the contents
616         
617         TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
618         filesystem::rename( rawpath, oldmetadata.path() );
619         // move the just downloaded there
620         filesystem::rename( tmpdir.path(), rawpath );
621
622         // we are done.
623         return;
624       }
625       catch ( const Exception &e )
626       {
627         ZYPP_CAUGHT(e);
628         ERR << "Trying another url..." << endl;
629
630         // remember the exception caught for the *first URL*
631         // if all other URLs fail, the rexception will be thrown with the
632         // cause of the problem of the first URL remembered
633         if (it == info.baseUrlsBegin())
634           rexception.remember(e);
635       }
636     } // for every url
637     ERR << "No more urls..." << endl;
638     ZYPP_THROW(rexception);
639   }
640
641   ////////////////////////////////////////////////////////////////////////////
642
643   void RepoManager::cleanMetadata( const RepoInfo &info,
644                                    const ProgressData::ReceiverFnc & progressfnc )
645   {
646     ProgressData progress(100);
647     progress.sendTo(progressfnc);
648
649     filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
650     progress.toMax();
651   }
652
653   void RepoManager::cleanPackages( const RepoInfo &info,
654                                    const ProgressData::ReceiverFnc & progressfnc )
655   {
656     ProgressData progress(100);
657     progress.sendTo(progressfnc);
658
659     filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
660     progress.toMax();
661   }
662
663   void RepoManager::buildCache( const RepoInfo &info,
664                                 CacheBuildPolicy policy,
665                                 const ProgressData::ReceiverFnc & progressrcv )
666   {
667     assert_alias(info);
668     Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
669
670     Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
671     Pathname solvfile = base.extend(".solv");
672
673     //cache::SolvStore store(_pimpl->options.repoCachePath);
674
675     RepoStatus raw_metadata_status = metadataStatus(info);
676     if ( raw_metadata_status.empty() )
677     {
678       ZYPP_THROW(RepoMetadataException(info));
679     }
680
681     bool needs_cleaning = false;
682     if ( isCached( info ) )
683     {
684       MIL << info.alias() << " is already cached." << endl;
685       //data::RecordId id = store.lookupRepository(info.alias());
686       RepoStatus cache_status = cacheStatus(info);
687
688       if ( cache_status.checksum() == raw_metadata_status.checksum() )
689       {
690         MIL << info.alias() << " cache is up to date with metadata." << endl;
691         if ( policy == BuildIfNeeded ) {
692           return;
693         }
694         else {
695           MIL << info.alias() << " cache rebuild is forced" << endl;
696         }
697       }
698
699       needs_cleaning = true;
700     }
701
702     ProgressData progress(100);
703     callback::SendReport<ProgressReport> report;
704     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
705     progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
706     progress.toMin();
707
708     if (needs_cleaning)
709     {
710 //       Pathname name = _pimpl->options.repoCachePath;
711 //       //data::RecordId id = store.lookupRepository(info.alias());
712 //       ostringstream os;
713 //       os << id.get();
714 //       name += os.str() + ".solv";
715 //       unlink (name);
716 //       cleanCacheInternal( store, info);
717       cleanCache(info);
718     }
719
720     MIL << info.alias() << " building cache..." << endl;
721     //data::RecordId id = store.lookupOrAppendRepository(info.alias());
722     // do we have type?
723     repo::RepoType repokind = info.type();
724
725     // if the type is unknown, try probing.
726     switch ( repokind.toEnum() )
727     {
728       case RepoType::NONE_e:
729         // unknown, probe the local metadata
730         repokind = probe(rawpath.asUrl());
731       break;
732       default:
733       break;
734     }
735
736     MIL << "repo type is " << repokind << endl;
737
738     switch ( repokind.toEnum() )
739     {
740       case RepoType::RPMMD_e :
741       case RepoType::YAST2_e :
742       {
743         MIL << "Executing solv converter" << endl;
744         // Take care we unlink the solvfile on exception
745         ManagedFile guard( solvfile, filesystem::unlink );
746
747         stringstream outputstr;
748         string cmd( str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() ) );
749         ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
750         for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
751           MIL << "  " << output;
752           outputstr << output;
753         }
754         int ret = prog.close();
755         if ( ret != 0 )
756           ZYPP_THROW(RepoUnknownTypeException("Error when creating repository cache: '" + outputstr.str() + "'"));
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     // check if the new alias already exists when renaming the repo
1172     if (alias != newinfo.alias())
1173     {
1174       std::list<RepoInfo> repos = knownRepositories();
1175       for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1176             it != repos.end();
1177             ++it )
1178       {
1179         if ( newinfo.alias() == (*it).alias() )
1180           ZYPP_THROW(RepoAlreadyExistsException(newinfo.alias()));
1181       }
1182     }
1183
1184     if (toedit.filepath().empty())
1185     {
1186       ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1187     }
1188     else
1189     {
1190       // figure how many repos are there in the file:
1191       std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1192
1193       // there are more repos in the same file
1194       // write them back except the deleted one.
1195       //TmpFile tmp;
1196       //std::ofstream file(tmp.path().c_str());
1197
1198       // assert the directory exists
1199       filesystem::assert_dir(toedit.filepath().dirname());
1200
1201       std::ofstream file(toedit.filepath().c_str());
1202       if (!file) {
1203         //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1204         ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1205       }
1206       for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1207             fit != filerepos.end();
1208             ++fit )
1209       {
1210           // if the alias is different, dump the original
1211           // if it is the same, dump the provided one
1212           if ( (*fit).alias() != toedit.alias() )
1213             (*fit).dumpRepoOn(file);
1214           else
1215             newinfo.dumpRepoOn(file);
1216       }
1217     }
1218   }
1219
1220   ////////////////////////////////////////////////////////////////////////////
1221
1222   RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1223                                            const ProgressData::ReceiverFnc & progressrcv )
1224   {
1225     std::list<RepoInfo> repos = knownRepositories();
1226     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1227           it != repos.end();
1228           ++it )
1229     {
1230       if ( (*it).alias() == alias )
1231         return *it;
1232     }
1233     RepoInfo info;
1234     info.setAlias(info.alias());
1235     ZYPP_THROW(RepoNotFoundException(info));
1236   }
1237
1238   ////////////////////////////////////////////////////////////////////////////
1239
1240   RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1241                                            const url::ViewOption & urlview,
1242                                            const ProgressData::ReceiverFnc & progressrcv )
1243   {
1244     std::list<RepoInfo> repos = knownRepositories();
1245     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1246           it != repos.end();
1247           ++it )
1248     {
1249       for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1250           urlit != (*it).baseUrlsEnd();
1251           ++urlit)
1252       {
1253         if ((*urlit).asString(urlview) == url.asString(urlview))
1254           return *it;
1255       }
1256     }
1257     RepoInfo info;
1258     info.setAlias(info.alias());
1259     info.setBaseUrl(url);
1260     ZYPP_THROW(RepoNotFoundException(info));
1261   }
1262
1263   ////////////////////////////////////////////////////////////////////////////
1264
1265   std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1266   {
1267     return str << *obj._pimpl;
1268   }
1269
1270   /////////////////////////////////////////////////////////////////
1271 } // namespace zypp
1272 ///////////////////////////////////////////////////////////////////