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