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