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