- add cache path only if it exists
[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
91       ~RepoCollector()
92       {}
93
94       bool collect( const RepoInfo &repo )
95       {
96         repos.push_back(repo);
97         return true;
98       }
99
100       RepoInfoList repos;
101     };
102
103   ////////////////////////////////////////////////////////////////////////////
104
105   /**
106    * Reads RepoInfo's from a repo file.
107    *
108    * \param file pathname of the file to read.
109    */
110   static std::list<RepoInfo> repositories_in_file( const Pathname & file )
111   {
112     MIL << "repo file: " << file << endl;
113     RepoCollector collector;
114     parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
115     return collector.repos;
116   }
117
118   ////////////////////////////////////////////////////////////////////////////
119
120   std::list<RepoInfo> readRepoFile(const Url & repo_file)
121    {
122      // no interface to download a specific file, using workaround:
123      //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
124      Url url(repo_file);
125      Pathname path(url.getPathName());
126      url.setPathName ("/");
127      MediaSetAccess access(url);
128      Pathname local = access.provideFile(path);
129
130      DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
131
132      return repositories_in_file(local);
133    }
134
135   ////////////////////////////////////////////////////////////////////////////
136
137   /**
138    * \short List of RepoInfo's from a directory
139    *
140    * Goes trough every file ending with ".repo" in a directory and adds all
141    * RepoInfo's contained in that file.
142    *
143    * \param dir pathname of the directory to read.
144    */
145   static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
146   {
147     MIL << "directory " << dir << endl;
148     list<RepoInfo> repos;
149     list<Pathname> entries;
150     if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
151       ZYPP_THROW(Exception("failed to read directory"));
152
153     str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
154     for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
155     {
156       if (str::regex_match(it->extension(), allowedRepoExt))
157       {
158         list<RepoInfo> tmp = repositories_in_file( *it );
159         repos.insert( repos.end(), tmp.begin(), tmp.end() );
160
161         //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
162         //MIL << "ok" << endl;
163       }
164     }
165     return repos;
166   }
167
168   ////////////////////////////////////////////////////////////////////////////
169
170   static void assert_alias( const RepoInfo &info )
171   {
172     if (info.alias().empty())
173         ZYPP_THROW(RepoNoAliasException());
174   }
175
176   ////////////////////////////////////////////////////////////////////////////
177
178   static void assert_urls( const RepoInfo &info )
179   {
180     if (info.baseUrlsEmpty())
181         ZYPP_THROW(RepoNoUrlException());
182   }
183
184   ////////////////////////////////////////////////////////////////////////////
185
186   /**
187    * \short Calculates the raw cache path for a repository
188    */
189   static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
190   {
191     assert_alias(info);
192     return opt.repoRawCachePath / info.escaped_alias();
193   }
194
195   /**
196    * \short Calculates the packages cache path for a repository
197    */
198   static Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
199   {
200     assert_alias(info);
201     return opt.repoPackagesCachePath / info.escaped_alias();
202   }
203
204   ///////////////////////////////////////////////////////////////////
205   //
206   //    CLASS NAME : RepoManager::Impl
207   //
208   ///////////////////////////////////////////////////////////////////
209
210   /**
211    * \short RepoManager implementation.
212    */
213   struct RepoManager::Impl
214   {
215     Impl( const RepoManagerOptions &opt )
216       : options(opt)
217     {
218
219     }
220
221     Impl()
222     {
223
224     }
225
226     RepoManagerOptions options;
227
228     map<string, RepoInfo> _repoinfos;
229
230   public:
231     /** Offer default Impl. */
232     static shared_ptr<Impl> nullimpl()
233     {
234       static shared_ptr<Impl> _nullimpl( new Impl );
235       return _nullimpl;
236     }
237
238   private:
239     friend Impl * rwcowClone<Impl>( const Impl * rhs );
240     /** clone for RWCOW_pointer */
241     Impl * clone() const
242     { return new Impl( *this ); }
243   };
244
245   ///////////////////////////////////////////////////////////////////
246
247   /** \relates RepoManager::Impl Stream output */
248   inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
249   {
250     return str << "RepoManager::Impl";
251   }
252
253   ///////////////////////////////////////////////////////////////////
254   //
255   //    CLASS NAME : RepoManager
256   //
257   ///////////////////////////////////////////////////////////////////
258
259   RepoManager::RepoManager( const RepoManagerOptions &opt )
260   : _pimpl( new Impl(opt) )
261   {}
262
263   ////////////////////////////////////////////////////////////////////////////
264
265   RepoManager::~RepoManager()
266   {}
267
268   ////////////////////////////////////////////////////////////////////////////
269
270   std::list<RepoInfo> RepoManager::knownRepositories() const
271   {
272     MIL << endl;
273
274     if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
275     {
276       RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
277       for ( RepoInfoList::iterator it = repos.begin();
278             it != repos.end();
279             ++it )
280       {
281         // set the metadata path for the repo
282         Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
283         (*it).setMetadataPath(metadata_path);
284
285         // set the downloaded packages path for the repo
286         Pathname packages_path = packagescache_path_for_repoinfo(_pimpl->options, (*it));
287         (*it).setPackagesPath(packages_path);
288       }
289       return repos;
290     }
291     else
292       return std::list<RepoInfo>();
293
294     MIL << endl;
295   }
296
297   ////////////////////////////////////////////////////////////////////////////
298
299   Pathname RepoManager::metadataPath( const RepoInfo &info ) const
300   {
301     return rawcache_path_for_repoinfo(_pimpl->options, info );
302   }
303
304   ////////////////////////////////////////////////////////////////////////////
305
306   RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
307   {
308     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
309     RepoType repokind = info.type();
310     RepoStatus status;
311
312     switch ( repokind.toEnum() )
313     {
314       case RepoType::NONE_e:
315       // unknown, probe the local metadata
316         repokind = probe(rawpath.asUrl());
317       break;
318       default:
319       break;
320     }
321
322     switch ( repokind.toEnum() )
323     {
324       case RepoType::RPMMD_e :
325       {
326         status = RepoStatus( rawpath + "/repodata/repomd.xml");
327       }
328       break;
329
330       case RepoType::YAST2_e :
331       {
332         status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
333       }
334       break;
335
336       case RepoType::RPMPLAINDIR_e :
337       {
338         if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
339           status = RepoStatus( rawpath + "/cookie");
340       }
341       break;
342
343       case RepoType::NONE_e :
344         // Return default RepoStatus in case of RepoType::NONE
345         // indicating it should be created?
346         // ZYPP_THROW(RepoUnknownTypeException());
347         break;
348     }
349     return status;
350   }
351
352   void RepoManager::touchIndexFile(const RepoInfo & info)
353   {
354     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
355
356     RepoType repokind = info.type();
357     if ( repokind.toEnum() == RepoType::NONE_e )
358       // unknown, probe the local metadata
359       repokind = probe(rawpath.asUrl());
360     // if still unknown, just return
361     if (repokind == RepoType::NONE_e)
362       return;
363
364     Pathname p;
365     switch ( repokind.toEnum() )
366     {
367       case RepoType::RPMMD_e :
368         p = Pathname(rawpath + "/repodata/repomd.xml");
369         break;
370
371       case RepoType::YAST2_e :
372         p = Pathname(rawpath + "/content");
373         break;
374
375       case RepoType::RPMPLAINDIR_e :
376         p = Pathname(rawpath + "/cookie");
377         break;
378
379       case RepoType::NONE_e :
380       default:
381         break;
382     }
383
384     // touch the file, ignore error (they are logged anyway)
385     filesystem::touch(p);
386   }
387
388   bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
389                                               const Url &url,
390                                               RawMetadataRefreshPolicy policy )
391   {
392     assert_alias(info);
393
394     RepoStatus oldstatus;
395     RepoStatus newstatus;
396
397     try
398     {
399       MIL << "Going to try to check whether refresh is needed for " << url << endl;
400
401       repo::RepoType repokind = info.type();
402
403       // if the type is unknown, try probing.
404       switch ( repokind.toEnum() )
405       {
406         case RepoType::NONE_e:
407           // unknown, probe it
408           repokind = probe(url);
409         break;
410         default:
411         break;
412       }
413
414       Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
415       filesystem::assert_dir(rawpath);
416       oldstatus = metadataStatus(info);
417
418       // now we've got the old (cached) status, we can decide repo.refresh.delay
419       if (policy != RefreshForced)
420       {
421         // difference in seconds
422         double diff = difftime(
423           (Date::ValueType)Date::now(),
424           (Date::ValueType)oldstatus.timestamp()) / 60;
425
426         DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
427         DBG << "current time: " << (Date::ValueType)Date::now() << endl;
428         DBG << "last refresh = " << diff << " minutes ago" << endl;
429
430         if (diff < ZConfig::instance().repo_refresh_delay())
431         {
432           MIL << "Repository '" << info.alias()
433               << "' has been refreshed less than repo.refresh.delay ("
434               << ZConfig::instance().repo_refresh_delay()
435               << ") minutes ago. Advising to skip refresh" << endl;
436           return false;
437         }
438       }
439
440       // create temp dir as sibling of rawpath
441       filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
442
443       if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
444            ( repokind.toEnum() == RepoType::YAST2_e ) )
445       {
446         MediaSetAccess media(url);
447         shared_ptr<repo::Downloader> downloader_ptr;
448
449         if ( repokind.toEnum() == RepoType::RPMMD_e )
450           downloader_ptr.reset(new yum::Downloader(info.path()));
451         else
452           downloader_ptr.reset( new susetags::Downloader(info.path()));
453
454         RepoStatus newstatus = downloader_ptr->status(media);
455         bool refresh = false;
456         if ( oldstatus.checksum() == newstatus.checksum() )
457         {
458           MIL << "repo has not changed" << endl;
459           if ( policy == RefreshForced )
460           {
461             MIL << "refresh set to forced" << endl;
462             refresh = true;
463           }
464         }
465         else
466         {
467           MIL << "repo has changed, going to refresh" << endl;
468           refresh = true;
469         }
470
471         if (!refresh)
472           touchIndexFile(info);
473
474         return refresh;
475       }
476 #if 0
477       else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
478       {
479         RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
480         bool refresh = false;
481         if ( oldstatus.checksum() == newstatus.checksum() )
482         {
483           MIL << "repo has not changed" << endl;
484           if ( policy == RefreshForced )
485           {
486             MIL << "refresh set to forced" << endl;
487             refresh = true;
488           }
489         }
490         else
491         {
492           MIL << "repo has changed, going to refresh" << endl;
493           refresh = true;
494         }
495
496         if (!refresh)
497           touchIndexFile(info);
498
499         return refresh;
500       }
501 #endif
502       else
503       {
504         ZYPP_THROW(RepoUnknownTypeException());
505       }
506     }
507     catch ( const Exception &e )
508     {
509       ZYPP_CAUGHT(e);
510       ERR << "refresh check failed for " << url << endl;
511       ZYPP_RETHROW(e);
512     }
513
514     return true; // default
515   }
516
517   void RepoManager::refreshMetadata( const RepoInfo &info,
518                                      RawMetadataRefreshPolicy policy,
519                                      const ProgressData::ReceiverFnc & progress )
520   {
521     assert_alias(info);
522     assert_urls(info);
523
524     // we will throw this later if no URL checks out fine
525     RepoException rexception(_("Valid metadata not found at specified URL(s)"));
526
527     // try urls one by one
528     for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
529     {
530       try
531       {
532         Url url(*it);
533
534         // check whether to refresh metadata
535         // if the check fails for this url, it throws, so another url will be checked
536         if (!checkIfToRefreshMetadata(info, url, policy))
537           return;
538
539         MIL << "Going to refresh metadata from " << url << endl;
540
541         repo::RepoType repokind = info.type();
542
543         // if the type is unknown, try probing.
544         switch ( repokind.toEnum() )
545         {
546           case RepoType::NONE_e:
547             // unknown, probe it
548             repokind = probe(*it);
549           break;
550           default:
551           break;
552         }
553
554         Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
555         filesystem::assert_dir(rawpath);
556
557         // create temp dir as sibling of rawpath
558         filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
559
560         if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
561              ( repokind.toEnum() == RepoType::YAST2_e ) )
562         {
563           MediaSetAccess media(url);
564           shared_ptr<repo::Downloader> downloader_ptr;
565
566           if ( repokind.toEnum() == RepoType::RPMMD_e )
567             downloader_ptr.reset(new yum::Downloader(info.path()));
568           else
569             downloader_ptr.reset( new susetags::Downloader(info.path()));
570
571           /**
572            * Given a downloader, sets the other repos raw metadata
573            * path as cache paths for the fetcher, so if another
574            * repo has the same file, it will not download it
575            * but copy it from the other repository
576            */
577           std::list<RepoInfo> repos = knownRepositories();
578           for ( std::list<RepoInfo>::const_iterator it = repos.begin();
579                 it != repos.end();
580                 ++it )
581           {
582             Pathname cachepath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
583             if ( PathInfo(cachepath).isExist() )  
584               downloader_ptr->addCachePath(cachepath);
585           }
586
587           downloader_ptr->download( media, tmpdir.path());
588         }
589 #if 0
590         else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
591         {
592           RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
593
594           std::ofstream file(( tmpdir.path() + "/cookie").c_str());
595           if (!file) {
596             ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
597           }
598           file << url << endl;
599           file << newstatus.checksum() << endl;
600
601           file.close();
602         }
603 #endif
604         else
605         {
606           ZYPP_THROW(RepoUnknownTypeException());
607         }
608
609         // ok we have the metadata, now exchange
610         // the contents
611
612         TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
613         filesystem::rename( rawpath, oldmetadata.path() );
614         // move the just downloaded there
615         filesystem::rename( tmpdir.path(), rawpath );
616
617         // we are done.
618         return;
619       }
620       catch ( const Exception &e )
621       {
622         ZYPP_CAUGHT(e);
623         ERR << "Trying another url..." << endl;
624
625         // remember the exception caught for the *first URL*
626         // if all other URLs fail, the rexception will be thrown with the
627         // cause of the problem of the first URL remembered
628         if (it == info.baseUrlsBegin())
629           rexception.remember(e);
630       }
631     } // for every url
632     ERR << "No more urls..." << endl;
633     ZYPP_THROW(rexception);
634   }
635
636   ////////////////////////////////////////////////////////////////////////////
637
638   void RepoManager::cleanMetadata( const RepoInfo &info,
639                                    const ProgressData::ReceiverFnc & progressfnc )
640   {
641     ProgressData progress(100);
642     progress.sendTo(progressfnc);
643
644     filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
645     progress.toMax();
646   }
647
648   void RepoManager::cleanPackages( const RepoInfo &info,
649                                    const ProgressData::ReceiverFnc & progressfnc )
650   {
651     ProgressData progress(100);
652     progress.sendTo(progressfnc);
653
654     filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
655     progress.toMax();
656   }
657
658   void RepoManager::buildCache( const RepoInfo &info,
659                                 CacheBuildPolicy policy,
660                                 const ProgressData::ReceiverFnc & progressrcv )
661   {
662     assert_alias(info);
663     Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
664
665     Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
666     Pathname solvfile = base.extend(".solv");
667
668
669     RepoStatus raw_metadata_status = metadataStatus(info);
670     if ( raw_metadata_status.empty() )
671     {
672        /* if there is no cache at this point, we refresh the raw
673           in case this is the first time - if it's !autorefresh,
674           we may still refresh */
675       refreshMetadata(info, RefreshIfNeeded, progressrcv );
676       raw_metadata_status = metadataStatus(info);
677     }
678
679     bool needs_cleaning = false;
680     if ( isCached( info ) )
681     {
682       MIL << info.alias() << " is already cached." << endl;
683       //data::RecordId id = store.lookupRepository(info.alias());
684       RepoStatus cache_status = cacheStatus(info);
685
686       if ( cache_status.checksum() == raw_metadata_status.checksum() )
687       {
688         MIL << info.alias() << " cache is up to date with metadata." << endl;
689         if ( policy == BuildIfNeeded ) {
690           return;
691         }
692         else {
693           MIL << info.alias() << " cache rebuild is forced" << endl;
694         }
695       }
696
697       needs_cleaning = true;
698     }
699
700     ProgressData progress(100);
701     callback::SendReport<ProgressReport> report;
702     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
703     progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
704     progress.toMin();
705
706     if (needs_cleaning)
707     {
708       cleanCache(info);
709     }
710
711     MIL << info.alias() << " building cache..." << endl;
712     // do we have type?
713     repo::RepoType repokind = info.type();
714
715     // if the type is unknown, try probing.
716     switch ( repokind.toEnum() )
717     {
718       case RepoType::NONE_e:
719         // unknown, probe the local metadata
720         repokind = probe(rawpath.asUrl());
721       break;
722       default:
723       break;
724     }
725
726     MIL << "repo type is " << repokind << endl;
727
728     switch ( repokind.toEnum() )
729     {
730       case RepoType::RPMMD_e :
731       case RepoType::YAST2_e :
732       {
733         // Take care we unlink the solvfile on exception
734         ManagedFile guard( solvfile, filesystem::unlink );
735
736         ostringstream cmd;
737         cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() );
738
739         MIL << "Executing: " << cmd.str() << endl;
740         ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
741
742         cmd << endl;
743         for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
744           WAR << "  " << output;
745           cmd << "     " << output;
746         }
747
748         int ret = prog.close();
749         if ( ret != 0 )
750         {
751           RepoException ex(str::form("Failed to cache repo (%d).", ret));
752           ex.remember( cmd.str() );
753           ZYPP_THROW(ex);
754         }
755
756         // We keep it.
757         guard.resetDispose();
758       }
759       break;
760       default:
761         ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
762       break;
763     }
764 #if 0
765     switch ( repokind.toEnum() )
766     {
767       case RepoType::RPMMD_e :
768       if (0)
769       {
770         CombinedProgressData subprogrcv( progress, 100);
771         parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
772         parser.parse(rawpath);
773           // no error
774       }
775       break;
776       case RepoType::YAST2_e :
777       if (0)
778       {
779         CombinedProgressData subprogrcv( progress, 100);
780         parser::susetags::RepoParser parser(id, store, subprogrcv);
781         parser.parse(rawpath);
782         // no error
783       }
784       break;
785 #endif
786 #if 0
787       case RepoType::RPMPLAINDIR_e :
788       {
789         CombinedProgressData subprogrcv( progress, 100);
790         InputStream is(rawpath + "cookie");
791         string buffer;
792         getline( is.stream(), buffer);
793         Url url(buffer);
794         parser::plaindir::RepoParser parser(id, store, subprogrcv);
795         parser.parse(url.getPathName());
796       }
797       break;
798
799       default:
800         ZYPP_THROW(RepoUnknownTypeException());
801     }
802 #endif
803     // update timestamp and checksum
804     //store.updateRepositoryStatus(id, raw_metadata_status);
805     setCacheStatus(info.escaped_alias(), raw_metadata_status);
806     MIL << "Commit cache.." << endl;
807     //store.commit();
808     //progress.toMax();
809   }
810
811   ////////////////////////////////////////////////////////////////////////////
812
813   repo::RepoType RepoManager::probe( const Url &url ) const
814   {
815     if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
816     {
817       // Handle non existing local directory in advance, as
818       // MediaSetAccess does not support it.
819       return repo::RepoType::NONE;
820     }
821
822     try
823     {
824       MediaSetAccess access(url);
825       if ( access.doesFileExist("/repodata/repomd.xml") )
826         return repo::RepoType::RPMMD;
827       if ( access.doesFileExist("/content") )
828         return repo::RepoType::YAST2;
829
830       // if it is a local url of type dir
831       if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
832       {
833         Pathname path = Pathname(url.getPathName());
834         if ( PathInfo(path).isDir() )
835         {
836           // allow empty dirs for now
837           return repo::RepoType::RPMPLAINDIR;
838         }
839       }
840     }
841     catch ( const media::MediaException &e )
842     {
843       ZYPP_CAUGHT(e);
844       RepoException enew("Error trying to read from " + url.asString());
845       enew.remember(e);
846       ZYPP_THROW(enew);
847     }
848     catch ( const Exception &e )
849     {
850       ZYPP_CAUGHT(e);
851       Exception enew("Unknown error reading from " + url.asString());
852       enew.remember(e);
853       ZYPP_THROW(enew);
854     }
855
856     return repo::RepoType::NONE;
857   }
858
859   ////////////////////////////////////////////////////////////////////////////
860
861   void RepoManager::cleanCache( const RepoInfo &info,
862                                 const ProgressData::ReceiverFnc & progressrcv )
863   {
864     ProgressData progress(100);
865     progress.sendTo(progressrcv);
866     progress.toMin();
867
868     unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".solv"));
869     progress.set(99);
870     unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".cookie"));
871
872     progress.toMax();
873   }
874
875   void RepoManager::cleanTargetCache(const ProgressData::ReceiverFnc & progressrcv)
876   {
877     unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".solv"));
878     unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".cookie"));
879   }
880
881   ////////////////////////////////////////////////////////////////////////////
882
883   bool RepoManager::isCached( const RepoInfo &info ) const
884   {
885     Pathname name = _pimpl->options.repoCachePath;
886     return PathInfo(name + Pathname(info.escaped_alias()).extend(".solv")).isExist();
887   }
888
889   RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
890   {
891
892     Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
893     Pathname cookiefile = base.extend(".cookie");
894
895     return RepoStatus::fromCookieFile(cookiefile);
896   }
897
898   void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
899   {
900     Pathname base = _pimpl->options.repoCachePath + alias;
901     Pathname cookiefile = base.extend(".cookie");
902
903     status.saveToCookieFile(cookiefile);
904   }
905
906   void RepoManager::loadFromCache( const RepoInfo & info,
907                                    const ProgressData::ReceiverFnc & progressrcv )
908   {
909     assert_alias(info);
910     string alias = info.escaped_alias();
911     Pathname solvfile = (_pimpl->options.repoCachePath / alias).extend(".solv");
912
913     if ( ! PathInfo(solvfile).isExist() )
914       ZYPP_THROW(RepoNotCachedException());
915
916     try
917     {
918       sat::Pool::instance().addRepoSolv( solvfile, info );
919     }
920     catch ( const Exception & exp )
921     {
922       ZYPP_CAUGHT( exp );
923       MIL << "Try to handle exception by rebuilding the solv-file" << endl;
924       cleanCache( info, progressrcv );
925       buildCache( info, BuildIfNeeded, progressrcv );
926
927       sat::Pool::instance().addRepoSolv( solvfile, info );
928     }
929   }
930
931   ////////////////////////////////////////////////////////////////////////////
932
933   /**
934    * Generate a non existing filename in a directory, using a base
935    * name. For example if a directory contains 3 files
936    *
937    * |-- bar
938    * |-- foo
939    * `-- moo
940    *
941    * If you try to generate a unique filename for this directory,
942    * based on "ruu" you will get "ruu", but if you use the base
943    * "foo" you will get "foo_1"
944    *
945    * \param dir Directory where the file needs to be unique
946    * \param basefilename string to base the filename on.
947    */
948   static Pathname generate_non_existing_name( const Pathname &dir,
949                                               const std::string &basefilename )
950   {
951     string final_filename = basefilename;
952     int counter = 1;
953     while ( PathInfo(dir + final_filename).isExist() )
954     {
955       final_filename = basefilename + "_" + str::numstring(counter);
956       counter++;
957     }
958     return dir + Pathname(final_filename);
959   }
960
961   ////////////////////////////////////////////////////////////////////////////
962
963   /**
964    * \short Generate a related filename from a repo info
965    *
966    * From a repo info, it will try to use the alias as a filename
967    * escaping it if necessary. Other fallbacks can be added to
968    * this function in case there is no way to use the alias
969    */
970   static std::string generate_filename( const RepoInfo &info )
971   {
972     std::string fnd="/";
973     std::string rep="_";
974     std::string filename = info.alias();
975     // replace slashes with underscores
976     size_t pos = filename.find(fnd);
977     while(pos!=string::npos)
978     {
979       filename.replace(pos,fnd.length(),rep);
980       pos = filename.find(fnd,pos+rep.length());
981     }
982     filename = Pathname(filename).extend(".repo").asString();
983     MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
984     return filename;
985   }
986
987
988   ////////////////////////////////////////////////////////////////////////////
989
990   void RepoManager::addRepository( const RepoInfo &info,
991                                    const ProgressData::ReceiverFnc & progressrcv )
992   {
993     assert_alias(info);
994
995     ProgressData progress(100);
996     callback::SendReport<ProgressReport> report;
997     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
998     progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
999     progress.toMin();
1000
1001     std::list<RepoInfo> repos = knownRepositories();
1002     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1003           it != repos.end();
1004           ++it )
1005     {
1006       if ( info.alias() == (*it).alias() )
1007         ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
1008     }
1009
1010     RepoInfo tosave = info;
1011
1012     // check the first url for now
1013     if ( ZConfig::instance().repo_add_probe()
1014         || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
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 ///////////////////////////////////////////////////////////////////