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